diff --git a/docs/services/iam.md b/docs/services/iam.md index 558139ea64..22c2c9b58b 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -193,6 +193,17 @@ own documented role subset. | UpdateAccessKey | Updates an access key's status. | | DeleteAccessKey | Deletes an access key from a user. | +`UserName` is optional on `UpdateAccessKey`, `ListAccessKeys` and `DeleteAccessKey`: it defaults to +the user resolved from the signing access key, the same fallback `GetUser` uses. + +`Status` takes any of the three values `statusType` publishes, `Active`, `Inactive` and `Expired`, +which is what the reference's Valid Values line on `UpdateAccessKey` lists, and it is held to that +set the same way `UpdateSigningCertificate`, `UpdateSSHPublicKey` and +`UpdateServiceSpecificCredential` hold theirs. It is read before the key is looked up, so a status +outside the set answers `ValidationError` whether or not the key exists. The `AWS::IAM::AccessKey` +CloudFormation resource takes the same three, its Allowed values line reading "Active | Inactive | +Expired" as well. + ### Account Aliases | Action | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java index f1ea84e5bd..6dff15754b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java @@ -9,6 +9,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -27,6 +28,8 @@ import java.util.Set; public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner { private static final String TYPE = "AWS::IAM::AccessKey"; + /** The resource's own Allowed values line, which matches the IAM API's {@code statusType}. */ + private static final List STATUS_VALUES = List.of("Active", "Inactive", "Expired"); private static final String SERIAL_ATTR = "__FlociAccessKeySerial"; private final IamService iamService; @@ -48,13 +51,14 @@ public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner { throw new AwsException("ValidationError", "AWS::IAM::AccessKey requires a UserName.", 400); } String serial = serialOf(props, ctx); - // Status (Active/Inactive) is a mutable property. Validate it up front, before any key is - // created, so a bad value fails cleanly: a user is capped at two keys, so creating one and - // only then rejecting the status could orphan it. + // Status is a mutable property whose Allowed values line reads "Active | Inactive | + // Expired", the same three the IAM API's statusType publishes. Validate it up front, + // before any key is created, so a bad value fails cleanly: a user is capped at two keys, + // so creating one and only then rejecting the status could orphan it. String status = ctx.resolveOptional(props, "Status"); - if (status != null && !"Active".equals(status) && !"Inactive".equals(status)) { + if (status != null && !STATUS_VALUES.contains(status)) { throw new AwsException("ValidationError", - "AWS::IAM::AccessKey Status must be Active or Inactive.", 400); + "AWS::IAM::AccessKey Status must be Active, Inactive or Expired.", 400); } Map attributesBefore = new HashMap<>(r.getAttributes()); @@ -75,8 +79,8 @@ public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().put("Id", key.getAccessKeyId()); r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey()); r.getAttributes().put(SERIAL_ATTR, serial); - // A new key is Active; only touch it when the template asked for Inactive. - if ("Inactive".equals(status)) { + // A new key is Active; only touch it when the template asked for something else. + if (status != null && !"Active".equals(status)) { iamService.updateAccessKey(userName, key.getAccessKeyId(), status); } // On a createOnly change this new key replaced the prior one; record it so the displaced 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.java index f68b81dd87..75614650e0 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 @@ -284,7 +284,7 @@ public class IamQueryHandler { case "CreateAccessKey" -> handleCreateAccessKey(params); case "DeleteAccessKey" -> handleDeleteAccessKey(params, authorization); case "ListAccessKeys" -> handleListAccessKeys(params, authorization); - case "UpdateAccessKey" -> handleUpdateAccessKey(params); + case "UpdateAccessKey" -> handleUpdateAccessKey(params, authorization); case "GetAccessKeyLastUsed" -> handleGetAccessKeyLastUsed(params); case "ListOrganizationsFeatures" -> handleListOrganizationsFeatures(params); @@ -358,8 +358,8 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelope("CreateUser", AwsNamespaces.IAM, result)).build(); } - // UserName is optional on GetUser/ListAccessKeys/DeleteAccessKey: real AWS determines - // it implicitly from the access key that signed the request. Mirrors moto: an access + // UserName is optional on GetUser/ListAccessKeys/DeleteAccessKey/UpdateAccessKey: real AWS + // determines it implicitly from the access key that signed the request. Mirrors moto: an access // key that maps to no stored IAM user is the documented NoSuchEntity error. private String resolveUserName(MultivaluedMap params, String authorization) { String userName = getParam(params, "UserName"); @@ -1964,9 +1964,12 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelope("ListAccessKeys", AwsNamespaces.IAM, xml.build())).build(); } - private Response handleUpdateAccessKey(MultivaluedMap params) { - iamService.updateAccessKey(getParam(params, "UserName"), - getParam(params, "AccessKeyId"), getParam(params, "Status")); + private Response handleUpdateAccessKey(MultivaluedMap params, String authorization) { + // "If the UserName is not specified, the user name is determined implicitly based on the + // AWS access key ID used to sign the request", the same sentence DeleteAccessKey carries. + // Read the way the other three statusType operations read theirs, the status included. + iamService.updateAccessKey(resolveUserName(params, authorization), + requireParam(params, "AccessKeyId"), getParam(params, "Status")); return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateAccessKey", 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.java index c3760f7ca7..03a0e60885 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 @@ -279,9 +279,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final String CREDENTIAL_STATUS_ACTIVE = "Active"; private static final String CREDENTIAL_STATUS_EXPIRED = "Expired"; /** - * statusType's values, shared by signing certificates and SSH public keys: Active, Inactive - * and Expired. Each operation's prose explains only the first two, so the third is easy to - * reject by mistake, while the API Reference lists all three as valid. + * statusType's values, shared by access keys, signing certificates, SSH public keys and + * service-specific credentials: Active, Inactive and Expired. Each operation's prose explains + * only the first two, so the third is easy to reject by mistake, while the API Reference lists + * all three as valid on each of them. */ private static final Set CREDENTIAL_STATUSES = Set.of(CREDENTIAL_STATUS_ACTIVE, "Inactive", CREDENTIAL_STATUS_EXPIRED); @@ -401,6 +402,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private final Object signingCertificateLock = new Object(); private final Object sshPublicKeyLock = new Object(); private final Object serviceCredentialLock = new Object(); + /** + * Guards every check-then-write on an access key, the way its three sibling credential + * families are guarded. Both halves of this family need it: CreateAccessKey counts a user's + * keys and only then stores another, so two requests racing the quota would both pass a check + * for two; and UpdateAccessKey reads a key, changes its status and writes it back, so an + * update racing a delete would store the key the delete had just removed. + */ + private final Object accessKeyLock = new Object(); /** * 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 @@ -835,39 +844,43 @@ public class IamService implements SessionAccountLookup, ResourceProvider { throw new AwsException("DeleteConflict", "Cannot delete entity, must delete policies first.", 409); } - if (!userAccessKeys(userName).isEmpty()) { - throw new AwsException("DeleteConflict", - "Cannot delete entity, must delete access keys first.", 409); - } - // Both locks are held across the delete rather than just the checks: UploadSigningCertificate - // UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so - // none of them can interleave into a credential owned by a deleted user. Taken in this - // order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock. - synchronized (serviceCredentialLock) { - // AWS lists these among the items to remove first, under their CodeCommit - // name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the - // cases above it has no message of its own: AWS falls back to the generic - // referenced-objects wording here. - if (!userServiceCredentials(userName).isEmpty()) { + // The credential locks are held across the delete rather than just the checks: + // CreateAccessKey, UploadSigningCertificate and EnableMFADevice each confirm the user + // under their own lock, so none of them can interleave into a credential owned by a + // user that is already gone. Access keys are the outermost of the five here, and + // UpdateUser takes that lock on its own rather than inside the others, so no two of + // them are ever held in opposite orders. + synchronized (accessKeyLock) { + if (!userAccessKeys(userName).isEmpty()) { throw new AwsException("DeleteConflict", - "Cannot delete entity, must remove referenced objects first.", 409); + "Cannot delete entity, must delete access keys first.", 409); } - synchronized (sshPublicKeyLock) { - if (!userSshPublicKeys(userName).isEmpty()) { + synchronized (serviceCredentialLock) { + // AWS lists these among the items to remove first, under their CodeCommit + // name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the + // cases above it has no message of its own: AWS falls back to the generic + // referenced-objects wording here. + if (!userServiceCredentials(userName).isEmpty()) { throw new AwsException("DeleteConflict", - "Cannot delete entity, must delete SSH public keys first.", 409); + "Cannot delete entity, must remove referenced objects first.", 409); } - synchronized (signingCertificateLock) { - if (!userSigningCertificates(userName).isEmpty()) { + synchronized (sshPublicKeyLock) { + if (!userSshPublicKeys(userName).isEmpty()) { throw new AwsException("DeleteConflict", - "Cannot delete entity, must delete signing certificates first.", 409); + "Cannot delete entity, must delete SSH public keys first.", 409); } - synchronized (mfaDeviceLock) { - if (!mfaDevicesForUser(userName).isEmpty()) { + synchronized (signingCertificateLock) { + if (!userSigningCertificates(userName).isEmpty()) { throw new AwsException("DeleteConflict", - "Cannot delete entity, must deactivate MFA device first.", 409); + "Cannot delete entity, must delete signing certificates first.", 409); + } + synchronized (mfaDeviceLock) { + if (!mfaDevicesForUser(userName).isEmpty()) { + throw new AwsException("DeleteConflict", + "Cannot delete entity, must deactivate MFA device first.", 409); + } + users.delete(userName); } - users.delete(userName); } } } @@ -904,7 +917,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider { throw new AwsException("EntityAlreadyExists", "User with name " + newUserName + " already exists.", 409); } - List keysToMove = userAccessKeys(userName); // The rename publishes the user under its new name and moves the credentials that // DeleteUser refuses to delete a user over: its MFA devices, its signing // certificates and its SSH public keys. Each moves under the lock DeleteUser checks it with, because split @@ -955,9 +967,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider { loginProfiles.put(newUserName, profile); }); } - for (AccessKey key : keysToMove) { - key.setUserName(newUserName); - accessKeys.put(key.getAccessKeyId(), key); + synchronized (accessKeyLock) { + // Read inside the lock that rewrites them, the way each credential above is + // read inside its own: a DeleteAccessKey landing between a read taken earlier + // and this loop would be undone, the deleted key coming back under the new + // name and still authenticating. + for (AccessKey key : userAccessKeys(userName)) { + key.setUserName(newUserName); + accessKeys.put(key.getAccessKeyId(), key); + } } for (String groupName : user.getGroupNames()) { groups.get(groupName).ifPresent(group -> { @@ -2231,31 +2249,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider { // ========================================================================= public AccessKey createAccessKey(String userName) { - getUser(userName); // validates existence - long existingCount = accessKeys.scan(k -> true).stream() - .filter(ak -> userName.equals(ak.getUserName())) - .count(); - if (existingCount >= 2) { - throw new AwsException("LimitExceeded", - "Cannot exceed quota for AccessKeysPerUser: 2", 409); + synchronized (accessKeyLock) { + // Confirmed under the lock, not before it, the way UploadSigningCertificate confirms + // its own: DeleteUser checks for access keys holding this same lock, so the two cannot + // interleave into a key owned by a user that no longer exists. + getUser(userName); + long existingCount = userAccessKeys(userName).size(); + if (existingCount >= 2) { + throw new AwsException("LimitExceeded", + "Cannot exceed quota for AccessKeysPerUser: 2", 409); + } + String keyId = "AKIA" + randomId(16); + String secretKey = randomSecret(40); + AccessKey key = new AccessKey(keyId, secretKey, userName); + accessKeys.put(keyId, key); + LOG.infov("Created access key for user: {0}", userName); + return key; } - String keyId = "AKIA" + randomId(16); - String secretKey = randomSecret(40); - AccessKey key = new AccessKey(keyId, secretKey, userName); - accessKeys.put(keyId, key); - LOG.infov("Created access key for user: {0}", userName); - return key; } public void deleteAccessKey(String userName, String accessKeyId) { - AccessKey key = accessKeys.get(accessKeyId) - .orElseThrow(() -> new AwsException("NoSuchEntity", - "Access key " + accessKeyId + " not found.", 404)); - if (!key.getUserName().equals(userName)) { - throw new AwsException("NoSuchEntity", - "Access key " + accessKeyId + " does not belong to user " + userName + ".", 404); + synchronized (accessKeyLock) { + AccessKey key = userAccessKey(userName, accessKeyId); + accessKeys.delete(key.getAccessKeyId()); } - accessKeys.delete(accessKeyId); } public List listAccessKeys(String userName) { @@ -2269,7 +2286,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider { .toList(); } + /** + * Sets an access key's status, validated before the key is looked up the way the other three + * {@code statusType} operations validate theirs: a status outside the enum is answered for the + * status whether or not the key exists. + */ public void updateAccessKey(String userName, String accessKeyId, String status) { + requireStatusFromEnum(status); + synchronized (accessKeyLock) { + AccessKey key = userAccessKey(userName, accessKeyId); + key.setStatus(status); + accessKeys.put(accessKeyId, key); + } + } + + /** The user's key with this id, or the NoSuchEntity each of these operations answers. */ + private AccessKey userAccessKey(String userName, String accessKeyId) { AccessKey key = accessKeys.get(accessKeyId) .orElseThrow(() -> new AwsException("NoSuchEntity", "Access key " + accessKeyId + " not found.", 404)); @@ -2277,12 +2309,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { throw new AwsException("NoSuchEntity", "Access key " + accessKeyId + " does not belong to user " + userName + ".", 404); } - if (!"Active".equals(status) && !"Inactive".equals(status)) { - throw new AwsException("ValidationError", - "Status must be Active or Inactive.", 400); - } - key.setStatus(status); - accessKeys.put(accessKeyId, key); + return key; } // ========================================================================= @@ -3284,12 +3311,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return getServerCertificate(name).getTags(); } - // Credential status, shared by the three operations that take statusType + // Credential status, shared by the four operations that take statusType // ========================================================================= /** - * {@code statusType}, shared by UpdateSigningCertificate, UpdateSSHPublicKey and - * UpdateServiceSpecificCredential. One rendering serves all three because one front end + * {@code statusType}, shared by UpdateAccessKey, UpdateSigningCertificate, UpdateSSHPublicKey + * and UpdateServiceSpecificCredential. One rendering serves all four because one front end * validates one shape: the recording is of UpdateServiceSpecificCredential, and AWS names * neither the offending value nor the permitted set, unlike this message elsewhere in the * tree. Matched rather than made uniform. diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java index 5938904ee7..3e62725db5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java @@ -117,6 +117,22 @@ class IamAccessKeyCfnProvisionerTest { verify(iam, never()).updateAccessKey(anyString(), anyString(), anyString()); } + @Test + void createWithExpiredStatusIsTakenToo() throws Exception { + // The resource's Allowed values line reads "Active | Inactive | Expired", so Expired is a + // status the template may declare and not one to refuse. + AccessKey key = new AccessKey(); + key.setAccessKeyId("AKIA1"); + key.setSecretAccessKey("secret-1"); + when(iam.createAccessKey("alice")).thenReturn(key); + + provisioner.provision(resource(), props("{\"UserName\": \"alice\", \"Status\": \"Expired\"}"), + ctx(null)); + + verify(iam).createAccessKey("alice"); + verify(iam).updateAccessKey("alice", "AKIA1", "Expired"); + } + @Test void aBogusStatusIsRejectedBeforeCreatingAKey() { AwsException e = assertThrows(AwsException.class, () -> provisioner.provision( diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java new file mode 100644 index 0000000000..e22abcb01c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamAccessKeyStatusIntegrationTest.java @@ -0,0 +1,168 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * {@code UpdateAccessKey} over the wire, for the three things the reference publishes about it that + * the handler did not follow. + * + *

The status is a {@code statusType}, whose Valid Values line reads "Active | Inactive | + * Expired", so {@code Expired} is a value the operation takes rather than one to refuse. A value + * outside that set breaks a constraint the model declares, which the Common Errors page answers as + * {@code ValidationError}, and it is read before the key is looked up, so it is answered even when + * the key named does not exist. And "if the UserName is not specified, the user name is determined + * implicitly based on the AWS access key ID used to sign the request", the sentence this operation + * shares with DeleteAccessKey and ListAccessKeys. + * + *

The refusal is the rendering {@code IamService.requireStatusFromEnum} already answers for the + * other three operations that take this shape, which names neither the offending value nor the + * permitted set, as AWS's own recording of one of them does not. + */ +@QuarkusTest +class IamAccessKeyStatusIntegrationTest { + + private static final String ACCOUNT = "000000000912"; + private static final String REGION = "us-east-1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void expiredIsAStatusTheOperationTakes() { + String userName = user("expired"); + String accessKeyId = accessKeyFor(userName); + + update(ACCOUNT, Map.of("UserName", userName, "AccessKeyId", accessKeyId, + "Status", "Expired")).statusCode(200); + + admin("ListAccessKeys", Map.of("UserName", userName)).statusCode(200) + .body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.Status", + equalTo("Expired")); + } + + @Test + void aStatusOutsideTheEnumIsAValidationError() { + String userName = user("bad-status"); + String accessKeyId = accessKeyFor(userName); + + update(ACCOUNT, Map.of("UserName", userName, "AccessKeyId", accessKeyId, + "Status", "Disabled")).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("1 validation error detected: Value at 'status' failed to satisfy " + + "constraint: Member must satisfy enum value set")); + + assertStatusStillActive(userName); + } + + @Test + void anAbsentStatusIsAnsweredTheSameWay() { + String userName = user("absent-status"); + String accessKeyId = accessKeyFor(userName); + + update(ACCOUNT, Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("at 'status'")); + + assertStatusStillActive(userName); + } + + /** A refused status leaves the key as it was: the value is read before anything is written. */ + private void assertStatusStillActive(String userName) { + admin("ListAccessKeys", Map.of("UserName", userName)).statusCode(200) + .body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.Status", + equalTo("Active")); + } + + @Test + void anAbsentAccessKeyIdNamesItself() { + update(ACCOUNT, Map.of("UserName", user("absent-id"), "Status", "Inactive")).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("Value null at 'accessKeyId'")); + } + + @Test + void theStatusIsReadBeforeTheKeyIsLookedUp() { + // Both are wrong, and the shape is what AWS answers for: the key would otherwise decide, + // which is NoSuchEntity 404 for a key that is not there. + update(ACCOUNT, Map.of("UserName", user("order"), "AccessKeyId", "AKIANOSUCHKEY00000", + "Status", "Disabled")).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + + update(ACCOUNT, Map.of("UserName", user("order-valid"), "AccessKeyId", "AKIANOSUCHKEY00000", + "Status", "Inactive")).statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + void theSignersOwnKeyNeedsNoUserName() { + String userName = user("implicit"); + String accessKeyId = accessKeyFor(userName); + + update(accessKeyId, Map.of("AccessKeyId", accessKeyId, "Status", "Inactive")) + .statusCode(200); + + admin("ListAccessKeys", Map.of("UserName", userName)).statusCode(200) + .body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.Status", + equalTo("Inactive")); + } + + @Test + void anotherUsersKeyIsStillNoSuchEntity() { + String owner = user("owner"); + String ownerKey = accessKeyFor(owner); + String stranger = user("stranger"); + + update(ACCOUNT, Map.of("UserName", stranger, "AccessKeyId", ownerKey, + "Status", "Inactive")).statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + private String user(String label) { + String userName = "access-key-status-" + label; + admin("CreateUser", Map.of("UserName", userName)).statusCode(200); + cleanup.register(() -> admin("DeleteUser", Map.of("UserName", userName)).statusCode(200)); + return userName; + } + + private String accessKeyFor(String userName) { + String accessKeyId = admin("CreateAccessKey", Map.of("UserName", userName)).statusCode(200) + .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey" + + ".AccessKeyId"); + cleanup.register(() -> admin("DeleteAccessKey", + Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(200)); + return accessKeyId; + } + + private static ValidatableResponse update(String accessKeyId, Map params) { + return iam(accessKeyId, "UpdateAccessKey", params); + } + + private static ValidatableResponse admin(String action, Map params) { + return iam(ACCOUNT, action, params); + } + + private static ValidatableResponse iam(String accessKeyId, String action, + Map params) { + RequestSpecification spec = given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId + + "/20261018/" + REGION + "/iam/aws4_request, SignedHeaders=host, " + + "Signature=abc") + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + params.forEach(spec::formParam); + return spec.when().post("/").then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java index 5495afbc45..5029dccc46 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java @@ -1,5 +1,6 @@ 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.storage.InMemoryStorage; import io.github.hectorvent.floci.services.iam.model.IamPolicy; @@ -15,6 +16,8 @@ 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.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.IntConsumer; import java.util.function.ToIntFunction; import java.util.stream.Stream; @@ -397,6 +400,175 @@ class IamConcurrencyTest { } } + @Test + void anUpdateCannotResurrectADeletedAccessKey() throws Exception { + // UpdateAccessKey reads a key, sets its status and writes it back, so without a lock the + // write lands after a delete that ran in between and the credential comes back. Measured + // at 80 of 2000 trials before the lock. + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + for (int trial = 0; trial < 2000; trial++) { + IamService iam = newIamService(); + iam.createUser("racer", "/"); + String keyId = iam.createAccessKey("racer").getAccessKeyId(); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(2); + List unexpected = new CopyOnWriteArrayList<>(); + + pool.execute(raceStep(start, done, unexpected, + () -> iam.updateAccessKey("racer", keyId, "Inactive"))); + pool.execute(raceStep(start, done, unexpected, + () -> iam.deleteAccessKey("racer", keyId))); + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "access key workers stalled"); + + if (!iam.listAccessKeys("racer").isEmpty() || !unexpected.isEmpty()) { + fail("access key trial " + trial + ": the deleted key is still listed" + + ", unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void concurrentAccessKeyCreatesStayInsideTheQuota() throws Exception { + // AccessKeysPerUser is 2, counted and then written, so without a lock four callers racing + // the count all pass it. Measured at 226 of 500 trials before the lock. + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + for (int trial = 0; trial < 500; trial++) { + IamService iam = newIamService(); + iam.createUser("racer", "/"); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(4); + List unexpected = new CopyOnWriteArrayList<>(); + + for (int i = 0; i < 4; i++) { + pool.execute(raceStep(start, done, unexpected, () -> iam.createAccessKey("racer"))); + } + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "access key workers stalled"); + + int stored = iam.listAccessKeys("racer").size(); + if (stored != 2 || !unexpected.isEmpty()) { + fail("access key quota trial " + trial + ": stored=" + stored + + " unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void aRenameCannotResurrectADeletedAccessKey() throws Exception { + // UpdateUser rewrites each key's owner. Reading that list before taking the lock lets a + // DeleteAccessKey land in between, and the loop then writes the deleted key back under the + // new name, where it authenticates again. + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + for (int trial = 0; trial < 2000; trial++) { + IamService iam = newIamService(); + iam.createUser("racer", "/"); + String keyId = iam.createAccessKey("racer").getAccessKeyId(); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(2); + List unexpected = new CopyOnWriteArrayList<>(); + AtomicBoolean deleted = new AtomicBoolean(); + + pool.execute(raceStep(start, done, unexpected, + () -> iam.updateUser("racer", "renamed", null))); + pool.execute(raceStep(start, done, unexpected, () -> { + iam.deleteAccessKey("racer", keyId); + deleted.set(true); + })); + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "rename workers stalled"); + + // The delete can lose the race, the key having moved to the new name before it + // looked, and then the key is meant to still be there. What may never happen is a + // delete that answered 200 and a key that is still stored. + boolean stored = iam.findUserNameByAccessKeyId(keyId).isPresent(); + if ((deleted.get() && stored) || !unexpected.isEmpty()) { + fail("rename trial " + trial + ": deleted=" + deleted.get() + + " stillStored=" + stored + " unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void anAccessKeyCannotBeCreatedForAUserBeingDeleted() throws Exception { + // CreateAccessKey confirming the user before taking the lock, and DeleteUser checking for + // keys without holding it, leaves the pair free to interleave: the create passes the check + // and stores a key for a user the delete has just removed. + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + for (int trial = 0; trial < 2000; trial++) { + IamService iam = newIamService(); + iam.createUser("racer", "/"); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(2); + List unexpected = new CopyOnWriteArrayList<>(); + AtomicReference created = new AtomicReference<>(); + + pool.execute(raceStep(start, done, unexpected, + () -> created.set(iam.createAccessKey("racer").getAccessKeyId()))); + pool.execute(raceStep(start, done, unexpected, () -> iam.deleteUser("racer"))); + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "delete-user workers stalled"); + + boolean userGone = userIsGone(iam); + boolean orphan = userGone && created.get() != null + && iam.findUserNameByAccessKeyId(created.get()).isPresent(); + if (orphan || !unexpected.isEmpty()) { + fail("delete-user trial " + trial + ": a key is stored for a user that is gone" + + ", unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + + private static boolean userIsGone(IamService iam) { + try { + iam.getUser("racer"); + return false; + } catch (AwsException e) { + return true; + } + } + + /** + * One racer: waits for the start, runs the step, and keeps any error that is not one of the + * refusals the race is allowed to produce, a key already gone, a quota already full or a user + * that still has a key when the delete looks. + */ + private static Runnable raceStep(CountDownLatch start, CountDownLatch done, + List unexpected, Runnable step) { + return () -> { + try { + start.await(10, TimeUnit.SECONDS); + step.run(); + } catch (AwsException e) { + if (!"NoSuchEntity".equals(e.getErrorCode()) + && !"LimitExceeded".equals(e.getErrorCode()) + && !"DeleteConflict".equals(e.getErrorCode())) { + unexpected.add(e.getErrorCode()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }; + } + private static String[] createPolicies(IamService iam, String prefix) { String[] arns = new String[N]; for (int i = 0; i < N; i++) { 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.java index 532d3229d8..e7968cd8e9 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 @@ -2030,6 +2030,52 @@ class IamServiceTest { assertTrue(iamService.listAccessKeys("alice").isEmpty()); } + @Test + void anAccessKeyTakesEveryStatusTheModelPublishes() { + // statusType is Active, Inactive or Expired, which is what the reference's Valid Values + // line on UpdateAccessKey lists, so Expired is a value to store rather than to refuse. + iamService.createUser("alice", "/"); + AccessKey key = iamService.createAccessKey("alice"); + + for (String status : List.of("Inactive", "Expired", "Active")) { + iamService.updateAccessKey("alice", key.getAccessKeyId(), status); + assertEquals(status, iamService.listAccessKeys("alice").getFirst().getStatus()); + } + } + + @Test + void anAccessKeyStatusIsReadBeforeTheKeyIsFound() { + // The key does not exist either, and the status is what answers: AWS reads a request's + // shape before it resolves anything, so the lookup's NoSuchEntity does not get there first. + iamService.createUser("alice", "/"); + + AwsException error = assertThrows(AwsException.class, + () -> iamService.updateAccessKey("alice", "AKIANOSUCHKEY00000", "Disabled")); + + assertEquals("ValidationError", error.getErrorCode()); + // The rendering the three sibling operations already answer with, taken from a recording + // of UpdateServiceSpecificCredential: AWS names neither the value nor the permitted set. + assertEquals("1 validation error detected: Value at 'status' failed to satisfy " + + "constraint: Member must satisfy enum value set", error.getMessage()); + } + + @Test + void anAbsentAccessKeyStatusIsAnsweredLikeAnInvalidOne() { + // The shared helper reads a null as a value outside the enum, which is how the other three + // statusType operations answer one. Changing that would change all four, so it stays. + iamService.createUser("alice", "/"); + AccessKey key = iamService.createAccessKey("alice"); + + AwsException error = assertThrows(AwsException.class, + () -> iamService.updateAccessKey("alice", key.getAccessKeyId(), null)); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals("1 validation error detected: Value at 'status' failed to satisfy " + + "constraint: Member must satisfy enum value set", error.getMessage()); + // And the key is as it was: the status is read before the lookup, so nothing is written. + assertEquals("Active", iamService.listAccessKeys("alice").getFirst().getStatus()); + } + @Test void aSessionWithNoRoleAndNoRecordedIssuerIsNoCredential() { // How GetSessionToken stored its sessions before it recorded the key that minted them. Such