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

+29
View File
@@ -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
@@ -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.
*
* <p>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".
*
* <p>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() {
@@ -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<String> userName = mfaUserName(accessKeyId);
if (userName.isEmpty()) {
return new RequestMfaClaim(true, holdsKey(accessKeyId) ? null : clock.instant());
return holdsKey(accessKeyId)
? RequestMfaClaim.unknownSerial()
: RequestMfaClaim.authenticated(clock.instant());
}
synchronized (mfaDeviceLock) {
Optional<VirtualMfaDevice> device = virtualMfaDevices.get(serialNumber)
.filter(candidate -> userName.get().equals(candidate.getUserName()));
if (device.isEmpty()) {
return new RequestMfaClaim(true, null);
return RequestMfaClaim.unknownSerial();
}
OptionalLong step = Totp.matchingStep(device.get().getBase32Seed(), tokenCode,
ENABLE_DRIFT_STEPS, Instant.now());
Long spent = device.get().getLastUsedTotpStep();
if (step.isEmpty() || (spent != null && step.getAsLong() <= spent)) {
return new RequestMfaClaim(true, null);
return RequestMfaClaim.invalidCode();
}
device.get().setLastUsedTotpStep(step.getAsLong());
virtualMfaDevices.put(serialNumber, device.get());
return new RequestMfaClaim(true, clock.instant());
return RequestMfaClaim.authenticated(clock.instant());
}
}
@@ -242,8 +242,9 @@ public class StsQueryHandler {
* GetSessionToken include MFA information, you can check for MFA in individual API operations
* made by the credentials". A call that names either member is a claim of MFA and has to make
* it good; what answers a claim that fails is the access denied AWS documents for the case,
* "an incorrect MFA code causes the API to return an access denied error", carrying the
* sentence the IAM actions already write for a code that does not match.
* "an incorrect MFA code causes the API to return an access denied error", in the two
* sentences {@link #mfaRefusal} carries, one for a serial that is not the caller's and one for
* a code that does not match the device it names.
*
* <p>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.
*
* <p>{@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) {
}
@@ -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);
}
}