From d0c7c23f6b1ffaddcc388d9c4d53147e8aca7a0f Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:51:47 -0400 Subject: [PATCH] feat(iam): model server certificates (#4975) Replace the ListServerCertificates stub with the server-certificate lifecycle: UploadServerCertificate, GetServerCertificate, UpdateServerCertificate, DeleteServerCertificate, ListServerCertificates and the tag operations. The uploaded material is really parsed, because two of the upload's modeled errors cannot be answered otherwise. CertificateBody, and every certificate in CertificateChain rather than only its first block, must be readable PEM or the upload is MalformedCertificate; the private key must match the certificate's public key or it is KeyPairMismatch. The match is a sign-then-verify check, so it holds for RSA and EC alike. All of it goes through core.common.Pem rather than a second copy of the parsing. Expiration is read from the certificate's own notAfter rather than stored separately, so it cannot drift from what it describes. ServerCertificateId uses AWS's ASCA prefix. The private key is stored and never returned: AWS marks privateKeyType sensitive and models it only on the upload, so neither reader echoes it back, and ListServerCertificates returns metadata only as AWS documents. Request shapes are enforced from the wire model: the 16384-character caps on the body and key, the much larger 2097152 cap on the chain, and the per-account quota of 20 that the User Guide's table publishes, counted under the same lock as the write. A rename that only changes case is allowed, excluding the certificate from its own duplicate check by id the way updateUser does. GetAccountSummary's ServerCertificates count is now backed by the store instead of a hardcoded zero. ResourceArnBuilder gains an iam case naming the certificate an operation targets, so a policy statement scoped to one certificate constrains it under enforcement. Every other IAM action still resolves to *, which is long-standing behaviour rather than something this adds; documented in docs/services/iam.md and tracked in #4979. DeleteServerCertificate does not raise the in-use DeleteConflict AWS returns when a load balancer still references the certificate. Floci cannot determine that yet, because ELB Classic and CloudFront store certificate identifiers without resolving them against IAM. Documented, and tracked in #4875. --- .../floci/test/IamServerCertificateTest.java | 232 ++++++++ docs/services/iam.md | 49 +- .../floci/core/common/AwsQueryController.java | 8 +- .../floci/services/iam/IamQueryHandler.java | 105 +++- .../floci/services/iam/IamService.java | 272 ++++++++- .../services/iam/ResourceArnBuilder.java | 98 +++- .../services/iam/model/ServerCertificate.java | 62 +++ .../iam/IamServicePersistenceTest.java | 2 +- .../floci/services/iam/IamServiceTest.java | 2 + .../services/iam/ResourceArnBuilderTest.java | 175 ++++++ ...tificateIamEnforcementIntegrationTest.java | 260 +++++++++ .../iam/ServerCertificateIntegrationTest.java | 525 ++++++++++++++++++ .../iam/ServerCertificateStateTest.java | 293 ++++++++++ .../iam/VirtualMfaAccountScopeTest.java | 2 + .../iam/VirtualMfaConcurrencyTest.java | 1 + .../iam/VirtualMfaIntegrationTest.java | 26 + 16 files changed, 2090 insertions(+), 22 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamServerCertificateTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/iam/model/ServerCertificate.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIamEnforcementIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamServerCertificateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamServerCertificateTest.java new file mode 100644 index 0000000000..84f9da1453 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamServerCertificateTest.java @@ -0,0 +1,232 @@ +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.DeleteServerCertificateRequest; +import software.amazon.awssdk.services.iam.model.GetServerCertificateRequest; +import software.amazon.awssdk.services.iam.model.GetServerCertificateResponse; +import software.amazon.awssdk.services.iam.model.ListServerCertificateTagsRequest; +import software.amazon.awssdk.services.iam.model.ListServerCertificateTagsResponse; +import software.amazon.awssdk.services.iam.model.ListServerCertificatesRequest; +import software.amazon.awssdk.services.iam.model.ListServerCertificatesResponse; +import software.amazon.awssdk.services.iam.model.NoSuchEntityException; +import software.amazon.awssdk.services.iam.model.ServerCertificateMetadata; +import software.amazon.awssdk.services.iam.model.Tag; +import software.amazon.awssdk.services.iam.model.TagServerCertificateRequest; +import software.amazon.awssdk.services.iam.model.UntagServerCertificateRequest; +import software.amazon.awssdk.services.iam.model.UpdateServerCertificateRequest; +import software.amazon.awssdk.services.iam.model.UploadServerCertificateRequest; +import software.amazon.awssdk.services.iam.model.UploadServerCertificateResponse; + +import java.time.Instant; + +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; + +/** + * Server 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. {@code UploadDate} and
+ * {@code Expiration} are the interesting ones, being the only timestamps in the shape.
+ */
+@DisplayName("IAM Server Certificates")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class IamServerCertificateTest {
+
+ private static IamClient iam;
+
+ private static final String CERT_NAME = "sdk-test-server-cert";
+ private static final String RENAMED = "sdk-test-server-cert-renamed";
+
+ /**
+ * A real self-signed certificate and its matching key, fixed rather than generated so this
+ * suite needs no crypto of its own. Floci parses both and verifies the key signs what the
+ * certificate verifies, so fabricated PEM would be rejected outright. Valid until 2036, which
+ * is also why the expiry assertion below can be a simple "after the epoch" check.
+ */
+ 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 final String KEY_PEM = """
+ -----BEGIN PRIVATE KEY-----
+ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDcmuNTvKArcUzk
+ UhaSRlw/vKX0AyGuM7Nc8mir39DliyEQQXDgG00QqPLyPJ84ruBzqv+0VStpW0ZH
+ fOoYLwpgVt02k5IN/ACusp07Y5YMcK/Q8sRh3sDADbWXH/7o9MqUq4KiEqe1cIjN
+ ykY0wRBBgVCtL8arIs0uIvHFLOSD5MLU9LXrm3xQb/vw8uTykKWAkihqUn4qKmzz
+ twRtjGIcU7pudscFzaatPLJQp5CgXG6EiQ5JgIstG247gWHdF/82xTYiS/3vdvZk
+ bnBg6wjm/8cMzt/rEEBjBzifNoJDPKndmJ32ikFo7+mLNg9knI4bKACBP4JO2nBR
+ F/rWTY3tAgMBAAECggEALm2PndozKGlwOhY3p2HU/NoGYDA/iKLbYxqmYlPYqlKp
+ avsm1xeP1MuF0+rjxKFzXgyVQ73wBLyfsiBtQRk3WRa2+Es/AB/zAdFYC312QRh/
+ PB23rHRdwx2vg8aJVrxcHUVqWRNNhf9Q32SseWJPekXNtaE6Md7BaW4TzYBY+JPK
+ zJQI6sPFScZR8y1AK1fKMAUIt/C5Cdl+wwdBAXd+P1o1oh4nSmkmGO8jsljNSZ7E
+ RFJ53fvvdecKuXDUOADCYFKQZGz4GieuYRPrguCLUbB27Detl5pOPYVMqTfNSQCV
+ JLLbGK4JDzCFHS2IF6WpDTNY719hJesYqQ9I5HtpeQKBgQDx+rk/WSo/U11loyug
+ yR2SVeDnl8NofQDo7tXW8W4kGXVnK/TceJpouAZUtNQkzk05PsK3xe65hFJACEwZ
+ kQjxETR1DLaPNL/IQDSDDW4WYLJ72tjI189Ec3r9blDxwCo3tF/+WUbt1sBTPirn
+ 2i10KwDitd3/7ISE9zh5l2j4aQKBgQDpYx5uFseZYbu73Zq7tnyXWBZTEpM5W4q2
+ /+aEj9WCT94NPlz5KX/B5xodO2BaXtlQsaq8KT+r3SnZsJs6PZwhi6nAT0Ih8m74
+ VtNrqDmS5r8FXgWg+D2wGwGjA2o8FrMsHPsGa40LUfl1ibz+9HhNuqKy5C0uq7ze
+ QiYvHYGY5QKBgQC6cMLQk2PgvNumVu1jifG18WNDLYSK+l18G6E5ZnXFbLQvlQep
+ 42adLsT5+QXHggiwBbJDpEbGO7Sfz4TK4huwmeAAG5aBilQF96o+G1fp+AEtOrZz
+ MQxqoktt/tRxH+2nU9vufl0PHbq7qJeoYktJSWT6SMROzq5gQJcL4GQpmQKBgGU/
+ QcFCkp6gvn+2mFzcwtopNa4ePc5BP0E6bLePanGY0lzudAkHjswAxNxvmNI7mY0f
+ NlFgl6WoUXKF4iF2/teyrhami6sMcEW97QQkO63V+oKKkmiNqL1QSfp9DcY5lssJ
+ W4EigVKq4kyyT1JPni0iTVjMEinQCSRmkAgahdFdAoGBAIzb9NKHv8iyoeFR4BeW
+ zyyge0JmXAa2W6NvdHH5sM9U15GFS60qx74t8Mf4X7v4jajk5i2rv9rqGjyN3DDF
+ SfIPqRfUDvWqSxRKJTIlT1jKopEgSvB04lBzVjQKuV5B4MmbHb1SNAmWcccLsz2g
+ B9HFJ5PLRjDOwlSZnOPlmLPP
+ -----END PRIVATE KEY-----
+ """;
+
+ @BeforeAll
+ static void setup() {
+ iam = TestFixtures.iamClient();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (iam != null) {
+ for (String name : new String[] {CERT_NAME, RENAMED}) {
+ try {
+ iam.deleteServerCertificate(DeleteServerCertificateRequest.builder()
+ .serverCertificateName(name).build());
+ } catch (Exception ignored) {
+ // Already gone, or never created because an earlier test failed.
+ }
+ }
+ }
+ }
+
+ @Test
+ @Order(1)
+ @DisplayName("UploadServerCertificate returns metadata the SDK can model")
+ void upload() {
+ UploadServerCertificateResponse response = iam.uploadServerCertificate(
+ UploadServerCertificateRequest.builder()
+ .serverCertificateName(CERT_NAME)
+ .certificateBody(CERT_PEM)
+ .privateKey(KEY_PEM)
+ .tags(Tag.builder().key("env").value("sdk-test").build())
+ .build());
+
+ ServerCertificateMetadata metadata = response.serverCertificateMetadata();
+ assertEquals(CERT_NAME, metadata.serverCertificateName());
+ assertEquals("/", metadata.path());
+ assertTrue(metadata.serverCertificateId().startsWith("ASCA"), metadata.serverCertificateId());
+ assertTrue(metadata.arn().endsWith(":server-certificate/" + CERT_NAME), metadata.arn());
+ // Both timestamps have to parse: the SDK rejects a format it does not recognise, which a
+ // raw-XML assertion would have accepted.
+ assertNotNull(metadata.uploadDate());
+ assertNotNull(metadata.expiration());
+ assertTrue(metadata.expiration().isAfter(Instant.EPOCH));
+ assertEquals("env", response.tags().get(0).key());
+ }
+
+ @Test
+ @Order(2)
+ @DisplayName("GetServerCertificate returns the body and no private key")
+ void get() {
+ GetServerCertificateResponse response = iam.getServerCertificate(
+ GetServerCertificateRequest.builder().serverCertificateName(CERT_NAME).build());
+
+ assertTrue(response.serverCertificate().certificateBody().contains("BEGIN CERTIFICATE"));
+ assertEquals(CERT_NAME,
+ response.serverCertificate().serverCertificateMetadata().serverCertificateName());
+ // The shape has no private-key member at all, so the best check is that what came back
+ // carries none of it.
+ assertTrue(!response.toString().contains("PRIVATE KEY"), "the private key must not be returned");
+ }
+
+ @Test
+ @Order(3)
+ @DisplayName("ListServerCertificates returns metadata only")
+ void list() {
+ ListServerCertificatesResponse response = iam.listServerCertificates(
+ ListServerCertificatesRequest.builder().build());
+
+ assertTrue(response.serverCertificateMetadataList().stream()
+ .anyMatch(m -> CERT_NAME.equals(m.serverCertificateName())));
+ assertNotNull(response.isTruncated());
+ }
+
+ @Test
+ @Order(4)
+ @DisplayName("Tags round trip through the SDK")
+ void tags() {
+ iam.tagServerCertificate(TagServerCertificateRequest.builder()
+ .serverCertificateName(CERT_NAME)
+ .tags(Tag.builder().key("owner").value("platform").build())
+ .build());
+
+ ListServerCertificateTagsResponse tags = iam.listServerCertificateTags(
+ ListServerCertificateTagsRequest.builder().serverCertificateName(CERT_NAME).build());
+ assertTrue(tags.tags().stream().anyMatch(t -> "owner".equals(t.key())
+ && "platform".equals(t.value())));
+
+ iam.untagServerCertificate(UntagServerCertificateRequest.builder()
+ .serverCertificateName(CERT_NAME).tagKeys("owner").build());
+ ListServerCertificateTagsResponse after = iam.listServerCertificateTags(
+ ListServerCertificateTagsRequest.builder().serverCertificateName(CERT_NAME).build());
+ assertTrue(after.tags().stream().noneMatch(t -> "owner".equals(t.key())));
+ }
+
+ @Test
+ @Order(5)
+ @DisplayName("UpdateServerCertificate renames and moves it")
+ void update() {
+ iam.updateServerCertificate(UpdateServerCertificateRequest.builder()
+ .serverCertificateName(CERT_NAME)
+ .newServerCertificateName(RENAMED)
+ .newPath("/sdk/")
+ .build());
+
+ GetServerCertificateResponse response = iam.getServerCertificate(
+ GetServerCertificateRequest.builder().serverCertificateName(RENAMED).build());
+ assertEquals("/sdk/", response.serverCertificate().serverCertificateMetadata().path());
+ assertTrue(response.serverCertificate().serverCertificateMetadata().arn()
+ .endsWith(":server-certificate/sdk/" + RENAMED));
+
+ assertThrows(NoSuchEntityException.class, () -> iam.getServerCertificate(
+ GetServerCertificateRequest.builder().serverCertificateName(CERT_NAME).build()));
+ }
+
+ @Test
+ @Order(6)
+ @DisplayName("DeleteServerCertificate removes it")
+ void delete() {
+ iam.deleteServerCertificate(DeleteServerCertificateRequest.builder()
+ .serverCertificateName(RENAMED).build());
+
+ assertThrows(NoSuchEntityException.class, () -> iam.getServerCertificate(
+ GetServerCertificateRequest.builder().serverCertificateName(RENAMED).build()));
+ }
+}
diff --git a/docs/services/iam.md b/docs/services/iam.md
index ba687ce658..6879f324d4 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -499,7 +499,7 @@ authorization means touching the request context and STS session shape, which is
| Action | Description |
|--------|-------------|
-| GetAccountSummary | Returns entity counts (users, groups, roles, customer-managed policies, instance profiles, MFA devices) and IAM quota values. `Providers` counts OIDC providers only; SAML providers are not included. Resources Floci does not track (server certificates) are reported as zero rather than omitted. |
+| GetAccountSummary | Returns entity counts (users, groups, roles, customer-managed policies, instance profiles, MFA devices) and IAM quota values. `Providers` counts OIDC providers only; SAML providers are not included. Resources Floci does not track (the account password) are reported as zero rather than omitted. |
| GetAccountAuthorizationDetails | Returns every user, group and role in the account, and the policies relevant to them: every local (customer-managed) policy, and every AWS-managed policy actually attached to or used as a permissions boundary by something in the account. |
| GenerateCredentialReport | Generates (or, within 4 hours of the last one, reuses) the account's credential report. |
| GetCredentialReport | Returns the most recently generated credential report as Base64-encoded CSV. |
@@ -544,13 +544,39 @@ Only the set of enabled features is stored, and enabling a feature twice is idem
model root credentials or root sessions themselves, so the flags change what `ListOrganizationsFeatures`
returns and nothing else.
-### Unmodeled Lists
+### Server Certificates
| Action | Description |
|--------|-------------|
-| ListServerCertificates | Always returns an empty list. |
+| UploadServerCertificate | Stores a PEM certificate, its private key and an optional chain under a name unique to the account. |
+| GetServerCertificate | Returns a stored certificate and its chain, never the private key. |
+| UpdateServerCertificate | Renames a certificate and/or changes its path; the ARN moves with it. |
+| DeleteServerCertificate | Deletes a stored certificate. |
+| ListServerCertificates | Lists certificate metadata, filtered by `PathPrefix`. |
+| TagServerCertificate | Adds tags to a server certificate. |
+| UntagServerCertificate | Removes tags from a server certificate. |
+| ListServerCertificateTags | Lists tags stored for a server certificate. |
-Server certificates are not stored, and no action creates them.
+The uploaded material is really parsed, because two of this operation's modeled errors cannot be
+answered otherwise. `CertificateBody` (and `CertificateChain`, when given) must be readable PEM or
+the upload is `MalformedCertificate`, and the private key must actually match the certificate's
+public key or it is `KeyPairMismatch`. The match is a sign-then-verify check, so it holds for RSA
+and EC alike. `Expiration` is read from the certificate's own `notAfter` rather than stored
+separately, so it cannot drift from the certificate it describes.
+
+The private key is stored and never returned. AWS marks `privateKeyType` sensitive and models it
+only on the upload, so neither `GetServerCertificate` nor `ListServerCertificates` echoes it back.
+`ListServerCertificates` returns metadata only, as AWS documents: it "does not return the
+certificate body, certificate chain, or private key".
+
+`ServerCertificateId` uses AWS's `ASCA` prefix for certificates. `GetAccountSummary`'s
+`ServerCertificates` count is backed by this store rather than reporting zero.
+
+One modeled error is not raised: AWS returns `DeleteConflict` from `DeleteServerCertificate` when a
+load balancer still references the certificate. Floci cannot determine that yet, because ELB
+Classic and CloudFront store certificate identifiers without resolving them against IAM. Tracked in
+[#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.
## AWS Managed Policies
@@ -701,6 +727,21 @@ These identities always bypass enforcement (backward-compatible defaults):
| No `Authorization` header | Allowed — unauthenticated path (e.g. health checks) |
| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
+**IAM's own resources are mostly not named.** When enforcement evaluates a request, the target
+resource comes from `ResourceArnBuilder`, which builds an ARN for S3, Lambda, SQS, SNS, DynamoDB,
+Kinesis, Secrets Manager, SSM, KMS, and, within IAM, only the server-certificate operations. Every
+other IAM action is evaluated against `*`, so a statement naming a specific user, role, policy,
+instance profile, MFA device or identity provider does not constrain it: a `Deny` on
+`arn:aws:iam::123456789012:user/bob` does not stop `DeleteUser` from running, and an `Allow`
+scoped to one role does not limit `DeleteRole` to it. Action-level matching works normally, so
+denying `iam:DeleteUser` outright does take effect; it is only the resource half that is missing.
+
+This is the behaviour IAM has always had here rather than a recent change, and it errs toward
+permissive, which is the direction worth knowing about. Closing it means mapping the resource of
+every dispatched IAM action, which is tracked in
+[#4979](https://github.com/floci-io/floci/issues/4979) rather than bundled into the
+server-certificate work that mapped the first few.
+
**Exception:** a bare 12-digit account-id key that equals its own account and sits under
an effective SCP ceiling is **not** treated as an unknown key — it is evaluated against
the SCP chain as the account root (see [Service control policies](#service-control-policies-scps)
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 2f8a857ada..07afc66c14 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
@@ -112,7 +112,13 @@ public class AwsQueryController {
"UpdateSAMLProvider", "DeleteSAMLProvider",
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags",
"GenerateServiceLastAccessedDetails", "GetServiceLastAccessedDetails",
- "GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess"
+ "GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess",
+ "UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
+ "DeleteServerCertificate", "ListServerCertificates",
+ "TagServerCertificate", "UntagServerCertificate", "ListServerCertificateTags",
+ "CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices",
+ "EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices",
+ "TagMFADevice", "UntagMFADevice", "ListMFADeviceTags"
);
private static final Set The operation is resolved through {@link AwsQueryServiceResolver#action(String, String)},
+ * so the legacy {@code Operation} parameter names the resource exactly as {@code Action} does.
+ * Reading {@code Action} alone would let a caller spell the operation the other way and have
+ * the request evaluated against {@code *}, skipping a deny that names the certificate.
+ *
+ * The path is taken from the stored certificate when one exists: a policy names the full
+ * ARN, path included, and only the store knows the path.
+ */
+ private String buildIamArn(ContainerRequestContext ctx, String region, String accountId) {
+ String action = AwsQueryServiceResolver.action(
+ RequestBodyReader.formField(ctx, "Action"),
+ RequestBodyReader.formField(ctx, "Operation"));
+ if (action == null || !SERVER_CERTIFICATE_ACTIONS.contains(action)) {
+ return "*";
+ }
+ String name = RequestBodyReader.formField(ctx, "ServerCertificateName");
+ if (name == null || name.isBlank()) {
+ return "*";
+ }
+ // Every operation but the upload acts on a certificate that already exists, so the check
+ // uses that certificate's own stored ARN instead of deriving one again. The stored ARN
+ // carries the path and, more to the point, the partition the certificate was created in:
+ // a resource stays in its partition, so re-minting from the caller's signing region would
+ // name an ARN that no resource has and leave a deny on the real one unmatched.
+ if (!"UploadServerCertificate".equals(action)) {
+ return storedServerCertificateArn(name);
+ }
+ // An upload names a certificate that does not exist yet, so its ARN is minted from the
+ // request: the path it asks for, in the partition it is being created in. Reading a stored
+ // path here would authorize an upload to /team/ against the root path.
+ String path = normalizeArnPath(RequestBodyReader.formField(ctx, "Path"));
+ // IAM is global, so the ARN carries no region. Minted in the request's partition rather
+ // than through a blank-region Arn.of, which would silently mean the commercial one.
+ return AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
+ "server-certificate" + path + name).toString();
+ }
+
+ /** A request's Path as it appears in an ARN: slash-delimited, defaulting to a bare slash. */
+ private static String normalizeArnPath(String path) {
+ if (path == null || path.isBlank()) {
+ return "/";
+ }
+ String normalized = path.startsWith("/") ? path : "/" + path;
+ return normalized.endsWith("/") ? normalized : normalized + "/";
+ }
+
+ /**
+ * The certificate's own ARN as stored, or {@code *} when this account has no certificate of
+ * that name: the operation fails as NoSuchEntity either way, and minting an ARN for a resource
+ * that is not there would only offer a policy something to match.
+ */
+ private String storedServerCertificateArn(String name) {
+ if (iamService == null) {
+ return "*";
+ }
+ return iamService.get().findServerCertificate(name)
+ .map(ServerCertificate::getArn)
+ .filter(arn -> !arn.isBlank())
+ .orElse("*");
+ }
+
// ── S3 ──────────────────────────────────────────────────────────────────────
// Minted in the request's partition; IamEnforcementFilter re-mints an existing bucket's ARN
// in the bucket's own partition through S3ResourcePolicyProvider before any policy sees it.
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/ServerCertificate.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/ServerCertificate.java
new file mode 100644
index 0000000000..4770d847de
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/ServerCertificate.java
@@ -0,0 +1,62 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * An IAM server certificate: a PEM certificate, its private key and an optional chain, stored under
+ * a name unique within the account.
+ *
+ * {@code expiration} is read off the certificate's {@code notAfter} at upload rather than stored
+ * independently, so it cannot drift from the certificate it describes.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ServerCertificate {
+ private String serverCertificateName;
+ private String serverCertificateId;
+ private String path = "/";
+ private String arn;
+ private String certificateBody;
+ /** PEM private key. Never echoed back: no AWS reader returns it once uploaded. */
+ private String privateKey;
+ /** Optional, and absent rather than empty when the upload omitted it. */
+ private String certificateChain;
+ private Instant uploadDate = Instant.now();
+ /** The certificate's own {@code notAfter}. */
+ private Instant expiration;
+ private Map Enumerated rather than sampled, because each defect so far hid in a combination the
+ * narrower tests did not reach: the mapping missing entirely, then {@code Operation} skipping
+ * it, then the partition coming from the signing region. Nothing here derives an ARN, so a
+ * regression has to show up as a mismatch.
+ */
+ @Test
+ void iamChecksEveryRouteAndSigningRegionAgainstTheStoredArn() {
+ for (String storedArn : List.of(
+ "arn:aws:iam::000000000000:server-certificate/c1",
+ "arn:aws-cn:iam::000000000000:server-certificate/team/c1",
+ "arn:aws-us-gov:iam::000000000000:server-certificate/deep/nested/c1")) {
+ ResourceArnBuilder stored = backedBy("c1", storedArn);
+ for (String action : List.of("GetServerCertificate", "UpdateServerCertificate",
+ "DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",
+ "ListServerCertificateTags")) {
+ for (String spelling : List.of("Action", "Operation")) {
+ for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) {
+ setFormBody(spelling + "=" + action + "&ServerCertificateName=c1");
+ assertEquals(storedArn,
+ stored.build("iam", ctx, region, "000000000000"),
+ action + " named by " + spelling + ", signed in " + region);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Nothing stored under that name means nothing to name: the operation fails as NoSuchEntity
+ * regardless, and minting an ARN for an absent resource would hand a policy something to match.
+ */
+ @Test
+ void iamFallsBackToTheWildcardWhenNoCertificateIsStored() {
+ setFormBody("Action=DeleteServerCertificate&ServerCertificateName=absent");
+ assertEquals("*", backedBy("other", "arn:aws:iam::000000000000:server-certificate/other")
+ .build("iam", ctx, "us-east-1", "000000000000"));
+ }
+
+ /**
+ * An upload names a certificate that does not exist yet, so its path has to come from the
+ * request. Taking it from the store would resolve to the root path and let a policy scoped to
+ * one path authorize an upload into another.
+ */
+ @Test
+ void iamTakesTheUploadPathFromTheRequest() {
+ setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1&Path=/team/");
+ assertEquals("arn:aws:iam::000000000000:server-certificate/team/c1",
+ builder.build("iam", ctx, "us-east-1", "000000000000"));
+
+ // Written without surrounding slashes, it still lands as a path segment.
+ setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1&Path=team");
+ assertEquals("arn:aws:iam::000000000000:server-certificate/team/c1",
+ builder.build("iam", ctx, "us-east-1", "000000000000"));
+
+ // Omitted, it is the root path.
+ setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1");
+ assertEquals("arn:aws:iam::000000000000:server-certificate/c1",
+ builder.build("iam", ctx, "us-east-1", "000000000000"));
+ }
+
+ /**
+ * IAM is global, so the ARN carries no region. An upload creates the certificate in the
+ * caller's own partition, so that is the partition its ARN is minted in.
+ */
+ @Test
+ void iamMintsAnUploadedCertificateArnInTheRequestPartition() {
+ setFormBody("Action=UploadServerCertificate&ServerCertificateName=my-cert");
+ assertEquals("arn:aws-cn:iam::000000000000:server-certificate/my-cert",
+ builder.build("iam", ctx, "cn-north-1", "000000000000"));
+
+ setFormBody("Action=UploadServerCertificate&ServerCertificateName=my-cert");
+ assertEquals("arn:aws-us-gov:iam::000000000000:server-certificate/my-cert",
+ builder.build("iam", ctx, "us-gov-west-1", "000000000000"));
+ }
+
+ /**
+ * An existing certificate stays in the partition it was created in, so the check reads the
+ * partition from its stored ARN. Deriving it from the caller's signing region instead would
+ * name an ARN no resource has, and a deny on the certificate's real ARN would not match it.
+ */
+ @Test
+ void iamKeepsTheStoredPartitionWhateverRegionSignedTheRequest() {
+ String arn = "arn:aws:iam::000000000000:server-certificate/my-cert";
+ ResourceArnBuilder stored = backedBy("my-cert", arn);
+
+ setFormBody("Action=DeleteServerCertificate&ServerCertificateName=my-cert");
+ assertEquals(arn, stored.build("iam", ctx, "cn-north-1", "000000000000"));
+
+ setFormBody("Action=DeleteServerCertificate&ServerCertificateName=my-cert");
+ assertEquals(arn, stored.build("iam", ctx, "us-gov-west-1", "000000000000"));
+ }
+
+ /**
+ * ListServerCertificates names no certificate, and every other IAM action is still unmapped,
+ * so both resolve to the wildcard rather than to a fabricated ARN.
+ */
+ @Test
+ void iamFallsBackToTheWildcardWhenNoCertificateIsNamed() {
+ setFormBody("Action=ListServerCertificates&PathPrefix=/team/");
+ assertEquals("*", builder.build("iam", ctx, "us-east-1", "000000000000"));
+
+ setFormBody("Action=DeleteUser&UserName=bob");
+ assertEquals("*", builder.build("iam", ctx, "us-east-1", "000000000000"));
+
+ setFormBody("Action=DeleteServerCertificate");
+ assertEquals("*", builder.build("iam", ctx, "us-east-1", "000000000000"));
+ }
+
private void setJsonBody(String json) {
contextProperties.clear();
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIamEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..91f661edcc
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIamEnforcementIntegrationTest.java
@@ -0,0 +1,260 @@
+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.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+
+/**
+ * A policy statement naming a single server certificate has to bind to that certificate and no
+ * other. Building the target ARN is only half of it; these drive the whole path, so a statement
+ * that is silently inert would fail here rather than pass unnoticed.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class ServerCertificateIamEnforcementIntegrationTest {
+
+ private static final String ACCOUNT_ID = "000000000000";
+ private static final String REGION = "us-east-1";
+ private static final CertificateGenerator GENERATOR = new CertificateGenerator();
+
+ private static String arn(String pathAndName) {
+ return "arn:aws:iam::" + ACCOUNT_ID + ":server-certificate/" + pathAndName;
+ }
+
+ @Test
+ void aDenyNamingOneCertificateLeavesTheOthersAlone() {
+ String suffix = suffix();
+ String denied = "deny-" + suffix;
+ String allowed = "keep-" + suffix;
+ upload(denied, null);
+ upload(allowed, null);
+
+ String akid = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:DeleteServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn(denied)));
+
+ userIam(akid, "DeleteServerCertificate", Map.of("ServerCertificateName", denied))
+ .statusCode(403).body(containsString("AccessDenied"));
+ userIam(akid, "DeleteServerCertificate", Map.of("ServerCertificateName", allowed))
+ .statusCode(200);
+ }
+
+ /**
+ * The reference gives the resource as {@code server-certificate/${CertificateNameWithPath}}, so
+ * a certificate at {@code /team/} is only named by an ARN carrying that path. The second half is
+ * what makes this discriminating: the same ARN without the path must not match.
+ */
+ @Test
+ void theStoredPathIsPartOfTheArn() {
+ String suffix = suffix();
+ String name = "pathed-" + suffix;
+ upload(name, "/team/");
+
+ String withPath = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:GetServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn("team/" + name)));
+ userIam(withPath, "GetServerCertificate", Map.of("ServerCertificateName", name))
+ .statusCode(403).body(containsString("AccessDenied"));
+
+ String withoutPath = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:GetServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn(name)));
+ userIam(withoutPath, "GetServerCertificate", Map.of("ServerCertificateName", name))
+ .statusCode(200);
+ }
+
+ @Test
+ void aResourceScopedAllowGrantsThatCertificateOnly() {
+ String suffix = suffix();
+ String granted = "allow-" + suffix;
+ String other = "other-" + suffix;
+ upload(granted, null);
+ upload(other, null);
+
+ String akid = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:GetServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn(granted)));
+
+ userIam(akid, "GetServerCertificate", Map.of("ServerCertificateName", granted))
+ .statusCode(200);
+ userIam(akid, "GetServerCertificate", Map.of("ServerCertificateName", other))
+ .statusCode(403).body(containsString("AccessDenied"));
+ }
+
+ /**
+ * An upload has no stored path to read, so its ARN comes from the request's own {@code Path}.
+ * The same name at a different path is a different resource and stays allowed.
+ */
+ @Test
+ void anUploadIsAuthorizedAgainstThePathItAsksFor() {
+ String name = "upload-" + suffix();
+ String akid = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:UploadServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn("team/" + name)));
+
+ CertificateGenerator.GeneratedCertificate pair = material();
+ uploadAs(akid, name, "/team/", pair)
+ .statusCode(403).body(containsString("AccessDenied"));
+ uploadAs(akid, name, null, pair)
+ .statusCode(200);
+ }
+
+ /**
+ * The Query controller accepts the legacy {@code Operation} parameter when {@code Action} is
+ * absent, and dispatches on it. The resource has to be resolved from the same place, or a
+ * caller can name the operation that way and have the deny evaluated against {@code *}.
+ */
+ @Test
+ void theLegacyOperationParameterIsAuthorizedAgainstTheCertificateToo() {
+ String name = "legacy-" + suffix();
+ upload(name, null);
+
+ String akid = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:DeleteServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn(name)));
+
+ given()
+ .header("Authorization", auth(akid, "iam"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Operation", "DeleteServerCertificate")
+ .formParam("Version", "2010-05-08")
+ .formParam("ServerCertificateName", name)
+ .when().post("/").then()
+ .statusCode(403).body(containsString("AccessDenied"));
+ }
+
+ /**
+ * A certificate stays in the partition it was created in, which is why the service re-mints a
+ * moved ARN beside its current one. The permission check has to read the partition from the
+ * stored ARN for the same reason: deriving it from the caller's signing region would let a
+ * request signed in another partition be checked against an ARN that names no real resource,
+ * and a deny on the certificate's actual ARN would not match it.
+ */
+ @Test
+ void signingInAnotherPartitionDoesNotEscapeTheDeny() {
+ String name = "partition-" + suffix();
+ upload(name, null);
+
+ String akid = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:DeleteServerCertificate","Resource":"%s"}]}"""
+ .formatted(arn(name)));
+
+ given()
+ .header("Authorization", auth(akid, "iam", "cn-north-1"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteServerCertificate")
+ .formParam("Version", "2010-05-08")
+ .formParam("ServerCertificateName", name)
+ .when().post("/").then()
+ .statusCode(403).body(containsString("AccessDenied"));
+ }
+
+ /**
+ * The reference lists no resource type for {@code ListServerCertificates}, so it is checked
+ * against {@code *} and a statement naming one certificate cannot reach it.
+ */
+ @Test
+ void theListIsNotScopedToACertificate() {
+ String name = "listed-" + suffix();
+ upload(name, null);
+
+ String akid = userWith("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"iam:*","Resource":"*"},
+ {"Effect":"Deny","Action":"iam:ListServerCertificates","Resource":"%s"}]}"""
+ .formatted(arn(name)));
+
+ userIam(akid, "ListServerCertificates", Map.of()).statusCode(200);
+ }
+
+ private static String suffix() {
+ return UUID.randomUUID().toString().substring(0, 8);
+ }
+
+ private static CertificateGenerator.GeneratedCertificate material() {
+ return GENERATOR.generateSelfSignedCertificate(
+ "certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
+ }
+
+ private static void upload(String name, String path) {
+ uploadAs(ACCOUNT_ID, name, path, material()).statusCode(200);
+ }
+
+ private static ValidatableResponse uploadAs(String akid, String name, String path,
+ CertificateGenerator.GeneratedCertificate pair) {
+ RequestSpecification spec = given()
+ .header("Authorization", auth(akid, "iam"))
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UploadServerCertificate")
+ .formParam("Version", "2010-05-08")
+ .formParam("ServerCertificateName", name)
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem());
+ if (path != null) {
+ spec.formParam("Path", path);
+ }
+ return spec.when().post("/").then();
+ }
+
+ /** An IAM user in {@link #ACCOUNT_ID} carrying {@code policy} inline. */
+ private static String userWith(String policy) {
+ String user = "cert-iam-" + suffix();
+ adminIam("CreateUser", Map.of("UserName", user)).statusCode(200);
+ adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
+ "PolicyDocument", policy)).statusCode(200);
+ return adminIam("CreateAccessKey", Map.of("UserName", user)).statusCode(200)
+ .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
+ }
+
+ private static ValidatableResponse adminIam(String action, Map IAM state is shared across the suite, so every test names its own entities uniquely. The
+ * per-account quota is deliberately not exercised here: filling it would starve every other test
+ * in the suite of its budget. {@code ServerCertificateStateTest} covers it against an isolated
+ * store instead.
+ */
+@QuarkusTest
+class ServerCertificateIntegrationTest {
+
+ 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);
+ }
+
+ private static CertificateGenerator.GeneratedCertificate material() {
+ return GENERATOR.generateSelfSignedCertificate("certs.test.local", List.of(), KeyAlgorithm.RSA_2048);
+ }
+
+ private static String upload(String name, CertificateGenerator.GeneratedCertificate pair) {
+ return iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", name)
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .when().post("/").then().statusCode(200)
+ .extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"
+ + ".ServerCertificateMetadata.Arn");
+ }
+
+ /**
+ * The reason the key is parsed rather than stored blind. Two separate calls to
+ * {@code material()} produce unrelated pairs, so this is a genuine mismatch rather than
+ * malformed input, and it must be distinguished from one.
+ */
+ @Test
+ void uploadRejectsAKeyThatDoesNotMatchTheCertificate() {
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-mismatch-" + suffix())
+ .formParam("CertificateBody", material().certificatePem())
+ .formParam("PrivateKey", material().privateKeyPem())
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("KeyPairMismatch"));
+ }
+
+ @Test
+ void uploadAcceptsAMatchingPairAndMintsAscaMetadata() {
+ String name = "sc-ok-" + suffix();
+ CertificateGenerator.GeneratedCertificate pair = material();
+
+ String base = "UploadServerCertificateResponse.UploadServerCertificateResult"
+ + ".ServerCertificateMetadata.";
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", name)
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .when().post("/").then()
+ .statusCode(200)
+ .body(base + "ServerCertificateName", equalTo(name))
+ .body(base + "Arn", equalTo("arn:aws:iam::000000000000:server-certificate/" + name))
+ .body(base + "Path", equalTo("/"))
+ .body(base + "ServerCertificateId", containsString("ASCA"))
+ // Read off the certificate's own notAfter, so it must be present.
+ .body(base + "Expiration", containsString("Z"));
+ }
+
+ /** An EC pair must work too: the key-pair check uses a different signature algorithm for it. */
+ @Test
+ void uploadAcceptsAnEcKeyPair() {
+ String name = "sc-ec-" + suffix();
+ CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
+ "ec.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", name)
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .when().post("/").then().statusCode(200);
+ }
+
+ @Test
+ void unreadableMaterialIsMalformedCertificate() {
+ CertificateGenerator.GeneratedCertificate pair = material();
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-bad-body-" + suffix())
+ .formParam("CertificateBody", "not a pem at all")
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-bad-key-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", "not a pem at all")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-bad-chain-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", "not a pem at all")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
+ }
+
+ /**
+ * {@code certificateBodyType} and {@code privateKeyType} are both capped at 16384, and
+ * {@code certificateChainType} at 2097152. Material past a cap is a request-shape error, not a
+ * malformed certificate, so it has to be distinguished from unreadable PEM.
+ */
+ @Test
+ void materialPastItsModeledLengthIsAValidationError() {
+ CertificateGenerator.GeneratedCertificate pair = material();
+ String tooLong = "A".repeat(16385);
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-long-body-" + suffix())
+ .formParam("CertificateBody", tooLong)
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-long-key-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", tooLong)
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+
+ // A chain of the same size is well within its own, much larger, limit, so it must be
+ // judged by parseability rather than by the body's cap.
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-long-chain-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", tooLong)
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
+ }
+
+ /**
+ * A PEM reader stops at the first block, so a chain whose first certificate is valid and whose
+ * second is not would otherwise be stored and only fail whenever something tried to use it.
+ */
+ @Test
+ void aChainWithABrokenLaterCertificateIsRejected() {
+ CertificateGenerator.GeneratedCertificate pair = material();
+ String goodThenBad = material().certificatePem()
+ + "-----BEGIN CERTIFICATE-----\nnot base64 at all\n-----END CERTIFICATE-----\n";
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-badchain2-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", goodThenBad)
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
+
+ // A chain of two good certificates is still accepted, so the check is per block rather
+ // than a refusal of anything with more than one.
+ String twoGood = material().certificatePem() + material().certificatePem();
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-goodchain2-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", twoGood)
+ .when().post("/").then().statusCode(200);
+ }
+
+ /**
+ * An omitted chain is allowed, but a present one must be a chain. {@code certificateChainType}
+ * has a minimum of 1, so an empty value breaks the request shape, while whitespace satisfies
+ * the length and fails as a certificate. Neither may be quietly stored as "no chain".
+ */
+ @Test
+ void aPresentButEmptyOrBlankChainIsRejected() {
+ CertificateGenerator.GeneratedCertificate pair = material();
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-emptychain-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", "")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", "sc-blankchain-" + suffix())
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", " \n ")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
+
+ // Omitting it entirely is still fine, and the certificate then has no chain to return.
+ String name = "sc-nochain-" + suffix();
+ upload(name, pair);
+ String got = iam("GetServerCertificate").formParam("ServerCertificateName", name)
+ .when().post("/").then().statusCode(200).extract().asString();
+ assertTrue(!got.contains("CertificateChain"), "an absent chain is omitted, not empty");
+ }
+
+ /**
+ * Names are compared case-insensitively, so the duplicate check has to exclude the certificate
+ * being renamed or changing only the case of its own name reports a collision with itself.
+ */
+ @Test
+ void aCaseOnlyRenameIsAllowed() {
+ String name = "SCCase" + suffix();
+ upload(name, material());
+
+ iam("UpdateServerCertificate")
+ .formParam("ServerCertificateName", name)
+ .formParam("NewServerCertificateName", name.toLowerCase())
+ .when().post("/").then().statusCode(200);
+
+ iam("GetServerCertificate").formParam("ServerCertificateName", name.toLowerCase())
+ .when().post("/").then()
+ .statusCode(200)
+ .body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"
+ + ".ServerCertificateMetadata.ServerCertificateName", equalTo(name.toLowerCase()));
+ }
+
+ @Test
+ void uploadingTheSameNameTwiceIsEntityAlreadyExists() {
+ String name = "sc-dup-" + suffix();
+ upload(name, material());
+
+ CertificateGenerator.GeneratedCertificate second = material();
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", name)
+ .formParam("CertificateBody", second.certificatePem())
+ .formParam("PrivateKey", second.privateKeyPem())
+ .when().post("/").then()
+ .statusCode(409)
+ .body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));
+ }
+
+ /** The private key is stored but no reader returns it: AWS models it only on the upload. */
+ @Test
+ void readersNeverReturnThePrivateKey() {
+ String name = "sc-nokey-" + suffix();
+ CertificateGenerator.GeneratedCertificate pair = material();
+ upload(name, pair);
+
+ String get = iam("GetServerCertificate").formParam("ServerCertificateName", name)
+ .when().post("/").then().statusCode(200).extract().asString();
+ assertTrue(get.contains("CertificateBody"), "the certificate body is part of the shape");
+ assertTrue(!get.contains("PrivateKey"), "but the private key is never echoed back");
+ assertTrue(!get.contains("PRIVATE KEY"), "nor its PEM header");
+
+ String list = iam("ListServerCertificates").when().post("/").then().statusCode(200)
+ .extract().asString();
+ assertTrue(!list.contains("PrivateKey"));
+ assertTrue(!list.contains("CertificateBody"), "the listing is metadata only");
+ }
+
+ @Test
+ void getReturnsTheChainWhenOneWasUploaded() {
+ String name = "sc-chain-" + suffix();
+ CertificateGenerator.GeneratedCertificate pair = material();
+ CertificateGenerator.GeneratedCertificate chain = material();
+
+ iam("UploadServerCertificate")
+ .formParam("ServerCertificateName", name)
+ .formParam("CertificateBody", pair.certificatePem())
+ .formParam("PrivateKey", pair.privateKeyPem())
+ .formParam("CertificateChain", chain.certificatePem())
+ .when().post("/").then().statusCode(200);
+
+ iam("GetServerCertificate").formParam("ServerCertificateName", name)
+ .when().post("/").then()
+ .statusCode(200)
+ .body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"
+ + ".CertificateChain", containsString("BEGIN CERTIFICATE"));
+ }
+
+ @Test
+ void listFiltersByPathPrefixAndPaginates() {
+ String tag = suffix();
+ CertificateGenerator.GeneratedCertificate a = material();
+ CertificateGenerator.GeneratedCertificate b = material();
+ iam("UploadServerCertificate").formParam("ServerCertificateName", "sc-pa-" + tag)
+ .formParam("Path", "/team-" + tag + "/")
+ .formParam("CertificateBody", a.certificatePem()).formParam("PrivateKey", a.privateKeyPem())
+ .when().post("/").then().statusCode(200);
+ iam("UploadServerCertificate").formParam("ServerCertificateName", "sc-pb-" + tag)
+ .formParam("Path", "/team-" + tag + "/")
+ .formParam("CertificateBody", b.certificatePem()).formParam("PrivateKey", b.privateKeyPem())
+ .when().post("/").then().statusCode(200);
+
+ List A server certificate holds a private key, so account isolation here is the same class of
+ * concern as an MFA seed: a leak across accounts would hand over usable key material.
+ */
+class ServerCertificateStateTest {
+
+ private static final String ACCOUNT_A = "000000000000";
+ private static final String ACCOUNT_B = "111111111111";
+ private static final CertificateGenerator GENERATOR = new CertificateGenerator();
+
+ private static CertificateGenerator.GeneratedCertificate material() {
+ return GENERATOR.generateSelfSignedCertificate("state.test.local", List.of(), KeyAlgorithm.RSA_2048);
+ }
+
+ /**
+ * For the trial-heavy tests below. What they exercise is the locking, which does not care which
+ * algorithm the key uses, and an EC key is generated far more cheaply than an RSA one: using
+ * RSA here cost most of this class's runtime for no extra coverage.
+ */
+ private static CertificateGenerator.GeneratedCertificate cheapMaterial() {
+ return GENERATOR.generateSelfSignedCertificate("state.test.local", List.of(),
+ KeyAlgorithm.EC_prime256v1);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Instance