Light, fluffy, and always free - The AWS Local Emulator alternative
feat(iam): model virtual MFA devices with real TOTP verification (#4820)
Priamo Germosenc7bb03ace3b8
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 1b50bba920..07994e7e1b 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -304,9 +304,10 @@ also checked against that policy's length and character-class requirements, withechoed back by any of these actions, matching AWS.`DeleteUser` returns `DeleteConflict`, as on AWS, while the user still has a login profile, access-keys, inline policies, attached managed policies, or group memberships: remove those first. Floci-has no actions that create signing certificates, SSH public keys, Git credentials, or MFA devices,-so there is nothing of those kinds to block on. Renaming a user with `UpdateUser` carries its login+keys, inline policies, attached managed policies, group memberships, or an+[enabled MFA device](#multi-factor-authentication): remove those first. Floci has no actions that+create signing certificates, SSH public keys, or Git credentials, so there is nothing of those+kinds to block on. Renaming a user with `UpdateUser` carries its loginprofile, access keys, and group membership to the new name. Unlike AWS, Floci does not rewritepolicy documents that name the user's ARN, so a resource or trust policy that referred to the oldname still refers to it after a rename.@@ -416,11 +417,89 @@ resource-based policies, ACLs, Organizations policies and trust policies are notResources and conditions are not evaluated either: the question is which policies could grant theservice at all, not whether one specific call would be authorized.+### Multi-Factor Authentication++| Action | Description |+|--------|-------------|+| CreateVirtualMFADevice | Creates an unassigned virtual MFA device and returns its `SerialNumber` and `Base32StringSeed`. |+| ListVirtualMFADevices | Lists the account's virtual MFA devices, filtered by `AssignmentStatus` (`Assigned`, `Unassigned` or `Any`, defaulting to `Any`). |+| DeleteVirtualMFADevice | Deletes a device. Returns `DeleteConflict` while it is still assigned to a user. |+| EnableMFADevice | Assigns a device to a user, after verifying two consecutive authentication codes. |+| DeactivateMFADevice | Detaches a device from its user, leaving the device itself in place. |+| ResyncMFADevice | Re-synchronizes an assigned device, again against two consecutive codes. |+| ListMFADevices | Lists the devices assigned to a user. |+| TagMFADevice / UntagMFADevice / ListMFADeviceTags | Manage a device's tags. |++The seed is real. `CreateVirtualMFADevice` generates a 160-bit secret from `SecureRandom` and+returns it as an RFC 4648 base32 string (base64-wrapped on the wire, as AWS models the member), so+an authenticator app seeded from it produces codes Floci accepts. `EnableMFADevice` and+`ResyncMFADevice` verify those codes as RFC 6238 TOTP (HMAC-SHA1 over 30-second steps, truncated+to six digits) and return `InvalidAuthenticationCode` when they don't match, so a caller that does+not hold the seed cannot enable a device. The two codes must be consecutive, as AWS asks ("a+subsequent authentication code"), so the same code sent twice is rejected. `EnableMFADevice`+allows one 30-second step of drift either side; `ResyncMFADevice` allows ten, since a device+needing resync is by definition one whose clock has wandered.++`SerialNumber` is the device ARN, `arn:aws:iam::<account>:mfa/<name>`, so `Path` and+`VirtualMFADeviceName` together identify a device. A device survives `DeactivateMFADevice` with its+seed intact, so re-enabling it needs no re-provisioning. `DeleteUser` returns `DeleteConflict` while+the user still holds a device, and a user with one reports `mfa_active` as `TRUE` in the credential+report. Renaming a user with `UpdateUser` carries the assignment to the new name, alongside the+login profile and access keys it already moved.++A user may hold up to 8 devices, the per-user limit the IAM User Guide documents, after which+`EnableMFADevice` returns `LimitExceeded`. That is the only MFA quota Floci enforces:+`CreateVirtualMFADevice` models `LimitExceeded` too, but AWS publishes no account-wide figure for+virtual MFA devices, so there is nothing to enforce it against.++Request shapes are checked before the device is resolved, so a `SerialNumber` outside its modeled+9-to-256 range is a `ValidationError` rather than a `NoSuchEntity` for a device that could not have+existed. Note that `VirtualMFADeviceName` is the one IAM name type with no documented maximum+length: a name longer than the 128 characters other IAM names stop at is accepted here, as on AWS.+`ListMFADeviceTags` honors `Marker` and `MaxItems`, sorting by tag key first as AWS documents, so a+client can walk the result a page at a time. IAM's other tag readers in Floci still return every+tag with `IsTruncated=false`.++`VirtualMFADeviceName` has no maximum length, but the serial number it mints does: 256 characters.+A name long enough to overflow that is rejected at creation rather than producing a device whose+serial every other MFA operation would refuse.++`QRCodePNG` is not returned. AWS marks it optional, and rendering a PNG would mean taking on a QR+encoder dependency for a field whose content is derivable: it encodes+`otpauth://totp/<device>@<account>?secret=<Base32String>`, which a caller can build from the+`Base32StringSeed` that *is* returned. `aws iam create-virtual-mfa-device` works against Floci with+`--bootstrap-method Base32StringSeed`, and fails only when asked for the QR code specifically.++`GetMFADevice` is not implemented: AWS states "for this API, we only accept FIDO security key+ARNs", and Floci models virtual devices only. Hardware TOTP tokens and FIDO security keys are not+modeled either, so `ListMFADevices` returns only virtual devices where AWS would return every type.++#### What a device does not yet affect++Enabling a device records state and nothing more. It does not change what a request is allowed to+do:++- **Policy evaluation ignores MFA.** `aws:MultiFactorAuthPresent` and `aws:MultiFactorAuthAge` are+ never placed in the request context, so under [enforcement](#iam-enforcement-mode) a statement+ conditioned on either key does not behave as it would on AWS. Both directions fail closed rather+ than open: an `Allow` gated on `Bool: {"aws:MultiFactorAuthPresent": "true"}` never grants,+ because a missing key fails the condition block; and the common+ `Deny` + `BoolIfExists: {"aws:MultiFactorAuthPresent": "false"}` lockout idiom always denies,+ because `IfExists` passes on a missing key. So an MFA-gated policy is stricter than AWS here, not+ laxer, but a device being enabled will not unlock it.+- **No MFA-authenticated credentials.** `GetSessionToken` and `AssumeRole` accept `SerialNumber`+ and `TokenCode` on AWS and return credentials that carry the MFA context keys. Floci's+ [STS](sts.md) implementations ignore both parameters, so there is no way to obtain a session that+ would satisfy an MFA condition even once the keys are populated.++Both are out of scope here: this covers the device lifecycle only, and wiring MFA into+authorization means touching the request context and STS session shape, which is separate work.+### Account| Action | Description ||--------|-------------|-| GetAccountSummary | Returns entity counts (users, groups, roles, customer-managed policies, instance profiles) and IAM quota values. `Providers` counts OIDC providers only; SAML providers are not included. Resources Floci does not track (MFA devices, server certificates) are reported as zero rather than omitted. |+| GetAccountSummary | Returns entity counts (users, groups, roles, customer-managed policies, instance profiles, MFA devices) and IAM quota values. `Providers` counts OIDC providers only; SAML providers are not included. Resources Floci does not track (server certificates) are reported as zero rather than omitted. || GetAccountAuthorizationDetails | Returns every user, group and role in the account, and the policies relevant to them: every local (customer-managed) policy, and every AWS-managed policy actually attached to or used as a permissions boundary by something in the account. || GenerateCredentialReport | Generates (or, within 4 hours of the last one, reuses) the account's credential report. || GetCredentialReport | Returns the most recently generated credential report as Base64-encoded CSV. |@@ -437,10 +516,11 @@ URL-encode either.The credential report holds the 23 columns AWS documents, always led by a `<root_account>` row.Floci does not model root account credentials at all (`GetAccountSummary`'s`AccountPasswordPresent`/`AccountAccessKeysPresent` are always zero for the same reason), so that-row is placeholder values throughout. MFA devices and X.509 signing certificates are not modeled-for IAM users either, so `mfa_active` and every `cert_*` column are always `FALSE`/`N/A`; access-key last-used tracking (date, region, service) is not modeled, so those three columns are always-`N/A` too. `password_last_used` is likewise not tracked, so it is always `no_information`.+row is placeholder values throughout, including its `mfa_active`, which reports on root rather+than on any IAM user's device. X.509 signing certificates are not modeled, so every `cert_*` column+is always `FALSE`/`N/A`; access key last-used tracking (date, region, service) is not modeled, so+those three columns are always `N/A` too. `mfa_active` on a user row is real, and is `TRUE` once+the user has a device enabled. `password_last_used` is likewise not tracked, so it is always `no_information`.`password_last_changed` reflects an `UpdateLoginProfile` password change, not just`CreateLoginProfile`. `additional_credentials_info` is Floci's own wording, since AWS does notdocument the exact text; in practice it is unreachable, since `CreateAccessKey` already enforces@@ -468,10 +548,9 @@ returns and nothing else.| Action | Description ||--------|-------------|-| ListMFADevices | Always returns an empty list. It does not check that the user exists, where AWS returns `NoSuchEntity` for an unknown user. || ListServerCertificates | Always returns an empty list. |-MFA devices and server certificates are not stored, and no action creates them.+Server certificates are not stored, and no action creates them.## AWS Managed Policiesdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/Totp.java b/src/main/java/io/github/hectorvent/floci/core/common/Totp.javaindex 60a1a9279d..77974fd709 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/Totp.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/Totp.java@@ -16,8 +16,8 @@ import javax.crypto.spec.SecretKeySpec;** <p>Lifted out of {@code CognitoTotp}, which is now a thin view over it, because the same* arithmetic is needed wherever a service hands a secret to an authenticator app and then verifies- * what the app produces. Cognito's software-token MFA is the only caller today; IAM's virtual MFA- * devices are the reason it lives here rather than inside Cognito.+ * what the app produces: Cognito's software-token MFA, and IAM's virtual MFA devices through+ * {@code VirtualMfaCodes}.** <p>The secret is real randomness and the codes are really derived from it, so a caller that does* not hold the secret cannot produce an accepted code. Secrets cross the wire as RFC 4648 base32,@@ -93,7 +93,7 @@ public final class Totp {}/** Whether the value has the shape of a code at all, before any secret is touched. */- static boolean isSixDigits(String code) {+ public static boolean isSixDigits(String code) {if (code == null || code.length() != DIGITS) {return false;}@@ -106,7 +106,7 @@ public final class Totp {}/** Length-independent comparison, so a wrong code does not leak its prefix through timing. */- static boolean codeEquals(String expected, String actual) {+ public static boolean codeEquals(String expected, String actual) {return MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII),actual.getBytes(StandardCharsets.US_ASCII));}@@ -131,7 +131,7 @@ public final class Totp {return encoded.toString();}- static byte[] base32Decode(String encoded) {+ public static byte[] base32Decode(String encoded) {int buffer = 0;int bitsLeft = 0;byte[] decoded = new byte[encoded.length() * 5 / 8];diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.javaindex fcdd4e6d55..844577d714 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java@@ -16,15 +16,18 @@ import io.github.hectorvent.floci.services.iam.model.PolicyVersion;import io.github.hectorvent.floci.services.iam.model.SAMLProvider;import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;+import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import jakarta.ws.rs.core.MultivaluedMap;import jakarta.ws.rs.core.Response;import org.jboss.logging.Logger;+import java.nio.charset.StandardCharsets;import java.time.Instant;import java.time.format.DateTimeFormatter;import java.util.ArrayList;+import java.util.Base64;import java.util.HashMap;import java.util.HashSet;import java.util.LinkedHashMap;@@ -90,12 +93,23 @@ public class IamQueryHandler {case "TagUser" -> handleTagUser(params);case "UntagUser" -> handleUntagUser(params);case "ListUserTags" -> handleListUserTags(params);- case "ListMFADevices" -> handleListMFADevices(params);case "CreateLoginProfile" -> handleCreateLoginProfile(params, authorization);case "GetLoginProfile" -> handleGetLoginProfile(params, authorization);case "UpdateLoginProfile" -> handleUpdateLoginProfile(params);case "DeleteLoginProfile" -> handleDeleteLoginProfile(params, authorization);+ // Multi-factor authentication+ case "CreateVirtualMFADevice" -> handleCreateVirtualMFADevice(params);+ case "ListVirtualMFADevices" -> handleListVirtualMFADevices(params);+ case "DeleteVirtualMFADevice" -> handleDeleteVirtualMFADevice(params);+ case "EnableMFADevice" -> handleEnableMFADevice(params);+ case "DeactivateMFADevice" -> handleDeactivateMFADevice(params, authorization);+ case "ResyncMFADevice" -> handleResyncMFADevice(params);+ case "ListMFADevices" -> handleListMFADevices(params, authorization);+ case "TagMFADevice" -> handleTagMFADevice(params);+ case "UntagMFADevice" -> handleUntagMFADevice(params);+ case "ListMFADeviceTags" -> handleListMFADeviceTags(params);+// Identity providers & server certificatescase "ListSAMLProviders" -> handleListSAMLProviders(authorization);case "CreateSAMLProvider" -> handleCreateSAMLProvider(params, authorization);@@ -342,15 +356,129 @@ public class IamQueryHandler {return Response.ok(AwsQueryResponse.envelope("ListUserTags", AwsNamespaces.IAM, result)).build();}- private Response handleListMFADevices(MultivaluedMap<String, String> params) {- // MFA device state is not modeled; return the wire-accurate empty result- // (MFADevices list + IsTruncated=false). Real AWS returns NoSuchEntity- // (HTTP 404) for an unknown user — Floci returns an empty list regardless.+ /**+ * {@code Base32StringSeed} and {@code QRCodePNG} are both typed as base64-encoded binary, so+ * the base32 seed string goes out base64-wrapped. The QR code is not returned: encoding a PNG+ * would mean a new dependency for an optional field, and the {@code otpauth://} URI it encodes+ * is derivable from the seed that is returned. {@code aws iam create-virtual-mfa-device} works+ * against this with {@code --bootstrap-method Base32StringSeed}, and fails only when asked for+ * the QR code specifically.+ */+ private Response handleCreateVirtualMFADevice(MultivaluedMap<String, String> params) {+ VirtualMfaDevice device = iamService.createVirtualMfaDevice(+ getParam(params, "VirtualMFADeviceName"), getParam(params, "Path"),+ extractTags(params, false));String result = new XmlBuilder()- .start("MFADevices").end("MFADevices")- .elem("IsTruncated", false)+ .start("VirtualMFADevice")+ .elem("SerialNumber", device.getSerialNumber())+ .elem("Base32StringSeed", base64(device.getBase32Seed()))+ .raw(tagsElement(new TreeMap<>(device.getTags())))+ .end("VirtualMFADevice").build();- return Response.ok(AwsQueryResponse.envelope("ListMFADevices", AwsNamespaces.IAM, result)).build();+ return Response.ok(AwsQueryResponse.envelope("CreateVirtualMFADevice", AwsNamespaces.IAM, result)).build();+ }++ /**+ * Neither the seed nor the tags appear here: AWS notes that "IAM resource-listing operations+ * return a subset of the available attributes for the resource... this operation does not+ * return tags", and handing the seed back on an unauthenticated-by-device list call would+ * leak the shared secret of every device in the account.+ */+ private Response handleListVirtualMFADevices(MultivaluedMap<String, String> params) {+ Page<VirtualMfaDevice> page = paginate(+ iamService.listVirtualMfaDevices(getParam(params, "AssignmentStatus")), params);+ XmlBuilder xml = new XmlBuilder().start("VirtualMFADevices");+ for (VirtualMfaDevice device : page.items()) {+ xml.start("member").elem("SerialNumber", device.getSerialNumber());+ if (device.isAssigned()) {+ xml.elem("EnableDate", isoDate(device.getEnableDate()));+ // Looked up rather than required: DeleteUser will not let a user go while a device+ // is still assigned, so a device pointing at a missing user means the two stores+ // have drifted on disk. User is an optional member, so this one device loses it+ // instead of the whole account-wide listing failing.+ iamService.findUser(device.getUserName())+ .ifPresent(user -> xml.start("User").raw(userXml(user, false)).end("User"));+ }+ xml.end("member");+ }+ xml.end("VirtualMFADevices").elem("IsTruncated", page.truncated());+ if (page.marker() != null) {+ xml.elem("Marker", page.marker());+ }+ return Response.ok(AwsQueryResponse.envelope("ListVirtualMFADevices", AwsNamespaces.IAM, xml.build())).build();+ }++ private Response handleDeleteVirtualMFADevice(MultivaluedMap<String, String> params) {+ iamService.deleteVirtualMfaDevice(getParam(params, "SerialNumber"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteVirtualMFADevice", AwsNamespaces.IAM)).build();+ }++ private Response handleEnableMFADevice(MultivaluedMap<String, String> params) {+ iamService.enableMfaDevice(getParam(params, "UserName"), getParam(params, "SerialNumber"),+ getParam(params, "AuthenticationCode1"), getParam(params, "AuthenticationCode2"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("EnableMFADevice", AwsNamespaces.IAM)).build();+ }++ private Response handleDeactivateMFADevice(MultivaluedMap<String, String> params, String authorization) {+ // UserName is optional here, unlike on Enable/Resync: "If no user name is included, it+ // defaults to the principal making the request."+ iamService.deactivateMfaDevice(resolveUserName(params, authorization),+ getParam(params, "SerialNumber"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("DeactivateMFADevice", AwsNamespaces.IAM)).build();+ }++ private Response handleResyncMFADevice(MultivaluedMap<String, String> params) {+ iamService.resyncMfaDevice(getParam(params, "UserName"), getParam(params, "SerialNumber"),+ getParam(params, "AuthenticationCode1"), getParam(params, "AuthenticationCode2"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("ResyncMFADevice", AwsNamespaces.IAM)).build();+ }++ private Response handleListMFADevices(MultivaluedMap<String, String> params, String authorization) {+ String userName = resolveUserName(params, authorization);+ Page<VirtualMfaDevice> page = paginate(iamService.listMfaDevices(userName), params);+ XmlBuilder xml = new XmlBuilder().start("MFADevices");+ for (VirtualMfaDevice device : page.items()) {+ xml.start("member")+ .elem("UserName", device.getUserName())+ .elem("SerialNumber", device.getSerialNumber())+ .elem("EnableDate", isoDate(device.getEnableDate()))+ .end("member");+ }+ xml.end("MFADevices").elem("IsTruncated", page.truncated());+ if (page.marker() != null) {+ xml.elem("Marker", page.marker());+ }+ return Response.ok(AwsQueryResponse.envelope("ListMFADevices", AwsNamespaces.IAM, xml.build())).build();+ }++ private Response handleTagMFADevice(MultivaluedMap<String, String> params) {+ iamService.tagMfaDevice(getParam(params, "SerialNumber"), extractTags(params, false));+ return Response.ok(AwsQueryResponse.envelopeNoResult("TagMFADevice", AwsNamespaces.IAM)).build();+ }++ private Response handleUntagMFADevice(MultivaluedMap<String, String> params) {+ iamService.untagMfaDevice(getParam(params, "SerialNumber"), extractTagKeys(params));+ return Response.ok(AwsQueryResponse.envelopeNoResult("UntagMFADevice", AwsNamespaces.IAM)).build();+ }++ /**+ * Unlike IAM's other tag readers here, this one honours {@code Marker} and {@code MaxItems}:+ * AWS models both on ListMFADeviceTags, and a client asking for a one-item page should be able+ * to walk the result. Tags are sorted by key first, as AWS documents ("the returned list of+ * tags is sorted by tag key"), so the marker names a stable position.+ */+ private Response handleListMFADeviceTags(MultivaluedMap<String, String> params) {+ Map<String, String> tags = new TreeMap<>(iamService.listMfaDeviceTags(getParam(params, "SerialNumber")));+ Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), params);+ XmlBuilder xml = new XmlBuilder().start("Tags");+ for (Map.Entry<String, String> tag : page.items()) {+ xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");+ }+ xml.end("Tags").elem("IsTruncated", page.truncated());+ if (page.marker() != null) {+ xml.elem("Marker", page.marker());+ }+ return Response.ok(AwsQueryResponse.envelope("ListMFADeviceTags", AwsNamespaces.IAM, xml.build())).build();}private Response handleCreateLoginProfile(MultivaluedMap<String, String> params, String authorization) {@@ -2362,6 +2490,11 @@ public class IamQueryHandler {return DateTimeFormatter.ISO_INSTANT.format(instant);}+ /** For a member AWS types as a blob, which the Query protocol carries base64-encoded. */+ private String base64(String value) {+ return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));+ }+private Response handleTagInstanceProfile(MultivaluedMap<String, String> params) {iamService.tagInstanceProfile(getParam(params, "InstanceProfileName"), extractTags(params, false));return Response.ok(AwsQueryResponse.envelopeNoResult("TagInstanceProfile", AwsNamespaces.IAM)).build();diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex e4f89ecac0..da97d92f55 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsPartitions;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.core.common.SessionAccountLookup;+import io.github.hectorvent.floci.core.common.Totp;import io.github.hectorvent.floci.core.resource.ExplorerResource;import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;@@ -28,6 +29,7 @@ import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;import io.github.hectorvent.floci.services.iam.model.PolicyVersion;import io.github.hectorvent.floci.services.iam.model.CallerContext;import io.github.hectorvent.floci.services.iam.model.SessionCredential;+import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;import com.fasterxml.jackson.core.type.TypeReference;import io.quarkus.runtime.Startup;import jakarta.annotation.PostConstruct;@@ -42,6 +44,7 @@ import java.time.Duration;import java.time.Instant;import java.time.format.DateTimeFormatter;import java.util.Base64;+import java.util.Comparator;import java.util.Optional;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;@@ -130,6 +133,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider {private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");private static final int IAM_PATH_MAX_LENGTH = 512;private static final int MAX_TAGS_PER_RESOURCE = 50;+ /**+ * "You can register up to eight MFA devices of any combination of the currently supported MFA+ * types" (IAM User Guide). Floci models only virtual devices, so this bounds those alone.+ */+ private static final int MAX_MFA_DEVICES_PER_USER = 8;+ /** {@code AuthenticationCode1}/{@code 2}: fixed length of 6, pattern {@code [\d]+}. */+ private static final Pattern AUTHENTICATION_CODE_PATTERN = Pattern.compile("[0-9]{6}");+ /**+ * {@code virtualMFADeviceName}: a minimum of 1 and this pattern, with no maximum length. IAM's+ * other name types are all capped at 64 or 128; this one is deliberately not.+ */+ private static final Pattern VIRTUAL_MFA_DEVICE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]+");+ /** {@code serialNumberType}: 9-256 characters, and a wider pattern than a name, allowing ARNs. */+ private static final Pattern SERIAL_NUMBER_PATTERN = Pattern.compile("[\\w+=/:,.@-]+");+ private static final int SERIAL_NUMBER_MIN_LENGTH = 9;+ private static final int SERIAL_NUMBER_MAX_LENGTH = 256;+ /**+ * How far the code pair may sit from the current 30-second window. Enabling a device is done+ * straight after reading the codes, so a window either side absorbs clock skew and the time+ * spent submitting; resync exists for a device that has drifted much further, and is given+ * five minutes in each direction.+ */+ private static final int ENABLE_DRIFT_STEPS = 1;+ private static final int RESYNC_DRIFT_STEPS = 10;private static final String ROOT_FEATURES_KEY = "org-root-features";private static final String CREDENTIAL_REPORT_KEY = "credential-report";/** AWS generates a fresh report only if the most recent one is older than this. */@@ -172,6 +199,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* one partition is never handed to a caller in another.*/private final StorageBackend<String, CredentialReport> credentialReports;+ /** Virtual MFA devices, keyed by serial number, which for a virtual device is its own ARN. */+ private final StorageBackend<String, VirtualMfaDevice> virtualMfaDevices;+ /**+ * Guards every check-then-write on an MFA device. Assignment is the reason it has to exist:+ * EnableMFADevice reads the device to confirm it is unassigned and reads the user's device+ * count to confirm it is under the quota, then writes. Two requests racing the same free+ * device would otherwise both see it unassigned and the second would silently steal it.+ */+ private final Object mfaDeviceLock = new Object();private final RegionResolver regionResolver;private final boolean seedDeployerPrincipal;private final String seededAccountAlias;@@ -204,6 +240,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {storageFactory.create("iam", "iam-slr-deletions.json", new TypeReference<>() {}),storageFactory.create("iam", "iam-org-root-features.json", new TypeReference<>() {}),storageFactory.create("iam", "iam-credential-reports.json", new TypeReference<>() {}),+ storageFactory.create("iam", "iam-virtual-mfa-devices.json", new TypeReference<>() {}),regionResolver,config.services().iam().seedDeployerPrincipal(),config.services().iam().accountAlias().orElse(null)@@ -233,7 +270,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),- new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);+ new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,+ seedDeployerPrincipal, null);}// 8-backend constructor (no org-root-features): kept for existing callers/tests;@@ -255,7 +293,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders,serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(),- regionResolver, seedDeployerPrincipal, seededAccountAlias);+ new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias);}// 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests;@@ -274,7 +312,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures,- new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);+ new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,+ seedDeployerPrincipal, null);}IamService(StorageBackend<String, IamUser> users,@@ -291,6 +330,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {StorageBackend<String, String> serviceLinkedRoleDeletions,StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,StorageBackend<String, CredentialReport> credentialReports,+ StorageBackend<String, VirtualMfaDevice> virtualMfaDevices,RegionResolver regionResolver,boolean seedDeployerPrincipal,String seededAccountAlias) {@@ -308,6 +348,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this.serviceLinkedRoleDeletions = serviceLinkedRoleDeletions;this.orgRootFeatures = orgRootFeatures;this.credentialReports = credentialReports;+ this.virtualMfaDevices = virtualMfaDevices;this.regionResolver = regionResolver;this.seedDeployerPrincipal = seedDeployerPrincipal;this.seededAccountAlias = seededAccountAlias;@@ -474,7 +515,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {throw new AwsException("DeleteConflict","Cannot delete entity, must delete access keys first.", 409);}- users.delete(userName);+ // Held across the delete, not just the check: EnableMFADevice confirms the user under this+ // same lock, so the two cannot interleave into a device assigned to a deleted user.+ synchronized (mfaDeviceLock) {+ if (!mfaDevicesForUser(userName).isEmpty()) {+ throw new AwsException("DeleteConflict",+ "Cannot delete entity, must deactivate MFA device first.", 409);+ }+ users.delete(userName);+ }LOG.infov("Deleted IAM user: {0}", userName);}@@ -511,11 +560,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {"User with name " + newUserName + " already exists.", 409);}List<AccessKey> keysToMove = userAccessKeys(userName);- users.delete(userName);- user.setUserName(newUserName);- if (newPath != null) user.setPath(normalizePath(newPath));- user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));- users.put(newUserName, user);+ // The rename publishes the user under its new name and moves its MFA devices to+ // match. Both happen under the MFA lock, because DeleteUser checks for devices and+ // removes the user under that same lock: split across it, a DeleteUser for the new+ // name could land after the user is published but before the devices follow, see+ // none, and delete a user whose device is about to be reassigned to it.+ synchronized (mfaDeviceLock) {+ users.delete(userName);+ user.setUserName(newUserName);+ if (newPath != null) {+ user.setPath(normalizePath(newPath));+ }+ user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));+ users.put(newUserName, user);+ for (VirtualMfaDevice device : mfaDevicesForUser(userName)) {+ device.setUserName(newUserName);+ virtualMfaDevices.put(device.getSerialNumber(), device);+ }+ }loginProfiles.get(userName).ifPresent(profile -> {loginProfiles.delete(userName);profile.setUserName(newUserName);@@ -1133,9 +1195,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* keys; quota values are cross-checked against AWS's published IAM service quotas* (docs.aws.amazon.com/general/latest/gr/iam-service.html), though floci itself enforces* only the 5-versions-per-policy cap in {@link #createPolicyVersion}. Resources floci does- * not track at all (MFA devices, SAML providers, server certificates, account password - all- * stub-empty elsewhere in this handler) are reported as zero rather than omitted, so callers- * indexing into the full AWS field set don't hit a missing-key error.+ * not track at all (server certificates, account password - stub-empty elsewhere in this+ * handler) are reported as zero rather than omitted, so callers indexing into the full AWS+ * field set don't hit a missing-key error.*/public Map<String, Long> getAccountSummary() {long localPolicyCount = 0;@@ -1176,8 +1238,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {summary.put("ServerCertificates", 0L);summary.put("ServerCertificatesQuota", 20L);summary.put("Providers", (long) oidcProviders.scan(k -> true).size());- summary.put("MFADevices", 0L);- summary.put("MFADevicesInUse", 0L);+ List<VirtualMfaDevice> mfaDevices = virtualMfaDevices.scan(k -> true);+ summary.put("MFADevices", (long) mfaDevices.size());+ summary.put("MFADevicesInUse", mfaDevices.stream().filter(VirtualMfaDevice::isAssigned).count());+ // AWS reports whether the *root* user has MFA enabled, not whether IAM users do. Floci+ // does not model root credentials, so this stays false however many user devices exist,+ // for the same reason AccountAccessKeysPresent below does.summary.put("AccountMFAEnabled", 0L);// AWS reports whether the root account has access keys, not whether IAM users do.// Floci does not model root access keys, so this remains false even when user keys exist.@@ -1952,6 +2018,275 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}}+ // Virtual MFA devices+ // =========================================================================++ /**+ * Creates an unassigned virtual MFA device. The seed is real randomness, not a placeholder:+ * AWS hands it out as {@code Base32StringSeed} precisely so an authenticator app can be+ * programmed from it, and {@link #enableMfaDevice} then verifies codes actually derived from+ * it. A caller that seeds a TOTP app from a Floci device gets working codes.+ */+ public VirtualMfaDevice createVirtualMfaDevice(String name, String path, Map<String, String> tags) {+ validateVirtualMfaDeviceName(name);+ validateIamPath(path, "Path");+ String normalizedPath = normalizePath(path);+ // The serial number is the ARN, and the ARN embeds the path, so two devices of the same+ // name under different paths are genuinely different devices, as AWS says: "Use with+ // path to uniquely identify a virtual MFA device."+ String serialNumber = iamArn("mfa", normalizedPath, name);+ // AWS's own model leaves a gap here: virtualMFADeviceName has no maximum length, but the+ // serial number it mints is a serialNumberType, capped at 256. A long-but-valid name would+ // therefore produce a device whose serial every other MFA operation rejects, so it could+ // never be enabled, tagged or deleted. Floci refuses it at creation instead of handing back+ // an unusable device; the limit named is the serial's, since the name itself has none.+ if (serialNumber.length() > SERIAL_NUMBER_MAX_LENGTH) {+ throw new AwsException("ValidationError",+ "VirtualMFADeviceName and Path together must produce a serial number of at most "+ + SERIAL_NUMBER_MAX_LENGTH + " characters; " + serialNumber.length()+ + " were produced.", 400);+ }+ if (tags != null && tags.size() > MAX_TAGS_PER_RESOURCE) {+ throw new AwsException("LimitExceeded",+ "Cannot exceed quota for TagsPerMFADevice: " + MAX_TAGS_PER_RESOURCE, 409);+ }+ VirtualMfaDevice device = new VirtualMfaDevice();+ device.setSerialNumber(serialNumber);+ device.setDeviceName(name);+ device.setPath(normalizedPath);+ device.setBase32Seed(Totp.newSecret());+ device.setTags(tags);+ synchronized (mfaDeviceLock) {+ if (virtualMfaDevices.get(serialNumber).isPresent()) {+ throw new AwsException("EntityAlreadyExists",+ "MFADevice entity at the same path and name already exists.", 409);+ }+ virtualMfaDevices.put(serialNumber, device);+ }+ LOG.infov("Created virtual MFA device: {0}", serialNumber);+ return device;+ }++ /**+ * Every virtual MFA device in the account, filtered by assignment. {@code assignmentStatus}+ * may be {@code Assigned}, {@code Unassigned} or {@code Any}; null defaults to {@code Any}.+ */+ public List<VirtualMfaDevice> listVirtualMfaDevices(String assignmentStatus) {+ String status = assignmentStatus == null || assignmentStatus.isBlank() ? "Any" : assignmentStatus;+ if (!status.equals("Any") && !status.equals("Assigned") && !status.equals("Unassigned")) {+ throw new AwsException("ValidationError",+ "1 validation error detected: Value '" + assignmentStatus+ + "' at 'assignmentStatus' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [Any, Unassigned, Assigned]", 400);+ }+ return virtualMfaDevices.scan(k -> true).stream()+ .filter(d -> switch (status) {+ case "Assigned" -> d.isAssigned();+ case "Unassigned" -> !d.isAssigned();+ default -> true;+ })+ .sorted(Comparator.comparing(VirtualMfaDevice::getSerialNumber))+ .toList();+ }++ /**+ * Deletes a virtual MFA device. AWS requires it to be deactivated first: "You must deactivate+ * a user's virtual MFA device before you can delete it", so a still-assigned device is the+ * documented DeleteConflict rather than a silent detach.+ */+ public void deleteVirtualMfaDevice(String serialNumber) {+ validateSerialNumber(serialNumber);+ synchronized (mfaDeviceLock) {+ VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);+ if (device.isAssigned()) {+ throw new AwsException("DeleteConflict",+ "Cannot delete entity, must deactivate the MFA device from user "+ + device.getUserName() + " first.", 409);+ }+ virtualMfaDevices.delete(serialNumber);+ }+ LOG.infov("Deleted virtual MFA device: {0}", serialNumber);+ }++ /**+ * Assigns a device to a user, after checking the two codes really came from its seed. The+ * codes must be consecutive, which is what AWS asks for ("a subsequent authentication code"),+ * so a caller replaying one code twice is rejected the way a real device's user would be.+ */+ public void enableMfaDevice(String userName, String serialNumber, String code1, String code2) {+ validateIamResourceName(userName, "UserName");+ validateSerialNumber(serialNumber);+ validateAuthenticationCode(code1, "AuthenticationCode1");+ validateAuthenticationCode(code2, "AuthenticationCode2");+ synchronized (mfaDeviceLock) {+ // The user's existence is confirmed under the same lock DeleteUser checks for devices+ // under. Checked outside it, a DeleteUser that saw no devices could remove the user+ // between that check and this write, leaving a device assigned to nobody, and one+ // that could never be freed, since deactivating it resolves the user first.+ getUser(userName);+ VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);+ if (device.isAssigned()) {+ throw new AwsException("EntityAlreadyExists",+ "Device with serial number " + serialNumber + " is already assigned to user "+ + device.getUserName() + ".", 409);+ }+ if (mfaDevicesForUser(userName).size() >= MAX_MFA_DEVICES_PER_USER) {+ throw new AwsException("LimitExceeded",+ "Cannot exceed quota for MFADevicesPerUser: " + MAX_MFA_DEVICES_PER_USER, 409);+ }+ // Codes are checked last, so a request that would be rejected for the device's state+ // does not depend on the caller having got the codes right.+ requireConsecutiveCodes(device, code1, code2, ENABLE_DRIFT_STEPS);+ device.setUserName(userName);+ device.setEnableDate(Instant.now());+ virtualMfaDevices.put(serialNumber, device);+ }+ LOG.infov("Enabled MFA device {0} for user {1}", serialNumber, userName);+ }++ /**+ * Detaches a device from its user, leaving the device itself in place. AWS "removes it from+ * association with the user name for which it was originally enabled", it does not delete it.+ * The seed survives, so the same authenticator entry keeps working if it is re-enabled.+ */+ public void deactivateMfaDevice(String userName, String serialNumber) {+ validateSerialNumber(serialNumber);+ getUser(userName);+ synchronized (mfaDeviceLock) {+ VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);+ if (!userName.equals(device.getUserName())) {+ throw new AwsException("NoSuchEntity",+ "Device with serial number " + serialNumber + " is not assigned to user "+ + userName + ".", 404);+ }+ device.setUserName(null);+ device.setEnableDate(null);+ virtualMfaDevices.put(serialNumber, device);+ }+ LOG.infov("Deactivated MFA device {0} for user {1}", serialNumber, userName);+ }++ /**+ * Re-synchronizes an assigned device. This is the same pair-of-codes check as+ * {@link #enableMfaDevice}, over a wider drift window: a device needing resync is by+ * definition one whose clock has wandered, so accepting only the current window would reject+ * exactly the case the operation exists to fix.+ */+ public void resyncMfaDevice(String userName, String serialNumber, String code1, String code2) {+ validateIamResourceName(userName, "UserName");+ validateSerialNumber(serialNumber);+ validateAuthenticationCode(code1, "AuthenticationCode1");+ getUser(userName);+ validateAuthenticationCode(code2, "AuthenticationCode2");+ synchronized (mfaDeviceLock) {+ VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);+ if (!userName.equals(device.getUserName())) {+ throw new AwsException("NoSuchEntity",+ "Device with serial number " + serialNumber + " is not assigned to user "+ + userName + ".", 404);+ }+ requireConsecutiveCodes(device, code1, code2, RESYNC_DRIFT_STEPS);+ }+ }++ /** The MFA devices assigned to a user, which is what ListMFADevices returns. */+ public List<VirtualMfaDevice> listMfaDevices(String userName) {+ getUser(userName);+ return mfaDevicesForUser(userName);+ }++ public void tagMfaDevice(String serialNumber, Map<String, String> newTags) {+ validateSerialNumber(serialNumber);+ synchronized (mfaDeviceLock) {+ VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);+ device.setTags(mergeTagsWithinQuota(device.getTags(), newTags, "TagsPerMFADevice", false));+ virtualMfaDevices.put(serialNumber, device);+ }+ }++ public void untagMfaDevice(String serialNumber, List<String> tagKeys) {+ validateSerialNumber(serialNumber);+ synchronized (mfaDeviceLock) {+ VirtualMfaDevice device = getVirtualMfaDevice(serialNumber);+ Map<String, String> remaining = new LinkedHashMap<>(device.getTags());+ if (tagKeys != null) {+ tagKeys.forEach(remaining::remove);+ }+ device.setTags(remaining);+ virtualMfaDevices.put(serialNumber, device);+ }+ }++ public Map<String, String> listMfaDeviceTags(String serialNumber) {+ validateSerialNumber(serialNumber);+ return getVirtualMfaDevice(serialNumber).getTags();+ }++ public VirtualMfaDevice getVirtualMfaDevice(String serialNumber) {+ if (serialNumber == null) {+ throw new AwsException("NoSuchEntity",+ "The MFA device with serial number null cannot be found.", 404);+ }+ return virtualMfaDevices.get(serialNumber)+ .orElseThrow(() -> new AwsException("NoSuchEntity",+ "The MFA device with serial number " + serialNumber + " cannot be found.", 404));+ }++ private List<VirtualMfaDevice> mfaDevicesForUser(String userName) {+ return virtualMfaDevices.scan(k -> true).stream()+ .filter(d -> userName.equals(d.getUserName()))+ .sorted(Comparator.comparing(VirtualMfaDevice::getSerialNumber))+ .toList();+ }++ private void validateAuthenticationCode(String code, String paramName) {+ if (code == null || !AUTHENTICATION_CODE_PATTERN.matcher(code).matches()) {+ throw new AwsException("ValidationError",+ paramName + " must be exactly 6 digits.", 400);+ }+ }++ /**+ * {@code virtualMFADeviceName} carries a minimum and a pattern but, unlike every other IAM+ * name type, no maximum length. So this cannot reuse+ * {@link #validateIamResourceName(String, String)}: capping the name at 128 would reject a+ * name AWS accepts.+ */+ private void validateVirtualMfaDeviceName(String name) {+ if (name == null || name.isEmpty() || !VIRTUAL_MFA_DEVICE_NAME_PATTERN.matcher(name).matches()) {+ throw new AwsException("ValidationError",+ "VirtualMFADeviceName must be at least 1 character matching [\\w+=,.@-].", 400);+ }+ }++ /**+ * {@code serialNumberType}: 9 to 256 characters of {@code [\w+=/:,.@-]}. Checked before the+ * device is looked up, so a malformed serial number is the ValidationError AWS returns rather+ * than a NoSuchEntity for a device that could never have existed under that name.+ */+ private void validateSerialNumber(String serialNumber) {+ if (serialNumber == null+ || serialNumber.length() < SERIAL_NUMBER_MIN_LENGTH+ || serialNumber.length() > SERIAL_NUMBER_MAX_LENGTH+ || !SERIAL_NUMBER_PATTERN.matcher(serialNumber).matches()) {+ throw new AwsException("ValidationError",+ "SerialNumber must be " + SERIAL_NUMBER_MIN_LENGTH + "-" + SERIAL_NUMBER_MAX_LENGTH+ + " characters matching [\\w+=/:,.@-].", 400);+ }+ }++ /**+ * Rejects the request unless the two codes are consecutive outputs of the device's seed,+ * allowing the counter to start anywhere within {@code driftSteps} of the current window.+ */+ private void requireConsecutiveCodes(VirtualMfaDevice device, String code1, String code2, int driftSteps) {+ if (!VirtualMfaCodes.matchesConsecutiveCodes(device.getBase32Seed(), code1, code2,+ driftSteps, Instant.now())) {+ throw new AwsException("InvalidAuthenticationCode",+ "Invalid MFA one time pass code.", 403);+ }+ }+// OIDC Identity Providers// =========================================================================@@ -3158,10 +3493,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* The 23 columns AWS documents for the credential report, in order, always led by the* {@code <root_account>} row. Floci does not model root account credentials at all (see* {@code GetAccountSummary}'s {@code AccountPasswordPresent}/{@code AccountAccessKeysPresent},- * always zero), so that row is always unused/not-present placeholders. MFA devices and X.509- * signing certificates are not modeled for IAM users either, so those columns are always- * {@code FALSE}/{@code N/A} for every row; access key last-used tracking (date, region,- * service) is not modeled, so those three columns are always {@code N/A} too.+ * always zero), so that row is always unused/not-present placeholders, including its+ * {@code mfa_active}, which reports on root rather than on any IAM user's device. X.509+ * signing certificates are not modeled, so those columns are always {@code FALSE}/{@code N/A}+ * for every row; access key last-used tracking (date, region, service) is not modeled, so+ * those three columns are always {@code N/A} too.*/private String buildCredentialReportCsv() {StringBuilder csv = new StringBuilder(@@ -3204,7 +3540,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {passwordLastUsedField(user, passwordEnabled),passwordEnabled ? isoDate(passwordLastChanged(loginProfile.get())) : "N/A",passwordNextRotationField(loginProfile, passwordEnabled),- "FALSE",+ mfaDevicesForUser(user.getUserName()).isEmpty() ? "FALSE" : "TRUE",accessKeyActiveField(key1), accessKeyRotatedField(key1), "N/A", "N/A", "N/A",accessKeyActiveField(key2), accessKeyRotatedField(key2), "N/A", "N/A", "N/A","FALSE", "N/A", "FALSE", "N/A",diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/VirtualMfaCodes.java b/src/main/java/io/github/hectorvent/floci/services/iam/VirtualMfaCodes.javanew file mode 100644index 0000000000..21ad0577c6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/VirtualMfaCodes.java@@ -0,0 +1,42 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.core.common.Totp;++import java.time.Instant;++/**+ * The one authentication-code rule specific to IAM. EnableMFADevice and ResyncMFADevice each take+ * two codes, and AWS asks for the second to be "a subsequent authentication code", so the pair has+ * to be consecutive outputs of the device's seed. Checking each code on its own would accept the+ * same code submitted twice, which no real authenticator would produce.+ *+ * <p>The seed and the code arithmetic itself are {@link Totp}, shared with Cognito's+ * software-token MFA.+ */+final class VirtualMfaCodes {++ private VirtualMfaCodes() {+ }++ /**+ * Whether {@code code1} and {@code code2} are two consecutive passwords from+ * {@code base32Seed}, with the pair allowed to start up to {@code driftSteps} windows either+ * side of the one current at {@code now}.+ */+ static boolean matchesConsecutiveCodes(String base32Seed, String code1, String code2,+ int driftSteps, Instant now) {+ if (base32Seed == null || !Totp.isSixDigits(code1) || !Totp.isSixDigits(code2)) {+ return false;+ }+ long current = Totp.stepAt(now);+ // The pair is read as (previous window, current window), so the undrifted case has code1+ // one step back; drift widens the search symmetrically around that.+ for (long offset = -driftSteps - 1; offset <= driftSteps - 1; offset++) {+ if (Totp.codeEquals(Totp.codeAt(base32Seed, current + offset), code1)+ && Totp.codeEquals(Totp.codeAt(base32Seed, current + offset + 1), code2)) {+ return true;+ }+ }+ return false;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/VirtualMfaDevice.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/VirtualMfaDevice.javanew file mode 100644index 0000000000..52c3fa77ee--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/VirtualMfaDevice.java@@ -0,0 +1,59 @@+package io.github.hectorvent.floci.services.iam.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;++/**+ * A virtual MFA device, keyed by its serial number, which for a virtual device is its own ARN,+ * {@code arn:aws:iam::<account>:mfa/<name>}.+ *+ * <p>A device exists independently of any user: CreateVirtualMFADevice makes it unassigned, and+ * EnableMFADevice is what attaches it to one. {@code userName} and {@code enableDate} are therefore+ * both null until then, and null again after DeactivateMFADevice. That pair is exactly what+ * ListVirtualMFADevices filters on with {@code AssignmentStatus}.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class VirtualMfaDevice {+ private String serialNumber;+ private String deviceName;+ private String path = "/";+ /** The base32 secret, as handed out in {@code Base32StringSeed} and used to compute TOTP codes. */+ private String base32Seed;+ /** The assigned user, or null while the device is unassigned. */+ private String userName;+ /** When the device was assigned, or null while it is unassigned. */+ private Instant enableDate;+ private Instant createDate = Instant.now();+ private Map<String, String> tags = new ConcurrentHashMap<>();++ public VirtualMfaDevice() {}++ public String getSerialNumber() { return serialNumber; }+ public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; }+ public String getDeviceName() { return deviceName; }+ public void setDeviceName(String deviceName) { this.deviceName = deviceName; }+ public String getPath() { return path; }+ public void setPath(String path) { this.path = path; }+ public String getBase32Seed() { return base32Seed; }+ public void setBase32Seed(String base32Seed) { this.base32Seed = base32Seed; }+ public String getUserName() { return userName; }+ public void setUserName(String userName) { this.userName = userName; }+ public Instant getEnableDate() { return enableDate; }+ public void setEnableDate(Instant enableDate) { this.enableDate = enableDate; }+ public Instant getCreateDate() { return createDate; }+ public void setCreateDate(Instant createDate) { this.createDate = createDate; }+ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) {+ this.tags = tags == null ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(tags);+ }++ /** Whether the device is attached to a user, which is what {@code AssignmentStatus} selects on. */+ public boolean isAssigned() {+ return userName != null;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamGetAccountSummaryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamGetAccountSummaryIntegrationTest.javaindex 6b7afe7bc8..8fddda9998 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamGetAccountSummaryIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamGetAccountSummaryIntegrationTest.java@@ -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"));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.javaindex 0a3569c34c..db28e720ae 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java@@ -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"));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.javaindex fc79cc503e..fbb0d96deb 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java@@ -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();diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex f9abab7e08..0fa22ade16 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -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();diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.javanew file mode 100644index 0000000000..ae1d4bc259--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java@@ -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()));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaCodesTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaCodesTest.javanew file mode 100644index 0000000000..a5a634526c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaCodesTest.java@@ -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");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.javanew file mode 100644index 0000000000..5414c07a1f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java@@ -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());+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.javanew file mode 100644index 0000000000..baf7f5117b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.java@@ -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"));+ }+}