From 532b64eaeaa3a5b3db987c9f1b0b4e0c451923df Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:27:02 -0400 Subject: [PATCH] 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. --- docs/services/iam.md | 29 +++ .../aws/core/common/RequestMfaClaim.java | 52 +++-- .../io/floci/aws/services/iam/IamService.java | 19 +- .../aws/services/iam/StsQueryHandler.java | 25 ++- .../IamMfaRefusalWordingIntegrationTest.java | 151 ++++++++++++++ .../StsMfaRefusalWordingIntegrationTest.java | 187 ++++++++++++++++++ .../floci/aws/testing/VirtualMfaFixtures.java | 86 ++++++++ 7 files changed, 524 insertions(+), 25 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/iam/IamMfaRefusalWordingIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/iam/StsMfaRefusalWordingIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/testing/VirtualMfaFixtures.java diff --git a/docs/services/iam.md b/docs/services/iam.md index d2a4b38402..5ab4f57584 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1384,6 +1384,35 @@ hold reports that user instead. Hardware TOTP tokens and FIDO security keys are not modeled, so `ListMFADevices` returns only virtual devices where AWS would return every type. +#### What a refused device answers + +Every MFA refusal here is the sentence AWS was recorded answering, and the sentences are not shared +between the two services. + +`EnableMFADevice` and `ResyncMFADevice` answer `InvalidAuthenticationCode` 403 with +`Authentication code for device is not valid.`, wholly fixed text, recorded 2026-11-05, and the +refusal leaves the device as it found it: a refused enable leaves an unassigned device unassigned, +and a refused resync leaves the assignment it requires in place, since resync is for a device that +is already the user's. A second virtual device at the same path and +name is `EntityAlreadyExists` 409 with `MFA device already exists.`, recorded the same day, where +this emulator used to name the entity type and describe the collision. + +`GetSessionToken` answers a failed claim 403 `AccessDenied` in one of two sentences, by which half +of the claim failed, both wholly fixed and neither echoing the serial or the code: + +- a serial no device of the caller's answers to, `MultiFactorAuthentication failed, unable to + validate MFA code. Please verify your MFA serial number is valid and associated with this + user.`, recorded 2026-10-29. The two consecutive spaces after `MFA code.` are AWS's own. +- a code the device did not produce, or produced for a step already spent, + `MultiFactorAuthentication failed with invalid MFA one time pass code. `, recorded 2026-11-13. + That sentence ends in a single space, which is also AWS's own. + +A caller cannot tell the two apart from the code or the status, so the sentence is the only signal, +which is why it is held byte for byte here. `AssumeRole` takes the same pair through the same seam +and carries no recording of its own, so it answers the same two sentences, which is a reading +rather than a measurement. A request naming one member and not the other is read as the half it +left out: no code is a code that cannot validate, no serial a device nothing can be looked up by. + #### What a device affects An enabled device is a device a session can be minted behind, and that session is what a statement diff --git a/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java b/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java index 4edd41a216..9f9ed398cd 100644 --- a/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java +++ b/src/main/java/io/floci/aws/core/common/RequestMfaClaim.java @@ -3,25 +3,47 @@ package io.floci.aws.core.common; import java.time.Instant; /** - * What one request's MFA members amount to: nothing claimed, a device presented and authenticated - * at an instant, or a claim that failed. + * The MFA a request claimed and whether this emulator could make the claim good, computed once per + * request because a one time code is spent when it authenticates. * - *
AWS "provides two API operations that let users pass MFA information: GetSessionToken and - * AssumeRole", and a claim either holds or is refused: "if a policy includes an MFA condition, a - * request is denied if users have not been MFA authenticated, or if they provide an invalid MFA - * device identifier or invalid TOTP". - * - *
It is read twice in one request and computed once, which is why it is held on the request
- * rather than recomputed where it is needed. The enforcement filter needs it because the policy for
- * the call is evaluated there, against the request that carries the device; the STS operation needs
- * it because it answers the refusal and mints the session, and because it runs whether or not
- * enforcement is on. Computing it twice would not do: a code is spent when it authenticates, so the
- * second reading would find the step taken and refuse what the first allowed.
+ * @param claimed whether the request named either MFA member at all
+ * @param authenticatedAt when the device was used, or null when the claim failed
+ * @param failure which half of the claim failed, null unless it did
*/
-public record RequestMfaClaim(boolean claimed, Instant authenticatedAt) {
+public record RequestMfaClaim(boolean claimed, Instant authenticatedAt, Failure failure) {
+
+ /**
+ * Which half of an MFA claim failed, because AWS answers the two with different sentences: a
+ * serial that is not the caller's device is one refusal, a code that does not match it
+ * another, and a caller cannot tell them apart from the code or the status, both being 403
+ * {@code AccessDenied}.
+ */
+ public enum Failure {
+
+ /** No device of the caller's answers to the serial the request named. */
+ SERIAL,
+
+ /** The device answered, and the code was not one of its outputs or was already spent. */
+ CODE
+ }
/** A request that named neither member, which claims nothing and refuses nothing. */
- public static final RequestMfaClaim NONE = new RequestMfaClaim(false, null);
+ public static final RequestMfaClaim NONE = new RequestMfaClaim(false, null, null);
+
+ /** A claim this emulator made good at {@code authenticatedAt}. */
+ public static RequestMfaClaim authenticated(Instant authenticatedAt) {
+ return new RequestMfaClaim(true, authenticatedAt, null);
+ }
+
+ /** A claim naming a serial no device of the caller's answers to. */
+ public static RequestMfaClaim unknownSerial() {
+ return new RequestMfaClaim(true, null, Failure.SERIAL);
+ }
+
+ /** A claim whose code the caller's device did not produce, or produced for a spent step. */
+ public static RequestMfaClaim invalidCode() {
+ return new RequestMfaClaim(true, null, Failure.CODE);
+ }
/** A claim this emulator could not make good, which is the operation's to answer. */
public boolean failed() {
diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java
index 05012912fa..b4e225b0c1 100644
--- a/src/main/java/io/floci/aws/services/iam/IamService.java
+++ b/src/main/java/io/floci/aws/services/iam/IamService.java
@@ -4494,7 +4494,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
synchronized (mfaDeviceLock) {
if (virtualMfaDevices.get(serialNumber).isPresent()) {
throw new AwsException("EntityAlreadyExists",
- "MFADevice entity at the same path and name already exists.", 409);
+ "MFA device already exists.", 409);
}
virtualMfaDevices.put(serialNumber, device);
}
@@ -4668,8 +4668,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private void requireConsecutiveCodes(VirtualMfaDevice device, String code1, String code2, int driftSteps) {
if (!VirtualMfaCodes.matchesConsecutiveCodes(device.getBase32Seed(), code1, code2,
driftSteps, Instant.now())) {
+ // Recorded on EnableMFADevice and ResyncMFADevice, 2026-11-05, wholly fixed text.
throw new AwsException("InvalidAuthenticationCode",
- "Invalid MFA one time pass code.", 403);
+ "Authentication code for device is not valid.", 403);
}
}
@@ -4722,27 +4723,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return RequestMfaClaim.NONE;
}
if (serialNumber == null || tokenCode == null) {
- return new RequestMfaClaim(true, null);
+ // Which half is missing decides the sentence: no code is a code that cannot validate,
+ // and no serial is a device nothing can be looked up by.
+ return tokenCode == null ? RequestMfaClaim.invalidCode() : RequestMfaClaim.unknownSerial();
}
Optional The claim is read through the request's own holder rather than taken here, because the
* policy for this call was evaluated before the operation ran and had to see the same device,
@@ -259,11 +260,29 @@ public class StsQueryHandler {
iamService.requestMfaClaim(requestContext, callerAccessKeyId(), serialNumber, tokenCode);
if (claim.failed()) {
return new MfaOutcome(null, AwsQueryResponse.error("AccessDenied",
- "Invalid MFA one time pass code.", AwsNamespaces.STS, 403));
+ mfaRefusal(claim.failure()), AwsNamespaces.STS, 403));
}
return new MfaOutcome(claim.authenticatedAt(), null);
}
+ /**
+ * The sentence a failed MFA claim earns, which AWS words by which half of the claim failed.
+ * Both are 403 {@code AccessDenied} with a sender fault, both are wholly fixed text, and
+ * neither echoes the serial or the code: a caller is told which half to look at and nothing
+ * about the values it sent. Recorded on {@code GetSessionToken} against a real account, the
+ * serial half on 2026-10-29 and the code half on 2026-11-13, and each carries whitespace AWS
+ * itself emits, two spaces inside the first and a trailing space on the second.
+ *
+ * {@code AssumeRole} takes the same pair through this seam and carries no recording of its
+ * own, so it answers the same two sentences, which is a reading rather than a measurement.
+ */
+ private static String mfaRefusal(RequestMfaClaim.Failure failure) {
+ return failure == RequestMfaClaim.Failure.SERIAL
+ ? "MultiFactorAuthentication failed, unable to validate MFA code. "
+ + "Please verify your MFA serial number is valid and associated with this user."
+ : "MultiFactorAuthentication failed with invalid MFA one time pass code. ";
+ }
+
/** The MFA a call authenticated, or the refusal it earned. */
private record MfaOutcome(Instant authenticatedAt, Response denial) {
}
diff --git a/src/test/java/io/floci/aws/services/iam/IamMfaRefusalWordingIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamMfaRefusalWordingIntegrationTest.java
new file mode 100644
index 0000000000..86ff3ebd91
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/iam/IamMfaRefusalWordingIntegrationTest.java
@@ -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.
+ *
+ * {@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 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.
+ *
+ * {@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 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