Light, fluffy, and always free - The AWS Local Emulator alternative
feat(iam): model server certificates (#4975)
Priamo Germosend0c7c23f6b1f
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.javanew file mode 100644index 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.+ *+ * <p>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.mdindex 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 idemmodel 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. |--Server certificates are not stored, and no action creates them.+| 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. |++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 underan effective SCP ceiling is **not** treated as an unknown key — it is evaluated againstthe 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.javaindex 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<String> AUTOSCALING_ACTIONS = Set.of(diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.javaindex b77d9741b5..4eea620720 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.iam.model.LoginProfile;import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;import io.github.hectorvent.floci.services.iam.model.PolicyVersion;import io.github.hectorvent.floci.services.iam.model.SAMLProvider;+import io.github.hectorvent.floci.services.iam.model.ServerCertificate;import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;@@ -130,7 +131,14 @@ public class IamQueryHandler {case "TagOpenIDConnectProvider" -> handleTagOpenIDConnectProvider(params);case "UntagOpenIDConnectProvider" -> handleUntagOpenIDConnectProvider(params);case "ListOpenIDConnectProviderTags" -> handleListOpenIDConnectProviderTags(params);+ case "UploadServerCertificate" -> handleUploadServerCertificate(params);+ case "GetServerCertificate" -> handleGetServerCertificate(params);+ case "UpdateServerCertificate" -> handleUpdateServerCertificate(params);+ case "DeleteServerCertificate" -> handleDeleteServerCertificate(params);case "ListServerCertificates" -> handleListServerCertificates(params);+ case "TagServerCertificate" -> handleTagServerCertificate(params);+ case "UntagServerCertificate" -> handleUntagServerCertificate(params);+ case "ListServerCertificateTags" -> handleListServerCertificateTags(params);// Account Aliasescase "ListAccountAliases" -> handleListAccountAliases(params);@@ -683,13 +691,100 @@ public class IamQueryHandler {return Response.ok(AwsQueryResponse.envelope("ListOpenIDConnectProviderTags", AwsNamespaces.IAM, result)).build();}- private Response handleListServerCertificates(MultivaluedMap<String, String> params) {- // Server certificates are not modeled; return an empty paginated list.+ private Response handleUploadServerCertificate(MultivaluedMap<String, String> params) {+ ServerCertificate certificate = iamService.uploadServerCertificate(+ getParam(params, "ServerCertificateName"), getParam(params, "Path"),+ getParam(params, "CertificateBody"), getParam(params, "PrivateKey"),+ getParam(params, "CertificateChain"), extractTags(params, false));String result = new XmlBuilder()- .start("ServerCertificateMetadataList").end("ServerCertificateMetadataList")- .elem("IsTruncated", false)+ .start("ServerCertificateMetadata").raw(serverCertificateMetadataXml(certificate))+ .end("ServerCertificateMetadata")+ .raw(tagsElement(new TreeMap<>(certificate.getTags())))+ .build();+ return Response.ok(AwsQueryResponse.envelope("UploadServerCertificate", AwsNamespaces.IAM, result)).build();+ }++ /**+ * Returns the stored certificate and its chain, but never the private key: AWS marks+ * {@code privateKeyType} sensitive and models it only on the upload, so no reader returns it.+ */+ private Response handleGetServerCertificate(MultivaluedMap<String, String> params) {+ ServerCertificate certificate = iamService.getServerCertificate(+ getParam(params, "ServerCertificateName"));+ XmlBuilder xml = new XmlBuilder().start("ServerCertificate")+ .start("ServerCertificateMetadata").raw(serverCertificateMetadataXml(certificate))+ .end("ServerCertificateMetadata")+ .elem("CertificateBody", certificate.getCertificateBody());+ if (certificate.getCertificateChain() != null) {+ xml.elem("CertificateChain", certificate.getCertificateChain());+ }+ xml.raw(tagsElement(new TreeMap<>(certificate.getTags()))).end("ServerCertificate");+ return Response.ok(AwsQueryResponse.envelope("GetServerCertificate", AwsNamespaces.IAM, xml.build())).build();+ }++ private Response handleUpdateServerCertificate(MultivaluedMap<String, String> params) {+ iamService.updateServerCertificate(getParam(params, "ServerCertificateName"),+ getParam(params, "NewServerCertificateName"), getParam(params, "NewPath"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateServerCertificate", AwsNamespaces.IAM)).build();+ }++ private Response handleDeleteServerCertificate(MultivaluedMap<String, String> params) {+ iamService.deleteServerCertificate(getParam(params, "ServerCertificateName"));+ return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteServerCertificate", AwsNamespaces.IAM)).build();+ }++ /**+ * The metadata list only, as AWS documents: "this operation does not return the certificate+ * body, certificate chain, or private key".+ */+ private Response handleListServerCertificates(MultivaluedMap<String, String> params) {+ Page<ServerCertificate> page = paginate(+ iamService.listServerCertificates(getParam(params, "PathPrefix")), params);+ XmlBuilder xml = new XmlBuilder().start("ServerCertificateMetadataList");+ for (ServerCertificate certificate : page.items()) {+ xml.start("member").raw(serverCertificateMetadataXml(certificate)).end("member");+ }+ xml.end("ServerCertificateMetadataList").elem("IsTruncated", page.truncated());+ if (page.marker() != null) {+ xml.elem("Marker", page.marker());+ }+ return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, xml.build())).build();+ }++ private Response handleTagServerCertificate(MultivaluedMap<String, String> params) {+ iamService.tagServerCertificate(getParam(params, "ServerCertificateName"), extractTags(params, false));+ return Response.ok(AwsQueryResponse.envelopeNoResult("TagServerCertificate", AwsNamespaces.IAM)).build();+ }++ private Response handleUntagServerCertificate(MultivaluedMap<String, String> params) {+ iamService.untagServerCertificate(getParam(params, "ServerCertificateName"), extractTagKeys(params));+ return Response.ok(AwsQueryResponse.envelopeNoResult("UntagServerCertificate", AwsNamespaces.IAM)).build();+ }++ private Response handleListServerCertificateTags(MultivaluedMap<String, String> params) {+ Map<String, String> tags = new TreeMap<>(iamService.listServerCertificateTags(+ getParam(params, "ServerCertificateName")));+ Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), params);+ XmlBuilder xml = new XmlBuilder().start("Tags");+ for (Map.Entry<String, String> tag : page.items()) {+ xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");+ }+ xml.end("Tags").elem("IsTruncated", page.truncated());+ if (page.marker() != null) {+ xml.elem("Marker", page.marker());+ }+ return Response.ok(AwsQueryResponse.envelope("ListServerCertificateTags", AwsNamespaces.IAM, xml.build())).build();+ }++ private String serverCertificateMetadataXml(ServerCertificate certificate) {+ return new XmlBuilder()+ .elem("Path", certificate.getPath())+ .elem("ServerCertificateName", certificate.getServerCertificateName())+ .elem("ServerCertificateId", certificate.getServerCertificateId())+ .elem("Arn", certificate.getArn())+ .elem("UploadDate", isoDate(certificate.getUploadDate()))+ .elem("Expiration", isoDate(certificate.getExpiration())).build();- return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, result)).build();}// =========================================================================diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex 23875c614d..c5b3c872f0 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsPartitions;+import io.github.hectorvent.floci.core.common.CertificateMaterialException;+import io.github.hectorvent.floci.core.common.Pem;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.core.common.SessionAccountLookup;@@ -28,6 +30,7 @@ import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;import io.github.hectorvent.floci.services.iam.model.PolicyVersion;import io.github.hectorvent.floci.services.iam.model.CallerContext;+import io.github.hectorvent.floci.services.iam.model.ServerCertificate;import io.github.hectorvent.floci.services.iam.model.SessionCredential;import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;import com.fasterxml.jackson.core.type.TypeReference;@@ -39,7 +42,9 @@ import org.jboss.logging.Logger;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;+import java.security.PrivateKey;import java.security.SecureRandom;+import java.security.cert.X509Certificate;import java.time.Duration;import java.time.Instant;import java.time.format.DateTimeFormatter;@@ -133,6 +138,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");private static final int IAM_PATH_MAX_LENGTH = 512;private static final int MAX_TAGS_PER_RESOURCE = 50;+ /**+ * The IAM User Guide's quota table gives "Server certificates per account" as 20, with 20 as+ * the maximum it can be raised to, so this is a real ceiling rather than a default.+ */+ private static final int MAX_SERVER_CERTIFICATES = 20;+ /** {@code certificateBodyType} and {@code privateKeyType} are both 1 to 16384 characters. */+ private static final int MAX_CERTIFICATE_BODY_LENGTH = 16384;+ /** {@code certificateChainType} is far larger, at 1 to 2097152. */+ private static final int MAX_CERTIFICATE_CHAIN_LENGTH = 2097152;/*** "You can register up to eight MFA devices of any combination of the currently supported MFA* types" (IAM User Guide). Floci models only virtual devices, so this bounds those alone.@@ -201,6 +215,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {private final StorageBackend<String, CredentialReport> credentialReports;/** Virtual MFA devices, keyed by serial number, which for a virtual device is its own ARN. */private final StorageBackend<String, VirtualMfaDevice> virtualMfaDevices;+ /** Server certificates, keyed by name, which is unique within the account. */+ private final StorageBackend<String, ServerCertificate> serverCertificates;+ /**+ * Guards the check-then-write on a server certificate. Upload checks the name is free before+ * storing, and UpdateServerCertificate checks a new name is free before moving to it, so two+ * requests racing the same name would otherwise both pass the check.+ */+ private final Object serverCertificateLock = new Object();/*** Guards every check-then-write on an MFA device. Assignment is the reason it has to exist:* EnableMFADevice reads the device to confirm it is unassigned and reads the user's device@@ -241,6 +263,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {storageFactory.create("iam", "iam-org-root-features.json", new TypeReference<>() {}),storageFactory.create("iam", "iam-credential-reports.json", new TypeReference<>() {}),storageFactory.create("iam", "iam-virtual-mfa-devices.json", new TypeReference<>() {}),+ storageFactory.create("iam", "iam-server-certificates.json", new TypeReference<>() {}),regionResolver,config.services().iam().seedDeployerPrincipal(),config.services().iam().accountAlias().orElse(null)@@ -270,8 +293,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),- new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,- seedDeployerPrincipal, null);+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ regionResolver, seedDeployerPrincipal, null);}// 8-backend constructor (no org-root-features): kept for existing callers/tests;@@ -293,7 +316,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders,serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(),- new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias);+ new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,+ seedDeployerPrincipal, seededAccountAlias);}// 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests;@@ -312,8 +336,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures,- new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver,- seedDeployerPrincipal, null);+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ regionResolver, seedDeployerPrincipal, null);}IamService(StorageBackend<String, IamUser> users,@@ -331,6 +355,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,StorageBackend<String, CredentialReport> credentialReports,StorageBackend<String, VirtualMfaDevice> virtualMfaDevices,+ StorageBackend<String, ServerCertificate> serverCertificates,RegionResolver regionResolver,boolean seedDeployerPrincipal,String seededAccountAlias) {@@ -349,6 +374,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {this.orgRootFeatures = orgRootFeatures;this.credentialReports = credentialReports;this.virtualMfaDevices = virtualMfaDevices;+ this.serverCertificates = serverCertificates;this.regionResolver = regionResolver;this.seedDeployerPrincipal = seedDeployerPrincipal;this.seededAccountAlias = seededAccountAlias;@@ -1213,9 +1239,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* keys; quota values are cross-checked against AWS's published IAM service quotas* (docs.aws.amazon.com/general/latest/gr/iam-service.html), though floci itself enforces* only the 5-versions-per-policy cap in {@link #createPolicyVersion}. Resources floci does- * not track at all (server certificates, account password - stub-empty elsewhere in this- * handler) are reported as zero rather than omitted, so callers indexing into the full AWS- * field set don't hit a missing-key error.+ * not track at all (the account password) are reported as zero rather than omitted, so+ * callers indexing into the full AWS field set don't hit a missing-key error.*/public Map<String, Long> getAccountSummary() {long localPolicyCount = 0;@@ -1253,7 +1278,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {summary.put("RolePolicySizeQuota", 10240L);summary.put("AccessKeysPerUserQuota", 2L);summary.put("SigningCertificatesPerUserQuota", 2L);- summary.put("ServerCertificates", 0L);+ summary.put("ServerCertificates", (long) serverCertificates.scan(k -> true).size());summary.put("ServerCertificatesQuota", 20L);summary.put("Providers", (long) oidcProviders.scan(k -> true).size());List<VirtualMfaDevice> mfaDevices = virtualMfaDevices.scan(k -> true);@@ -2036,6 +2061,235 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}}+ // Server certificates+ // =========================================================================++ /**+ * Stores an uploaded server certificate. The PEM material is really parsed and the key really+ * checked against the certificate, so a caller cannot store something unusable: AWS models+ * MalformedCertificate and KeyPairMismatch on this operation, and neither can be answered+ * without reading the material. {@code Expiration} is read off the certificate rather than+ * stored separately, so it cannot drift from what it describes.+ */+ public ServerCertificate uploadServerCertificate(String name, String path, String certificateBody,+ String privateKeyPem, String certificateChain,+ Map<String, String> tags) {+ validateIamResourceName(name, "ServerCertificateName");+ validateIamPath(path, "Path");+ if (certificateBody == null || certificateBody.isBlank()) {+ throw new AwsException("ValidationError",+ "The request must contain the parameter CertificateBody.", 400);+ }+ if (privateKeyPem == null || privateKeyPem.isBlank()) {+ throw new AwsException("ValidationError",+ "The request must contain the parameter PrivateKey.", 400);+ }+ // Length before parsing: an over-long body is a request-shape error, and rejecting it here+ // keeps a multi-megabyte string from reaching the PEM reader at all.+ checkMaterialLength(certificateBody, "CertificateBody", MAX_CERTIFICATE_BODY_LENGTH);+ checkMaterialLength(privateKeyPem, "PrivateKey", MAX_CERTIFICATE_BODY_LENGTH);+ checkMaterialLength(certificateChain, "CertificateChain", MAX_CERTIFICATE_CHAIN_LENGTH);+ if (tags != null && tags.size() > MAX_TAGS_PER_RESOURCE) {+ throw new AwsException("LimitExceeded",+ "Cannot exceed quota for TagsPerServerCertificate: " + MAX_TAGS_PER_RESOURCE, 409);+ }+ X509Certificate certificate = parseUploadedCertificate(certificateBody, "CertificateBody");+ if (certificateChain != null) {+ // An omitted chain is fine, an empty one is not: certificateChainType has a minimum+ // of 1, so a present-but-empty value breaks the request shape. Anything longer is+ // parsed, which is what makes a whitespace-only chain a malformed certificate rather+ // than silently storing no chain at all.+ if (certificateChain.isEmpty()) {+ throw new AwsException("ValidationError",+ "1 validation error detected: Value at 'CertificateChain' failed to satisfy "+ + "constraint: Member must have length greater than or equal to 1", 400);+ }+ parseUploadedChain(certificateChain);+ }+ PrivateKey privateKey;+ try {+ privateKey = Pem.parsePrivateKey(privateKeyPem);+ } catch (CertificateMaterialException e) {+ // The key itself is unreadable, which AWS reports as a malformed certificate too:+ // MalformedCertificate covers the uploaded material, not only the certificate body.+ throw new AwsException("MalformedCertificate",+ "The private key is not a valid PEM private key.", 400);+ }+ boolean matches;+ try {+ matches = Pem.isPair(privateKey, certificate.getPublicKey());+ } catch (Exception e) {+ // A key and certificate of different algorithms cannot be compared by signing, which+ // is itself a mismatch rather than a server-side failure.+ LOG.debugv("Server certificate key pair could not be verified: {0}", e.getMessage());+ matches = false;+ }+ if (!matches) {+ throw new AwsException("KeyPairMismatch",+ "The public key certificate and the private key do not match.", 400);+ }++ String normalizedPath = normalizePath(path);+ ServerCertificate stored = new ServerCertificate();+ stored.setServerCertificateName(name);+ stored.setServerCertificateId("ASCA" + randomId(16));+ stored.setPath(normalizedPath);+ stored.setArn(iamArn("server-certificate", normalizedPath, name));+ stored.setCertificateBody(certificateBody);+ stored.setPrivateKey(privateKeyPem);+ stored.setCertificateChain(certificateChain);+ stored.setExpiration(certificate.getNotAfter().toInstant());+ stored.setTags(tags);+ synchronized (serverCertificateLock) {+ if (containsNameIgnoreCase(serverCertificates, ServerCertificate::getServerCertificateName, name)) {+ throw new AwsException("EntityAlreadyExists",+ "The Server Certificate with name " + name + " already exists.", 409);+ }+ // Counted under the same lock as the write, so concurrent uploads cannot both see+ // room for one more and together exceed the quota.+ if (serverCertificates.scan(k -> true).size() >= MAX_SERVER_CERTIFICATES) {+ throw new AwsException("LimitExceeded",+ "Cannot exceed quota for ServerCertificatesPerAccount: "+ + MAX_SERVER_CERTIFICATES, 409);+ }+ serverCertificates.put(name, stored);+ }+ LOG.infov("Uploaded IAM server certificate: {0}", name);+ return stored;+ }++ private void checkMaterialLength(String value, String paramName, int limit) {+ if (value != null && value.length() > limit) {+ throw new AwsException("ValidationError",+ "1 validation error detected: Value at '" + paramName+ + "' failed to satisfy constraint: Member must have length less than "+ + "or equal to " + limit, 400);+ }+ }++ /**+ * Every certificate in an uploaded chain, not just the first. A PEM reader stops at the first+ * block, so checking the chain with one call would store a chain whose later certificates are+ * unreadable and only surface them when something tried to use it.+ */+ private void parseUploadedChain(String chainPem) {+ int blocks = 0;+ for (String block : chainPem.split("(?<=-----END CERTIFICATE-----)")) {+ if (block.isBlank()) {+ continue;+ }+ parseUploadedCertificate(block, "CertificateChain");+ blocks++;+ }+ if (blocks == 0) {+ throw new AwsException("MalformedCertificate",+ "CertificateChain is not a valid PEM certificate.", 400);+ }+ }++ /** Parses uploaded PEM, reporting AWS's MalformedCertificate rather than a parse exception. */+ private X509Certificate parseUploadedCertificate(String pem, String paramName) {+ try {+ return Pem.parseCertificate(pem);+ } catch (CertificateMaterialException e) {+ LOG.debugv("Rejected unparseable {0}: {1}", paramName, e.getMessage());+ throw new AwsException("MalformedCertificate",+ paramName + " is not a valid PEM certificate.", 400);+ }+ }++ /** The certificate, when one is stored under that name, for callers that must not throw. */+ public Optional<ServerCertificate> findServerCertificate(String name) {+ return name == null ? Optional.empty() : serverCertificates.get(name);+ }++ public ServerCertificate getServerCertificate(String name) {+ validateIamResourceName(name, "ServerCertificateName");+ return serverCertificates.get(name)+ .orElseThrow(() -> new AwsException("NoSuchEntity",+ "The Server Certificate with name " + name + " cannot be found.", 404));+ }++ public List<ServerCertificate> listServerCertificates(String pathPrefix) {+ String prefix = pathPrefix != null && !pathPrefix.isEmpty() ? pathPrefix : "/";+ return serverCertificates.scan(k -> true).stream()+ .filter(c -> c.getPath().startsWith(prefix))+ .sorted(Comparator.comparing(ServerCertificate::getServerCertificateName))+ .toList();+ }++ /**+ * Renames or moves a server certificate. The stored material is untouched, so the certificate+ * keeps its id and expiry; only the name, path and the ARN built from them change.+ */+ public ServerCertificate updateServerCertificate(String name, String newName, String newPath) {+ validateIamResourceName(name, "ServerCertificateName");+ if (newName != null) {+ validateIamResourceName(newName, "NewServerCertificateName");+ }+ validateIamPath(newPath, "NewPath");+ synchronized (serverCertificateLock) {+ ServerCertificate existing = getServerCertificate(name);+ String targetName = newName != null ? newName : name;+ // Excluded by id, not by name: a rename that only changes case would otherwise match+ // the certificate against itself, the same reason updateUser compares user ids here.+ boolean taken = resourcesInCurrentAccount(serverCertificates)+ .filter(other -> !other.getServerCertificateId().equals(existing.getServerCertificateId()))+ .anyMatch(other -> other.getServerCertificateName().equalsIgnoreCase(targetName));+ if (taken) {+ throw new AwsException("EntityAlreadyExists",+ "The Server Certificate with name " + targetName + " already exists.", 409);+ }+ if (newPath != null) {+ existing.setPath(normalizePath(newPath));+ }+ existing.setServerCertificateName(targetName);+ existing.setArn(iamArnBeside(existing.getArn(), "server-certificate",+ existing.getPath(), targetName));+ if (!targetName.equals(name)) {+ serverCertificates.delete(name);+ }+ serverCertificates.put(targetName, existing);+ return existing;+ }+ }++ public void deleteServerCertificate(String name) {+ validateIamResourceName(name, "ServerCertificateName");+ synchronized (serverCertificateLock) {+ getServerCertificate(name);+ serverCertificates.delete(name);+ }+ LOG.infov("Deleted IAM server certificate: {0}", name);+ }++ public void tagServerCertificate(String name, Map<String, String> newTags) {+ validateIamResourceName(name, "ServerCertificateName");+ synchronized (serverCertificateLock) {+ ServerCertificate certificate = getServerCertificate(name);+ certificate.setTags(mergeTagsWithinQuota(certificate.getTags(), newTags,+ "TagsPerServerCertificate", false));+ serverCertificates.put(certificate.getServerCertificateName(), certificate);+ }+ }++ public void untagServerCertificate(String name, List<String> tagKeys) {+ validateIamResourceName(name, "ServerCertificateName");+ synchronized (serverCertificateLock) {+ ServerCertificate certificate = getServerCertificate(name);+ Map<String, String> remaining = new LinkedHashMap<>(certificate.getTags());+ if (tagKeys != null) {+ tagKeys.forEach(remaining::remove);+ }+ certificate.setTags(remaining);+ serverCertificates.put(certificate.getServerCertificateName(), certificate);+ }+ }++ public Map<String, String> listServerCertificateTags(String name) {+ return getServerCertificate(name).getTags();+ }+// Virtual MFA devices// =========================================================================diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.javaindex c14860f8e3..25e8b44ca0 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java@@ -3,8 +3,11 @@ package io.github.hectorvent.floci.services.iam;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;import io.github.hectorvent.floci.core.common.AwsRegions;+import io.github.hectorvent.floci.services.iam.model.ServerCertificate;import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.inject.Instance;import jakarta.inject.Inject;import jakarta.ws.rs.container.ContainerRequestContext;@@ -27,15 +30,34 @@ import java.util.Set;@ApplicationScopedpublic class ResourceArnBuilder {+ /**+ * The IAM actions whose resource this builder can name. Deliberately only the+ * server-certificate operations; see {@link #buildIamArn}.+ */+ private static final Set<String> SERVER_CERTIFICATE_ACTIONS = Set.of(+ "UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",+ "DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",+ "ListServerCertificateTags");+private final ObjectMapper objectMapper;+ /**+ * Looked up lazily through a provider: this builder is constructed by the enforcement filter,+ * which IamService itself does not depend on, and a direct injection would close that loop.+ */+ private final Instance<IamService> iamService;@Inject- public ResourceArnBuilder(ObjectMapper objectMapper) {+ public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {this.objectMapper = objectMapper;+ this.iamService = iamService;}public ResourceArnBuilder() {- this(new ObjectMapper());+ this(new ObjectMapper(), null);+ }++ public ResourceArnBuilder(ObjectMapper objectMapper) {+ this(objectMapper, null);}public String build(String credentialScope, ContainerRequestContext ctx,@@ -60,10 +82,82 @@ public class ResourceArnBuilder {case "secretsmanager" -> List.of(buildSecretsManagerArn(ctx, region, accountId));case "ssm" -> List.of(buildSsmArn(ctx, region, accountId));case "kms" -> List.of(buildKmsArn(path, region, accountId));+ case "iam" -> List.of(buildIamArn(ctx, region, accountId));default -> List.of("*");};}+ // ── IAM ─────────────────────────────────────────────────────────────────────++ /**+ * IAM resource ARNs are only built for the server-certificate operations. Every other IAM+ * action still resolves to {@code *}, so a policy naming a specific user, role, policy or MFA+ * device does not constrain it. That is how IAM behaved before server certificates existed,+ * and closing it for the rest means mapping the resource of every dispatched IAM action, which+ * is its own change rather than a side effect of this one: tracked in issue 4979, and+ * described in docs/services/iam.md.+ *+ * <p>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.+ *+ * <p>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.javanew file mode 100644index 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.+ *+ * <p>{@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<String, String> tags = new ConcurrentHashMap<>();++ public ServerCertificate() {}++ public String getServerCertificateName() { return serverCertificateName; }+ public void setServerCertificateName(String serverCertificateName) {+ this.serverCertificateName = serverCertificateName;+ }+ public String getServerCertificateId() { return serverCertificateId; }+ public void setServerCertificateId(String serverCertificateId) {+ this.serverCertificateId = serverCertificateId;+ }+ public String getPath() { return path; }+ public void setPath(String path) { this.path = path; }+ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }+ public String getCertificateBody() { return certificateBody; }+ public void setCertificateBody(String certificateBody) { this.certificateBody = certificateBody; }+ public String getPrivateKey() { return privateKey; }+ public void setPrivateKey(String privateKey) { this.privateKey = privateKey; }+ public String getCertificateChain() { return certificateChain; }+ public void setCertificateChain(String certificateChain) { this.certificateChain = certificateChain; }+ public Instant getUploadDate() { return uploadDate; }+ public void setUploadDate(Instant uploadDate) { this.uploadDate = uploadDate; }+ public Instant getExpiration() { return expiration; }+ public void setExpiration(Instant expiration) { this.expiration = expiration; }+ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) {+ this.tags = tags == null ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(tags);+ }+}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.javaindex fbb0d96deb..3b3b5e7e07 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@@ -230,7 +230,7 @@ class IamServicePersistenceTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),- new InMemoryStorage<>(), devices,+ new InMemoryStorage<>(), devices, 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.javaindex 0fa22ade16..9738060862 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@@ -2304,6 +2304,7 @@ class IamServiceTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),+ new InMemoryStorage<>(),new RegionResolver("us-east-1", "000000000000"), false, null);AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);@@ -2321,6 +2322,7 @@ class IamServiceTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), credentialReports, 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/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.javaindex d13da58115..d75b4b3750 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java@@ -1,7 +1,10 @@package io.github.hectorvent.floci.services.iam;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.iam.model.ServerCertificate;+import jakarta.enterprise.inject.Instance;import jakarta.ws.rs.container.ContainerRequestContext;+import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.MultivaluedMap;import jakarta.ws.rs.core.UriInfo;@@ -15,6 +18,7 @@ import java.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.Optional;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;@@ -50,6 +54,177 @@ class ResourceArnBuilderTest {}).when(ctx).setProperty(any(), any());}+ /** Query-protocol services carry their parameters in a form body, as IAM does. */+ private void setFormBody(String form) {+ contextProperties.clear();+ byte[] bytes = form.getBytes(StandardCharsets.UTF_8);+ ByteArrayInputStream in = new ByteArrayInputStream(bytes);+ when(ctx.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);+ when(ctx.getEntityStream()).thenReturn(in);+ doAnswer(inv -> {+ InputStream newIn = inv.getArgument(0);+ when(ctx.getEntityStream()).thenReturn(newIn);+ return null;+ }).when(ctx).setEntityStream(any(InputStream.class));+ }++ // ── IAM ──────────────────────────────────────────────────────────────────────++ /**+ * A builder whose store holds one certificate under {@code name} with {@code arn}, which is+ * what the check reads for every operation acting on a certificate that already exists.+ */+ private ResourceArnBuilder backedBy(String name, String arn) {+ ServerCertificate stored = new ServerCertificate();+ stored.setServerCertificateName(name);+ stored.setArn(arn);+ IamService service = mock(IamService.class);+ when(service.findServerCertificate(name)).thenReturn(Optional.of(stored));+ @SuppressWarnings("unchecked")+ Instance<IamService> instance = mock(Instance.class);+ when(instance.get()).thenReturn(service);+ return new ResourceArnBuilder(new ObjectMapper(), instance);+ }++ /**+ * The resource a certificate-specific policy statement has to match. Without this the action+ * is evaluated against {@code *}, so a deny naming the certificate never applies.+ */+ @Test+ void iamNamesTheServerCertificateBeingActedOn() {+ String arn = "arn:aws:iam::000000000000:server-certificate/my-cert";+ setFormBody("Action=DeleteServerCertificate&ServerCertificateName=my-cert");+ assertEquals(arn, backedBy("my-cert", arn).build("iam", ctx, "us-east-1", "000000000000"));+ }++ @Test+ void iamNamesTheCertificateForEveryOperationThatTakesOne() {+ String arn = "arn:aws:iam::000000000000:server-certificate/c1";+ ResourceArnBuilder stored = backedBy("c1", arn);+ for (String action : List.of("GetServerCertificate", "UpdateServerCertificate",+ "DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",+ "ListServerCertificateTags")) {+ setFormBody("Action=" + action + "&ServerCertificateName=c1");+ assertEquals(arn, stored.build("iam", ctx, "us-east-1", "000000000000"), action);+ }+ // The upload is the one that mints rather than reads: nothing is stored yet.+ setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1");+ assertEquals(arn, builder.build("iam", ctx, "us-east-1", "000000000000"));+ }++ /**+ * The one invariant behind every way this has been got wrong: for an operation acting on a+ * certificate that exists, the ARN the permission check uses is that certificate's own stored+ * ARN -- whatever spelling named the operation, and whatever partition signed the request.+ *+ * <p>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.javanew file mode 100644index 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<String, String> params) {+ return iamCall(ACCOUNT_ID, action, params);+ }++ private static ValidatableResponse userIam(String akid, String action, Map<String, String> params) {+ return iamCall(akid, action, params);+ }++ private static ValidatableResponse iamCall(String akid, String action, Map<String, String> params) {+ RequestSpecification spec = given()+ .header("Authorization", auth(akid, "iam"))+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", action)+ .formParam("Version", "2010-05-08");+ params.forEach(spec::formParam);+ return spec.when().post("/").then();+ }++ private static String auth(String accessKeyId, String service) {+ return auth(accessKeyId, service, REGION);+ }++ private static String auth(String accessKeyId, String service, String region) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260919/" + region + "/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIntegrationTest.javanew file mode 100644index 0000000000..0bae77992c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateIntegrationTest.java@@ -0,0 +1,525 @@+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.hasItem;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * The server-certificate lifecycle over the wire. Material is generated rather than hardcoded, so+ * the upload path is exercised with certificates and keys that genuinely belong together, and the+ * rejection paths with ones that genuinely do not.+ *+ * <p>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<String> scoped = iam("ListServerCertificates")+ .formParam("PathPrefix", "/team-" + tag + "/").formParam("MaxItems", "1000")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getList("ListServerCertificatesResponse.ListServerCertificatesResult"+ + ".ServerCertificateMetadataList.member.ServerCertificateName", String.class);+ assertTrue(scoped.contains("sc-pa-" + tag));+ assertTrue(scoped.contains("sc-pb-" + tag));+ assertTrue(scoped.size() == 2, "the prefix excluded everything else, got " + scoped);++ String marker = iam("ListServerCertificates")+ .formParam("PathPrefix", "/team-" + tag + "/").formParam("MaxItems", "1")+ .when().post("/").then().statusCode(200)+ .body("ListServerCertificatesResponse.ListServerCertificatesResult.IsTruncated",+ equalTo("true"))+ .extract().path("ListServerCertificatesResponse.ListServerCertificatesResult.Marker");+ assertNotNull(marker, "a truncated page carries a Marker");+ }++ @Test+ void updateRenamesAndMovesTheCertificate() {+ String name = "sc-rename-" + suffix();+ String renamed = "sc-renamed-" + suffix();+ upload(name, material());++ iam("UpdateServerCertificate")+ .formParam("ServerCertificateName", name)+ .formParam("NewServerCertificateName", renamed)+ .formParam("NewPath", "/moved/")+ .when().post("/").then().statusCode(200);++ iam("GetServerCertificate").formParam("ServerCertificateName", renamed)+ .when().post("/").then()+ .statusCode(200)+ .body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"+ + ".ServerCertificateMetadata.Path", equalTo("/moved/"))+ .body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"+ + ".ServerCertificateMetadata.Arn",+ equalTo("arn:aws:iam::000000000000:server-certificate/moved/" + renamed));++ iam("GetServerCertificate").formParam("ServerCertificateName", name)+ .when().post("/").then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));+ }++ @Test+ void renamingOntoATakenNameIsEntityAlreadyExists() {+ String first = "sc-taken-a-" + suffix();+ String second = "sc-taken-b-" + suffix();+ upload(first, material());+ upload(second, material());++ iam("UpdateServerCertificate")+ .formParam("ServerCertificateName", first)+ .formParam("NewServerCertificateName", second)+ .when().post("/").then()+ .statusCode(409)+ .body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));+ }++ @Test+ void deleteRemovesItAndIsThenNoSuchEntity() {+ String name = "sc-delete-" + suffix();+ upload(name, material());++ iam("DeleteServerCertificate").formParam("ServerCertificateName", name)+ .when().post("/").then().statusCode(200);++ iam("DeleteServerCertificate").formParam("ServerCertificateName", name)+ .when().post("/").then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));+ }++ @Test+ void unknownCertificateIsNoSuchEntity() {+ iam("GetServerCertificate").formParam("ServerCertificateName", "sc-missing-" + suffix())+ .when().post("/").then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));+ }++ @Test+ void tagsRoundTripSortedByKeyAndPaginate() {+ String name = "sc-tags-" + suffix();+ upload(name, material());++ iam("TagServerCertificate").formParam("ServerCertificateName", name)+ .formParam("Tags.member.1.Key", "zone").formParam("Tags.member.1.Value", "b")+ .formParam("Tags.member.2.Key", "env").formParam("Tags.member.2.Value", "test")+ .when().post("/").then().statusCode(200);++ String base = "ListServerCertificateTagsResponse.ListServerCertificateTagsResult.";+ iam("ListServerCertificateTags").formParam("ServerCertificateName", name)+ .when().post("/").then()+ .statusCode(200)+ .body(base + "Tags.member[0].Key", equalTo("env"))+ .body(base + "Tags.member[1].Key", equalTo("zone"));++ iam("ListServerCertificateTags").formParam("ServerCertificateName", name)+ .formParam("MaxItems", "1")+ .when().post("/").then()+ .statusCode(200)+ .body(base + "IsTruncated", equalTo("true"))+ .body(base + "Tags.member.Key", equalTo("env"));++ iam("UntagServerCertificate").formParam("ServerCertificateName", name)+ .formParam("TagKeys.member.1", "zone")+ .when().post("/").then().statusCode(200);++ iam("ListServerCertificateTags").formParam("ServerCertificateName", name)+ .when().post("/").then()+ .statusCode(200)+ .body(base + "Tags.member.Key", equalTo("env"));+ }++ @Test+ void tagsGivenAtUploadAreKeptAndReturned() {+ String name = "sc-uploadtag-" + suffix();+ CertificateGenerator.GeneratedCertificate pair = material();++ iam("UploadServerCertificate")+ .formParam("ServerCertificateName", name)+ .formParam("CertificateBody", pair.certificatePem())+ .formParam("PrivateKey", pair.privateKeyPem())+ .formParam("Tags.member.1.Key", "owner").formParam("Tags.member.1.Value", "platform")+ .when().post("/").then()+ .statusCode(200)+ .body("UploadServerCertificateResponse.UploadServerCertificateResult.Tags.member.Key",+ equalTo("owner"));++ iam("ListServerCertificateTags").formParam("ServerCertificateName", name)+ .when().post("/").then()+ .statusCode(200)+ .body("ListServerCertificateTagsResponse.ListServerCertificateTagsResult"+ + ".Tags.member.Value", equalTo("platform"));+ }++ /**+ * With no Authorization header there is no SigV4 credential scope to resolve, so the+ * controller routes on the action name alone through {@code AwsQueryController.IAM_ACTIONS}.+ * An action missing from that set falls through to SQS and answers UnsupportedOperation, so+ * every new operation has to be listed there. The whole scenario stays unauthenticated to+ * keep the upload and the reads in one account context.+ */+ @Test+ void certificateActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {+ String name = "sc-fallback-" + suffix();+ CertificateGenerator.GeneratedCertificate pair = material();++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "UploadServerCertificate")+ .formParam("ServerCertificateName", name)+ .formParam("CertificateBody", pair.certificatePem())+ .formParam("PrivateKey", pair.privateKeyPem())+ .when().post("/").then()+ .statusCode(200)+ .body("UploadServerCertificateResponse.UploadServerCertificateResult"+ + ".ServerCertificateMetadata.ServerCertificateName", equalTo(name));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ListServerCertificates")+ .formParam("MaxItems", "1000")+ .when().post("/").then()+ .statusCode(200)+ .body("ListServerCertificatesResponse.ListServerCertificatesResult"+ + ".ServerCertificateMetadataList.member.ServerCertificateName",+ hasItem(name));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteServerCertificate")+ .formParam("ServerCertificateName", name)+ .when().post("/").then().statusCode(200);+ }++ /** The account summary counts the store rather than reporting a hardcoded zero. */+ @Test+ void theAccountSummaryCountsStoredCertificates() {+ long before = summaryValue("ServerCertificates");+ upload("sc-summary-" + suffix(), material());+ assertTrue(summaryValue("ServerCertificates") == before + 1,+ "ServerCertificates did not follow the store");+ assertTrue(summaryValue("ServerCertificatesQuota") == 20L, "the documented quota");+ }++ private static long summaryValue(String key) {+ String value = iam("GetAccountSummary").when().post("/").then().statusCode(200)+ .extract().path("GetAccountSummaryResponse.GetAccountSummaryResult.SummaryMap.entry"+ + ".find { it.key == '" + key + "' }.value");+ assertNotNull(value, key + " missing from the summary map");+ return Long.parseLong(value);+ }+}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.javanew file mode 100644index 0000000000..e249bfe171--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServerCertificateStateTest.java@@ -0,0 +1,293 @@+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.ServerCertificate;+import jakarta.enterprise.inject.Instance;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Path;+import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.concurrent.CopyOnWriteArrayList;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.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 server-certificate store that the wire tests cannot reach: that it survives+ * a restart, that one account cannot see another's, and that its check-then-write paths hold when+ * two requests race.+ *+ * <p>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<RequestContext> requestContextFor(AtomicReference<String> accountId) {+ RequestContext rc = mock(RequestContext.class);+ when(rc.getAccountId()).thenAnswer(invocation -> accountId.get());+ Instance<RequestContext> inst = mock(Instance.class);+ when(inst.get()).thenReturn(rc);+ return inst;+ }++ private static IamService newService(StorageBackend<String, ServerCertificate> certificates,+ String defaultAccount) {+ return new IamService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ certificates,+ new RegionResolver("us-east-1", defaultAccount), false, null);+ }++ /**+ * The private key and the expiry both have to survive a restart. The expiry is read from the+ * certificate at upload, so if it failed to round trip the certificate would come back+ * claiming no expiry at all rather than visibly breaking.+ */+ @Test+ void aServerCertificateSurvivesRestart(@TempDir Path dir) {+ PersistentStorage<String, ServerCertificate> first =+ new PersistentStorage<>(dir.resolve("iam-server-certificates.json"), new TypeReference<>() {});+ first.load();+ CertificateGenerator.GeneratedCertificate pair = material();+ ServerCertificate created = newService(first, ACCOUNT_A)+ .uploadServerCertificate("persisted", "/team/", pair.certificatePem(),+ pair.privateKeyPem(), null, Map.of("env", "prod"));++ PersistentStorage<String, ServerCertificate> reopened =+ new PersistentStorage<>(dir.resolve("iam-server-certificates.json"), new TypeReference<>() {});+ reopened.load();+ ServerCertificate reloaded = newService(reopened, ACCOUNT_A).getServerCertificate("persisted");++ assertEquals(created.getCertificateBody(), reloaded.getCertificateBody());+ assertEquals(created.getPrivateKey(), reloaded.getPrivateKey(), "the private key must survive");+ assertEquals(created.getServerCertificateId(), reloaded.getServerCertificateId());+ assertEquals(created.getArn(), reloaded.getArn());+ assertEquals("/team/", reloaded.getPath());+ assertEquals("prod", reloaded.getTags().get("env"));+ assertEquals(created.getExpiration(), reloaded.getExpiration(), "the expiry must survive");+ }++ @Test+ void anotherAccountCanNeitherSeeNorReachACertificate() {+ AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);+ AccountAwareStorageBackend<ServerCertificate> certificates = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);+ IamService service = newService(certificates, ACCOUNT_A);+ CertificateGenerator.GeneratedCertificate pair = material();+ service.uploadServerCertificate("scoped", "/", pair.certificatePem(), pair.privateKeyPem(),+ null, Map.of());++ account.set(ACCOUNT_B);+ assertTrue(service.listServerCertificates(null).isEmpty(),+ "account B must not see account A's certificates");+ assertEquals("NoSuchEntity",+ assertThrows(AwsException.class, () -> service.getServerCertificate("scoped")).getErrorCode());+ assertEquals("NoSuchEntity",+ assertThrows(AwsException.class, () -> service.deleteServerCertificate("scoped")).getErrorCode());+ // The key must not be reachable through the tag reader either.+ assertThrows(AwsException.class, () -> service.listServerCertificateTags("scoped"));++ // Account B may use the same name without colliding, and that must not disturb A's copy.+ CertificateGenerator.GeneratedCertificate other = material();+ service.uploadServerCertificate("scoped", "/", other.certificatePem(), other.privateKeyPem(),+ null, Map.of());+ assertEquals(other.privateKeyPem(), service.getServerCertificate("scoped").getPrivateKey());++ account.set(ACCOUNT_A);+ assertEquals(pair.privateKeyPem(), service.getServerCertificate("scoped").getPrivateKey(),+ "account A's key was replaced by account B's upload");+ }++ private static int raceTogether(Runnable... actions) throws InterruptedException {+ AtomicInteger succeeded = new AtomicInteger();+ CountDownLatch start = new CountDownLatch(1);+ CountDownLatch done = new CountDownLatch(actions.length);+ ExecutorService pool = Executors.newFixedThreadPool(actions.length);+ try {+ for (Runnable action : actions) {+ pool.submit(() -> {+ try {+ start.await();+ action.run();+ succeeded.incrementAndGet();+ } catch (AwsException expected) {+ // One side of a race is meant to lose; the count is the assertion.+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ } finally {+ done.countDown();+ }+ });+ }+ start.countDown();+ assertTrue(done.await(10, TimeUnit.SECONDS), "actions did not finish");+ } finally {+ pool.shutdownNow();+ }+ return succeeded.get();+ }++ /** Two uploads of one name: the loser must be told, not silently replace the winner's key. */+ @Test+ void onlyOneOfTwoUploadsOfTheSameNameSucceeds() throws InterruptedException {+ for (int trial = 0; trial < 100; trial++) {+ IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);+ CertificateGenerator.GeneratedCertificate a = cheapMaterial();+ CertificateGenerator.GeneratedCertificate b = cheapMaterial();++ int won = raceTogether(+ () -> service.uploadServerCertificate("contended", "/", a.certificatePem(),+ a.privateKeyPem(), null, Map.of()),+ () -> service.uploadServerCertificate("contended", "/", b.certificatePem(),+ b.privateKeyPem(), null, Map.of()));++ assertEquals(1, won, "both uploads were told they stored the certificate");+ assertEquals(1, service.listServerCertificates(null).size());+ }+ }++ /**+ * Concurrent uploads must not push the account past its quota. Counted and written under one+ * lock, exactly 20 can land; an unguarded count would let several read 19 together.+ */+ @Test+ void theAccountQuotaHoldsUnderConcurrentUploads() throws InterruptedException {+ for (int trial = 0; trial < 10; trial++) {+ IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);+ Runnable[] uploads = new Runnable[24];+ for (int i = 0; i < uploads.length; i++) {+ String name = "quota-" + i;+ CertificateGenerator.GeneratedCertificate pair = cheapMaterial();+ uploads[i] = () -> service.uploadServerCertificate(name, "/", pair.certificatePem(),+ pair.privateKeyPem(), null, Map.of());+ }++ raceTogether(uploads);++ assertEquals(20, service.listServerCertificates(null).size(),+ "the per-account quota let more than 20 certificates through");+ }+ }++ /** Renaming must not lose the material, the id, the expiry or the tags. */+ @Test+ void renameKeepsEverythingButTheNameAndArn() {+ IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);+ CertificateGenerator.GeneratedCertificate pair = material();+ ServerCertificate before = service.uploadServerCertificate("before", "/", pair.certificatePem(),+ pair.privateKeyPem(), pair.certificatePem(), Map.of("env", "prod"));+ String originalId = before.getServerCertificateId();+ Instant originalExpiry = before.getExpiration();++ service.updateServerCertificate("before", "after", "/moved/");++ ServerCertificate after = service.getServerCertificate("after");+ assertEquals(originalId, after.getServerCertificateId(), "the id is immutable across a rename");+ assertEquals(originalExpiry, after.getExpiration());+ assertEquals(pair.privateKeyPem(), after.getPrivateKey());+ assertEquals(pair.certificatePem(), after.getCertificateChain());+ assertEquals("prod", after.getTags().get("env"));+ assertEquals("/moved/", after.getPath());+ assertTrue(after.getArn().endsWith(":server-certificate/moved/after"), after.getArn());+ assertEquals("NoSuchEntity",+ assertThrows(AwsException.class, () -> service.getServerCertificate("before")).getErrorCode());+ }++ /**+ * A rename racing a delete. Counting entries is not enough: that still passes if the rename+ * reports success while losing the material, or if a worker dies on something other than an+ * AwsException. So each side's outcome is recorded and checked against the state it implies.+ */+ @Test+ void renamingNeverRacesADeleteIntoLosingTheCertificate() throws InterruptedException {+ List<String> broken = new CopyOnWriteArrayList<>();+ for (int trial = 0; trial < 100; trial++) {+ IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);+ CertificateGenerator.GeneratedCertificate pair = cheapMaterial();+ service.uploadServerCertificate("from", "/", pair.certificatePem(), pair.privateKeyPem(),+ null, Map.of());+ AtomicReference<String> renameOutcome = new AtomicReference<>("not-run");+ AtomicReference<String> deleteOutcome = new AtomicReference<>("not-run");++ raceTogether(+ () -> renameOutcome.set(record(() -> service.updateServerCertificate("from", "to", null))),+ () -> deleteOutcome.set(record(() -> service.deleteServerCertificate("from"))));++ String state = "trial " + trial + " rename=" + renameOutcome.get()+ + " delete=" + deleteOutcome.get();+ if (renameOutcome.get().startsWith("threw:") || deleteOutcome.get().startsWith("threw:")) {+ broken.add(state + " (unexpected exception)");+ continue;+ }+ List<ServerCertificate> remaining = service.listServerCertificates(null);+ if (remaining.size() > 1) {+ broken.add(state + " left " + remaining.size() + " entries");+ } else if ("ok".equals(renameOutcome.get())) {+ // The rename won, so the certificate must exist under the new name, intact.+ if (remaining.size() != 1 || !"to".equals(remaining.get(0).getServerCertificateName())+ || !pair.privateKeyPem().equals(remaining.get(0).getPrivateKey())) {+ broken.add(state + " renamed but the material did not follow");+ }+ } else if ("ok".equals(deleteOutcome.get()) && !remaining.isEmpty()) {+ broken.add(state + " deleted but a certificate remains");+ }+ }+ assertTrue(broken.isEmpty(), "rename racing delete left inconsistent state: " + broken);+ }++ /** Runs an action, reporting "ok", its AWS error code, or an unexpected throwable. */+ private static String record(Runnable action) {+ try {+ action.run();+ return "ok";+ } catch (AwsException e) {+ return e.getErrorCode();+ } catch (RuntimeException e) {+ return "threw:" + e.getClass().getSimpleName();+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.javaindex ae1d4bc259..36127e6ff2 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaAccountScopeTest.java@@ -50,6 +50,7 @@ class VirtualMfaAccountScopeTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), devices,+ new InMemoryStorage<>(),new RegionResolver("us-east-1", ACCOUNT_A), false, null);VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of());@@ -87,6 +88,7 @@ class VirtualMfaAccountScopeTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), devices,+ new InMemoryStorage<>(),new RegionResolver("us-east-1", ACCOUNT_A), false, null);VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of());diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.javaindex 5414c07a1f..354ef47ba6 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaConcurrencyTest.java@@ -37,6 +37,7 @@ class VirtualMfaConcurrencyTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(),new RegionResolver("eu-central-1", "000000000000"), false, null);}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.javaindex baf7f5117b..383f9bf43a 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/VirtualMfaIntegrationTest.java@@ -566,6 +566,32 @@ class VirtualMfaIntegrationTest {.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.IsTruncated", equalTo("false"));}+ /**+ * The MFA actions were missing from {@code AwsQueryController.IAM_ACTIONS} as well, so an+ * unauthenticated client reached SQS instead of IAM. Pinned here because the two families+ * regressed the same way and nothing else covers this routing for MFA.+ */+ @Test+ void mfaActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {+ String name = "mfa-fallback-" + suffix();++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateVirtualMFADevice")+ .formParam("VirtualMFADeviceName", name)+ .when().post("/").then()+ .statusCode(200)+ .body("CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult"+ + ".VirtualMFADevice.SerialNumber",+ equalTo("arn:aws:iam::000000000000:mfa/" + name));++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteVirtualMFADevice")+ .formParam("SerialNumber", "arn:aws:iam::000000000000:mfa/" + name)+ .when().post("/").then().statusCode(200);+ }+@Testvoid tagsRoundTripAndAreListedSortedByKey() {Device device = createDevice("mfa-tags-" + suffix());