From 312fe377fc138d9d8575b2f336760cd82665756b Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Thu, 9 Jul 2026 13:23:28 +0900 Subject: [PATCH] feat(ses): implement PutEmailIdentityConfigurationSetAttributes for SES v2 (#1698) * feat(ses): implement PutEmailIdentityConfigurationSetAttributes for SES v2 Add the v2 PutEmailIdentityConfigurationSetAttributes API and wire an email identity's default configuration set into the send path so its event destinations fire. This includes Raw sends with no explicit FromEmailAddress: the configuration set is re-resolved from the MIME "From" header once parsed, so an omitted-sender Raw send still routes through the identity default. Unknown identities surface the AWS-matched error message. * test(ses): log instead of swallowing cleanup failures in the identity config-set compat test * docs(ses): clarify default config-set precedence and clear-on-null semantics * fix(ses): fail send when an identity's default configuration set was deleted Per the SES Developer Guide, sending through an identity whose default configuration set has been deleted fails with a bad-request error. The default resolution was silently dropping the stale association; make it throw BadRequestException ("Configuration set does not exist.") to match AWS. --- .../SesEmailIdentityConfigurationSetTest.java | 107 ++++++ docs/services/ses.md | 1 + .../floci/services/ses/SesController.java | 42 +++ .../floci/services/ses/SesService.java | 91 ++++- .../floci/services/ses/model/Identity.java | 6 + ...tityConfigurationSetV2IntegrationTest.java | 353 ++++++++++++++++++ 6 files changed, 593 insertions(+), 7 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEmailIdentityConfigurationSetTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesEmailIdentityConfigurationSetV2IntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEmailIdentityConfigurationSetTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEmailIdentityConfigurationSetTest.java new file mode 100644 index 0000000000..1892ccf304 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEmailIdentityConfigurationSetTest.java @@ -0,0 +1,107 @@ +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.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.NotFoundException; +import software.amazon.awssdk.services.sesv2.model.PutEmailIdentityConfigurationSetAttributesRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * SDK compatibility test for the SES v2 {@code PutEmailIdentityConfigurationSetAttributes} + * action using the AWS Java SDK v2 {@link SesV2Client}: associating a default configuration set + * with an email identity, reading it back via {@code GetEmailIdentity}, clearing it, and the + * modeled {@link NotFoundException} for an unknown identity. + */ +@DisplayName("SES V2 PutEmailIdentityConfigurationSetAttributes") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesEmailIdentityConfigurationSetTest { + + private static SesV2Client sesV2; + private static String identity; + private static String configSet; + + @BeforeAll + static void setup() { + sesV2 = TestFixtures.sesV2Client(); + String suffix = TestFixtures.uniqueName(); + identity = "sdk-cs-attr-" + suffix + "@example.com"; + configSet = "sdk-cs-attr-" + suffix; + sesV2.createConfigurationSet(CreateConfigurationSetRequest.builder() + .configurationSetName(configSet).build()); + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder() + .emailIdentity(identity).build()); + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder() + .emailIdentity(identity).build()); + } catch (Exception e) { + System.err.println("[SesEmailIdentityConfigurationSetTest] cleanup warning – " + + "deleteEmailIdentity: " + e.getMessage()); + } + try { + sesV2.deleteConfigurationSet(DeleteConfigurationSetRequest.builder() + .configurationSetName(configSet).build()); + } catch (Exception e) { + System.err.println("[SesEmailIdentityConfigurationSetTest] cleanup warning – " + + "deleteConfigurationSet: " + e.getMessage()); + } + sesV2.close(); + } + } + + @Test + @Order(1) + void associate_readsBackViaGetEmailIdentity() { + sesV2.putEmailIdentityConfigurationSetAttributes( + PutEmailIdentityConfigurationSetAttributesRequest.builder() + .emailIdentity(identity) + .configurationSetName(configSet) + .build()); + + assertThat(sesV2.getEmailIdentity(GetEmailIdentityRequest.builder() + .emailIdentity(identity).build()).configurationSetName()) + .isEqualTo(configSet); + } + + @Test + @Order(2) + void emptyRequest_clearsAssociation() { + sesV2.putEmailIdentityConfigurationSetAttributes( + PutEmailIdentityConfigurationSetAttributesRequest.builder() + .emailIdentity(identity) + .build()); + + assertThat(sesV2.getEmailIdentity(GetEmailIdentityRequest.builder() + .emailIdentity(identity).build()).configurationSetName()) + .isNull(); + } + + @Test + @Order(3) + void unknownIdentity_raisesNotFound() { + assertThatThrownBy(() -> sesV2.putEmailIdentityConfigurationSetAttributes( + PutEmailIdentityConfigurationSetAttributesRequest.builder() + .emailIdentity("sdk-cs-attr-ghost-" + System.currentTimeMillis() + "@example.com") + .configurationSetName(configSet) + .build())) + .isInstanceOf(NotFoundException.class); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index 15fa695911..b713bc291c 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -176,6 +176,7 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `PUT` | `/v2/email/identities/{emailIdentity}/dkim` | `PutEmailIdentityDkimAttributes` | | `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/outbound-emails` | `SendEmail` (simple / raw / templated) | | `POST` | `/v2/email/outbound-bulk-emails` | `SendBulkEmail` (templated, multiple destinations) | | `GET` | `/v2/email/account` | `GetAccount` | 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 ca0c495237..22c149a996 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 @@ -258,6 +258,44 @@ public class SesController { } } + // ──────────────── Identity Configuration Set ──────────────────── + + @PUT + @Path("/identities/{emailIdentity}/configuration-set") + public Response putEmailIdentityConfigurationSetAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + String configurationSetName = null; + if (body != null && !body.isEmpty()) { + // Only a truly empty body is "no body". A non-empty body must be a JSON object; a + // whitespace-only or otherwise unparseable body is a serialization error (verified + // against real AWS: whitespace-only returns SerializationException and does not + // clear). Within a valid object, an omitted or explicit-null ConfigurationSetName + // clears the association (as does an empty body / {}). + JsonNode request = objectMapper.readTree(body); + if (request == null || !request.isObject()) { + throw new AwsException("SerializationException", null, 400); + } + JsonNode node = request.path("ConfigurationSetName"); + if (!node.isMissingNode() && !node.isNull()) { + if (!node.isTextual()) { + throw new AwsException("BadRequestException", + "ConfigurationSetName must be a JSON string.", 400); + } + configurationSetName = node.asText(); + } + } + sesService.setEmailIdentityConfigurationSet(emailIdentity, configurationSetName, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new AwsException("SerializationException", null, 400); + } + } + // ──────────────────────────── Send Email ──────────────────────────── @POST @@ -1553,6 +1591,10 @@ public class SesController { mailFromAttributes.put("MailFromDomainStatus", toV2Status(identity.getMailFromDomainStatus())); } + if (identity.getConfigurationSetName() != null && !identity.getConfigurationSetName().isEmpty()) { + result.put("ConfigurationSetName", identity.getConfigurationSetName()); + } + result.putObject("Policies"); ArrayNode tags = result.putArray("Tags"); for (Tag t : identity.getTags()) { 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 9f88d6cd26..a27531b9dc 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 @@ -257,7 +257,8 @@ public class SesService { if (!hasRecipient) { throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400); } - validateConfigurationSet(configurationSetName, region); + String effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, source, region); + validateConfigurationSet(effectiveConfigSet, region); String messageId = UUID.randomUUID().toString(); SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses, @@ -265,7 +266,7 @@ public class SesService { emailStore.put("email::" + region + "::" + messageId, email); List envelope = allRecipients(toAddresses, ccAddresses, bccAddresses); - Map suppressedReasons = collectSuppressedReasons(envelope, configurationSetName, region); + Map suppressedReasons = collectSuppressedReasons(envelope, effectiveConfigSet, region); List relayedTo = filterUnsuppressed(toAddresses, suppressedReasons); List relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons); @@ -280,7 +281,7 @@ public class SesService { LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}", source, toAddresses, subject, messageId); - publishSendEvents(configurationSetName, messageId, source, subject, + publishSendEvents(effectiveConfigSet, messageId, source, subject, toAddresses, ccAddresses, bccAddresses, envelope, suppressedReasons, emailTags, additionalHeaders, region); return messageId; @@ -292,10 +293,11 @@ public class SesService { if (rawMessage == null || rawMessage.isBlank()) { throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400); } - validateConfigurationSet(configurationSetName, region); + String effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, source, region); + validateConfigurationSet(effectiveConfigSet, region); boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty(); boolean sourceOmitted = source == null || source.isBlank(); - boolean willPublishEvents = (configurationSetName != null && !configurationSetName.isBlank()) + boolean willPublishEvents = (effectiveConfigSet != null && !effectiveConfigSet.isBlank()) || !resolveIdentityNotificationTargets(source, region).isEmpty(); SmtpRelay.RawMessageHeaders headers = (hasExplicitDestinations && !willPublishEvents && !sourceOmitted) ? null @@ -310,6 +312,14 @@ public class SesService { // both with this message. throw new AwsException("InvalidParameterValue", "Missing required header 'From'.", 400); } + // FromEmailAddress was omitted, so the configuration set couldn't be resolved from the + // sender until the MIME "From" was parsed. Re-resolve from the effective sender now so an + // email identity's default configuration set still applies to a Raw send without an + // explicit FromEmailAddress. + if (sourceOmitted && (configurationSetName == null || configurationSetName.isBlank())) { + effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, effectiveSource, region); + validateConfigurationSet(effectiveConfigSet, region); + } List effectiveDestinations = hasExplicitDestinations ? destinations : allRecipients(headers.to(), headers.cc(), headers.bcc()); @@ -321,7 +331,7 @@ public class SesService { SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage); emailStore.put("email::" + region + "::" + messageId, email); - Map suppressedReasons = collectSuppressedReasons(effectiveDestinations, configurationSetName, region); + Map suppressedReasons = collectSuppressedReasons(effectiveDestinations, effectiveConfigSet, region); List relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons); if (!relayedDestinations.isEmpty()) { @@ -332,7 +342,7 @@ public class SesService { } LOG.infov("SES raw email sent: from={0}, messageId={1}", effectiveSource, messageId); - publishSendEvents(configurationSetName, messageId, effectiveSource, + publishSendEvents(effectiveConfigSet, messageId, effectiveSource, headers != null ? headers.subject() : "", headers != null ? headers.to() : List.of(), headers != null ? headers.cc() : List.of(), @@ -738,6 +748,73 @@ public class SesService { LOG.infov("Updated feedback forwarding for {0}: enabled={1}", identityValue, enabled); } + public void setEmailIdentityConfigurationSet(String identityValue, String configurationSetName, + String region) { + String key = identityKey(region, identityValue); + Identity identity = identityStore.get(key) + .orElseThrow(() -> new AwsException("NotFoundException", + "Identity <" + identityValue + "> does not exist.", 404)); + boolean clearing = configurationSetName == null || configurationSetName.isEmpty(); + if (!clearing) { + getConfigurationSet(configurationSetName, region); + } + identity.setConfigurationSetName(clearing ? null : configurationSetName); + identityStore.put(key, identity); + LOG.infov("Updated default ConfigurationSet for {0}: {1}", + identityValue, clearing ? "" : configurationSetName); + } + + /** + * Resolves the configuration set a send should use: a non-blank configuration set explicitly + * supplied by the caller takes precedence (a blank value is treated as absent); otherwise the + * default configuration set associated with the sending identity (set via + * {@code PutEmailIdentityConfigurationSetAttributes}) is used, with the email-address identity + * taking precedence over its parent domain. If that default association is stale (its + * configuration set was deleted), the send fails with a bad-request error, matching AWS. + */ + private String resolveDefaultConfigurationSet(String configurationSetName, String source, String region) { + if (configurationSetName != null && !configurationSetName.isBlank()) { + return configurationSetName; + } + if (source == null || source.isBlank()) { + return configurationSetName; + } + String email = extractEmailAddress(source); + if (email.isBlank()) { + return configurationSetName; + } + String fromEmail = existingDefaultConfigSet(identityStore.get(identityKey(region, email)).orElse(null), region); + if (fromEmail != null) { + return fromEmail; + } + int at = email.indexOf('@'); + if (at >= 0 && at < email.length() - 1) { + String fromDomain = existingDefaultConfigSet( + identityStore.get(identityKey(region, email.substring(at + 1))).orElse(null), region); + if (fromDomain != null) { + return fromDomain; + } + } + return configurationSetName; + } + + private String existingDefaultConfigSet(Identity identity, String region) { + if (identity == null) { + return null; + } + String cs = identity.getConfigurationSetName(); + if (cs == null || cs.isEmpty()) { + return null; + } + // AWS: deleting the configuration set that is an identity's default, then sending through + // that identity, fails with a bad-request error rather than silently sending without it. + if (configSetStore.get(configSetKey(region, cs)).isEmpty()) { + throw new AwsException("BadRequestException", + "Configuration set <" + cs + "> does not exist.", 400); + } + return cs; + } + public void setMailFromDomain(String identityValue, String mailFromDomain, String behaviorOnMxFailure, String region) { String normalizedBehavior = null; diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java index 7e1e85e1cc..1214ebfbbe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java @@ -50,6 +50,9 @@ public class Identity { @JsonProperty("MailFromDomainStatus") private String mailFromDomainStatus = "Pending"; + @JsonProperty("ConfigurationSetName") + private String configurationSetName; + @JsonProperty("HeadersInNotificationsEnabled") private Map headersInNotificationsEnabled = new HashMap<>(); @@ -107,6 +110,9 @@ public class Identity { public String getMailFromDomainStatus() { return mailFromDomainStatus; } public void setMailFromDomainStatus(String mailFromDomainStatus) { this.mailFromDomainStatus = mailFromDomainStatus; } + public String getConfigurationSetName() { return configurationSetName; } + public void setConfigurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; } + public Map getHeadersInNotificationsEnabled() { return headersInNotificationsEnabled; } public void setHeadersInNotificationsEnabled(Map headersInNotificationsEnabled) { this.headersInNotificationsEnabled = headersInNotificationsEnabled; } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesEmailIdentityConfigurationSetV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesEmailIdentityConfigurationSetV2IntegrationTest.java new file mode 100644 index 0000000000..f8b87ffc9d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEmailIdentityConfigurationSetV2IntegrationTest.java @@ -0,0 +1,353 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +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 java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration tests for the SES v2 {@code PutEmailIdentityConfigurationSetAttributes} action: + * associating a default configuration set with an email identity, surfacing it through + * {@code GetEmailIdentity}, clearing it, and the resulting event-publishing behavior — a send + * from the identity with no explicit configuration set must route through the identity's default + * configuration set's event destinations. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesEmailIdentityConfigurationSetV2IntegrationTest { + + private static final String SES_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String SNS_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/sns/aws4_request"; + private static final String SQS_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/sqs/aws4_request"; + private static final String JSON_10 = "application/x-amz-json-1.0"; + + private static final String IDENTITY = "cs-attr-sender@floci.test"; + private static final String CS = "cs-attr-default-cs"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String topicArn; + private static String queueUrl; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void setup_identity_configSet_snsEventDestination() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"EmailIdentity\":\"" + IDENTITY + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when().post("/v2/email/configuration-sets").then().statusCode(200); + + queueUrl = given().contentType(JSON_10).header("Authorization", SQS_AUTH) + .header("X-Amz-Target", "AmazonSQS.CreateQueue") + .body("{\"QueueName\":\"cs-attr-queue\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("QueueUrl"); + String queueArn = given().contentType(JSON_10).header("Authorization", SQS_AUTH) + .header("X-Amz-Target", "AmazonSQS.GetQueueAttributes") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"AttributeNames\":[\"All\"]}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Attributes.QueueArn"); + + topicArn = given().contentType(JSON_10).header("Authorization", SNS_AUTH) + .header("X-Amz-Target", "SNS_20100331.CreateTopic") + .body("{\"Name\":\"cs-attr-topic\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("TopicArn"); + assertNotNull(topicArn); + + given().contentType(JSON_10).header("Authorization", SNS_AUTH) + .header("X-Amz-Target", "SNS_20100331.Subscribe") + .body("{\"TopicArn\":\"" + topicArn + "\",\"Protocol\":\"sqs\",\"Endpoint\":\"" + queueArn + "\"}") + .when().post("/").then().statusCode(200); + + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + { + "EventDestinationName": "ed-sns", + "EventDestination": { + "Enabled": true, + "MatchingEventTypes": ["SEND", "BOUNCE"], + "SnsDestination": {"TopicArn": "%s"} + } + } + """.formatted(topicArn)) + .when().post("/v2/email/configuration-sets/" + CS + "/event-destinations") + .then().statusCode(200); + } + + @Test + @Order(2) + void putEmailIdentityConfigurationSet_associatesAndSurfacesInGet() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(200); + + given().header("Authorization", SES_AUTH) + .when().get("/v2/email/identities/" + IDENTITY) + .then().statusCode(200) + .body("ConfigurationSetName", equalTo(CS)); + } + + @Test + @Order(3) + void sendWithoutConfigSet_routesThroughIdentityDefault_publishesEvent() throws Exception { + drainQueue(); + // No ConfigurationSetName on the send — it must resolve to the identity's default. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + { + "FromEmailAddress": "%s", + "Destination": {"ToAddresses": ["bounce@simulator.amazonses.com"]}, + "Content": {"Simple": {"Subject": {"Data": "cs-attr"}, "Body": {"Text": {"Data": "hi"}}}} + } + """.formatted(IDENTITY)) + .when().post("/v2/email/outbound-emails").then().statusCode(200); + + List events = receiveEvents(2); + assertTrue(events.stream().anyMatch(e -> "Send".equals(e.path("eventType").asText())), + "Send event must publish via the identity's default configuration set"); + JsonNode bounce = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + assertEquals(CS, bounce.path("mail").path("tags").path("ses:configuration-set").get(0).asText()); + } + + @Test + @Order(4) + void clearConfigurationSet_removesAssociation() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{}") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(200); + + given().header("Authorization", SES_AUTH) + .when().get("/v2/email/identities/" + IDENTITY) + .then().statusCode(200) + .body("$", org.hamcrest.Matchers.not(org.hamcrest.Matchers.hasKey("ConfigurationSetName"))); + } + + @Test + @Order(5) + void sendRawContentWithoutConfigSet_routesThroughIdentityDefault() throws Exception { + // Re-associate (Order 4 cleared it) so this test is self-contained. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(200); + + drainQueue(); + String raw = "From: " + IDENTITY + "\r\n" + + "To: bounce@simulator.amazonses.com\r\n" + + "Subject: cs-attr-raw\r\n\r\nbody"; + String rawB64 = Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + // SendEmail with Raw content and no ConfigurationSetName must route through the + // identity's default, just like the Simple-content path. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + { + "FromEmailAddress": "%s", + "Destination": {"ToAddresses": ["bounce@simulator.amazonses.com"]}, + "Content": {"Raw": {"Data": "%s"}} + } + """.formatted(IDENTITY, rawB64)) + .when().post("/v2/email/outbound-emails").then().statusCode(200); + + List events = receiveEvents(2); + JsonNode bounce = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + assertEquals(CS, bounce.path("mail").path("tags").path("ses:configuration-set").get(0).asText(), + "Raw-content sends must also route through the identity default configuration set"); + } + + @Test + @Order(6) + void unknownIdentity_returns404() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when().put("/v2/email/identities/cs-attr-ghost@floci.test/configuration-set") + .then().statusCode(404) + .body("message", equalTo("Identity does not exist.")); + } + + @Test + @Order(7) + void unknownConfigurationSet_returns404() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"cs-attr-missing\"}") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(404) + .body("message", equalTo("Configuration set does not exist.")); + } + + @Test + @Order(8) + void sendRawContentWithoutFromAddress_routesThroughIdentityDefault() throws Exception { + // Re-associate so this test is self-contained. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(200); + + drainQueue(); + // Raw content with NO FromEmailAddress: the sender is taken only from the MIME "From". + // The identity's default configuration set must still be resolved from that header. + String raw = "From: " + IDENTITY + "\r\n" + + "To: bounce@simulator.amazonses.com\r\n" + + "Subject: cs-attr-raw-nofrom\r\n\r\nbody"; + String rawB64 = Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + { + "Destination": {"ToAddresses": ["bounce@simulator.amazonses.com"]}, + "Content": {"Raw": {"Data": "%s"}} + } + """.formatted(rawB64)) + .when().post("/v2/email/outbound-emails").then().statusCode(200); + + List events = receiveEvents(2); + JsonNode bounce = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + assertEquals(CS, bounce.path("mail").path("tags").path("ses:configuration-set").get(0).asText(), + "A Raw send without FromEmailAddress must route through the identity default " + + "configuration set resolved from the MIME From header"); + } + + @Test + @Order(9) + void putConfigurationSet_whitespaceOnlyBody_returnsSerializationExceptionAndKeepsAssociation() { + // Re-associate so we can confirm a whitespace-only body does NOT clear. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(200); + + // A whitespace-only body is a serialization error on real AWS, not a silent clear. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(" \n") + .when().put("/v2/email/identities/" + IDENTITY + "/configuration-set") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")); + + // The association is unchanged (the invalid body neither cleared nor updated it). + given().header("Authorization", SES_AUTH) + .when().get("/v2/email/identities/" + IDENTITY) + .then().statusCode(200) + .body("ConfigurationSetName", equalTo(CS)); + } + + @Test + @Order(10) + void sendThroughIdentityWhoseDefaultConfigSetWasDeleted_returns400() { + // Verified against the SES Developer Guide: deleting the configuration set that is an + // identity's default, then sending through that identity, fails with a bad-request error. + String id = "cs-attr-stale@floci.test"; + String cs = "cs-attr-stale-cs"; + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"EmailIdentity\":\"" + id + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + cs + "\"}") + .when().post("/v2/email/configuration-sets").then().statusCode(200); + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ConfigurationSetName\":\"" + cs + "\"}") + .when().put("/v2/email/identities/" + id + "/configuration-set").then().statusCode(200); + + // Delete the configuration set that is now the identity's default. + given().header("Authorization", SES_AUTH) + .when().delete("/v2/email/configuration-sets/" + cs).then().statusCode(200); + + // A send with no explicit ConfigurationSetName must fail rather than silently drop it. + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + { + "FromEmailAddress": "%s", + "Destination": {"ToAddresses": ["bounce@simulator.amazonses.com"]}, + "Content": {"Simple": {"Subject": {"Data": "stale"}, "Body": {"Text": {"Data": "hi"}}}} + } + """.formatted(id)) + .when().post("/v2/email/outbound-emails").then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Configuration set <" + cs + "> does not exist.")); + } + + private void drainQueue() { + for (int i = 0; i < 5; i++) { + Response r = given().contentType(JSON_10).header("Authorization", SQS_AUTH) + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":10,\"WaitTimeSeconds\":0}") + .when().post("/").then().statusCode(200).extract().response(); + List handles = r.jsonPath().getList("Messages.ReceiptHandle"); + if (handles == null || handles.isEmpty()) { + return; + } + deleteMessages(handles); + } + } + + private List receiveEvents(int expectedAtLeast) throws Exception { + List events = new ArrayList<>(); + for (int attempt = 0; attempt < 10 && events.size() < expectedAtLeast; attempt++) { + Response r = given().contentType(JSON_10).header("Authorization", SQS_AUTH) + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":10,\"WaitTimeSeconds\":1}") + .when().post("/").then().statusCode(200).extract().response(); + List bodies = r.jsonPath().getList("Messages.Body"); + List handles = r.jsonPath().getList("Messages.ReceiptHandle"); + if (bodies == null || bodies.isEmpty()) { + continue; + } + for (String body : bodies) { + JsonNode wrapper = MAPPER.readTree(body); + events.add(MAPPER.readTree(wrapper.path("Message").asText())); + } + deleteMessages(handles); + } + return events; + } + + private void deleteMessages(List receiptHandles) { + StringBuilder entries = new StringBuilder(); + for (int i = 0; i < receiptHandles.size(); i++) { + if (i > 0) { + entries.append(","); + } + entries.append("{\"Id\":\"m").append(i).append("\",\"ReceiptHandle\":\"") + .append(receiptHandles.get(i)).append("\"}"); + } + given().contentType(JSON_10).header("Authorization", SQS_AUTH) + .header("X-Amz-Target", "AmazonSQS.DeleteMessageBatch") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"Entries\":[" + entries + "]}") + .when().post("/").then().statusCode(200); + } +}