diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPolicyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPolicyTest.java new file mode 100644 index 0000000000..526dd20543 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPolicyTest.java @@ -0,0 +1,147 @@ +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.ses.SesClient; +import software.amazon.awssdk.services.ses.model.DeleteIdentityPolicyRequest; +import software.amazon.awssdk.services.ses.model.GetIdentityPoliciesRequest; +import software.amazon.awssdk.services.ses.model.ListIdentityPoliciesRequest; +import software.amazon.awssdk.services.ses.model.PutIdentityPolicyRequest; + +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.AlreadyExistsException; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityPolicyRequest; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityPoliciesRequest; +import software.amazon.awssdk.services.sesv2.model.NotFoundException; +import software.amazon.awssdk.services.sesv2.model.UpdateEmailIdentityPolicyRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * SDK compatibility test for the SES identity-policy (sending authorization) APIs + * across both protocols against a live Floci instance: the AWS Java SDK v2 + * Create/Get/Update/DeleteEmailIdentityPolicy and the v1 Put/Get/List/DeleteIdentityPolicy, + * including the v2 create-duplicate / update-missing errors and the shared store + * (a v1-written policy is visible via the v2 Get). + */ +@DisplayName("SES identity policies (v1 + v2)") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesIdentityPolicyTest { + + private static final String IDENTITY = "sdk-policy.example.com"; + private static final String DOC = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + + private static SesClient sesV1; + private static SesV2Client sesV2; + + @BeforeAll + static void setup() { + sesV1 = TestFixtures.sesClient(); + sesV2 = TestFixtures.sesV2Client(); + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(IDENTITY).build()); + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + try { + // Best-effort cleanup: deleting the identity also drops its policies. Ignore errors + // (e.g. the identity was never created) so they don't mask the actual test result. + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(IDENTITY).build()); + } catch (Exception ignored) { } + sesV2.close(); + } + if (sesV1 != null) { + sesV1.close(); + } + } + + @Test + @Order(1) + void v2_createThenGet() { + sesV2.createEmailIdentityPolicy(CreateEmailIdentityPolicyRequest.builder() + .emailIdentity(IDENTITY).policyName("p1").policy(DOC).build()); + + assertThat(sesV2.getEmailIdentityPolicies(GetEmailIdentityPoliciesRequest.builder() + .emailIdentity(IDENTITY).build()).policies()) + .containsKey("p1"); + } + + @Test + @Order(2) + void v2_createDuplicate_throwsAlreadyExists() { + assertThatThrownBy(() -> sesV2.createEmailIdentityPolicy(CreateEmailIdentityPolicyRequest.builder() + .emailIdentity(IDENTITY).policyName("p1").policy(DOC).build())) + .isInstanceOf(AlreadyExistsException.class) + .hasMessageContaining("Policy already exists"); + } + + @Test + @Order(3) + void v2_updateThenGet() { + String updated = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"U\"}]}"; + sesV2.updateEmailIdentityPolicy(UpdateEmailIdentityPolicyRequest.builder() + .emailIdentity(IDENTITY).policyName("p1").policy(updated).build()); + + assertThat(sesV2.getEmailIdentityPolicies(GetEmailIdentityPoliciesRequest.builder() + .emailIdentity(IDENTITY).build()).policies().get("p1")) + .contains("\"Sid\":\"U\""); + } + + @Test + @Order(4) + void v2_updateMissing_throwsNotFound() { + assertThatThrownBy(() -> sesV2.updateEmailIdentityPolicy(UpdateEmailIdentityPolicyRequest.builder() + .emailIdentity(IDENTITY).policyName("nope").policy(DOC).build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Policy does not exist"); + } + + @Test + @Order(5) + void v1_putUpsert_listGet() { + sesV1.putIdentityPolicy(PutIdentityPolicyRequest.builder() + .identity(IDENTITY).policyName("v1p").policy(DOC).build()); + // Upsert: same name again with no error. + sesV1.putIdentityPolicy(PutIdentityPolicyRequest.builder() + .identity(IDENTITY).policyName("v1p").policy(DOC).build()); + + assertThat(sesV1.listIdentityPolicies(ListIdentityPoliciesRequest.builder() + .identity(IDENTITY).build()).policyNames()).contains("v1p"); + assertThat(sesV1.getIdentityPolicies(GetIdentityPoliciesRequest.builder() + .identity(IDENTITY).policyNames("v1p").build()).policies()).containsKey("v1p"); + } + + @Test + @Order(6) + void v1PolicyVisibleViaV2_andV2VisibleViaV1() { + // v1-written policy shows up in the v2 Get (shared store). + assertThat(sesV2.getEmailIdentityPolicies(GetEmailIdentityPoliciesRequest.builder() + .emailIdentity(IDENTITY).build()).policies()).containsKeys("p1", "v1p"); + // v2-written policy shows up in the v1 List. + assertThat(sesV1.listIdentityPolicies(ListIdentityPoliciesRequest.builder() + .identity(IDENTITY).build()).policyNames()).contains("p1", "v1p"); + } + + @Test + @Order(7) + void v1_deleteIsIdempotent() { + sesV1.deleteIdentityPolicy(DeleteIdentityPolicyRequest.builder() + .identity(IDENTITY).policyName("v1p").build()); + // Deleting again does not throw on v1. + sesV1.deleteIdentityPolicy(DeleteIdentityPolicyRequest.builder() + .identity(IDENTITY).policyName("v1p").build()); + + assertThat(sesV1.listIdentityPolicies(ListIdentityPoliciesRequest.builder() + .identity(IDENTITY).build()).policyNames()).doesNotContain("v1p"); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index b529c48672..b08141443a 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -38,6 +38,10 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an | `SetIdentityMailFromDomain` | Set or clear the MAIL FROM domain for an identity | | `GetIdentityMailFromDomainAttributes` | Read MAIL FROM domain settings | | `GetIdentityDkimAttributes` | Return DKIM status for identities | +| `PutIdentityPolicy` | Create or replace a sending-authorization policy on an identity | +| `GetIdentityPolicies` | Return the requested policies for an identity | +| `ListIdentityPolicies` | List an identity's policy names | +| `DeleteIdentityPolicy` | Delete a policy from an identity | | `CreateConfigurationSet` | Create a configuration set | | `DescribeConfigurationSet` | Read a configuration set | | `ListConfigurationSets` | List configuration sets | @@ -156,6 +160,7 @@ curl $AWS_ENDPOINT_URL/_aws/ses - Identity verification succeeds immediately; no real DNS or inbox verification flow is required. - `SendEmail` stores the text body or the HTML body as the captured message body. - `SetIdentityNotificationTopic` publishes to the configured topic on a Bounce/Complaint/Delivery event (triggered via the mailbox simulator addresses or the suppression list), independent of any configuration set. The payload uses the legacy format (`notificationType`, no `mail.tags`, headers only when `SetIdentityHeadersInNotificationsEnabled` is on). +- Identity (sending authorization) policies are stored and returned as metadata: the policy document, the per-identity limit of 20, and the create/update/delete error shapes match AWS, but Floci does not evaluate policy authorization (Principal-account existence, Resource-ARN match) or gate sending on it. - For the REST JSON API see [SES v2](#v2) below. ## SES v2 (REST JSON) {#v2} @@ -177,6 +182,10 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `PUT` | `/v2/email/identities/{emailIdentity}/feedback` | `PutEmailIdentityFeedbackAttributes` | | `PUT` | `/v2/email/identities/{emailIdentity}/mail-from` | `PutEmailIdentityMailFromAttributes` | | `PUT` | `/v2/email/identities/{emailIdentity}/configuration-set` | `PutEmailIdentityConfigurationSetAttributes` | +| `POST` | `/v2/email/identities/{emailIdentity}/policies/{policyName}` | `CreateEmailIdentityPolicy` | +| `GET` | `/v2/email/identities/{emailIdentity}/policies` | `GetEmailIdentityPolicies` | +| `PUT` | `/v2/email/identities/{emailIdentity}/policies/{policyName}` | `UpdateEmailIdentityPolicy` | +| `DELETE` | `/v2/email/identities/{emailIdentity}/policies/{policyName}` | `DeleteEmailIdentityPolicy` | | `POST` | `/v2/email/outbound-emails` | `SendEmail` (simple / raw / templated) | | `POST` | `/v2/email/outbound-bulk-emails` | `SendBulkEmail` (templated, multiple destinations) | | `GET` | `/v2/email/account` | `GetAccount` | @@ -246,4 +255,4 @@ Suppressed recipients are filtered out of the SMTP relay step (non-suppressed re Tag operations support these ARN forms: `arn:aws:ses:::configuration-set/`, `arn:aws:ses:::template/`, and `arn:aws:ses:::identity/`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, and `CreateEmailIdentity` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` does not modify tags. Other resource types return `NotFoundException`. -Identity, template, configuration-set, and sent-message state is shared between the v1 Query API and the v2 REST JSON API, so a template created with `CreateTemplate` resolves through `SendEmail` on v2 (and vice versa), a configuration set created with `CreateConfigurationSet` is visible to both `DescribeConfigurationSet` (v1) and `GetConfigurationSet` (v2), and every send appears in the same `GET /_aws/ses` inspection mailbox. +Identity, identity-policy, template, configuration-set, and sent-message state is shared between the v1 Query API and the v2 REST JSON API, so a template created with `CreateTemplate` resolves through `SendEmail` on v2 (and vice versa), a policy written with `PutIdentityPolicy` (v1) is returned by `GetEmailIdentityPolicies` (v2), a configuration set created with `CreateConfigurationSet` is visible to both `DescribeConfigurationSet` (v1) and `GetConfigurationSet` (v2), and every send appears in the same `GET /_aws/ses` inspection mailbox. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 9185cedb73..1efe93825d 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 @@ -391,6 +391,7 @@ public class AwsQueryController { "SetIdentityHeadersInNotificationsEnabled", "SetIdentityMailFromDomain", "GetIdentityMailFromDomainAttributes", "GetIdentityDkimAttributes", + "PutIdentityPolicy", "GetIdentityPolicies", "ListIdentityPolicies", "DeleteIdentityPolicy", "CreateTemplate", "UpdateTemplate", "GetTemplate", "DeleteTemplate", "ListTemplates", "SendTemplatedEmail", "SendBulkTemplatedEmail", "TestRenderTemplate", diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java index 9cd9084009..9bedca0a62 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -48,6 +48,7 @@ import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; /** * REST JSON controller for the AWS SES V2 API. @@ -175,6 +176,85 @@ public class SesController { return Response.ok(objectMapper.createObjectNode()).build(); } + // ────────────────── Identity policies (sending authorization) ──────────────── + + @POST + @Path("/identities/{emailIdentity}/policies/{policyName}") + public Response createEmailIdentityPolicy(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + @PathParam("policyName") String policyName, String body) { + String region = regionResolver.resolveRegion(headers); + try { + String policy = readPolicyBody(body); + sesService.createEmailIdentityPolicy(emailIdentity, policyName, policy, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @PUT + @Path("/identities/{emailIdentity}/policies/{policyName}") + public Response updateEmailIdentityPolicy(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + @PathParam("policyName") String policyName, String body) { + String region = regionResolver.resolveRegion(headers); + try { + String policy = readPolicyBody(body); + sesService.updateEmailIdentityPolicy(emailIdentity, policyName, policy, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @GET + @Path("/identities/{emailIdentity}/policies") + public Response getEmailIdentityPolicies(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity) { + String region = regionResolver.resolveRegion(headers); + Map policies = sesService.getEmailIdentityPolicies(emailIdentity, region); + ObjectNode result = objectMapper.createObjectNode(); + ObjectNode policiesNode = result.putObject("Policies"); + policies.forEach(policiesNode::put); + return Response.ok(result).build(); + } + + @DELETE + @Path("/identities/{emailIdentity}/policies/{policyName}") + public Response deleteEmailIdentityPolicy(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + @PathParam("policyName") String policyName) { + String region = regionResolver.resolveRegion(headers); + sesService.deleteEmailIdentityPolicy(emailIdentity, policyName, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private String readPolicyBody(String body) throws com.fasterxml.jackson.core.JsonProcessingException { + if (body == null || body.isBlank()) { + throw new AwsException("BadRequestException", "Request body is required.", 400); + } + JsonNode request = objectMapper.readTree(body); + requireJsonObject(request); + JsonNode policyNode = request.path("Policy"); + if (policyNode.isMissingNode() || policyNode.isNull()) { + // Verified against AWS: a missing/null required member is a Smithy validation error. + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'policy' failed to satisfy constraint: " + + "Member must not be null", 400); + } + if (!policyNode.isTextual()) { + // Policy is a String; AWS rejects a non-string with an empty-bodied 400. Don't coerce + // (asText would turn 123 into "123"); surface a serialization error instead. + throw new AwsException("SerializationException", null, 400); + } + return policyNode.textValue(); + } + // ──────────────────────── Identity DKIM ───────────────────────── @PUT @@ -2116,7 +2196,7 @@ public class SesController { private static AwsException remapV1Exception(AwsException e) { return switch (e.getErrorCode()) { - case "InvalidParameterValue", "InvalidTemplate", + case "InvalidParameterValue", "InvalidTemplate", "ValidationError", "InvalidRenderingParameter", "MissingRenderingAttribute" -> new AwsException("BadRequestException", e.getMessage(), 400); case "TemplateDoesNotExist", "ConfigurationSetDoesNotExist" -> diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java index 0ded3a8a23..00389ef832 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java @@ -27,6 +27,7 @@ import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Map; /** * Query-protocol handler for SES actions. @@ -72,6 +73,10 @@ public class SesQueryHandler { case "SetIdentityMailFromDomain" -> handleSetIdentityMailFromDomain(params, region); case "GetIdentityMailFromDomainAttributes" -> handleGetIdentityMailFromDomainAttributes(params, region); case "GetIdentityDkimAttributes" -> handleGetIdentityDkimAttributes(params, region); + case "PutIdentityPolicy" -> handlePutIdentityPolicy(params, region); + case "GetIdentityPolicies" -> handleGetIdentityPolicies(params, region); + case "ListIdentityPolicies" -> handleListIdentityPolicies(params, region); + case "DeleteIdentityPolicy" -> handleDeleteIdentityPolicy(params, region); case "CreateTemplate" -> handleCreateTemplate(params, region); case "UpdateTemplate" -> handleUpdateTemplate(params, region); case "GetTemplate" -> handleGetTemplate(params, region); @@ -399,6 +404,43 @@ public class SesQueryHandler { return Response.ok(AwsQueryResponse.envelope("GetIdentityMailFromDomainAttributes", AwsNamespaces.SES, xml.build())).build(); } + // --- Identity (sending authorization) policies --- + + private Response handlePutIdentityPolicy(MultivaluedMap params, String region) { + String identity = requireParam(params, "Identity"); + String policyName = requireParam(params, "PolicyName"); + String policy = requireParam(params, "Policy"); + sesService.putIdentityPolicy(identity, policyName, policy, region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult("PutIdentityPolicy", AwsNamespaces.SES)).build(); + } + + private Response handleGetIdentityPolicies(MultivaluedMap params, String region) { + String identity = requireParam(params, "Identity"); + List names = extractMembers(params, "PolicyNames"); + Map policies = sesService.getIdentityPolicies(identity, names, region); + var xml = new XmlBuilder().start("Policies"); + policies.forEach((name, doc) -> xml.start("entry").elem("key", name).elem("value", doc).end("entry")); + xml.end("Policies"); + return Response.ok(AwsQueryResponse.envelope("GetIdentityPolicies", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleListIdentityPolicies(MultivaluedMap params, String region) { + String identity = requireParam(params, "Identity"); + var xml = new XmlBuilder().start("PolicyNames"); + for (String name : sesService.listIdentityPolicyNames(identity, region)) { + xml.elem("member", name); + } + xml.end("PolicyNames"); + return Response.ok(AwsQueryResponse.envelope("ListIdentityPolicies", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleDeleteIdentityPolicy(MultivaluedMap params, String region) { + String identity = requireParam(params, "Identity"); + String policyName = requireParam(params, "PolicyName"); + sesService.deleteIdentityPolicy(identity, policyName, region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteIdentityPolicy", AwsNamespaces.SES)).build(); + } + // --- Templates --- private Response handleCreateTemplate(MultivaluedMap params, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 9d0132405f..dc4c177690 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -87,11 +87,17 @@ public class SesService { private final StorageBackend dedicatedIpPoolStore; private final StorageBackend contactListStore; private final StorageBackend contactStore; + // Identity (sending authorization) policies: key policy::::::, + // value the (normalized) policy JSON. One store shared by the v1 and v2 policy APIs. + private final StorageBackend policyStore; // Guards the one-list-per-account check-then-create so concurrent creates can't both pass. private final Object contactListCreateLock = new Object(); // Serializes contact create/update against contact-list deletion so a concurrent delete // can't purge the list between validation and the write, leaving an orphaned contact. private final Object contactMutationLock = new Object(); + // Serializes the per-identity policy count check-then-put so concurrent creates can't both pass. + private final Object policyMutationLock = new Object(); + static final int MAX_POLICIES_PER_IDENTITY = 20; private final SmtpRelay smtpRelay; private final ObjectMapper objectMapper; private final SesEventPublisher eventPublisher; @@ -124,6 +130,8 @@ public class SesService { new TypeReference>() {}); this.contactStore = storageFactory.create("ses", "ses-contacts.json", new TypeReference>() {}); + this.policyStore = storageFactory.create("ses", "ses-identity-policies.json", + new TypeReference>() {}); this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = eventPublisher; @@ -142,11 +150,12 @@ public class SesService { StorageBackend dedicatedIpPoolStore, StorageBackend contactListStore, StorageBackend contactStore, + StorageBackend policyStore, SmtpRelay smtpRelay, ObjectMapper objectMapper, Clock clock) { this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore, - accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, smtpRelay, + accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, policyStore, smtpRelay, objectMapper, null, clock); } @@ -160,6 +169,7 @@ public class SesService { StorageBackend dedicatedIpPoolStore, StorageBackend contactListStore, StorageBackend contactStore, + StorageBackend policyStore, SmtpRelay smtpRelay, ObjectMapper objectMapper, Route53Service route53Service, @@ -174,6 +184,7 @@ public class SesService { this.dedicatedIpPoolStore = dedicatedIpPoolStore; this.contactListStore = contactListStore; this.contactStore = contactStore; + this.policyStore = policyStore; this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = null; @@ -235,6 +246,17 @@ public class SesService { } } + // Policies are sub-resources of the identity; drop them too so they can't resurrect into a + // same-named identity recreated later (and so the per-identity count stays correct). + synchronized (policyMutationLock) { + String policyPrefix = policyPrefix(region, identityValue); + for (String policyKey : new ArrayList<>(policyStore.keys())) { + if (policyKey.startsWith(policyPrefix)) { + policyStore.delete(policyKey); + } + } + } + LOG.infov("Deleted identity: {0}", identityValue); } @@ -1434,6 +1456,171 @@ public class SesService { } } + // ──────────────── Identity (sending authorization) policies ──────────────── + // One shared store behind the v1 (PutIdentityPolicy/GetIdentityPolicies/ListIdentityPolicies/ + // DeleteIdentityPolicy) and v2 (Create/Get/Update/DeleteEmailIdentityPolicy) APIs. Verified + // against real AWS. Floci stores and returns policies but does not enforce the authorization + // (Principal-account existence, Resource-ARN match, or send-time checks) — it has no account + // registry and does not gate sending, so these are treated as metadata. + private static final Pattern POLICY_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+"); + + // v1 PutIdentityPolicy: upsert (create or overwrite); v1 does not require the identity to exist. + public void putIdentityPolicy(String identity, String policyName, String policy, String region) { + validatePolicyName(policyName); + String normalized = normalizePolicy(policy); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isEmpty()) { + enforcePolicyLimit(region, identity, false); + } + policyStore.put(key, normalized); + } + LOG.infov("SES PutIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v2 CreateEmailIdentityPolicy: fails if the name already exists; requires the identity. + public void createEmailIdentityPolicy(String identity, String policyName, String policy, String region) { + requireIdentityExists(identity, region); + validatePolicyName(policyName); + String normalized = normalizePolicy(policy); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", + "Policy <" + policyName + "> already exists", 400); + } + enforcePolicyLimit(region, identity, true); + policyStore.put(key, normalized); + } + LOG.infov("SES v2 CreateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v2 UpdateEmailIdentityPolicy: fails if the name is missing; requires the identity. + public void updateEmailIdentityPolicy(String identity, String policyName, String policy, String region) { + requireIdentityExists(identity, region); + validatePolicyName(policyName); + String normalized = normalizePolicy(policy); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isEmpty()) { + throw policyNotFound(policyName); + } + policyStore.put(key, normalized); + } + LOG.infov("SES v2 UpdateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v2 GetEmailIdentityPolicies: all policies for the identity; requires the identity. + public Map getEmailIdentityPolicies(String identity, String region) { + requireIdentityExists(identity, region); + return listPolicies(region, identity); + } + + // v1 GetIdentityPolicies: requested names only, missing silently omitted; no identity check. + public Map getIdentityPolicies(String identity, List policyNames, String region) { + Map out = new LinkedHashMap<>(); + for (String name : policyNames) { + policyStore.get(policyKey(region, identity, name)).ifPresent(doc -> out.put(name, doc)); + } + return out; + } + + // v1 ListIdentityPolicies: policy names (sorted); no identity check. + public List listIdentityPolicyNames(String identity, String region) { + return listPolicies(region, identity).keySet().stream().sorted().toList(); + } + + // v2 DeleteEmailIdentityPolicy: requires the identity; NotFound if the policy is missing. + public void deleteEmailIdentityPolicy(String identity, String policyName, String region) { + requireIdentityExists(identity, region); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isEmpty()) { + throw policyNotFound(policyName); + } + policyStore.delete(key); + } + LOG.infov("SES v2 DeleteEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v1 DeleteIdentityPolicy: idempotent; no identity check, no error on a missing policy. + public void deleteIdentityPolicy(String identity, String policyName, String region) { + policyStore.delete(policyKey(region, identity, policyName)); + LOG.infov("SES DeleteIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + private Map listPolicies(String region, String identity) { + String prefix = policyPrefix(region, identity); + Map out = new LinkedHashMap<>(); + for (String key : policyStore.keys()) { + if (key.startsWith(prefix)) { + policyStore.get(key).ifPresent(doc -> out.put(key.substring(prefix.length()), doc)); + } + } + return out; + } + + private void enforcePolicyLimit(String region, String identity, boolean v2) { + long count = policyStore.keys().stream() + .filter(k -> k.startsWith(policyPrefix(region, identity))).count(); + if (count >= MAX_POLICIES_PER_IDENTITY) { + String msg = "Number of policies for <" + identity + + "> exceeds max allowed number of policies per resource"; + throw new AwsException(v2 ? "LimitExceededException" : "InvalidParameterValue", msg, 400); + } + } + + private void requireIdentityExists(String identity, String region) { + if (identityStore.get(identityKey(region, identity)).isEmpty()) { + throw new AwsException("NotFoundException", + "Email identity <" + identity + "> does not exist.", 404); + } + } + + // Error codes are the v1 (Query) codes verified against AWS; the v2 controller remaps them to + // BadRequestException. The messages are identical across v1 and v2. + private static void validatePolicyName(String policyName) { + if (policyName == null || policyName.isBlank()) { + throw new AwsException("InvalidParameterValue", "PolicyName is required.", 400); + } + if (policyName.length() > 64) { + throw new AwsException("ValidationError", + "1 validation error detected: Value at 'policyName' failed to satisfy constraint: " + + "Member must have length less than or equal to 64", 400); + } + if (!POLICY_NAME_CHARS.matcher(policyName).matches()) { + throw new AwsException("InvalidParameterValue", + "PolicyName is invalid. Policy names must only include alpha-numeric characters, " + + "dashes, and underscores.", 400); + } + } + + private String normalizePolicy(String policy) { + if (policy == null || policy.isBlank()) { + throw new AwsException("InvalidParameterValue", "Policy is required.", 400); + } + try { + // AWS returns the policy with insignificant whitespace stripped; compact it to match. + return objectMapper.readTree(policy).toString(); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + // Floci does not validate policy semantics; keep an unparseable document verbatim. + LOG.debugv("Identity policy is not valid JSON, storing as-is: {0}", e.getMessage()); + return policy; + } + } + + private static AwsException policyNotFound(String policyName) { + return new AwsException("NotFoundException", "Policy <" + policyName + "> does not exist", 404); + } + + private static String policyKey(String region, String identity, String policyName) { + return policyPrefix(region, identity) + policyName; + } + + private static String policyPrefix(String region, String identity) { + return "policy::" + region + "::" + identity + "::"; + } + // Validates Create/Update input in the same two-phase order as real AWS (verified by probe): // protocol-layer (Smithy) checks across all fields first, then service-level constraints with // ContactListName ahead of topic/description constraints. diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPolicyV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPolicyV1IntegrationTest.java new file mode 100644 index 0000000000..a03923ab3f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPolicyV1IntegrationTest.java @@ -0,0 +1,137 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +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 static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * Integration tests for the SES V1 Query-protocol identity-policy APIs + * (Put/Get/List/DeleteIdentityPolicy). Verified against real AWS: v1 Put is an + * upsert, v1 Delete is idempotent, v1 List/Get do not require the identity, and + * policies are shared with the V2 store (a v1 policy is visible via V2 Get). + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesIdentityPolicyV1IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; + private static final String V2_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String IDENTITY = "policy-v1.floci.test"; + private static final String DOC_A = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"AAA\"}]}"; + private static final String DOC_B = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"BBB\"}]}"; + + private static io.restassured.specification.RequestSpecification query(String action) { + return given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", action); + } + + @Test + @Order(0) + void setup_createIdentity() { + query("VerifyDomainIdentity").formParam("Domain", IDENTITY).when().post("/").then().statusCode(200); + } + + @Test + @Order(1) + void putIdentityPolicy_thenUpsert() { + query("PutIdentityPolicy").formParam("Identity", IDENTITY) + .formParam("PolicyName", "pA").formParam("Policy", DOC_A) + .when().post("/").then().statusCode(200) + .body(containsString("PutIdentityPolicyResponse")); + + // Same name again with a different document -> upsert, no error. + query("PutIdentityPolicy").formParam("Identity", IDENTITY) + .formParam("PolicyName", "pA").formParam("Policy", DOC_B) + .when().post("/").then().statusCode(200); + } + + @Test + @Order(2) + void getIdentityPolicies_returnsUpdatedDoc() { + query("GetIdentityPolicies").formParam("Identity", IDENTITY) + .formParam("PolicyNames.member.1", "pA") + .when().post("/").then().statusCode(200) + .body(containsString("pA")) + .body(containsString("BBB")) + .body(not(containsString("AAA"))); + } + + @Test + @Order(3) + void getIdentityPolicies_missingNameOmitted() { + query("GetIdentityPolicies").formParam("Identity", IDENTITY) + .formParam("PolicyNames.member.1", "pA") + .formParam("PolicyNames.member.2", "nope") + .when().post("/").then().statusCode(200) + .body(containsString("pA")) + .body(not(containsString("nope"))); + } + + @Test + @Order(4) + void listIdentityPolicies() { + query("ListIdentityPolicies").formParam("Identity", IDENTITY) + .when().post("/").then().statusCode(200) + .body(containsString("pA")); + } + + @Test + @Order(5) + void deleteIdentityPolicy_isIdempotent() { + query("DeleteIdentityPolicy").formParam("Identity", IDENTITY).formParam("PolicyName", "pA") + .when().post("/").then().statusCode(200); + // Deleting a missing policy again succeeds (no error) on v1. + query("DeleteIdentityPolicy").formParam("Identity", IDENTITY).formParam("PolicyName", "pA") + .when().post("/").then().statusCode(200) + .body(containsString("DeleteIdentityPolicyResponse")); + } + + @Test + @Order(6) + void listAndGetOnMissingIdentity_returnEmpty() { + query("ListIdentityPolicies").formParam("Identity", "never-verified.floci.test") + .when().post("/").then().statusCode(200) + .body(containsString("InvalidParameterValue")) + .body(containsString("Policy names must only include")); + query("PutIdentityPolicy").formParam("Identity", IDENTITY) + .formParam("PolicyName", "a".repeat(65)).formParam("Policy", DOC_A) + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("length less than or equal to 64")); + } + + @Test + @Order(7) + void v1Policy_isVisibleViaV2() { + query("PutIdentityPolicy").formParam("Identity", IDENTITY) + .formParam("PolicyName", "shared").formParam("Policy", DOC_A) + .when().post("/").then().statusCode(200); + + given().header("Authorization", V2_AUTH) + .when().get("/v2/email/identities/" + IDENTITY + "/policies") + .then().statusCode(200) + .body("Policies.shared", containsString("AAA")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPolicyV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPolicyV2IntegrationTest.java new file mode 100644 index 0000000000..a022c31ded --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPolicyV2IntegrationTest.java @@ -0,0 +1,216 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +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 static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * Integration tests for the SES V2 REST JSON identity-policy APIs + * (Create/Get/Update/DeleteEmailIdentityPolicy). Behaviour and error shapes are + * verified against real AWS (per-identity limit, create-dup/update-missing/ + * delete-missing errors, PolicyName constraints, missing-identity handling). + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesIdentityPolicyV2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String IDENTITY = "policy-v2.floci.test"; + private static final String BASE = "/v2/email/identities/" + IDENTITY + "/policies"; + private static final String DOC = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + + private static String policyBody(String doc) { + return "{\"Policy\":\"" + doc.replace("\"", "\\\"") + "\"}"; + } + + @Test + @Order(0) + void setup_createIdentity() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\": \"" + IDENTITY + "\"}") + .when().post("/v2/email/identities") + .then().statusCode(200); + } + + @Test + @Order(1) + void createPolicy_thenGet() { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/p1") + .then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get(BASE) + .then().statusCode(200) + .body("Policies.p1", notNullValue()); + } + + @Test + @Order(2) + void createDuplicateName_throwsAlreadyExists() { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/p1") + .then().statusCode(400) + .body("__type", equalTo("AlreadyExistsException")) + .body("message", equalTo("Policy already exists")); + } + + @Test + @Order(3) + void createSameContentDifferentName_ok() { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/p2") + .then().statusCode(200); + } + + @Test + @Order(4) + void updatePolicy_replaces() { + String updated = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"X\"}]}"; + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(updated)) + .when().put(BASE + "/p1") + .then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get(BASE) + .then().statusCode(200) + .body("Policies.p1", equalTo(updated)); + } + + @Test + @Order(5) + void updateMissing_throwsNotFound() { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().put(BASE + "/nope") + .then().statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("Policy does not exist")); + } + + @Test + @Order(6) + void deletePolicy_thenGone() { + given().header("Authorization", AUTH) + .when().delete(BASE + "/p2") + .then().statusCode(200); + + given().header("Authorization", AUTH) + .when().get(BASE) + .then().statusCode(200) + .body("Policies.p2", nullValue()); + } + + @Test + @Order(7) + void deleteMissing_throwsNotFound() { + given().header("Authorization", AUTH) + .when().delete(BASE + "/nope") + .then().statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + @Test + @Order(8) + void operationsOnMissingIdentity_throwNotFound() { + String ghost = "/v2/email/identities/ghost-v2.floci.test/policies"; + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(ghost + "/p") + .then().statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("Email identity does not exist.")); + given().header("Authorization", AUTH).when().get(ghost).then().statusCode(404); + } + + @Test + @Order(9) + void invalidPolicyName_chars_returns400() { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/bad%20name") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("PolicyName is invalid. Policy names must only include " + + "alpha-numeric characters, dashes, and underscores.")); + } + + @Test + @Order(10) + void invalidPolicyName_tooLong_returns400() { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/" + "a".repeat(65)) + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("1 validation error detected: Value at 'policyName' failed " + + "to satisfy constraint: Member must have length less than or equal to 64")); + } + + @Test + @Order(11) + void perIdentityLimit_21stThrowsLimitExceeded() { + // p1 already exists (Order 4). Fill to 20, then the 21st create fails. + for (int i = 2; i <= 20; i++) { + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/lp" + i) + .then().statusCode(200); + } + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(BASE + "/overflow") + .then().statusCode(400) + .body("__type", equalTo("LimitExceededException")) + .body("message", equalTo("Number of policies for <" + IDENTITY + + "> exceeds max allowed number of policies per resource")); + } + + @Test + @Order(12) + void deleteIdentity_purgesPolicies_noResurrectOnRecreate() { + String id = "cascade.floci.test"; + String base = "/v2/email/identities/" + id + "/policies"; + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\": \"" + id + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH).body(policyBody(DOC)) + .when().post(base + "/c1").then().statusCode(200); + + given().header("Authorization", AUTH) + .when().delete("/v2/email/identities/" + id).then().statusCode(200); + + // Recreate the same-named identity: the old policy must not leak back in. + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\": \"" + id + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + given().header("Authorization", AUTH) + .when().get(base).then().statusCode(200) + .body("Policies.size()", equalTo(0)); + } + + @Test + @Order(13) + void policyWrongType_returns400() { + // Policy is a string field; a non-string must be rejected, not coerced to "123". + given().contentType("application/json").header("Authorization", AUTH).body("{\"Policy\": 123}") + .when().post(BASE + "/wrongtype") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + @Order(14) + void policyMissingOrNull_returnsValidationError() { + String expected = "1 validation error detected: Value at 'policy' failed to satisfy " + + "constraint: Member must not be null"; + given().contentType("application/json").header("Authorization", AUTH).body("{}") + .when().post(BASE + "/missing") + .then().statusCode(400).body("message", equalTo(expected)); + given().contentType("application/json").header("Authorization", AUTH).body("{\"Policy\": null}") + .when().post(BASE + "/nullpol") + .then().statusCode(400).body("message", equalTo(expected)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java index 9ce801d65b..bc50f7b6d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java @@ -57,6 +57,7 @@ class SesServiceDkimLookupCacheTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), route53Service, diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java index e48a0156dd..71c061ff21 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java @@ -46,6 +46,7 @@ class SesServiceLegacyDkimTokensTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java index 7ab427ad85..b82649c466 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java @@ -45,6 +45,7 @@ class SesServiceSmtpTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), smtpRelay, new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java index e3f746453c..54ddd642b1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java @@ -53,6 +53,7 @@ class SesServiceSuppressionLegacyKeyTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java index 823002359a..6a460401d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java @@ -53,6 +53,7 @@ class SesServiceSuppressionReasonTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC());