feat(iam): model virtual MFA devices with real TOTP verification (#4820)

Replace the ListMFADevices stub with the virtual MFA device lifecycle:
CreateVirtualMFADevice, ListVirtualMFADevices, DeleteVirtualMFADevice,
EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices,
and the device tag readers/writers.

The seed is real rather than a placeholder. CreateVirtualMFADevice
generates a 160-bit secret from SecureRandom and returns it as an RFC
4648 base32 string, and EnableMFADevice/ResyncMFADevice verify codes
against it as RFC 6238 TOTP, so a caller that does not hold the seed
cannot enable a device. The codes must be consecutive, as AWS asks for.
Implemented on the JDK's own javax.crypto, with no new dependency.

The TOTP arithmetic is the shared core.common.Totp primitive (#4814):
CognitoTotp keeps its single-code window and attempt budget, and
VirtualMfaCodes holds the consecutive-pair rule that is specific to IAM.

Request shapes are validated against the wire model before the device is
resolved, so a malformed SerialNumber is a ValidationError rather than a
NoSuchEntity, and UserName is enforced as required on Enable and Resync.
VirtualMFADeviceName gets its own validator because it is the one IAM
name type with no documented maximum length, so borrowing the usual
1-to-128 name check would have rejected names AWS accepts.

Device state also reaches the places that report on it: DeleteUser now
returns DeleteConflict while a user still holds a device, GetAccountSummary
counts devices and their assignments, and the credential report's
mfa_active column is backed by real state instead of a constant.

Documented as out of scope: QRCodePNG is not returned (it needs a QR
encoder, and the otpauth URI it encodes is derivable from the seed that
is returned), GetMFADevice takes only FIDO security key ARNs, hardware
and FIDO devices are not modeled, MFA still has no effect on
authorization because the aws:MultiFactorAuth* keys are never populated,
and STS does not accept SerialNumber/TokenCode.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-01 21:17:50 -05:00
1 parent 44e9b1600e
commit c7bb03ace3
14 files changed
+1924 -50

No files matched your search

@@ -129,8 +129,10 @@ class IamGetAccountSummaryIntegrationTest {
+ ".find { it.key == 'AssumeRolePolicySizeQuota' }.value", equalTo("2048"))
.body("GetAccountSummaryResponse.GetAccountSummaryResult.SummaryMap.entry"
+ ".find { it.key == 'AccountPasswordPresent' }.value", equalTo("0"))
// Root MFA, like the root password and root access keys above: not modeled, so it
// stays zero however many devices the account's IAM users hold.
.body("GetAccountSummaryResponse.GetAccountSummaryResult.SummaryMap.entry"
+ ".find { it.key == 'MFADevices' }.value", equalTo("0"));
+ ".find { it.key == 'AccountMFAEnabled' }.value", equalTo("0"));
}
@Test
@@ -614,18 +614,18 @@ class IamIntegrationTest {
@Test
@Order(50)
void listMfaDevicesReturnsEmptyList() {
void listMfaDevicesRejectsAnUnknownUser() {
given()
.formParam("Action", "ListMFADevices")
.formParam("UserName", "any-user")
.formParam("UserName", "no-such-mfa-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.statusCode(404)
.contentType("application/xml")
.body("ListMFADevicesResponse.ListMFADevicesResult.IsTruncated", equalTo("false"));
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
@@ -14,6 +16,7 @@ import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -181,6 +184,56 @@ class IamServicePersistenceTest {
null);
}
/**
* A virtual MFA device's seed is the shared secret an authenticator app was programmed with,
* so losing it on restart would silently break every paired device: the codes would keep
* being generated and would simply stop being accepted. The assignment has to survive too,
* or a restart would quietly detach every user's MFA.
*/
@Test
void virtualMfaDeviceSurvivesRestartWithItsSeedAndAssignment(@TempDir Path dir) {
StorageBackend<String, IamUser> users = load(dir, "iam-users.json", new TypeReference<>() {});
StorageBackend<String, VirtualMfaDevice> devices =
load(dir, "iam-virtual-mfa-devices.json", new TypeReference<>() {});
IamService first = newServiceWithMfa(users, devices);
first.createUser("mfa-persist-user", "/");
VirtualMfaDevice created = first.createVirtualMfaDevice("mfa-persist", "/", Map.of("env", "prod"));
long step = Totp.stepAt(Instant.now());
first.enableMfaDevice("mfa-persist-user", created.getSerialNumber(),
Totp.codeAt(created.getBase32Seed(), step - 1),
Totp.codeAt(created.getBase32Seed(), step));
// A fresh service over the same files is a restart with the same data dir.
IamService restarted = newServiceWithMfa(
load(dir, "iam-users.json", new TypeReference<>() {}),
load(dir, "iam-virtual-mfa-devices.json", new TypeReference<>() {}));
VirtualMfaDevice reloaded = restarted.getVirtualMfaDevice(created.getSerialNumber());
assertEquals(created.getBase32Seed(), reloaded.getBase32Seed(), "the seed must survive");
assertEquals("mfa-persist-user", reloaded.getUserName());
assertEquals("prod", reloaded.getTags().get("env"));
// enableDate and createDate are Instants, so a broken time round trip surfaces here.
assertNotNull(reloaded.getEnableDate());
assertEquals(created.getCreateDate(), reloaded.getCreateDate());
// And the reloaded seed still verifies a code, which is what actually matters to a caller.
long afterRestart = Totp.stepAt(Instant.now());
restarted.resyncMfaDevice("mfa-persist-user", created.getSerialNumber(),
Totp.codeAt(reloaded.getBase32Seed(), afterRestart - 1),
Totp.codeAt(reloaded.getBase32Seed(), afterRestart));
}
private IamService newServiceWithMfa(StorageBackend<String, IamUser> users,
StorageBackend<String, VirtualMfaDevice> devices) {
return new IamService(
users, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), devices,
new RegionResolver("us-east-1", "000000000000"), false, null);
}
private <V> StorageBackend<String, V> load(Path dir, String file, TypeReference<Map<String, V>> type) {
PersistentStorage<String, V> backend = new PersistentStorage<>(dir.resolve(file), type);
backend.load();
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -20,6 +21,7 @@ import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -2223,7 +2225,41 @@ class IamServiceTest {
assertEquals("TRUE", fields[3], "password_enabled");
assertEquals("TRUE", fields[8], "access_key_1_active");
assertEquals("FALSE", fields[7], "mfa_active is never modeled");
assertEquals("FALSE", fields[7], "mfa_active, with no device enabled for this user");
}
/**
* The {@code mfa_active} column is backed by real device state rather than a constant, so a
* user holding an enabled device reports TRUE while the untouched user beside them stays FALSE.
*/
@Test
void credentialReportMarksUsersHoldingAnMfaDeviceAsMfaActive() {
iamService.createUser("mfa-report-with", "/");
iamService.createUser("mfa-report-without", "/");
VirtualMfaDevice device = iamService.createVirtualMfaDevice("mfa-report-device", "/", Map.of());
String[] codes = consecutiveCodes(device.getBase32Seed());
iamService.enableMfaDevice("mfa-report-with", device.getSerialNumber(), codes[0], codes[1]);
iamService.generateCredentialReport();
String csv = new String(Base64.getDecoder().decode(iamService.getCredentialReport().base64Content()));
assertEquals("TRUE", mfaActiveColumn(csv, "mfa-report-with"));
assertEquals("FALSE", mfaActiveColumn(csv, "mfa-report-without"));
}
private static String mfaActiveColumn(String csv, String userName) {
return csv.lines().filter(line -> line.startsWith(userName + ","))
.findFirst()
.orElseThrow(() -> new AssertionError("no row for " + userName + " in: " + csv))
.split(",", -1)[7];
}
/** The pair an authenticator would show now, which is what EnableMFADevice asks for. */
private static String[] consecutiveCodes(String base32Seed) {
long step = Totp.stepAt(Instant.now());
return new String[] {
Totp.codeAt(base32Seed, step - 1),
Totp.codeAt(base32Seed, step)
};
}
/**
@@ -2267,7 +2303,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), credentialReports,
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);
@@ -2284,7 +2320,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), credentialReports,
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport();
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* A virtual MFA device holds a shared secret, so it must not be reachable from another account.
* These drive one {@link IamService} whose request account can be switched, which is what a
* caller presenting credentials for a different account amounts to.
*/
class VirtualMfaAccountScopeTest {
private static final String ACCOUNT_A = "000000000000";
private static final String ACCOUNT_B = "111111111111";
@SuppressWarnings("unchecked")
private static Instance<RequestContext> requestContextFor(AtomicReference<String> accountId) {
RequestContext rc = mock(RequestContext.class);
when(rc.getAccountId()).thenAnswer(invocation -> accountId.get());
Instance<RequestContext> inst = mock(Instance.class);
when(inst.get()).thenReturn(rc);
return inst;
}
@Test
void aDeviceIsInvisibleAndUnusableFromAnotherAccount() {
AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);
AccountAwareStorageBackend<VirtualMfaDevice> devices = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);
IamService service = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of());
String serial = device.getSerialNumber();
assertTrue(serial.contains(ACCOUNT_A), "the serial number carries the owning account");
// Now the same service, serving a request that belongs to another account.
account.set(ACCOUNT_B);
assertTrue(service.listVirtualMfaDevices("Any").isEmpty(),
"account B must not see account A's devices");
AwsException read = assertThrows(AwsException.class, () -> service.getVirtualMfaDevice(serial));
assertEquals("NoSuchEntity", read.getErrorCode());
AwsException delete = assertThrows(AwsException.class,
() -> service.deleteVirtualMfaDevice(serial));
assertEquals("NoSuchEntity", delete.getErrorCode());
// And the seed cannot be reached indirectly through the tag reader either.
assertThrows(AwsException.class, () -> service.listMfaDeviceTags(serial));
// Account A still has it, so nothing was destroyed by the cross-account attempts.
account.set(ACCOUNT_A);
assertEquals(serial, service.getVirtualMfaDevice(serial).getSerialNumber());
assertEquals(1, service.listVirtualMfaDevices("Any").size());
}
/** The same device name in two accounts is two devices, each with its own secret. */
@Test
void theSameDeviceNameInTwoAccountsGetsDistinctSeeds() {
AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);
AccountAwareStorageBackend<VirtualMfaDevice> devices = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);
IamService service = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of());
account.set(ACCOUNT_B);
VirtualMfaDevice inB = service.createVirtualMfaDevice("same-name", "/", Map.of());
assertTrue(!inA.getBase32Seed().equals(inB.getBase32Seed()),
"a device in another account must not share the secret");
// Codes minted from account A's seed must not open account B's device.
long step = Totp.stepAt(Instant.now());
assertTrue(!VirtualMfaCodes.matchesConsecutiveCodes(inB.getBase32Seed(),
Totp.codeAt(inA.getBase32Seed(), step - 1),
Totp.codeAt(inA.getBase32Seed(), step), 1, Instant.now()));
}
}
@@ -0,0 +1,81 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.Totp;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* IAM's consecutive-pair rule. The underlying arithmetic is covered against RFC 6238's published
* vectors in {@code TotpTest}; what matters here is that two codes have to be successive outputs
* of the same seed, which is what AWS asks the caller of EnableMFADevice for.
*/
class VirtualMfaCodesTest {
/** RFC 6238's test secret, so the pairs below are reproducible. */
private static final String SEED = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
private static final Instant NOW = Instant.ofEpochSecond(1_700_000_000L);
private static boolean matchesPair(long firstOffset, int driftSteps) {
long step = Totp.stepAt(NOW);
return VirtualMfaCodes.matchesConsecutiveCodes(SEED,
Totp.codeAt(SEED, step + firstOffset),
Totp.codeAt(SEED, step + firstOffset + 1), driftSteps, NOW);
}
@Test
void acceptsTheCurrentPairOfConsecutiveCodes() {
assertTrue(matchesPair(-1, 1));
}
/** The same code in both fields is what a caller pasting one code twice would send. */
@Test
void rejectsTheSameCodeSubmittedTwice() {
String code = Totp.codeAt(SEED, Totp.stepAt(NOW));
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED, code, code, 1, NOW));
}
@Test
void rejectsTwoValidCodesThatAreNotConsecutive() {
long step = Totp.stepAt(NOW);
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED,
Totp.codeAt(SEED, step - 5), Totp.codeAt(SEED, step), 1, NOW));
}
/** A correctly ordered pair must not pass when reversed. */
@Test
void rejectsAConsecutivePairInTheWrongOrder() {
long step = Totp.stepAt(NOW);
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED,
Totp.codeAt(SEED, step), Totp.codeAt(SEED, step - 1), 1, NOW));
}
@Test
void rejectsCodesFromADifferentSeed() {
String otherSeed = Totp.newSecret();
long step = Totp.stepAt(NOW);
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED,
Totp.codeAt(otherSeed, step - 1), Totp.codeAt(otherSeed, step), 1, NOW));
}
@Test
void rejectsAnythingThatIsNotSixDigits() {
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED, null, "123456", 1, NOW));
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED, "123456", null, 1, NOW));
assertFalse(VirtualMfaCodes.matchesConsecutiveCodes(SEED, "12345", "123456", 1, NOW));
}
/**
* The drift window is what separates enabling a device from resyncing one, so its edges are
* worth pinning: a pair one step outside the allowance must fail at the width that excludes it
* and pass at the width that includes it.
*/
@Test
void driftWindowBoundsAreExact() {
assertFalse(matchesPair(-4, 2), "three steps behind is outside a two-step allowance");
assertTrue(matchesPair(-4, 3), "and inside a three-step one");
}
}
@@ -0,0 +1,249 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The MFA operations that read state and then write it (assigning a device, deleting the user it
* would be assigned to, spending the per-user quota) run over many trials, because each one is a
* check-then-act that only misbehaves when two requests interleave inside it.
*/
class VirtualMfaConcurrencyTest {
private static final int TRIALS = 150;
private static IamService newIamService() {
return new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("eu-central-1", "000000000000"), false, null);
}
private static String[] codesFor(String seed) {
long step = Totp.stepAt(Instant.now());
return new String[] {
Totp.codeAt(seed, step - 1),
Totp.codeAt(seed, step)
};
}
/**
* Runs the given actions at once and returns how many returned without an AwsException.
* The count matters as much as the stored state: two callers each told they won is a bug
* even when only one owner survives in the store.
*/
private static int raceTogether(Runnable... actions) throws InterruptedException {
AtomicInteger succeeded = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(actions.length);
ExecutorService pool = Executors.newFixedThreadPool(actions.length);
try {
for (Runnable action : actions) {
pool.submit(() -> {
try {
start.await();
action.run();
succeeded.incrementAndGet();
} catch (AwsException expected) {
// One side of a race is meant to lose; the assertions cover both halves.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
});
}
start.countDown();
assertTrue(done.await(10, TimeUnit.SECONDS), "actions did not finish");
} finally {
pool.shutdownNow();
}
return succeeded.get();
}
/**
* Deleting a user races enabling a device for that user. Either order is fine; what must never
* happen is both succeeding, which would leave a device assigned to a user that no longer
* exists, and one that could never be deactivated, since deactivation resolves the user first.
*/
@Test
void deletingAUserNeverRacesADeviceOntoIt() throws InterruptedException {
List<String> orphans = new CopyOnWriteArrayList<>();
for (int trial = 0; trial < TRIALS; trial++) {
IamService iam = newIamService();
iam.createUser("racer", "/");
VirtualMfaDevice device = iam.createVirtualMfaDevice("dev", "/", Map.of());
String[] codes = codesFor(device.getBase32Seed());
raceTogether(
() -> iam.deleteUser("racer"),
() -> iam.enableMfaDevice("racer", device.getSerialNumber(), codes[0], codes[1]));
boolean userGone = iam.findUser("racer").isEmpty();
boolean deviceAssigned = iam.getVirtualMfaDevice(device.getSerialNumber()).isAssigned();
if (userGone && deviceAssigned) {
orphans.add("trial " + trial);
}
}
assertTrue(orphans.isEmpty(), "device left assigned to a deleted user in: " + orphans);
}
/**
* Renaming a user races a delete of the name it is being renamed to. The rename publishes the
* user under the new name and moves its devices to match; if those are split across the MFA
* lock, a delete can land between them, see no devices, and remove a user that a device is
* about to be reassigned to. That device would then be unreachable: deactivating it resolves
* the user first, and deleting it is refused while it is assigned.
*/
@Test
void renamingAUserNeverRacesADeleteIntoStrandingItsDevice() throws InterruptedException {
List<String> stranded = new CopyOnWriteArrayList<>();
int reachedTheRace = 0;
for (int trial = 0; trial < TRIALS; trial++) {
IamService iam = newIamService();
iam.createUser("rename-from", "/");
VirtualMfaDevice device = iam.createVirtualMfaDevice("dev" + trial, "/", Map.of());
String[] codes = codesFor(device.getBase32Seed());
iam.enableMfaDevice("rename-from", device.getSerialNumber(), codes[0], codes[1]);
// Starting both at once never reaches the window: the delete runs before the rename has
// published anything and fails on a missing user. So the deleting side waits for the
// new name to appear and goes the instant it does, which is exactly where the two
// halves of the rename could be split.
//
// The wait is on a condition, not a spin budget: it ends when the user appears, or when
// the rename has finished and there is nothing left to race. A slow or loaded runner
// therefore makes this thread wait longer rather than give up, which a fixed budget
// would have turned into a scheduling-dependent failure of the assertion below.
AtomicReference<String> deleteOutcome = new AtomicReference<>("never-ran");
CountDownLatch renameFinished = new CountDownLatch(1);
raceTogether(
() -> {
try {
iam.updateUser("rename-from", "rename-to", null);
} finally {
renameFinished.countDown();
}
},
() -> {
while (iam.findUser("rename-to").isEmpty() && renameFinished.getCount() > 0) {
Thread.yield();
}
try {
iam.deleteUser("rename-to");
deleteOutcome.set("deleted");
} catch (AwsException e) {
deleteOutcome.set(e.getErrorCode());
}
});
// NoSuchEntity means the delete never saw the renamed user, so this trial got nowhere
// near the window. Counted rather than ignored: without it the trial would assert
// "nothing stranded" vacuously and the whole test could pass having raced nothing.
if (!"NoSuchEntity".equals(deleteOutcome.get())) {
reachedTheRace++;
}
VirtualMfaDevice after = iam.getVirtualMfaDevice(device.getSerialNumber());
if (after.isAssigned() && iam.findUser(after.getUserName()).isEmpty()) {
stranded.add("trial " + trial + " -> assigned to missing user " + after.getUserName()
+ " (delete=" + deleteOutcome.get() + ")");
}
}
assertTrue(stranded.isEmpty(), "device stranded on a deleted user in: " + stranded);
assertTrue(reachedTheRace > TRIALS / 2,
"only " + reachedTheRace + " of " + TRIALS + " trials reached the race, so this test "
+ "is no longer exercising it: the delete has to observe the renamed user");
}
/**
* Nine devices enabled at once against a user whose quota is eight. Checked and written under
* one lock, exactly eight can win; an unguarded check would let several read "seven" together
* and all write.
*/
@Test
void theDevicesPerUserQuotaHoldsUnderConcurrentEnables() throws InterruptedException {
for (int trial = 0; trial < 20; trial++) {
IamService iam = newIamService();
iam.createUser("quota-racer", "/");
Runnable[] enables = new Runnable[9];
for (int i = 0; i < enables.length; i++) {
VirtualMfaDevice device = iam.createVirtualMfaDevice("dev" + i, "/", Map.of());
String[] codes = codesFor(device.getBase32Seed());
enables[i] = () -> iam.enableMfaDevice("quota-racer", device.getSerialNumber(),
codes[0], codes[1]);
}
raceTogether(enables);
assertEquals(8, iam.listMfaDevices("quota-racer").size(),
"the per-user quota let more than eight devices through");
}
}
/**
* Two users reach for the same unassigned device at once. Only one call may return success:
* the loser has to get EntityAlreadyExists, because a caller told its EnableMFADevice
* succeeded will go on believing it holds that device.
*/
@Test
void onlyOneOfTwoUsersIsToldItClaimedTheDevice() throws InterruptedException {
for (int trial = 0; trial < TRIALS; trial++) {
IamService iam = newIamService();
iam.createUser("first", "/");
iam.createUser("second", "/");
VirtualMfaDevice device = iam.createVirtualMfaDevice("contended", "/", Map.of());
String[] codes = codesFor(device.getBase32Seed());
int won = raceTogether(
() -> iam.enableMfaDevice("first", device.getSerialNumber(), codes[0], codes[1]),
() -> iam.enableMfaDevice("second", device.getSerialNumber(), codes[0], codes[1]));
assertEquals(1, won, "both callers were told they claimed the same device");
assertEquals(1, iam.listMfaDevices("first").size() + iam.listMfaDevices("second").size());
}
}
/**
* Creating the same name twice at once must leave one device and tell the loser
* EntityAlreadyExists. Two successes would mean the second create silently replaced the
* first caller's device, invalidating a seed it had already been handed.
*/
@Test
void onlyOneOfTwoIdenticalCreatesSucceeds() throws InterruptedException {
for (int trial = 0; trial < TRIALS; trial++) {
IamService iam = newIamService();
int won = raceTogether(
() -> iam.createVirtualMfaDevice("same", "/", Map.of()),
() -> iam.createVirtualMfaDevice("same", "/", Map.of()));
assertEquals(1, won, "both creates succeeded, so one seed was silently replaced");
assertEquals(1, iam.listVirtualMfaDevices("Any").size());
}
}
}
@@ -0,0 +1,700 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.Totp;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The virtual MFA device lifecycle over the wire: create, enable against real TOTP codes,
* list, resync, deactivate, delete.
*
* <p>These drive the device the way a client does, reading {@code Base32StringSeed} from the
* create response and computing codes from it, so a test that enables a device proves the seed it
* handed is the one the service verifies against.
*
* <p>IAM state is shared across the suite, so every test names its own entities uniquely.
*/
@QuarkusTest
class VirtualMfaIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private static String createUser(String userName) {
iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200);
return userName;
}
/** Creates a device and returns its serial number and decoded base32 seed. */
private static Device createDevice(String deviceName) {
ExtractableResponse<Response> created = iam("CreateVirtualMFADevice")
.formParam("VirtualMFADeviceName", deviceName)
.when().post("/").then().statusCode(200).extract();
String base = "CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice.";
String encodedSeed = created.path(base + "Base32StringSeed");
String seed = new String(Base64.getDecoder().decode(encodedSeed.trim()), StandardCharsets.UTF_8);
return new Device(created.path(base + "SerialNumber"), seed);
}
private record Device(String serialNumber, String seed) {
/** The consecutive pair a real authenticator would show now, as the API asks for. */
String[] currentCodes() {
long step = Totp.stepAt(Instant.now());
return new String[] {
Totp.codeAt(seed, step - 1),
Totp.codeAt(seed, step)
};
}
}
private static void enable(String userName, Device device) {
String[] codes = device.currentCodes();
iam("EnableMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", codes[0])
.formParam("AuthenticationCode2", codes[1])
.when().post("/").then().statusCode(200);
}
@Test
void createReturnsAnArnSerialNumberAndAUsableSeed() {
String name = "mfa-create-" + suffix();
Device device = createDevice(name);
assertEquals("arn:aws:iam::000000000000:mfa/" + name, device.serialNumber());
// 160 bits of base32 is 32 characters, and it has to decode as base32 for an
// authenticator app to accept it.
assertEquals(32, device.seed().length());
assertEquals(20, Totp.base32Decode(device.seed()).length);
}
@Test
void creatingTheSameNameTwiceIsEntityAlreadyExists() {
String name = "mfa-dup-" + suffix();
createDevice(name);
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", name)
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));
}
@Test
void enablingWithCodesFromTheSeedAssignsTheDeviceToTheUser() {
String userName = createUser("mfa-enable-user-" + suffix());
Device device = createDevice("mfa-enable-" + suffix());
enable(userName, device);
iam("ListMFADevices").formParam("UserName", userName)
.when().post("/").then()
.statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber",
equalTo(device.serialNumber()))
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.UserName",
equalTo(userName))
.body("ListMFADevicesResponse.ListMFADevicesResult.IsTruncated", equalTo("false"));
}
/**
* The whole reason the seed is real: a caller that does not hold it cannot enable the device.
* A stub that accepted any six digits would pass every other test in this file.
*/
@Test
void enablingWithCodesThatDoNotComeFromTheSeedIsRejected() {
String userName = createUser("mfa-badcode-user-" + suffix());
Device device = createDevice("mfa-badcode-" + suffix());
iam("EnableMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", "000000")
.formParam("AuthenticationCode2", "111111")
.when().post("/").then()
.statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("InvalidAuthenticationCode"));
// And the failure left the device unassigned, rather than half-enabling it.
iam("ListMFADevices").formParam("UserName", userName)
.when().post("/").then()
.statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices", equalTo(""));
}
/** AWS asks for "a subsequent authentication code", so one code pasted twice is not a pair. */
@Test
void enablingWithTheSameCodeTwiceIsRejected() {
String userName = createUser("mfa-samecode-user-" + suffix());
Device device = createDevice("mfa-samecode-" + suffix());
String code = device.currentCodes()[1];
iam("EnableMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", code)
.formParam("AuthenticationCode2", code)
.when().post("/").then()
.statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("InvalidAuthenticationCode"));
}
/**
* {@code virtualMFADeviceName} is the one IAM name type with a minimum and a pattern but no
* maximum length, so a name past the 128 that other IAM names stop at must still be accepted.
*/
@Test
void aDeviceNameLongerThanOtherIamNamesAllowIsAccepted() {
String name = "mfa-long-" + "n".repeat(200) + suffix();
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", name)
.when().post("/").then()
.statusCode(200)
.body("CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult"
+ ".VirtualMFADevice.SerialNumber", equalTo("arn:aws:iam::000000000000:mfa/" + name));
}
@Test
void aDeviceNameOutsideTheModeledPatternIsAValidationError() {
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", "not a valid name")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
/**
* A serial number outside {@code serialNumberType}'s 9-to-256 range could never name a real
* device, so AWS rejects the request shape rather than reporting the device missing.
*/
@Test
void aMalformedSerialNumberIsAValidationErrorNotNoSuchEntity() {
iam("DeleteVirtualMFADevice").formParam("SerialNumber", "abc")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("ListMFADeviceTags").formParam("SerialNumber", "n".repeat(257))
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("DeleteVirtualMFADevice").formParam("SerialNumber", "has spaces in it")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
/** UserName is {@code Required: Yes} on EnableMFADevice and ResyncMFADevice. */
@Test
void omittingTheRequiredUserNameIsAValidationError() {
Device device = createDevice("mfa-nouser-" + suffix());
iam("EnableMFADevice")
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", "123456")
.formParam("AuthenticationCode2", "654321")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("ResyncMFADevice")
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", "123456")
.formParam("AuthenticationCode2", "654321")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
@Test
void authenticationCodesThatAreNotSixDigitsAreAValidationError() {
String userName = createUser("mfa-shortcode-user-" + suffix());
Device device = createDevice("mfa-shortcode-" + suffix());
iam("EnableMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", "12345")
.formParam("AuthenticationCode2", "123456")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
@Test
void enablingADeviceThatIsAlreadyAssignedIsEntityAlreadyExists() {
String firstUser = createUser("mfa-taken-a-" + suffix());
String secondUser = createUser("mfa-taken-b-" + suffix());
Device device = createDevice("mfa-taken-" + suffix());
enable(firstUser, device);
String[] codes = device.currentCodes();
iam("EnableMFADevice")
.formParam("UserName", secondUser)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", codes[0])
.formParam("AuthenticationCode2", codes[1])
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));
}
@Test
void assignmentStatusSelectsBetweenAssignedAndUnassignedDevices() {
String userName = createUser("mfa-status-user-" + suffix());
Device assigned = createDevice("mfa-status-on-" + suffix());
Device unassigned = createDevice("mfa-status-off-" + suffix());
enable(userName, assigned);
List<String> assignedSerials = listSerials("Assigned");
assertTrue(assignedSerials.contains(assigned.serialNumber()));
assertTrue(!assignedSerials.contains(unassigned.serialNumber()));
List<String> unassignedSerials = listSerials("Unassigned");
assertTrue(unassignedSerials.contains(unassigned.serialNumber()));
assertTrue(!unassignedSerials.contains(assigned.serialNumber()));
// Omitted AssignmentStatus defaults to Any, so both appear.
List<String> all = listSerials(null);
assertTrue(all.contains(assigned.serialNumber()));
assertTrue(all.contains(unassigned.serialNumber()));
}
private static List<String> listSerials(String assignmentStatus) {
RequestSpecification request = iam("ListVirtualMFADevices").formParam("MaxItems", "1000");
if (assignmentStatus != null) {
request = request.formParam("AssignmentStatus", assignmentStatus);
}
return request.when().post("/").then().statusCode(200)
.extract().xmlPath().getList("ListVirtualMFADevicesResponse.ListVirtualMFADevicesResult"
+ ".VirtualMFADevices.member.SerialNumber", String.class);
}
@Test
void anUnknownAssignmentStatusIsAValidationError() {
iam("ListVirtualMFADevices").formParam("AssignmentStatus", "Sometimes")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
/**
* The listing carries the assigned user but never the seed: it is the account-wide reader,
* so returning seeds there would hand out every device's shared secret at once.
*/
@Test
void listingCarriesTheUserButNeverTheSeed() {
String userName = createUser("mfa-noseed-user-" + suffix());
Device device = createDevice("mfa-noseed-" + suffix());
enable(userName, device);
String body = iam("ListVirtualMFADevices").formParam("MaxItems", "1000")
.when().post("/").then().statusCode(200).extract().asString();
assertTrue(body.contains(device.serialNumber()));
assertTrue(body.contains(userName), "the assigned user is part of the modeled shape");
assertTrue(!body.contains(device.seed()), "but the seed is not");
assertTrue(!body.contains("Base32StringSeed"));
}
@Test
void resyncAcceptsCodesFromTheSeedAndRejectsOthers() {
String userName = createUser("mfa-resync-user-" + suffix());
Device device = createDevice("mfa-resync-" + suffix());
enable(userName, device);
String[] codes = device.currentCodes();
iam("ResyncMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", codes[0])
.formParam("AuthenticationCode2", codes[1])
.when().post("/").then().statusCode(200);
iam("ResyncMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", "000000")
.formParam("AuthenticationCode2", "111111")
.when().post("/").then()
.statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("InvalidAuthenticationCode"));
}
/**
* Resync exists for a device whose clock has drifted, so it has to accept a pair the enable
* path would refuse, otherwise it could never fix the condition it is named for.
*/
@Test
void resyncAcceptsADriftedPairThatEnableWouldReject() {
String userName = createUser("mfa-drift-user-" + suffix());
Device device = createDevice("mfa-drift-" + suffix());
long step = Totp.stepAt(Instant.now());
String drifted1 = Totp.codeAt(device.seed(), step - 6);
String drifted2 = Totp.codeAt(device.seed(), step - 5);
iam("EnableMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", drifted1)
.formParam("AuthenticationCode2", drifted2)
.when().post("/").then()
.statusCode(403)
.body("ErrorResponse.Error.Code", equalTo("InvalidAuthenticationCode"));
enable(userName, device);
iam("ResyncMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.formParam("AuthenticationCode1", drifted1)
.formParam("AuthenticationCode2", drifted2)
.when().post("/").then().statusCode(200);
}
@Test
void deactivateDetachesTheDeviceButKeepsIt() {
String userName = createUser("mfa-deact-user-" + suffix());
Device device = createDevice("mfa-deact-" + suffix());
enable(userName, device);
iam("DeactivateMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200);
iam("ListMFADevices").formParam("UserName", userName)
.when().post("/").then()
.statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices", equalTo(""));
// The device itself survives, unassigned: AWS removes the association, not the device.
assertTrue(listSerials("Unassigned").contains(device.serialNumber()));
}
/** The same seed still works afterwards, so re-enabling does not require re-provisioning. */
@Test
void aDeactivatedDeviceCanBeEnabledAgainWithTheSameSeed() {
String userName = createUser("mfa-reenable-user-" + suffix());
Device device = createDevice("mfa-reenable-" + suffix());
enable(userName, device);
iam("DeactivateMFADevice").formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200);
enable(userName, device);
iam("ListMFADevices").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber",
equalTo(device.serialNumber()));
}
@Test
void deactivatingADeviceAssignedToSomeoneElseIsNoSuchEntity() {
String owner = createUser("mfa-wrong-owner-" + suffix());
String other = createUser("mfa-wrong-other-" + suffix());
Device device = createDevice("mfa-wrong-" + suffix());
enable(owner, device);
iam("DeactivateMFADevice")
.formParam("UserName", other)
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
void deletingAnAssignedDeviceIsDeleteConflict() {
String userName = createUser("mfa-delconflict-user-" + suffix());
Device device = createDevice("mfa-delconflict-" + suffix());
enable(userName, device);
iam("DeleteVirtualMFADevice").formParam("SerialNumber", device.serialNumber())
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("DeleteConflict"));
}
@Test
void deleteRemovesAnUnassignedDevice() {
Device device = createDevice("mfa-delete-" + suffix());
iam("DeleteVirtualMFADevice").formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200);
assertTrue(!listSerials(null).contains(device.serialNumber()));
iam("DeleteVirtualMFADevice").formParam("SerialNumber", device.serialNumber())
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
/** DeleteUser's prerequisite chain: AWS refuses while the user still holds a device. */
@Test
void aUserWithAnEnabledDeviceCannotBeDeleted() {
String userName = createUser("mfa-userdel-" + suffix());
Device device = createDevice("mfa-userdel-dev-" + suffix());
enable(userName, device);
iam("DeleteUser").formParam("UserName", userName)
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("DeleteConflict"));
iam("DeactivateMFADevice").formParam("UserName", userName)
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200);
iam("DeleteUser").formParam("UserName", userName)
.when().post("/").then().statusCode(200);
}
/**
* A device records its holder by name, so a rename has to carry the assignment. If it does
* not, DeleteUser sees no device under the new name and lets the user go, stranding a device
* that can then never be deactivated (that resolves the user first) nor deleted (deletion
* refuses while it is assigned).
*/
@Test
void renamingAUserCarriesItsMfaDeviceAssignment() {
String original = createUser("mfa-rename-" + suffix());
String renamed = "mfa-renamed-" + suffix();
Device device = createDevice("mfa-rename-dev-" + suffix());
enable(original, device);
iam("UpdateUser").formParam("UserName", original).formParam("NewUserName", renamed)
.when().post("/").then().statusCode(200);
iam("ListMFADevices").formParam("UserName", renamed)
.when().post("/").then()
.statusCode(200)
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber",
equalTo(device.serialNumber()))
.body("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.UserName",
equalTo(renamed));
// The user is still held by the device, so deleting them is still refused.
iam("DeleteUser").formParam("UserName", renamed)
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("DeleteConflict"));
// And the device is reachable under the new name, so it can still be freed.
iam("DeactivateMFADevice").formParam("UserName", renamed)
.formParam("SerialNumber", device.serialNumber())
.when().post("/").then().statusCode(200);
iam("DeleteUser").formParam("UserName", renamed).when().post("/").then().statusCode(200);
}
/**
* {@code virtualMFADeviceName} has no maximum length but the serial number it mints is capped
* at 256, so a long-but-valid name could otherwise produce a device that every other operation
* rejects. Creation refuses it rather than handing back an unusable serial.
*/
@Test
void aNameThatWouldMintAnUnusableSerialNumberIsRejected() {
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", "n".repeat(250))
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
// A name just inside the limit still works, so the check is not simply capping at 128.
String name = "m".repeat(200) + suffix();
String serial = iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", name)
.when().post("/").then().statusCode(200)
.extract().path("CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult"
+ ".VirtualMFADevice.SerialNumber");
assertTrue(serial.length() <= 256);
// And the serial it handed back is one the other operations accept.
iam("DeleteVirtualMFADevice").formParam("SerialNumber", serial)
.when().post("/").then().statusCode(200);
}
/** AWS models Marker and MaxItems on ListMFADeviceTags, so a one-item page must paginate. */
@Test
void listMfaDeviceTagsPaginates() {
Device device = createDevice("mfa-tagpage-" + suffix());
iam("TagMFADevice").formParam("SerialNumber", device.serialNumber())
.formParam("Tags.member.1.Key", "aaa").formParam("Tags.member.1.Value", "1")
.formParam("Tags.member.2.Key", "bbb").formParam("Tags.member.2.Value", "2")
.when().post("/").then().statusCode(200);
ExtractableResponse<Response> first = iam("ListMFADeviceTags")
.formParam("SerialNumber", device.serialNumber()).formParam("MaxItems", "1")
.when().post("/").then().statusCode(200)
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.IsTruncated", equalTo("true"))
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member.Key", equalTo("aaa"))
.extract();
String marker = first.path("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Marker");
assertNotNull(marker, "a truncated tag page carries a Marker");
iam("ListMFADeviceTags").formParam("SerialNumber", device.serialNumber())
.formParam("MaxItems", "1").formParam("Marker", marker)
.when().post("/").then()
.statusCode(200)
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member.Key", equalTo("bbb"))
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.IsTruncated", equalTo("false"));
}
@Test
void tagsRoundTripAndAreListedSortedByKey() {
Device device = createDevice("mfa-tags-" + suffix());
iam("TagMFADevice").formParam("SerialNumber", device.serialNumber())
.formParam("Tags.member.1.Key", "zone").formParam("Tags.member.1.Value", "b")
.formParam("Tags.member.2.Key", "env").formParam("Tags.member.2.Value", "test")
.when().post("/").then().statusCode(200);
iam("ListMFADeviceTags").formParam("SerialNumber", device.serialNumber())
.when().post("/").then()
.statusCode(200)
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member[0].Key", equalTo("env"))
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member[1].Key", equalTo("zone"));
iam("UntagMFADevice").formParam("SerialNumber", device.serialNumber())
.formParam("TagKeys.member.1", "zone")
.when().post("/").then().statusCode(200);
iam("ListMFADeviceTags").formParam("SerialNumber", device.serialNumber())
.when().post("/").then()
.statusCode(200)
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member.Key", equalTo("env"));
}
@Test
void tagsGivenAtCreationAreKept() {
String name = "mfa-createtag-" + suffix();
iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", name)
.formParam("Tags.member.1.Key", "owner").formParam("Tags.member.1.Value", "platform")
.when().post("/").then().statusCode(200);
iam("ListMFADeviceTags").formParam("SerialNumber", "arn:aws:iam::000000000000:mfa/" + name)
.when().post("/").then()
.statusCode(200)
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member.Key", equalTo("owner"))
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.Tags.member.Value", equalTo("platform"));
}
@Test
void operationsAgainstAnUnknownSerialNumberAreNoSuchEntity() {
String missing = "arn:aws:iam::000000000000:mfa/mfa-missing-" + suffix();
String userName = createUser("mfa-missing-user-" + suffix());
iam("EnableMFADevice").formParam("UserName", userName).formParam("SerialNumber", missing)
.formParam("AuthenticationCode1", "123456").formParam("AuthenticationCode2", "654321")
.when().post("/").then().statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
iam("ListMFADeviceTags").formParam("SerialNumber", missing)
.when().post("/").then().statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
void theAccountSummaryCountsDevicesAndTheirAssignments() {
String userName = createUser("mfa-summary-user-" + suffix());
long before = summaryValue("MFADevices");
long inUseBefore = summaryValue("MFADevicesInUse");
Device assigned = createDevice("mfa-summary-on-" + suffix());
createDevice("mfa-summary-off-" + suffix());
enable(userName, assigned);
assertEquals(before + 2, summaryValue("MFADevices"));
assertEquals(inUseBefore + 1, summaryValue("MFADevicesInUse"));
}
private static long summaryValue(String key) {
String value = iam("GetAccountSummary").when().post("/").then().statusCode(200)
.extract().path("GetAccountSummaryResponse.GetAccountSummaryResult.SummaryMap.entry"
+ ".find { it.key == '" + key + "' }.value");
assertNotNull(value, key + " missing from the summary map");
return Long.parseLong(value);
}
@Test
void listVirtualMfaDevicesPaginatesWithMaxItemsAndMarker() {
String prefix = "mfa-page-" + suffix();
createDevice(prefix + "-a");
createDevice(prefix + "-b");
ExtractableResponse<Response> firstPage = iam("ListVirtualMFADevices").formParam("MaxItems", "1")
.when().post("/").then().statusCode(200)
.body("ListVirtualMFADevicesResponse.ListVirtualMFADevicesResult.IsTruncated", equalTo("true"))
.extract();
String marker = firstPage.path("ListVirtualMFADevicesResponse."
+ "ListVirtualMFADevicesResult.Marker");
String firstSerial = firstPage.path("ListVirtualMFADevicesResponse."
+ "ListVirtualMFADevicesResult.VirtualMFADevices.member.SerialNumber");
assertNotNull(marker, "a truncated page carries a Marker");
String secondSerial = iam("ListVirtualMFADevices").formParam("MaxItems", "1")
.formParam("Marker", marker)
.when().post("/").then().statusCode(200)
.extract().path("ListVirtualMFADevicesResponse."
+ "ListVirtualMFADevicesResult.VirtualMFADevices.member.SerialNumber");
assertTrue(!firstSerial.equals(secondSerial), "the marker advanced past the first device");
}
@Test
void maxItemsOutsideTheModeledRangeIsAValidationError() {
iam("ListVirtualMFADevices").formParam("MaxItems", "0")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("ListVirtualMFADevices").formParam("MaxItems", "1001")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
@Test
void enablingMoreThanTheDevicesPerUserQuotaIsLimitExceeded() {
String userName = createUser("mfa-quota-user-" + suffix());
for (int i = 0; i < 8; i++) {
enable(userName, createDevice("mfa-quota-" + i + "-" + suffix()));
}
Device ninth = createDevice("mfa-quota-9-" + suffix());
String[] codes = ninth.currentCodes();
iam("EnableMFADevice")
.formParam("UserName", userName)
.formParam("SerialNumber", ninth.serialNumber())
.formParam("AuthenticationCode1", codes[0])
.formParam("AuthenticationCode2", codes[1])
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("LimitExceeded"));
}
}