fix(iam): answer a refused MFA device as AWS words it (#8855)

Every MFA refusal here was this package's own sentence. IAM answers
EnableMFADevice and ResyncMFADevice with 'Authentication code for device
is not valid.' and a duplicate virtual device with 'MFA device already
exists.', both recorded and both wholly fixed text.

STS answers two sentences rather than one, by which half of the claim
failed: a serial no device of the caller's answers to, or a code that
device did not produce. Both are 403 AccessDenied, so the sentence is the
only thing that tells a caller which half to look at, and the whitespace
inside them is AWS's own. RequestMfaClaim carries the reason now, so the
seam both session operations share can word them apart.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 08:27:02 -04:00
1 parent 29fc72d156
commit 532b64eaea
7 files changed
+524 -25

No files matched your search

@@ -0,0 +1,151 @@
package io.floci.aws.services.iam;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.VirtualMfaFixtures;
import io.floci.aws.testing.VirtualMfaFixtures.Device;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* What IAM answers for a device it will not take: the code that is not one of the device's outputs,
* and the second device at a path and name another already has. Both sentences are recorded against
* a real account and both are wholly fixed text.
*
* <p>{@code docs/services/iam.md} carries the recordings.
*/
@QuarkusTest
class IamMfaRefusalWordingIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261118/us-east-1/iam/aws4_request";
private static final String CODE = "ErrorResponse.Error.Code";
private static final String MESSAGE = "ErrorResponse.Error.Message";
/** Recorded on EnableMFADevice and ResyncMFADevice, 2026-11-05. */
private static final String BAD_CODE = "Authentication code for device is not valid.";
/** Recorded on CreateVirtualMFADevice for a second device at the same path and name. */
private static final String DUPLICATE = "MFA device already exists.";
/** What {@code EnableMFADevice} accepts either side of the current step. */
private static final int ENABLE_DRIFT_STEPS = 1;
/** What {@code ResyncMFADevice} accepts, the operation being for a device that has drifted. */
private static final int RESYNC_DRIFT_STEPS = 10;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
private static String unique(String prefix) {
return prefix + "-" + System.nanoTime();
}
private String createUser() {
String userName = unique("mfa-wording-user");
iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName)
.when().post("/").then().statusCode(200));
return userName;
}
/** A device of this account's, with the seed its creation handed back. */
private Device createDevice(String deviceName) {
Device device = VirtualMfaFixtures.deviceFrom(
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", deviceName)
.when().post("/").then().statusCode(200).extract().xmlPath());
cleanup.register(() -> iam("DeleteVirtualMFADevice")
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200));
return device;
}
/**
* Enables {@code device} for {@code userName} with two of its own consecutive codes, and
* registers the deactivate. Cleanup runs last-registered first, and neither the device nor the
* user it is assigned to can be deleted while the assignment stands, so this registration has
* to come after both deletes to run before them.
*/
private void enableDevice(String userName, Device device) {
List<String> codes = VirtualMfaFixtures.twoConsecutiveCodes(device.seed());
iam("EnableMFADevice").formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", codes.get(0))
.formParam("AuthenticationCode2", codes.get(1))
.when().post("/").then().statusCode(200);
cleanup.register(() -> iam("DeactivateMFADevice").formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200));
}
/** Codes the device never produced are refused with AWS's own sentence, and nothing changes. */
@Test
void enablingWithCodesTheDeviceNeverProducedAnswersTheRecordedSentence() {
String userName = createUser();
Device device = createDevice(unique("mfa-wording-device"));
List<String> wrong = VirtualMfaFixtures.codesTheDeviceCannotProduce(
device.seed(), ENABLE_DRIFT_STEPS, 2);
iam("EnableMFADevice").formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", wrong.get(0))
.formParam("AuthenticationCode2", wrong.get(1))
.when().post("/").then().statusCode(403)
.body(CODE, equalTo("InvalidAuthenticationCode"))
.body(MESSAGE, equalTo(BAD_CODE));
iam("ListVirtualMFADevices").formParam("AssignmentStatus", "Unassigned")
.when().post("/").then().statusCode(200);
}
/** Resyncing answers the same sentence, the recordings covering both operations. */
@Test
void resyncingWithCodesTheDeviceNeverProducedAnswersTheSameSentence() {
String userName = createUser();
Device device = createDevice(unique("mfa-wording-resync"));
enableDevice(userName, device);
List<String> wrong = VirtualMfaFixtures.codesTheDeviceCannotProduce(
device.seed(), RESYNC_DRIFT_STEPS, 2);
iam("ResyncMFADevice").formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", wrong.get(0))
.formParam("AuthenticationCode2", wrong.get(1))
.when().post("/").then().statusCode(403)
.body(CODE, equalTo("InvalidAuthenticationCode"))
.body(MESSAGE, equalTo(BAD_CODE));
}
/** A second device at the same path and name, which AWS answers in five words. */
@Test
void aSecondDeviceAtTheSamePathAndNameAnswersTheRecordedSentence() {
String deviceName = unique("mfa-wording-duplicate");
createDevice(deviceName);
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", deviceName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("EntityAlreadyExists"))
.body(MESSAGE, equalTo(DUPLICATE));
}
/** The control: two real codes still enable the device, and it is the user's afterwards. */
@Test
void twoRealCodesStillEnableTheDevice() {
String userName = createUser();
Device device = createDevice(unique("mfa-wording-control"));
enableDevice(userName, device);
iam("ListMFADevices").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber",
equalTo(device.serialNumber()));
}
}
@@ -0,0 +1,187 @@
package io.floci.aws.services.iam;
import io.floci.aws.core.common.Totp;
import io.floci.aws.testing.ValidateSignaturesProfile;
import io.floci.aws.testing.VirtualMfaFixtures;
import io.floci.aws.testing.VirtualMfaFixtures.Device;
import io.floci.aws.testutil.StsRequests.Credentials;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testutil.StsRequests.request;
import static org.hamcrest.Matchers.equalTo;
/**
* The two sentences a failed MFA claim earns on STS, which AWS words by the half of the claim that
* failed: a serial no device of the caller's answers to, and a code that device did not produce.
* Both are 403 {@code AccessDenied}, so the sentence is the only thing that tells a caller which
* half to look at, and both are held here byte for byte, the whitespace inside them included.
*
* <p>The requests are signed because the claim is read against the caller the key belongs to: a
* device is the user's, and an unsigned request names no user to own one.
*
* <p>{@code docs/services/iam.md} carries the recordings.
*/
@QuarkusTest
@TestProfile(ValidateSignaturesProfile.class)
class StsMfaRefusalWordingIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final Credentials ROOT = new Credentials("test", "test", null);
private static final String CODE = "ErrorResponse.Error.Code";
private static final String MESSAGE = "ErrorResponse.Error.Message";
/** Recorded 2026-10-29. The two spaces after {@code MFA code.} are AWS's own. */
private static final String SERIAL_FAILED =
"MultiFactorAuthentication failed, unable to validate MFA code. "
+ "Please verify your MFA serial number is valid and associated with this user.";
/** Recorded 2026-11-13. The sentence ends in a single space, which is also AWS's own. */
private static final String CODE_FAILED =
"MultiFactorAuthentication failed with invalid MFA one time pass code. ";
/** What a session request's token code is accepted within, either side of the current step. */
private static final int TOKEN_DRIFT_STEPS = 1;
private final List<Runnable> cleanup = new ArrayList<>();
@AfterEach
void cleanup() {
AssertionError failures = null;
for (int i = cleanup.size() - 1; i >= 0; i--) {
try {
cleanup.get(i).run();
} catch (AssertionError failure) {
if (failures == null) {
failures = new AssertionError("Fixture cleanup failed");
}
failures.addSuppressed(failure);
}
}
if (failures != null) {
throw failures;
}
}
/** A serial nothing of this caller's answers to names the serial half. */
@Test
void aSerialTheCallerHoldsNoDeviceForNamesTheSerialHalf() throws Exception {
Credentials user = createUser();
request(user, "sts", "GetSessionToken",
Map.of("SerialNumber", "arn:aws:iam::" + ACCOUNT + ":mfa/no-such-device",
"TokenCode", "123456"))
.then().statusCode(403)
.body(CODE, equalTo("AccessDenied"))
.body(MESSAGE, equalTo(SERIAL_FAILED));
}
/** A code the caller's own device did not produce names the code half instead. */
@Test
void aCodeTheDeviceDidNotProduceNamesTheCodeHalf() throws Exception {
Credentials user = createUser();
Device device = enableDevice(user);
request(user, "sts", "GetSessionToken",
Map.of("SerialNumber", device.serialNumber(), "TokenCode",
VirtualMfaFixtures.codeTheDeviceCannotProduce(
device.seed(), TOKEN_DRIFT_STEPS)))
.then().statusCode(403)
.body(CODE, equalTo("AccessDenied"))
.body(MESSAGE, equalTo(CODE_FAILED));
}
/**
* {@code AssumeRole} reads the same pair through the same seam and carries no recording of its
* own, so it answers the same sentence, which is a reading rather than a measurement.
*/
@Test
void assumeRoleAnswersTheSameSentence() throws Exception {
Credentials user = createUser();
Device device = enableDevice(user);
request(user, "sts", "AssumeRole",
Map.of("RoleArn", "arn:aws:iam::" + ACCOUNT + ":role/mfa-wording-role",
"RoleSessionName", "mfa-wording",
"SerialNumber", device.serialNumber(), "TokenCode",
VirtualMfaFixtures.codeTheDeviceCannotProduce(
device.seed(), TOKEN_DRIFT_STEPS)))
.then().statusCode(403)
.body(CODE, equalTo("AccessDenied"))
.body(MESSAGE, equalTo(CODE_FAILED));
}
/** The control: the device's own code still mints a session. */
@Test
void aRealCodeStillMintsASession() throws Exception {
Credentials user = createUser();
Device device = enableDevice(user);
Response minted = request(user, "sts", "GetSessionToken",
Map.of("SerialNumber", device.serialNumber(),
"TokenCode", Totp.codeAt(device.seed(), Totp.stepAt(Instant.now()))));
minted.then().statusCode(200);
}
/**
* A user holding one access key, created as root through the same signed transport these tests
* use. The enforcement suites' shared fixture speaks the header transport instead, which this
* profile refuses, so the two steps are taken here.
*/
private Credentials createUser() throws Exception {
String name = "mfa-wording-" + UUID.randomUUID();
request(ROOT, "iam", "CreateUser", Map.of("UserName", name)).then().statusCode(200);
cleanup.add(() -> remove("DeleteUser", Map.of("UserName", name)));
Response created = request(ROOT, "iam", "CreateAccessKey", Map.of("UserName", name));
created.then().statusCode(200);
String prefix = "CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.";
String key = created.xmlPath().getString(prefix + "AccessKeyId");
cleanup.add(() -> remove("DeleteAccessKey", Map.of("UserName", name, "AccessKeyId", key)));
return new Credentials(key, created.xmlPath().getString(prefix + "SecretAccessKey"), null);
}
/** A virtual device of that user's, enabled with two of its own consecutive codes. */
private Device enableDevice(Credentials user) throws Exception {
String userName = userNameOf(user);
Response created = request(ROOT, "iam", "CreateVirtualMFADevice",
Map.of("VirtualMFADeviceName", userName + "-device"));
created.then().statusCode(200);
Device device = VirtualMfaFixtures.deviceFrom(created.xmlPath());
List<String> codes = VirtualMfaFixtures.twoConsecutiveCodes(device.seed());
request(ROOT, "iam", "EnableMFADevice",
Map.of("UserName", userName, "SerialNumber", device.serialNumber(),
"AuthenticationCode1", codes.get(0),
"AuthenticationCode2", codes.get(1))).then().statusCode(200);
// Cleanup runs last-registered first, and an assigned device cannot be deleted at all:
// the delete is registered first so the deactivate runs ahead of it.
cleanup.add(() -> remove("DeleteVirtualMFADevice",
Map.of("SerialNumber", device.serialNumber())));
cleanup.add(() -> remove("DeactivateMFADevice",
Map.of("UserName", userName, "SerialNumber", device.serialNumber())));
return device;
}
/** The user the caller's key belongs to, which is who a device has to be enabled for. */
private String userNameOf(Credentials user) throws Exception {
Response caller = request(user, "sts", "GetCallerIdentity", Map.of());
caller.then().statusCode(200);
String arn = caller.xmlPath()
.getString("GetCallerIdentityResponse.GetCallerIdentityResult.Arn");
return arn.substring(arn.lastIndexOf('/') + 1);
}
private void remove(String action, Map<String, String> params) {
try {
request(ROOT, "iam", action, params).then().statusCode(200);
} catch (Exception failure) {
throw new AssertionError("Failed cleanup " + action, failure);
}
}
}
@@ -0,0 +1,86 @@
package io.floci.aws.testing;
import io.floci.aws.core.common.Totp;
import io.restassured.path.xml.XmlPath;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* The parts of a virtual MFA device a test needs after creating one: the seed its creation handed
* back, the pair of consecutive codes an enable or a resync takes, and codes the device cannot
* produce. The transport stays with each test, which is the only part that differs between the
* classes using this: one speaks the Authorization header, another signs every request.
*/
public final class VirtualMfaFixtures {
private static final String DEVICE_MEMBER =
"CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice.";
/** The accepted window either side of the current step, plus a step of margin. */
private static final int MARGIN_STEPS = 1;
private VirtualMfaFixtures() {
}
/** A device and the seed it answers codes from, read off a {@code CreateVirtualMFADevice}. */
public record Device(String serialNumber, String seed) {
}
/**
* What a {@code CreateVirtualMFADevice} response describes. {@code Base32StringSeed} is sent
* the way AWS sends it, base64 over the base32 text, so it is decoded once here.
*/
public static Device deviceFrom(XmlPath created) {
return new Device(created.getString(DEVICE_MEMBER + "SerialNumber"),
new String(Base64.getDecoder()
.decode(created.getString(DEVICE_MEMBER + "Base32StringSeed").trim()),
StandardCharsets.UTF_8));
}
/**
* The two codes an enable or a resync takes, oldest first: the step before the current one and
* the current one, which is what a caller reading two codes off an authenticator sends.
*/
public static List<String> twoConsecutiveCodes(String seed) {
long step = Totp.stepAt(Instant.now());
return List.of(Totp.codeAt(seed, step - 1), Totp.codeAt(seed, step));
}
/**
* A six-digit code the device cannot produce for any step the operation would accept, with a
* step of margin either side in case the window moves while the request is in flight.
*
* <p>A literal will not do. Every six-digit string is a code that some step produces, so a
* fixed {@code 000000} is a code the device may well answer with at the moment the test runs,
* and the refusal it is checking would not happen.
*/
public static String codeTheDeviceCannotProduce(String seed, int driftSteps) {
return codesTheDeviceCannotProduce(seed, driftSteps, 1).getFirst();
}
/** The same, {@code count} of them, each different from the others. */
public static List<String> codesTheDeviceCannotProduce(String seed, int driftSteps, int count) {
long step = Totp.stepAt(Instant.now());
Set<String> accepted = new HashSet<>();
for (long s = step - driftSteps - MARGIN_STEPS; s <= step + driftSteps + MARGIN_STEPS; s++) {
accepted.add(Totp.codeAt(seed, s));
}
List<String> unused = new ArrayList<>();
for (int candidate = 0; candidate < 1_000_000 && unused.size() < count; candidate++) {
String code = "%06d".formatted(candidate);
if (!accepted.contains(code)) {
unused.add(code);
}
}
if (unused.size() < count) {
throw new IllegalStateException("No unused six-digit code left for seed window");
}
return List.copyOf(unused);
}
}