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 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 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 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