diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamSigningCertificateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamSigningCertificateTest.java new file mode 100644 index 0000000000..1930f170c0 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamSigningCertificateTest.java @@ -0,0 +1,192 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.CreateUserRequest; +import software.amazon.awssdk.services.iam.model.DeleteSigningCertificateRequest; +import software.amazon.awssdk.services.iam.model.DeleteUserRequest; +import software.amazon.awssdk.services.iam.model.ListSigningCertificatesRequest; +import software.amazon.awssdk.services.iam.model.ListSigningCertificatesResponse; +import software.amazon.awssdk.services.iam.model.NoSuchEntityException; +import software.amazon.awssdk.services.iam.model.SigningCertificate; +import software.amazon.awssdk.services.iam.model.StatusType; +import software.amazon.awssdk.services.iam.model.UpdateSigningCertificateRequest; +import software.amazon.awssdk.services.iam.model.UploadSigningCertificateRequest; +import software.amazon.awssdk.services.iam.model.UploadSigningCertificateResponse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Signing certificates driven through the AWS SDK rather than hand-written requests. + * + *

This is the check the handcrafted XML assertions cannot make: the SDK parses the response + * against its own model, so a missing required member, a mis-named element or a timestamp in the + * wrong format fails here even though the raw XML looked right. The shape marks UserName, + * CertificateId, CertificateBody and Status required, and UploadDate is its only timestamp. + * + *

Status also round-trips through the SDK's {@code StatusType} enum, so a value the model does + * not know would surface as {@code UNKNOWN_TO_SDK_VERSION} rather than as a string that merely + * looked right on the wire. + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IamSigningCertificateTest { + + private static final String USER_NAME = "sdk-test-signing-user"; + + /** A real self-signed certificate, valid to 2036, generated with openssl. */ + private static final String CERT_PEM = """ + + -----BEGIN CERTIFICATE----- + MIIDDTCCAfWgAwIBAgIUQKw8vNoVuYpX79WK4/CF2csyLBYwDQYJKoZIhvcNAQEL + BQAwFjEUMBIGA1UEAwwLc2RrLnRlc3QuaW8wHhcNMjYxMDAzMDAxOTQ2WhcNMzYw + OTMwMDAxOTQ2WjAWMRQwEgYDVQQDDAtzZGsudGVzdC5pbzCCASIwDQYJKoZIhvcN + AQEBBQADggEPADCCAQoCggEBANya41O8oCtxTORSFpJGXD+8pfQDIa4zs1zyaKvf + 0OWLIRBBcOAbTRCo8vI8nziu4HOq/7RVK2lbRkd86hgvCmBW3TaTkg38AK6ynTtj + lgxwr9DyxGHewMANtZcf/uj0ypSrgqISp7VwiM3KRjTBEEGBUK0vxqsizS4i8cUs + 5IPkwtT0teubfFBv+/Dy5PKQpYCSKGpSfioqbPO3BG2MYhxTum52xwXNpq08slCn + kKBcboSJDkmAiy0bbjuBYd0X/zbFNiJL/e929mRucGDrCOb/xwzO3+sQQGMHOJ82 + gkM8qd2YnfaKQWjv6Ys2D2ScjhsoAIE/gk7acFEX+tZNje0CAwEAAaNTMFEwHQYD + VR0OBBYEFNCvcqlMKI/qgcPfKhsIfpyUq/YpMB8GA1UdIwQYMBaAFNCvcqlMKI/q + gcPfKhsIfpyUq/YpMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEB + AJykw94trHhwwaua0JI0mHv6YbBmUreuc1UDTzNW+yuoEGpWef3HkkNCn9XlLn2h + EZFQRtrLvvxqFwo9P97NX/ehSsqjnuUV5zPXPaQuydd4gOWUt8Ysq0eqIqzy28Pa + vQTrGPkPFcL3gll2lecvXZgLTJtQKSoM6VDkUO3cbSNWHeDFxr82NXGPEsRqlVTE + bQI1BNOypYjrtkmav2jlgWD0hIT2w54SxCoHldVcACrGeU9DHdVmQueXF+9uppAN + inCkDT+tT4RN7hcm72EKke95XQwh0IW7ibFklkapGzVPYLS1oDJg17aaI9Ob/xem + t2joILbhDvtwYcpNPaTAIdY= + -----END CERTIFICATE----- + """; + + private static IamClient iam; + private static String certificateId; + + @BeforeAll + static void setup() { + iam = TestFixtures.iamClient(); + cleanupUser(); + iam.createUser(CreateUserRequest.builder().userName(USER_NAME).build()); + } + + @AfterAll + static void cleanup() { + cleanupUser(); + } + + private static void cleanupUser() { + if (iam == null) { + return; + } + try { + ListSigningCertificatesResponse existing = iam.listSigningCertificates( + ListSigningCertificatesRequest.builder().userName(USER_NAME).build()); + for (SigningCertificate certificate : existing.certificates()) { + iam.deleteSigningCertificate(DeleteSigningCertificateRequest.builder() + .userName(USER_NAME) + .certificateId(certificate.certificateId()) + .build()); + } + iam.deleteUser(DeleteUserRequest.builder().userName(USER_NAME).build()); + } catch (NoSuchEntityException expected) { + // Nothing left over from an earlier run, which is the normal case. + } + } + + @Test + @Order(1) + @DisplayName("UploadSigningCertificate returns a parseable certificate with an Active status") + void upload() { + UploadSigningCertificateResponse response = iam.uploadSigningCertificate( + UploadSigningCertificateRequest.builder() + .userName(USER_NAME) + .certificateBody(CERT_PEM) + .build()); + + SigningCertificate certificate = response.certificate(); + assertNotNull(certificate, "the response must carry the certificate"); + assertEquals(USER_NAME, certificate.userName()); + assertEquals(StatusType.ACTIVE, certificate.status(), + "a newly uploaded certificate is Active"); + assertTrue(certificate.certificateBody().contains("BEGIN CERTIFICATE")); + assertNotNull(certificate.uploadDate(), "UploadDate must parse as a timestamp"); + assertNotNull(certificate.certificateId()); + assertTrue(certificate.certificateId().length() >= 24, + "certificateIdType has a minimum of 24: " + certificate.certificateId()); + + certificateId = certificate.certificateId(); + } + + @Test + @Order(2) + @DisplayName("ListSigningCertificates returns the uploaded certificate") + void list() { + ListSigningCertificatesResponse response = iam.listSigningCertificates( + ListSigningCertificatesRequest.builder().userName(USER_NAME).build()); + + assertEquals(1, response.certificates().size()); + SigningCertificate certificate = response.certificates().get(0); + assertEquals(certificateId, certificate.certificateId()); + assertEquals(USER_NAME, certificate.userName()); + assertNotNull(certificate.uploadDate()); + assertTrue(response.isTruncated() == null || !response.isTruncated()); + } + + @Test + @Order(3) + @DisplayName("UpdateSigningCertificate sets the status and the SDK reads it back as an enum") + void updateStatus() { + iam.updateSigningCertificate(UpdateSigningCertificateRequest.builder() + .userName(USER_NAME) + .certificateId(certificateId) + .status(StatusType.INACTIVE) + .build()); + + ListSigningCertificatesResponse response = iam.listSigningCertificates( + ListSigningCertificatesRequest.builder().userName(USER_NAME).build()); + assertEquals(StatusType.INACTIVE, response.certificates().get(0).status(), + "the status must come back as a value the SDK model knows"); + } + + @Test + @Order(4) + @DisplayName("UserName is optional: the operation resolves it from the signing credentials") + void userNameIsOptional() { + // Omitting UserName must reach the implied-caller resolution rather than fail for a + // missing parameter. The fixture signs with an access key that belongs to no stored IAM + // user, which that resolution reports as NoSuchEntity, so this is the error that proves + // the path ran: were UserName required, it would be a ValidationError instead. + NoSuchEntityException thrown = assertThrows(NoSuchEntityException.class, + () -> iam.listSigningCertificates(ListSigningCertificatesRequest.builder().build())); + assertTrue(thrown.getMessage().contains("Access Key"), + "the failure must come from resolving the key, not from a missing parameter: " + + thrown.getMessage()); + } + + @Test + @Order(5) + @DisplayName("DeleteSigningCertificate removes it, and an unknown id is NoSuchEntity") + void delete() { + iam.deleteSigningCertificate(DeleteSigningCertificateRequest.builder() + .userName(USER_NAME) + .certificateId(certificateId) + .build()); + + ListSigningCertificatesResponse response = iam.listSigningCertificates( + ListSigningCertificatesRequest.builder().userName(USER_NAME).build()); + assertTrue(response.certificates().isEmpty()); + + assertThrows(NoSuchEntityException.class, () -> iam.deleteSigningCertificate( + DeleteSigningCertificateRequest.builder() + .userName(USER_NAME) + .certificateId(certificateId) + .build())); + } +} diff --git a/docs/services/iam.md b/docs/services/iam.md index 1684904cdb..753dbfb598 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -578,6 +578,52 @@ Classic and CloudFront store certificate identifiers without resolving them agai [#4875](https://github.com/floci-io/floci/issues/4875), which covers both directions: rejecting a reference to a certificate that does not exist, and refusing to delete one that is in use. +### Signing Certificates + +| Action | Description | +|--------|-------------| +| UploadSigningCertificate | Stores an X.509 signing certificate against an IAM user and returns its generated `CertificateId`. | +| ListSigningCertificates | Lists a user's signing certificates, with `Marker` and `MaxItems` paging. | +| UpdateSigningCertificate | Sets a certificate's status to `Active`, `Inactive` or `Expired`. | +| DeleteSigningCertificate | Deletes one of a user's signing certificates. | + +A signing certificate is not a server certificate: it belongs to a user rather than the account, it +carries no private key, no name and no path, and the generated `CertificateId` is the only handle +to it. The body is parsed on upload, because `MalformedCertificate` cannot be answered without +reading the material, and the status starts as `Active`. + +`UserName` is optional on all four operations. Left out, it resolves to the user owning the access +key that signed the request, which is what the model documents. + +Two certificates per user, which the User Guide states directly: "Users can have up to two X.509 +signing certificates, to make certificate rotation easier". A third upload is `LimitExceeded`. The +count is taken inside the same lock as the write, so concurrent uploads cannot both see room for +the last slot. + +`DuplicateCertificate` is account-wide rather than per user: AWS describes it as "the same +certificate is associated with an IAM user in the account", so a second user cannot upload material +the first already holds. The comparison is made on the encoded certificate rather than the PEM +text, so the same certificate re-wrapped or re-indented still counts as the same one. + +`UpdateSigningCertificate` accepts `Expired` as well as `Active` and `Inactive`. The parameter's +prose explains only the first two, but the API Reference gives all three as valid values. + +A signing certificate blocks `DeleteUser` until it is removed, which is one of the items AWS lists +as a prerequisite for deleting a user programmatically. It also follows the user across an +`UpdateUser` rename: left behind, a certificate would be stranded on a name that no longer exists, +invisible to its owner because listing goes through the user. + +The credential report's `cert_1_active` and `cert_2_active` columns are backed by this store +instead of always reporting `FALSE`. The matching `cert_*_last_rotated` columns report the upload +date, and `N/A` when the certificate is not `Active`, which is how the User Guide defines them. +`GetAccountSummary`'s `AccountSigningCertificatesPresent` is unaffected: it reports the account root +user's certificates, and Floci does not model root credentials. + +Under [enforcement](#iam-enforcement-mode) these actions are evaluated against `*` rather than the +owning user's ARN, along with every other IAM action except the server-certificate operations. That +is the general gap tracked in [#4979](https://github.com/floci-io/floci/issues/4979), not something +specific to signing certificates. + ## AWS Managed Policies Floci seeds a catalog of commonly-used AWS managed policies at startup. These are attachable immediately without any setup: diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 07afc66c14..c8db010ae2 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -118,7 +118,9 @@ public class AwsQueryController { "TagServerCertificate", "UntagServerCertificate", "ListServerCertificateTags", "CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices", "EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices", - "TagMFADevice", "UntagMFADevice", "ListMFADeviceTags" + "TagMFADevice", "UntagMFADevice", "ListMFADeviceTags", + "UploadSigningCertificate", "ListSigningCertificates", + "UpdateSigningCertificate", "DeleteSigningCertificate" ); private static final Set AUTOSCALING_ACTIONS = Set.of( 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 4eea620720..f83e3f3742 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 @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider; 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.ServerCertificate; +import io.github.hectorvent.floci.services.iam.model.SigningCertificate; 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; @@ -91,6 +92,10 @@ public class IamQueryHandler { case "DeleteUser" -> handleDeleteUser(params); case "ListUsers" -> handleListUsers(params); case "UpdateUser" -> handleUpdateUser(params); + case "UploadSigningCertificate" -> handleUploadSigningCertificate(params, authorization); + case "ListSigningCertificates" -> handleListSigningCertificates(params, authorization); + case "UpdateSigningCertificate" -> handleUpdateSigningCertificate(params, authorization); + case "DeleteSigningCertificate" -> handleDeleteSigningCertificate(params, authorization); case "TagUser" -> handleTagUser(params); case "UntagUser" -> handleUntagUser(params); case "ListUserTags" -> handleListUserTags(params); @@ -751,6 +756,63 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, xml.build())).build(); } + /** + * UserName is optional on every signing-certificate operation: the model says it is determined + * implicitly from the access key that signed the request. + */ + private Response handleUploadSigningCertificate(MultivaluedMap params, + String authorization) { + SigningCertificate certificate = iamService.uploadSigningCertificate( + resolveUserName(params, authorization), getParam(params, "CertificateBody")); + XmlBuilder xml = new XmlBuilder() + .start("Certificate").raw(signingCertificateXml(certificate)).end("Certificate"); + return Response.ok(AwsQueryResponse.envelope("UploadSigningCertificate", + AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleListSigningCertificates(MultivaluedMap params, + String authorization) { + Page page = paginate( + iamService.listSigningCertificates(resolveUserName(params, authorization)), params); + XmlBuilder xml = new XmlBuilder().start("Certificates"); + for (SigningCertificate certificate : page.items()) { + xml.start("member").raw(signingCertificateXml(certificate)).end("member"); + } + xml.end("Certificates").elem("IsTruncated", page.truncated()); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("ListSigningCertificates", + AwsNamespaces.IAM, xml.build())).build(); + } + + private Response handleUpdateSigningCertificate(MultivaluedMap params, + String authorization) { + iamService.updateSigningCertificate(resolveUserName(params, authorization), + requireParam(params, "CertificateId"), getParam(params, "Status")); + return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateSigningCertificate", + AwsNamespaces.IAM)).build(); + } + + private Response handleDeleteSigningCertificate(MultivaluedMap params, + String authorization) { + iamService.deleteSigningCertificate(resolveUserName(params, authorization), + requireParam(params, "CertificateId")); + return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteSigningCertificate", + AwsNamespaces.IAM)).build(); + } + + /** The four members the model marks required, plus UploadDate. */ + private String signingCertificateXml(SigningCertificate certificate) { + return new XmlBuilder() + .elem("UserName", certificate.getUserName()) + .elem("CertificateId", certificate.getCertificateId()) + .elem("CertificateBody", certificate.getCertificateBody()) + .elem("Status", certificate.getStatus()) + .elem("UploadDate", isoDate(certificate.getUploadDate())) + .build(); + } + private Response handleTagServerCertificate(MultivaluedMap params) { iamService.tagServerCertificate(getParam(params, "ServerCertificateName"), extractTags(params, false)); return Response.ok(AwsQueryResponse.envelopeNoResult("TagServerCertificate", 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 c5b3c872f0..a5875b1d35 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 @@ -31,6 +31,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.ServerCertificate; +import io.github.hectorvent.floci.services.iam.model.SigningCertificate; 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; @@ -44,10 +45,12 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.SecureRandom; +import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; +import java.util.Arrays; import java.util.Base64; import java.util.Comparator; import java.util.Optional; @@ -143,6 +146,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * the maximum it can be raised to, so this is a real ceiling rather than a default. */ private static final int MAX_SERVER_CERTIFICATES = 20; + /** IAM User Guide quota table, and GetAccountSummary's SigningCertificatesPerUserQuota. */ + private static final int MAX_SIGNING_CERTIFICATES_PER_USER = 2; + /** certificateIdType is 24 to 128 of [\w]+, so a 32-character id sits inside that. */ + private static final int SIGNING_CERTIFICATE_ID_LENGTH = 32; + private static final String SIGNING_CERTIFICATE_ACTIVE = "Active"; + /** + * UpdateSigningCertificate's Status, whose documented valid values are Active, Inactive and + * Expired. The prose explains only the first two, so the third is easy to reject by mistake. + */ + private static final Set SIGNING_CERTIFICATE_STATUSES = + Set.of(SIGNING_CERTIFICATE_ACTIVE, "Inactive", "Expired"); /** {@code certificateBodyType} and {@code privateKeyType} are both 1 to 16384 characters. */ private static final int MAX_CERTIFICATE_BODY_LENGTH = 16384; /** {@code certificateChainType} is far larger, at 1 to 2097152. */ @@ -217,12 +231,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private final StorageBackend virtualMfaDevices; /** Server certificates, keyed by name, which is unique within the account. */ private final StorageBackend serverCertificates; + private final StorageBackend signingCertificates; /** * Guards the check-then-write on a server certificate. Upload checks the name is free before * storing, and UpdateServerCertificate checks a new name is free before moving to it, so two * requests racing the same name would otherwise both pass the check. */ private final Object serverCertificateLock = new Object(); + private final Object signingCertificateLock = 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 @@ -264,6 +280,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { storageFactory.create("iam", "iam-credential-reports.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-virtual-mfa-devices.json", new TypeReference<>() {}), storageFactory.create("iam", "iam-server-certificates.json", new TypeReference<>() {}), + storageFactory.create("iam", "iam-signing-certificates.json", new TypeReference<>() {}), regionResolver, config.services().iam().seedDeployerPrincipal(), config.services().iam().accountAlias().orElse(null) @@ -294,6 +311,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null); } @@ -316,8 +334,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions, accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders, serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, - seedDeployerPrincipal, seededAccountAlias); + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + regionResolver, seedDeployerPrincipal, seededAccountAlias); } // 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests; @@ -337,6 +355,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null); } @@ -356,6 +375,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { StorageBackend credentialReports, StorageBackend virtualMfaDevices, StorageBackend serverCertificates, + StorageBackend signingCertificates, RegionResolver regionResolver, boolean seedDeployerPrincipal, String seededAccountAlias) { @@ -375,6 +395,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { this.credentialReports = credentialReports; this.virtualMfaDevices = virtualMfaDevices; this.serverCertificates = serverCertificates; + this.signingCertificates = signingCertificates; this.regionResolver = regionResolver; this.seedDeployerPrincipal = seedDeployerPrincipal; this.seededAccountAlias = seededAccountAlias; @@ -549,14 +570,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider { throw new AwsException("DeleteConflict", "Cannot delete entity, must delete access keys first.", 409); } - // 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()) { + // Both locks are held across the delete rather than just the checks: UploadSigningCertificate + // and EnableMFADevice confirm the user under their own lock, so neither can interleave into + // a credential owned by a deleted user. Taken in this order, and nowhere else in both, so + // the nesting cannot deadlock. + 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); } LOG.infov("Deleted IAM user: {0}", userName); } @@ -594,22 +623,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider { "User with name " + newUserName + " already exists.", 409); } List keysToMove = userAccessKeys(userName); - // 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)); + // The rename publishes the user under its new name and moves the credentials that + // DeleteUser refuses to delete a user over: its MFA devices and its signing + // certificates. Each moves under the lock DeleteUser checks it with, because split + // across that lock a DeleteUser for the new name could land after the user is + // published but before the credential follows, see none, and delete a user whose + // credential is about to be reassigned to it. The two locks are taken in the same + // order DeleteUser takes them, so the nesting cannot deadlock. + synchronized (signingCertificateLock) { + List certificatesToMove = userSigningCertificates(userName); + 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); + } } - 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); + for (SigningCertificate certificate : certificatesToMove) { + certificate.setUserName(newUserName); + signingCertificates.put(certificate.getCertificateId(), certificate); } } loginProfiles.get(userName).ifPresent(profile -> { @@ -2290,6 +2328,133 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return getServerCertificate(name).getTags(); } + // Signing certificates + // ========================================================================= + + /** + * Stores an uploaded X.509 signing certificate against a user. The body is really parsed, so a + * caller cannot store something unusable: the model defines MalformedCertificate on this + * operation and it cannot be answered without reading the material. + * + *

Unlike a server certificate there is no private key and no name. The generated + * {@code CertificateId} is the handle, and its status starts as {@code Active}. + */ + public SigningCertificate uploadSigningCertificate(String userName, String certificateBody) { + if (certificateBody == null || certificateBody.isBlank()) { + throw new AwsException("ValidationError", + "The request must contain the parameter CertificateBody.", 400); + } + checkMaterialLength(certificateBody, "CertificateBody", MAX_CERTIFICATE_BODY_LENGTH); + X509Certificate parsed = parseUploadedCertificate(certificateBody, "CertificateBody"); + synchronized (signingCertificateLock) { + // Confirmed under the lock, not before it: DeleteUser checks for certificates holding + // the same lock, so the two cannot interleave into a certificate owned by a user that + // no longer exists. + getUser(userName); + // Counted inside the lock with the write, so two concurrent uploads cannot both see + // room for one more. + if (userSigningCertificates(userName).size() >= MAX_SIGNING_CERTIFICATES_PER_USER) { + throw new AwsException("LimitExceeded", + "Cannot exceed quota for SigningCertificatesPerUser: " + + MAX_SIGNING_CERTIFICATES_PER_USER, 409); + } + // The model's DuplicateCertificate is account-wide, not per user: "the same + // certificate is associated with an IAM user in the account". + if (storedSigningCertificateMatching(parsed)) { + throw new AwsException("DuplicateCertificate", + "The same certificate is associated with an IAM user in the account.", 409); + } + SigningCertificate stored = new SigningCertificate(); + stored.setUserName(userName); + stored.setCertificateId(randomId(SIGNING_CERTIFICATE_ID_LENGTH)); + stored.setCertificateBody(certificateBody); + stored.setStatus(SIGNING_CERTIFICATE_ACTIVE); + stored.setUploadDate(Instant.now()); + signingCertificates.put(stored.getCertificateId(), stored); + LOG.infov("Uploaded signing certificate {0} for user {1}", + stored.getCertificateId(), userName); + return stored; + } + } + + public List listSigningCertificates(String userName) { + getUser(userName); // validates existence + return userSigningCertificates(userName); + } + + public void updateSigningCertificate(String userName, String certificateId, String status) { + if (status == null || !SIGNING_CERTIFICATE_STATUSES.contains(status)) { + throw new AwsException("ValidationError", + "Value '" + status + "' at 'status' failed to satisfy constraint: Member must " + + "satisfy enum value set: [" + String.join(", ", + SIGNING_CERTIFICATE_STATUSES) + "]", 400); + } + synchronized (signingCertificateLock) { + SigningCertificate certificate = userSigningCertificate(userName, certificateId); + certificate.setStatus(status); + signingCertificates.put(certificate.getCertificateId(), certificate); + } + } + + public void deleteSigningCertificate(String userName, String certificateId) { + synchronized (signingCertificateLock) { + SigningCertificate certificate = userSigningCertificate(userName, certificateId); + signingCertificates.delete(certificate.getCertificateId()); + } + } + + /** + * The user's certificate of that id. A certificate belonging to another user is reported as + * missing rather than as a permission problem, the way an access key of another user is. + */ + private SigningCertificate userSigningCertificate(String userName, String certificateId) { + getUser(userName); // validates existence + SigningCertificate certificate = signingCertificates.get(certificateId) + .orElseThrow(() -> new AwsException("NoSuchEntity", + "The Signing Certificate with id " + certificateId + + " cannot be found.", 404)); + if (!userName.equals(certificate.getUserName())) { + throw new AwsException("NoSuchEntity", + "The Signing Certificate with id " + certificateId + + " cannot be found.", 404); + } + return certificate; + } + + private List userSigningCertificates(String userName) { + return signingCertificates.scan(key -> true).stream() + .filter(certificate -> userName.equals(certificate.getUserName())) + .sorted(Comparator.comparing(SigningCertificate::getCertificateId)) + .toList(); + } + + /** + * Whether an equivalent certificate is already stored in this account, compared on the encoded + * form rather than the PEM text so that the same certificate re-wrapped or re-indented still + * counts as the same one. + */ + private boolean storedSigningCertificateMatching(X509Certificate candidate) { + byte[] encoded; + try { + encoded = candidate.getEncoded(); + } catch (CertificateEncodingException e) { + // A certificate that just parsed should always re-encode. Treating it as unique is the + // safe direction: it refuses nothing the model accepts. + LOG.debugv("Could not re-encode an uploaded signing certificate: {0}", e.getMessage()); + return false; + } + return signingCertificates.scan(key -> true).stream().anyMatch(stored -> { + try { + return Arrays.equals(encoded, + Pem.parseCertificate(stored.getCertificateBody()).getEncoded()); + } catch (CertificateMaterialException | CertificateEncodingException e) { + LOG.debugv("Skipping unreadable stored signing certificate {0}: {1}", + stored.getCertificateId(), e.getMessage()); + return false; + } + }); + } + // Virtual MFA devices // ========================================================================= @@ -3801,6 +3966,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider { List keys = userAccessKeys(user.getUserName()); AccessKey key1 = keys.size() > 0 ? keys.get(0) : null; AccessKey key2 = keys.size() > 1 ? keys.get(1) : null; + List certificates = userSigningCertificates(user.getUserName()); + SigningCertificate cert1 = certificates.size() > 0 ? certificates.get(0) : null; + SigningCertificate cert2 = certificates.size() > 1 ? certificates.get(1) : null; Optional loginProfile = loginProfiles.get(user.getUserName()); boolean passwordEnabled = loginProfile.isPresent(); @@ -3815,7 +3983,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { 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", + signingCertificateActiveField(cert1), signingCertificateRotatedField(cert1), + signingCertificateActiveField(cert2), signingCertificateRotatedField(cert2), additionalCredentialsInfoField(keys)); } @@ -3853,6 +4022,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return profile.getPasswordLastChanged() != null ? profile.getPasswordLastChanged() : profile.getCreateDate(); } + private String signingCertificateActiveField(SigningCertificate certificate) { + return certificate != null && SIGNING_CERTIFICATE_ACTIVE.equals(certificate.getStatus()) + ? "TRUE" : "FALSE"; + } + + /** + * The upload date, and {@code N/A} unless the certificate is Active. The User Guide is + * explicit that this column is N/A when the user "does not have an active signing + * certificate", so an Inactive certificate reports no date even though one is stored. + * + *

It describes the date the certificate "was created or last changed". Floci records only + * the upload, which is the one of those two it can know: a status change rewrites no material. + */ + private String signingCertificateRotatedField(SigningCertificate certificate) { + return certificate != null + && SIGNING_CERTIFICATE_ACTIVE.equals(certificate.getStatus()) + ? isoDate(certificate.getUploadDate()) : "N/A"; + } + private String accessKeyActiveField(AccessKey key) { return key != null && "Active".equals(key.getStatus()) ? "TRUE" : "FALSE"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SigningCertificate.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SigningCertificate.java new file mode 100644 index 0000000000..676582186f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SigningCertificate.java @@ -0,0 +1,38 @@ +package io.github.hectorvent.floci.services.iam.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * An IAM X.509 signing certificate, owned by one IAM user. Unlike a server certificate it has no + * name, no path and no private key: AWS stores only the certificate body, and the generated + * {@code certificateId} is what every later operation addresses it by. + * + *

{@code status} is {@code Active} on upload, which is what the model documents. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SigningCertificate { + private String userName; + private String certificateId; + private String certificateBody; + private String status = "Active"; + private Instant uploadDate = Instant.now(); + + public SigningCertificate() {} + + public String getUserName() { return userName; } + public void setUserName(String userName) { this.userName = userName; } + public String getCertificateId() { return certificateId; } + public void setCertificateId(String certificateId) { this.certificateId = certificateId; } + public String getCertificateBody() { return certificateBody; } + public void setCertificateBody(String certificateBody) { + this.certificateBody = certificateBody; + } + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + public Instant getUploadDate() { return uploadDate; } + public void setUploadDate(Instant uploadDate) { this.uploadDate = uploadDate; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServicePersistenceTest.java index 3b3b5e7e07..47f2d11385 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 @@ -231,6 +231,7 @@ class IamServicePersistenceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), devices, new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false, null); } 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 9738060862..69073f685a 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 @@ -2305,6 +2305,7 @@ class IamServiceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), false, null); AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport); @@ -2323,6 +2324,7 @@ class IamServiceTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(), new InMemoryStorage<>(), + 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/ServerCertificateStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java index e249bfe171..57af3db77d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java @@ -79,6 +79,7 @@ class ServerCertificateStateTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), certificates, + new InMemoryStorage<>(), new RegionResolver("us-east-1", defaultAccount), false, null); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java new file mode 100644 index 0000000000..b82ed67432 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java @@ -0,0 +1,367 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.services.acm.CertificateGenerator; +import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The signing-certificate lifecycle over the wire. Material is generated rather than hardcoded, so + * the upload path reads real X.509 and the rejection paths reject things that genuinely are not. + * + *

IAM state is shared across the suite, so every test makes its own user. The per-user quota is + * only two certificates, which is small enough to exercise here without starving anything else: + * each test owns its user, so it owns that user's whole budget. + */ +@QuarkusTest +class SigningCertificateIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + private static final CertificateGenerator GENERATOR = new CertificateGenerator(); + + 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); + } + + /** EC rather than RSA: these tests generate a lot of material and never check the algorithm. */ + private static String certificatePem() { + return GENERATOR.generateSelfSignedCertificate( + "signing.test.local", List.of(), KeyAlgorithm.EC_prime256v1).certificatePem(); + } + + private static String user() { + String name = "signing-user-" + suffix(); + iam("CreateUser").formParam("UserName", name) + .when().post("/").then().statusCode(200); + return name; + } + + private static String upload(String userName, String body) { + return iam("UploadSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateBody", body) + .when().post("/").then().statusCode(200) + .extract().path("UploadSigningCertificateResponse.UploadSigningCertificateResult" + + ".Certificate.CertificateId"); + } + + @Test + void uploadReturnsTheCertificateWithAnActiveStatusAndAModelShapedId() { + String userName = user(); + String body = certificatePem(); + + String id = iam("UploadSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateBody", body) + .when().post("/").then().statusCode(200) + .body("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate" + + ".UserName", equalTo(userName)) + .body("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate" + + ".Status", equalTo("Active")) + .body("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate" + + ".CertificateBody", containsString("BEGIN CERTIFICATE")) + .extract().path("UploadSigningCertificateResponse.UploadSigningCertificateResult" + + ".Certificate.CertificateId"); + + assertNotNull(id); + // certificateIdType: 24 to 128 characters of [\w]+. + assertTrue(id.length() >= 24 && id.length() <= 128, "id length: " + id.length()); + assertTrue(id.matches("\\w+"), "id must be word characters only: " + id); + } + + @Test + void theUploadDateIsReturned() { + String userName = user(); + upload(userName, certificatePem()); + + iam("ListSigningCertificates").formParam("UserName", userName) + .when().post("/").then().statusCode(200) + .body("ListSigningCertificatesResponse.ListSigningCertificatesResult.Certificates" + + ".member.UploadDate", containsString("T")); + } + + @Test + void listReturnsTheUsersCertificatesAndNoOneElses() { + String mine = user(); + String theirs = user(); + String myId = upload(mine, certificatePem()); + String theirId = upload(theirs, certificatePem()); + + iam("ListSigningCertificates").formParam("UserName", mine) + .when().post("/").then().statusCode(200) + .body(containsString(myId)) + .body(not(containsString(theirId))); + } + + @Test + void theStatusCanBeSetToEveryDocumentedValue() { + String userName = user(); + String id = upload(userName, certificatePem()); + + // The API Reference gives Active, Inactive and Expired as the valid values, even though + // the prose only explains the first two. + for (String status : List.of("Inactive", "Expired", "Active")) { + iam("UpdateSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateId", id) + .formParam("Status", status) + .when().post("/").then().statusCode(200); + + iam("ListSigningCertificates").formParam("UserName", userName) + .when().post("/").then().statusCode(200) + .body("ListSigningCertificatesResponse.ListSigningCertificatesResult.Certificates" + + ".member.Status", equalTo(status)); + } + } + + @Test + void anUnknownStatusIsRejected() { + String userName = user(); + String id = upload(userName, certificatePem()); + + iam("UpdateSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateId", id) + .formParam("Status", "Revoked") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")); + } + + @Test + void deleteRemovesIt() { + String userName = user(); + String id = upload(userName, certificatePem()); + + iam("DeleteSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateId", id) + .when().post("/").then().statusCode(200); + + iam("ListSigningCertificates").formParam("UserName", userName) + .when().post("/").then().statusCode(200) + .body(not(containsString(id))); + } + + @Test + void malformedMaterialIsRejectedAsMalformedCertificate() { + String userName = user(); + + iam("UploadSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateBody", "-----BEGIN CERTIFICATE-----\nnot base64\n" + + "-----END CERTIFICATE-----\n") + .when().post("/").then().statusCode(400) + .body(containsString("MalformedCertificate")); + } + + @Test + void anAbsentBodyIsRejected() { + String userName = user(); + + iam("UploadSigningCertificate").formParam("UserName", userName) + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")); + } + + /** certificateBodyType caps the body at 16384, which is a request-shape error, not bad PEM. */ + @Test + void anOverLongBodyIsRejectedBeforeItIsParsed() { + String userName = user(); + + iam("UploadSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateBody", "A".repeat(16385)) + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")); + } + + /** "Users can have up to two X.509 signing certificates", per the User Guide. */ + @Test + void aThirdCertificateExceedsThePerUserQuota() { + String userName = user(); + upload(userName, certificatePem()); + upload(userName, certificatePem()); + + iam("UploadSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateBody", certificatePem()) + .when().post("/").then().statusCode(409) + .body(containsString("LimitExceeded")) + .body(containsString("SigningCertificatesPerUser")); + } + + /** + * DuplicateCertificate is account-wide: "the same certificate is associated with an IAM user in + * the account", so a second user uploading the same material is refused too. + */ + @Test + void theSameCertificateCannotBeUploadedTwiceInTheAccount() { + String first = user(); + String second = user(); + String body = certificatePem(); + upload(first, body); + + iam("UploadSigningCertificate") + .formParam("UserName", second) + .formParam("CertificateBody", body) + .when().post("/").then().statusCode(409) + .body(containsString("DuplicateCertificate")); + } + + /** + * The duplicate check compares the encoded certificate rather than the PEM text, so the same + * certificate re-wrapped is still the same certificate. + */ + @Test + void aReindentedCopyOfTheSameCertificateIsStillADuplicate() { + String userName = user(); + String body = certificatePem(); + upload(userName, body); + + // Same DER, different surrounding whitespace. + String reindented = body.replace("\n", "\r\n") + "\n"; + iam("UploadSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateBody", reindented) + .when().post("/").then().statusCode(409) + .body(containsString("DuplicateCertificate")); + } + + @Test + void aCertificateOfAnotherUserCannotBeUpdatedOrDeleted() { + String owner = user(); + String other = user(); + String id = upload(owner, certificatePem()); + + iam("UpdateSigningCertificate") + .formParam("UserName", other) + .formParam("CertificateId", id) + .formParam("Status", "Inactive") + .when().post("/").then().statusCode(404) + .body(containsString("NoSuchEntity")); + + iam("DeleteSigningCertificate") + .formParam("UserName", other) + .formParam("CertificateId", id) + .when().post("/").then().statusCode(404) + .body(containsString("NoSuchEntity")); + } + + @Test + void anUnknownUserIsNoSuchEntity() { + iam("ListSigningCertificates").formParam("UserName", "absent-" + suffix()) + .when().post("/").then().statusCode(404) + .body(containsString("NoSuchEntity")); + } + + /** + * CertificateId is required on both operations. Omitted, it must be a validation error: the + * store is a map that rejects a null key, so passing it through would surface as an unhandled + * failure rather than as the error the model defines. + */ + @Test + void anAbsentCertificateIdIsAValidationError() { + String userName = user(); + + iam("DeleteSigningCertificate").formParam("UserName", userName) + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("certificateId")); + + // Update validates the status first, so this only reaches the lookup with a valid one. + iam("UpdateSigningCertificate") + .formParam("UserName", userName) + .formParam("Status", "Inactive") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("certificateId")); + } + + @Test + void anUnknownCertificateIdIsNoSuchEntity() { + String userName = user(); + + iam("DeleteSigningCertificate") + .formParam("UserName", userName) + .formParam("CertificateId", "ABSENTCERTIFICATEID0000000000") + .when().post("/").then().statusCode(404) + .body(containsString("NoSuchEntity")); + } + + /** + * UserName is optional on every one of these operations: the model determines it from the + * access key that signed the request. Signing as the user's own key must reach the user's own + * certificates without naming them. + */ + @Test + void theUserNameIsImpliedFromTheSigningAccessKey() { + String userName = user(); + String id = upload(userName, certificatePem()); + String akid = iam("CreateAccessKey").formParam("UserName", userName) + .when().post("/").then().statusCode(200) + .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"); + + given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + akid + + "/20260227/us-east-1/iam/aws4_request") + .formParam("Action", "ListSigningCertificates") + .when().post("/").then().statusCode(200) + .body(containsString(id)) + .body("ListSigningCertificatesResponse.ListSigningCertificatesResult.Certificates" + + ".member.UserName", equalTo(userName)); + } + + @Test + void listHonoursMaxItemsAndMarker() { + String userName = user(); + upload(userName, certificatePem()); + upload(userName, certificatePem()); + + String marker = iam("ListSigningCertificates") + .formParam("UserName", userName) + .formParam("MaxItems", "1") + .when().post("/").then().statusCode(200) + .body("ListSigningCertificatesResponse.ListSigningCertificatesResult.IsTruncated", + equalTo("true")) + .extract().path("ListSigningCertificatesResponse.ListSigningCertificatesResult.Marker"); + + assertNotNull(marker, "a truncated page must carry a marker"); + iam("ListSigningCertificates") + .formParam("UserName", userName) + .formParam("Marker", marker) + .when().post("/").then().statusCode(200) + .body("ListSigningCertificatesResponse.ListSigningCertificatesResult.IsTruncated", + equalTo("false")); + } + + /** + * Without an Authorization header the Query controller infers the service from the action name + * alone, so these have to be in its IAM set or they fall through to SQS and come back + * UnsupportedOperation. The IAM namespace on the error is what proves the routing. + */ + @Test + void certificateActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() { + for (String action : List.of("UploadSigningCertificate", "ListSigningCertificates", + "UpdateSigningCertificate", "DeleteSigningCertificate")) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2010-05-08") + .when().post("/").then() + .body(containsString("iam.amazonaws.com/doc/2010-05-08")); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java new file mode 100644 index 0000000000..cd90a40671 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateStateTest.java @@ -0,0 +1,417 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.core.type.TypeReference; +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.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.acm.CertificateGenerator; +import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; +import io.github.hectorvent.floci.services.iam.model.CredentialReport; +import io.github.hectorvent.floci.services.iam.model.IamUser; +import io.github.hectorvent.floci.services.iam.model.SigningCertificate; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The properties of the signing-certificate store the wire tests cannot reach: that it survives a + * restart, that one account cannot see another's, that the quota holds when uploads race, and that + * the credentials a user owns follow the user through a rename and block a delete. + */ +class SigningCertificateStateTest { + + private static final String ACCOUNT_A = "000000000000"; + private static final String ACCOUNT_B = "111111111111"; + private static final CertificateGenerator GENERATOR = new CertificateGenerator(); + + /** EC: these tests exercise locking and storage, never the key algorithm. */ + private static String certificatePem() { + return GENERATOR.generateSelfSignedCertificate( + "state.test.local", List.of(), KeyAlgorithm.EC_prime256v1).certificatePem(); + } + + @SuppressWarnings("unchecked") + private static Instance requestContextFor(AtomicReference accountId) { + RequestContext rc = mock(RequestContext.class); + when(rc.getAccountId()).thenAnswer(invocation -> accountId.get()); + Instance inst = mock(Instance.class); + when(inst.get()).thenReturn(rc); + return inst; + } + + private static IamService newService(StorageBackend certificates, + String defaultAccount) { + 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 InMemoryStorage<>(), + certificates, + new RegionResolver("us-east-1", defaultAccount), false, null); + } + + private static IamService newService(StorageBackend users, + StorageBackend reports, + StorageBackend certificates, + String defaultAccount) { + 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<>(), reports, new InMemoryStorage<>(), + new InMemoryStorage<>(), + certificates, + new RegionResolver("us-east-1", defaultAccount), false, null); + } + + @Test + void aCertificateSurvivesARestart(@TempDir Path dir) { + Path file = dir.resolve("signing-certificates.json"); + String body = certificatePem(); + + PersistentStorage first = + new PersistentStorage<>(file, new TypeReference<>() {}); + first.load(); + IamService before = newService(first, ACCOUNT_A); + before.createUser("restart-user", "/"); + String id = before.uploadSigningCertificate("restart-user", body).getCertificateId(); + before.updateSigningCertificate("restart-user", id, "Inactive"); + + PersistentStorage second = + new PersistentStorage<>(file, new TypeReference<>() {}); + second.load(); + IamService after = newService(second, ACCOUNT_A); + after.createUser("restart-user", "/"); + List reloaded = after.listSigningCertificates("restart-user"); + + assertEquals(1, reloaded.size()); + assertEquals(id, reloaded.getFirst().getCertificateId()); + assertEquals(body, reloaded.getFirst().getCertificateBody()); + // The status is the part most likely to be dropped on the way through, because a default + // of Active would hide the loss. + assertEquals("Inactive", reloaded.getFirst().getStatus()); + } + + @Test + void oneAccountCannotSeeAnothersCertificates() { + AtomicReference account = new AtomicReference<>(ACCOUNT_A); + AccountAwareStorageBackend store = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A); + IamService service = newService(store, ACCOUNT_A); + + service.createUser("shared-name", "/"); + service.uploadSigningCertificate("shared-name", certificatePem()); + assertEquals(1, service.listSigningCertificates("shared-name").size()); + + // The users store here is not account-aware, so the user is already present under the + // same name. That is what makes this discriminating: only the certificate store is + // scoped, so a leak would show up as account B seeing A's certificate. + account.set(ACCOUNT_B); + assertEquals(0, service.listSigningCertificates("shared-name").size(), + "account B must not see account A's certificate"); + + // And B filling its own quota must not be refused because A already has certificates. + service.uploadSigningCertificate("shared-name", certificatePem()); + service.uploadSigningCertificate("shared-name", certificatePem()); + assertEquals(2, service.listSigningCertificates("shared-name").size()); + + account.set(ACCOUNT_A); + assertEquals(1, service.listSigningCertificates("shared-name").size(), + "account A's view must be unchanged by account B's uploads"); + } + + /** + * The quota is counted inside the same lock as the write, so concurrent uploads cannot both + * see room for the second-to-last slot. Asserted by counting what actually succeeded, because + * an invariant phrased as "the store holds at most two" passes even with the lock removed. + */ + @Test + void concurrentUploadsCannotExceedTheQuota() throws Exception { + IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A); + service.createUser("race-user", "/"); + + int attempts = 12; + List bodies = new ArrayList<>(); + for (int i = 0; i < attempts; i++) { + bodies.add(certificatePem()); + } + ExecutorService pool = Executors.newFixedThreadPool(attempts); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger accepted = new AtomicInteger(); + try { + for (int i = 0; i < attempts; i++) { + String body = bodies.get(i); + pool.submit(() -> { + start.await(); + try { + service.uploadSigningCertificate("race-user", body); + accepted.incrementAndGet(); + } catch (AwsException expected) { + // LimitExceeded for the losers, which is the point of the race. + } + return null; + }); + } + start.countDown(); + pool.shutdown(); + assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "uploads did not finish"); + } finally { + pool.shutdownNow(); + } + + assertEquals(2, accepted.get(), "exactly the quota should have been accepted"); + assertEquals(2, service.listSigningCertificates("race-user").size()); + } + + /** + * The quota race above uses a different certificate per thread, so it never exercises the + * duplicate check. Uploading the same body from several threads has to leave exactly one + * stored. + * + *

This one does not discriminate the lock: with the upload's lock made per-call it still + * passes, because the first write lands long before the other threads finish parsing the + * stored material to compare it. The lock is covered by the quota race, which does fail + * without it. Kept because it pins the outcome rather than the mechanism. + */ + @Test + void concurrentUploadsOfTheSameCertificateLeaveExactlyOne() throws Exception { + IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A); + service.createUser("dup-race", "/"); + String body = certificatePem(); + + int threads = 8; + ExecutorService pool = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger accepted = new AtomicInteger(); + try { + for (int i = 0; i < threads; i++) { + pool.submit(() -> { + start.await(); + try { + service.uploadSigningCertificate("dup-race", body); + accepted.incrementAndGet(); + } catch (AwsException expected) { + // DuplicateCertificate for the losers. + } + return null; + }); + } + start.countDown(); + pool.shutdown(); + assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "uploads did not finish"); + } finally { + pool.shutdownNow(); + } + + assertEquals(1, accepted.get(), "only one upload of the same certificate may succeed"); + assertEquals(1, service.listSigningCertificates("dup-race").size()); + } + + /** + * An upload must never land on a user DeleteUser has just removed. Both hold the signing lock, + * so only two orders exist: the delete is refused because a certificate is there, or the upload + * fails because the user is gone. A certificate owned by a user that does not exist is the + * state neither order may produce, and nothing in the API would ever report it: the owner + * cannot list it, because listing goes through the user. + * + *

Asserted against the store rather than through the service, for that reason. + */ + @Test + void anUploadNeverStrandsACertificateOnADeletedUser() throws Exception { + for (int trial = 0; trial < 300; trial++) { + InMemoryStorage store = new InMemoryStorage<>(); + IamService service = newService(store, ACCOUNT_A); + service.createUser("delete-race", "/"); + String body = certificatePem(); + + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch start = new CountDownLatch(1); + try { + pool.submit(() -> { + start.await(); + try { + service.uploadSigningCertificate("delete-race", body); + } catch (AwsException expected) { + // NoSuchEntity when the delete won. + } + return null; + }); + pool.submit(() -> { + start.await(); + try { + service.deleteUser("delete-race"); + } catch (AwsException expected) { + // DeleteConflict when the upload won. + } + return null; + }); + start.countDown(); + pool.shutdown(); + assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish"); + } finally { + pool.shutdownNow(); + } + + boolean userExists; + try { + service.getUser("delete-race"); + userExists = true; + } catch (AwsException gone) { + userExists = false; + } + List stored = store.scan(key -> true); + if (!userExists) { + assertTrue(stored.isEmpty(), + "trial " + trial + ": certificate left behind on a deleted user"); + } + } + } + + /** + * The same hazard on the rename path: a certificate uploaded while a rename is in flight must + * end up under whichever name the user actually has, never stranded on the old one. + */ + @Test + void anUploadNeverStrandsACertificateOnTheOldNameDuringARename() throws Exception { + for (int trial = 0; trial < 300; trial++) { + InMemoryStorage store = new InMemoryStorage<>(); + IamService service = newService(store, ACCOUNT_A); + service.createUser("rename-race-from", "/"); + String body = certificatePem(); + + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch start = new CountDownLatch(1); + try { + pool.submit(() -> { + start.await(); + try { + service.uploadSigningCertificate("rename-race-from", body); + } catch (AwsException expected) { + // NoSuchEntity when the rename landed first. + } + return null; + }); + pool.submit(() -> { + start.await(); + service.updateUser("rename-race-from", "rename-race-to", null); + return null; + }); + start.countDown(); + pool.shutdown(); + assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish"); + } finally { + pool.shutdownNow(); + } + + for (SigningCertificate certificate : store.scan(key -> true)) { + assertEquals("rename-race-to", certificate.getUserName(), + "trial " + trial + ": certificate stranded on the pre-rename name"); + } + } + } + + /** AWS lists the signing certificate among the things that must be removed before DeleteUser. */ + @Test + void aUserWithACertificateCannotBeDeleted() { + IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A); + service.createUser("blocked-user", "/"); + String id = service.uploadSigningCertificate("blocked-user", certificatePem()) + .getCertificateId(); + + AwsException refused = assertThrows(AwsException.class, + () -> service.deleteUser("blocked-user")); + assertEquals("DeleteConflict", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("signing certificate"), + "the message should name what is in the way: " + refused.getMessage()); + + service.deleteSigningCertificate("blocked-user", id); + service.deleteUser("blocked-user"); + } + + /** + * A rename must carry the certificates with it. Left behind, a certificate is stranded on a + * user name that no longer exists: invisible to its owner and undeletable. + */ + @Test + void aRenameCarriesTheCertificates() { + IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A); + service.createUser("before-rename", "/"); + String id = service.uploadSigningCertificate("before-rename", certificatePem()) + .getCertificateId(); + + service.updateUser("before-rename", "after-rename", null); + + List moved = service.listSigningCertificates("after-rename"); + assertEquals(1, moved.size(), "the certificate should have followed the rename"); + assertEquals(id, moved.getFirst().getCertificateId()); + assertEquals("after-rename", moved.getFirst().getUserName()); + // And the rename must not leave the user undeletable for a certificate it cannot see. + service.deleteSigningCertificate("after-rename", id); + service.deleteUser("after-rename"); + } + + /** + * The credential report's cert columns, which the User Guide defines precisely: TRUE only for + * an Active certificate, and N/A for the rotation date when the user has no active one. + */ + @Test + void theCredentialReportReflectsCertificateStatus() { + StorageBackend users = new InMemoryStorage<>(); + StorageBackend certificates = new InMemoryStorage<>(); + IamService service = newService(users, new InMemoryStorage<>(), certificates, ACCOUNT_A); + service.createUser("report-user", "/"); + String id = service.uploadSigningCertificate("report-user", certificatePem()) + .getCertificateId(); + + String active = reportRowFor(service, "report-user"); + assertTrue(active.contains("TRUE"), "an active certificate should report TRUE: " + active); + + service.updateSigningCertificate("report-user", id, "Inactive"); + // GenerateCredentialReport reuses a report generated in the past four hours, so the + // second row has to come from a service that has not generated one yet. + IamService regenerated = newService(users, new InMemoryStorage<>(), certificates, ACCOUNT_A); + String inactive = reportRowFor(regenerated, "report-user"); + String[] columns = inactive.split(",", -1); + // cert_1_active is FALSE, and cert_1_last_rotated is N/A rather than the upload date: + // "If the user does not have an active signing certificate, the value in this field is N/A". + int certActive = columns.length - 5; + assertEquals("FALSE", columns[certActive], "cert_1_active for an Inactive certificate"); + assertEquals("N/A", columns[certActive + 1], + "cert_1_last_rotated must be N/A when no active certificate exists"); + } + + private static String reportRowFor(IamService service, String userName) { + service.generateCredentialReport(); + String csv = new String(Base64.getDecoder() + .decode(service.getCredentialReport().base64Content()), StandardCharsets.UTF_8); + return csv.lines() + .filter(line -> line.startsWith(userName + ",")) + .findFirst() + .orElseThrow(() -> new AssertionError("no report row for " + userName)); + } +} 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.java index 36127e6ff2..7c64ddcae2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java @@ -51,6 +51,7 @@ class VirtualMfaAccountScopeTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), devices, new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("us-east-1", ACCOUNT_A), false, null); VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of()); @@ -89,6 +90,7 @@ class VirtualMfaAccountScopeTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), devices, new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("us-east-1", ACCOUNT_A), false, null); VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of()); 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.java index 354ef47ba6..c04922818a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java @@ -38,6 +38,7 @@ class VirtualMfaConcurrencyTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("eu-central-1", "000000000000"), false, null); }