feat(ses): publish SES events to SNS configuration set destinations (#1106)

* feat(ses): publish SES events to SNS configuration set destinations

Add SES V2 event publishing to SnsDestination targets configured on a
ConfigurationSet. When SendEmail / SendRawEmail / SendTemplatedEmail /
SendBulkEmail is invoked with a ConfigurationSetName, Floci builds the
matching AWS-format event payload (a `mail` block plus an event-type-
specific block) and publishes it to each enabled SNS destination whose
MatchingEventTypes includes that event.

Events emitted
- SEND on every successful send.
- DELIVERY / BOUNCE / COMPLAINT / REJECT when a recipient matches the
  corresponding AWS mailbox simulator address (success@ / bounce@ /
  complaint@ / suppressionlist@simulator.amazonses.com).
- Per-event-type recipient lists (delivery.recipients,
  bounce.bouncedRecipients, complaint.complainedRecipients) are
  filtered to only the simulator address that triggered the event and
  emitted in their canonical trimmed form; mail.destination carries
  the full envelope.

Wire-level fidelity
- Event payload mirrors the AWS SES SNS notification format documented
  at https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-examples.html.
- mail.tags includes user-supplied EmailTags / DefaultEmailTags /
  ReplacementTags (V2) and Tags.member.N / DefaultTags.member.N /
  Destinations.member.N.ReplacementTags (V1 Query). Each tag emits as
  {Name: [Value]}.
- mail.headers[] appends user-supplied Content.Simple.Headers and
  Content.Template.Headers after the auto-emitted From/To/Cc/Subject;
  null/blank Names are rejected with "The header name must be
  specified." (BadRequestException 400).
- V2 SendBulkEmail BulkEmailEntries accept ReplacementTags (merged by
  Name onto DefaultEmailTags) and ReplacementHeaders (merged
  case-insensitively per RFC 5322 onto DefaultContent.Template.Headers).
- mail.sendingAccountId resolves from EmulatorConfig.defaultAccountId().
- ConfigurationSet existence is validated up-front on sendEmail /
  sendRawEmail / sendBulkTemplatedEmail — an unknown name fails fast
  with ConfigurationSetDoesNotExist (V2 controller remaps to
  NotFoundException 404, V1 returns 400) before any message is stored
  or relayed.

Validation errors aligned with live AWS
- EmailTags blank Name: BadRequestException 400 "The tag name must be
  specified." (V2) / InvalidParameterValue 400 same message (V1).
- ConfigurationSetName not found: same error code, status, and message
  as AWS.

Raw email handling
- For V2 SendEmail with Raw content (and V1 SendRawEmail), when the
  caller did not provide Destinations, Floci falls back to To/Cc/Bcc
  parsed from the raw MIME via SmtpRelay.parseRawHeaders (extracted
  from the existing relay logic). MIME parsing is only invoked when
  needed (no explicit Destinations or event publishing active).

Internal shape
- New records: model/MessageTag (Name, Value, for EmailTags) and
  model/MessageHeader (Name, Value, for Content.Headers) — kept
  distinct from the resource-tag Tag (Key, Value).
- SesEventPublisher dispatches to SnsService; non-SNS destination
  types log a warning and are skipped (Firehose / EventBridge /
  CloudWatch / Pinpoint), and missing SnsDestination.TopicArn likewise
  warns instead of silently dropping. Failures preserve the throwable
  in the warn log.

Tests
- SesEventPayloadTest covers mail/commonHeaders/headers/tags shape,
  per-event filtering, and the headers/tags propagation paths.
- SesServiceMergeEmailTagsTest / SesServiceMergeHeadersTest pin Bulk
  Default vs per-entry merge semantics (tags by Name case-sensitive,
  headers by Name case-insensitive per RFC 5322).
- SesEventPublishingV2IntegrationTest exercises Send / Delivery /
  Bounce / SendOnly / mixed-recipient / disabled-destination /
  V1-MIME-fallback / EmailTags / V1-Tags / Simple.Headers paths
  end-to-end through SES -> SNS -> SQS.
- compatibility-tests/sdk-test-java/SesEventPublishingTest validates
  SendEmail with EmailTags/Headers and SendBulkEmail with per-entry
  ReplacementHeaders override using AWS Java SDK V2 clients.

* fix(ses): address Copilot review on upstream PR #1106

- SesService.validateConfigurationSet: clarify the Javadoc — the
  helper always throws with httpStatus = 400, and the V2 controller's
  remapV1Exception is what turns ConfigurationSetDoesNotExist into
  NotFoundException 404. The previous "(404 in V2, 400 in V1)" hint
  read as if the helper itself picked the status, which is misleading.
- SesController.parseEmailTagsArray: reject non-object entries with
  "<fieldName> entries must be JSON objects.", mirroring the existing
  parseHeadersArray check. Previously a string/number element would
  hit the blank-Name path and report a less specific message.
- SesService.mergeHeaders / mergeEmailTags: also skip entries whose
  name is the empty string, not just null. Both parsers reject blank
  names at the boundary, but defending the merge helpers keeps them
  safe for direct callers (e.g., future tests) and matches the intent
  of the boundary validation.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-06-01 00:20:37 -05:00
1 parent d33d6b67c0
commit 35211adc4a
19 files changed
+2184 -32

No files matched your search

@@ -0,0 +1,249 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.github.hectorvent.floci.services.ses.model.MessageTag;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests for {@link SesEventPayload}'s JSON shape, mirroring the AWS SES
* SNS notification format documented at
* https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-contents.html.
*/
class SesEventPayloadTest {
private final ObjectMapper mapper = new ObjectMapper();
private final Instant ts = Instant.parse("2026-05-30T00:00:00Z");
@Test
void send_buildsMailBlockWithCommonHeadersAndTags() {
ObjectNode node = SesEventPayload.build(mapper, "SEND", "msg-1", "from@example.com",
"arn:aws:ses:us-east-1:000000000000:identity/from@example.com",
"000000000000", "Hello", List.of("to@example.com"), List.of("cc@example.com"),
List.of(), List.of("to@example.com", "cc@example.com"), "my-cs", List.of(), List.of(), ts);
assertEquals("Send", node.get("eventType").asText());
assertTrue(node.has("send"));
ObjectNode mail = (ObjectNode) node.get("mail");
assertEquals("from@example.com", mail.get("source").asText());
assertEquals("msg-1", mail.get("messageId").asText());
assertEquals("2026-05-30T00:00:00.000Z", mail.get("timestamp").asText());
assertEquals("000000000000", mail.get("sendingAccountId").asText());
assertEquals("to@example.com", mail.get("destination").get(0).asText());
// headers array contains From, To, Cc, Subject
ObjectNode commonHeaders = (ObjectNode) mail.get("commonHeaders");
assertEquals("msg-1", commonHeaders.get("messageId").asText());
assertEquals("Sat, 30 May 2026 00:00:00 +0000", commonHeaders.get("date").asText());
assertEquals("from@example.com", commonHeaders.get("from").get(0).asText());
assertEquals("to@example.com", commonHeaders.get("to").get(0).asText());
assertEquals("cc@example.com", commonHeaders.get("cc").get(0).asText());
assertFalse(commonHeaders.has("bcc"));
assertEquals("Hello", commonHeaders.get("subject").asText());
// headers array
assertTrue(mail.get("headers").isArray());
String headers = mail.get("headers").toString();
assertTrue(headers.contains("\"name\":\"From\""));
assertTrue(headers.contains("\"name\":\"To\""));
assertTrue(headers.contains("\"name\":\"Cc\""));
assertTrue(headers.contains("\"name\":\"Subject\""));
// tags
assertEquals("my-cs", mail.get("tags").get("ses:configuration-set").get(0).asText());
}
@Test
void delivery_includesRecipientsAndSmtpResponse() {
ObjectNode node = SesEventPayload.build(mapper, "DELIVERY", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("success@simulator.amazonses.com"), List.of(), List.of(),
List.of("success@simulator.amazonses.com"), "cs", List.of(), List.of(), ts);
assertEquals("Delivery", node.get("eventType").asText());
ObjectNode delivery = (ObjectNode) node.get("delivery");
assertEquals("success@simulator.amazonses.com",
delivery.get("recipients").get(0).asText());
assertNotNull(delivery.get("smtpResponse"));
assertNotNull(delivery.get("reportingMTA"));
}
@Test
void bounce_includesBouncedRecipientsAndPermanentType() {
ObjectNode node = SesEventPayload.build(mapper, "BOUNCE", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("bounce@simulator.amazonses.com"), List.of(), List.of(),
List.of("bounce@simulator.amazonses.com"), "cs", List.of(), List.of(), ts);
assertEquals("Bounce", node.get("eventType").asText());
ObjectNode bounce = (ObjectNode) node.get("bounce");
assertEquals("Permanent", bounce.get("bounceType").asText());
assertEquals("General", bounce.get("bounceSubType").asText());
assertEquals("bounce@simulator.amazonses.com",
bounce.get("bouncedRecipients").get(0).get("emailAddress").asText());
}
@Test
void complaint_includesComplainedRecipients() {
ObjectNode node = SesEventPayload.build(mapper, "COMPLAINT", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("complaint@simulator.amazonses.com"), List.of(), List.of(),
List.of("complaint@simulator.amazonses.com"), "cs", List.of(), List.of(), ts);
assertEquals("Complaint", node.get("eventType").asText());
assertEquals("complaint@simulator.amazonses.com",
node.get("complaint").get("complainedRecipients").get(0).get("emailAddress").asText());
}
@Test
void bounce_filtersBouncedRecipientsToBounceSimulatorOnly() {
ObjectNode node = SesEventPayload.build(mapper, "BOUNCE", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("normal@example.com", "bounce@simulator.amazonses.com"),
List.of(), List.of(),
List.of("normal@example.com", "bounce@simulator.amazonses.com"),
"cs", List.of(), List.of(), ts);
var bounced = (com.fasterxml.jackson.databind.node.ArrayNode)
node.get("bounce").get("bouncedRecipients");
assertEquals(1, bounced.size());
assertEquals("bounce@simulator.amazonses.com",
bounced.get(0).get("emailAddress").asText());
// mail.destination retains the full envelope
assertEquals(2, node.get("mail").get("destination").size());
}
@Test
void delivery_filtersRecipientsToSuccessSimulatorOnly() {
ObjectNode node = SesEventPayload.build(mapper, "DELIVERY", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("normal@example.com", "success@simulator.amazonses.com"),
List.of(), List.of(),
List.of("normal@example.com", "success@simulator.amazonses.com"),
"cs", List.of(), List.of(), ts);
var recipients = node.get("delivery").get("recipients");
assertEquals(1, recipients.size());
assertEquals("success@simulator.amazonses.com", recipients.get(0).asText());
}
@Test
void complaint_filtersComplainedRecipientsToComplaintSimulatorOnly() {
ObjectNode node = SesEventPayload.build(mapper, "COMPLAINT", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("normal@example.com", "complaint@simulator.amazonses.com"),
List.of(), List.of(),
List.of("normal@example.com", "complaint@simulator.amazonses.com"),
"cs", List.of(), List.of(), ts);
var complained = node.get("complaint").get("complainedRecipients");
assertEquals(1, complained.size());
assertEquals("complaint@simulator.amazonses.com",
complained.get(0).get("emailAddress").asText());
}
@Test
void send_emailTagsAppearInMailTagsAlongsideConfigurationSet() {
ObjectNode node = SesEventPayload.build(mapper, "SEND", "msg-1", "from@example.com",
null, "000000000000", "Hello",
List.of("to@example.com"), List.of(), List.of(),
List.of("to@example.com"),
"my-cs",
List.of(new MessageTag("campaign", "launch"), new MessageTag("env", "prod")),
List.of(),
ts);
ObjectNode tags = (ObjectNode) node.get("mail").get("tags");
assertEquals("my-cs", tags.get("ses:configuration-set").get(0).asText());
assertEquals("launch", tags.get("campaign").get(0).asText());
assertEquals("prod", tags.get("env").get(0).asText());
}
@Test
void send_emailTagsTolerateNullValueAndDuplicateKey() {
ObjectNode node = SesEventPayload.build(mapper, "SEND", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("to@example.com"), List.of(), List.of(),
List.of("to@example.com"),
"cs",
List.of(new MessageTag("k", null), new MessageTag("k", "v2")),
List.of(),
ts);
var arr = node.get("mail").get("tags").get("k");
assertEquals(2, arr.size(), "duplicate keys append into the same array");
assertEquals("", arr.get(0).asText());
assertEquals("v2", arr.get(1).asText());
}
@Test
void send_additionalHeadersAppendToMailHeadersAfterAutoHeaders() {
ObjectNode node = SesEventPayload.build(mapper, "SEND", "msg-1", "from@example.com",
null, "000000000000", "Hi",
List.of("to@example.com"), List.of(), List.of(),
List.of("to@example.com"),
"cs",
List.of(),
List.of(
new MessageHeader("X-Mailer", "floci"),
new MessageHeader("List-Unsubscribe", "<mailto:u@example.com>")),
ts);
ArrayNode headers = (ArrayNode) node.get("mail").get("headers");
// From, To, Subject auto-emitted first; then user headers in order.
assertEquals("From", headers.get(0).get("name").asText());
assertEquals("To", headers.get(1).get("name").asText());
assertEquals("Subject", headers.get(2).get("name").asText());
assertEquals("X-Mailer", headers.get(3).get("name").asText());
assertEquals("floci", headers.get(3).get("value").asText());
assertEquals("List-Unsubscribe", headers.get(4).get("name").asText());
}
@Test
void send_additionalHeadersSkipNullOrBlankName() {
ObjectNode node = SesEventPayload.build(mapper, "SEND", "msg-1", "from@example.com",
null, "000000000000", "Hi",
List.of("to@example.com"), List.of(), List.of(),
List.of("to@example.com"),
"cs",
List.of(),
List.of(
new MessageHeader(null, "ignored"),
new MessageHeader("", "ignored-too"),
new MessageHeader("X-Real", "ok")),
ts);
ArrayNode headers = (ArrayNode) node.get("mail").get("headers");
// Only the auto headers (From/To/Subject) and the single valid X-Real.
boolean hasXReal = false;
for (com.fasterxml.jackson.databind.JsonNode h : headers) {
String name = h.path("name").asText();
assertFalse(name.isBlank(), "no blank-named header should be emitted");
if ("X-Real".equals(name)) {
hasXReal = true;
}
}
assertTrue(hasXReal);
}
@Test
void reject_hasReason() {
ObjectNode node = SesEventPayload.build(mapper, "REJECT", "msg-1", "from@example.com",
null, "000000000000", "",
List.of("suppressionlist@simulator.amazonses.com"), List.of(), List.of(),
List.of("suppressionlist@simulator.amazonses.com"), "cs", List.of(), List.of(), ts);
assertEquals("Reject", node.get("eventType").asText());
assertNotNull(node.get("reject").get("reason"));
}
}
@@ -0,0 +1,547 @@
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.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End-to-end integration test for SES V2 event publishing: SES SendEmail with a
* ConfigurationSetName whose event destination points at an SNS topic results in
* AWS-format event JSON being published to that topic and delivered to a
* subscribed SQS queue.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesEventPublishingV2IntegrationTest {
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 SQS_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String SNS_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String CS = "ses-events-cs";
private static final String SENDER = "evt-from@floci.test";
private static String queueUrl;
private static String queueArn;
private static String topicArn;
private static final ObjectMapper MAPPER = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void setupSqsQueueAndSnsTopicAndSubscription() {
queueUrl = given()
.contentType(SQS_CONTENT_TYPE)
.header("Authorization", SQS_AUTH)
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
.body("{\"QueueName\":\"ses-events-queue\"}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("QueueUrl");
assertNotNull(queueUrl);
queueArn = given()
.contentType(SQS_CONTENT_TYPE)
.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");
assertNotNull(queueArn);
topicArn = given()
.contentType(SNS_CONTENT_TYPE)
.header("Authorization", SNS_AUTH)
.header("X-Amz-Target", "SNS_20100331.CreateTopic")
.body("{\"Name\":\"ses-events-topic\"}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("TopicArn");
assertNotNull(topicArn);
given()
.contentType(SNS_CONTENT_TYPE)
.header("Authorization", SNS_AUTH)
.header("X-Amz-Target", "SNS_20100331.Subscribe")
.body("{\"TopicArn\":\"" + topicArn + "\",\"Protocol\":\"sqs\",\"Endpoint\":\"" + queueArn + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(2)
void setupSesIdentityConfigSetAndEventDestination() {
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("{\"EmailIdentity\":\"" + SENDER + "\"}")
.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("""
{
"EventDestinationName": "ed-sns",
"EventDestination": {
"Enabled": true,
"MatchingEventTypes": ["SEND", "DELIVERY", "BOUNCE", "COMPLAINT", "REJECT"],
"SnsDestination": {"TopicArn": "%s"}
}
}
""".formatted(topicArn))
.when()
.post("/v2/email/configuration-sets/" + CS + "/event-destinations")
.then()
.statusCode(200);
}
@Test
@Order(3)
void sendToSuccessSimulator_publishesSendAndDelivery() throws Exception {
drainQueue();
sendEmail("success@simulator.amazonses.com");
List<JsonNode> events = receiveSesEvents(2);
assertEquals(2, events.size(), "expected Send and Delivery events");
assertTrue(events.stream().anyMatch(e -> "Send".equals(e.path("eventType").asText())));
assertTrue(events.stream().anyMatch(e -> "Delivery".equals(e.path("eventType").asText())));
JsonNode delivery = events.stream()
.filter(e -> "Delivery".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
assertEquals(SENDER, delivery.path("mail").path("source").asText());
assertEquals("success@simulator.amazonses.com",
delivery.path("delivery").path("recipients").get(0).asText());
assertEquals(CS, delivery.path("mail").path("tags").path("ses:configuration-set").get(0).asText());
assertEquals("evt", delivery.path("mail").path("commonHeaders").path("subject").asText());
assertEquals("success@simulator.amazonses.com",
delivery.path("mail").path("commonHeaders").path("to").get(0).asText());
assertTrue(delivery.path("mail").path("commonHeaders").path("date").asText().length() > 0);
}
@Test
@Order(4)
void sendToBounceSimulator_publishesSendAndBounce() throws Exception {
drainQueue();
sendEmail("bounce@simulator.amazonses.com");
List<JsonNode> events = receiveSesEvents(2);
assertEquals(2, events.size());
assertTrue(events.stream().anyMatch(e -> "Send".equals(e.path("eventType").asText())));
JsonNode bounce = events.stream()
.filter(e -> "Bounce".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
assertEquals("Permanent", bounce.path("bounce").path("bounceType").asText());
assertEquals("bounce@simulator.amazonses.com",
bounce.path("bounce").path("bouncedRecipients").get(0).path("emailAddress").asText());
assertEquals("evt", bounce.path("mail").path("commonHeaders").path("subject").asText());
}
@Test
@Order(5)
void sendToRegularAddress_publishesSendOnly() throws Exception {
drainQueue();
sendEmail("recipient@example.com");
List<JsonNode> events = receiveSesEvents(1);
assertEquals(1, events.size());
assertEquals("Send", events.get(0).path("eventType").asText());
}
@Test
@Order(6)
void v1SendRawEmail_recipientOnlyInMimeHeader_publishesBounceFromMimeTo() throws Exception {
drainQueue();
String raw = "From: " + SENDER + "\r\n"
+ "To: bounce@simulator.amazonses.com\r\n"
+ "Subject: mime-only\r\n\r\nbody";
String rawB64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SES_AUTH)
.body("Action=SendRawEmail"
+ "&Source=" + java.net.URLEncoder.encode(SENDER, java.nio.charset.StandardCharsets.UTF_8)
+ "&RawMessage.Data=" + java.net.URLEncoder.encode(rawB64, java.nio.charset.StandardCharsets.UTF_8)
+ "&ConfigurationSetName=" + CS
+ "&Version=2010-12-01")
.when()
.post("/")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
assertEquals(2, events.size(), "expected Send and Bounce events from MIME-only recipient");
assertTrue(events.stream().anyMatch(e -> "Send".equals(e.path("eventType").asText())));
JsonNode bounce = events.stream()
.filter(e -> "Bounce".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
assertEquals("bounce@simulator.amazonses.com",
bounce.path("bounce").path("bouncedRecipients").get(0).path("emailAddress").asText());
assertEquals("mime-only", bounce.path("mail").path("commonHeaders").path("subject").asText());
assertEquals("bounce@simulator.amazonses.com",
bounce.path("mail").path("commonHeaders").path("to").get(0).asText());
}
@Test
@Order(7)
void disabledEventDestination_skipsPublish() throws Exception {
String csDisabled = "v2-cs-ed-disabled";
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("{\"ConfigurationSetName\":\"" + csDisabled + "\"}")
.when()
.post("/v2/email/configuration-sets")
.then()
.statusCode(200);
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("""
{
"EventDestinationName": "ed-sns-disabled",
"EventDestination": {
"Enabled": false,
"MatchingEventTypes": ["SEND", "DELIVERY", "BOUNCE"],
"SnsDestination": {"TopicArn": "%s"}
}
}
""".formatted(topicArn))
.when()
.post("/v2/email/configuration-sets/" + csDisabled + "/event-destinations")
.then()
.statusCode(200);
drainQueue();
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["success@simulator.amazonses.com"]},
"ConfigurationSetName": "%s",
"Content": {
"Simple": {
"Subject": {"Data": "should-not-publish"},
"Body": {"Text": {"Data": "hi"}}
}
}
}
""".formatted(SENDER, csDisabled))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(0);
assertEquals(0, events.size(), "disabled event destination should skip publishing");
}
@Test
@Order(8)
void mixedRecipients_filterBouncedRecipientsToSimulatorOnly() throws Exception {
drainQueue();
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["normal@example.com", "bounce@simulator.amazonses.com"]},
"ConfigurationSetName": "%s",
"Content": {
"Simple": {
"Subject": {"Data": "mixed"},
"Body": {"Text": {"Data": "hi"}}
}
}
}
""".formatted(SENDER, CS))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
assertEquals(2, events.size(), "expected Send and Bounce events");
assertTrue(events.stream().anyMatch(e -> "Send".equals(e.path("eventType").asText())));
JsonNode bounce = events.stream()
.filter(e -> "Bounce".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
JsonNode bouncedRecipients = bounce.path("bounce").path("bouncedRecipients");
assertEquals(1, bouncedRecipients.size(),
"bouncedRecipients should contain only the simulator address, not normal recipients");
assertEquals("bounce@simulator.amazonses.com",
bouncedRecipients.get(0).path("emailAddress").asText());
// mail.destination keeps the full envelope recipient list
assertEquals(2, bounce.path("mail").path("destination").size());
}
@Test
@Order(9)
void sendEmail_emailTagsPropagateIntoMailTags() throws Exception {
drainQueue();
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["success@simulator.amazonses.com"]},
"ConfigurationSetName": "%s",
"EmailTags": [
{"Name": "campaign", "Value": "launch"},
{"Name": "env", "Value": "prod"}
],
"Content": {
"Simple": {
"Subject": {"Data": "tagged"},
"Body": {"Text": {"Data": "hi"}}
}
}
}
""".formatted(SENDER, CS))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
assertTrue(events.size() >= 1, "expected at least Send event");
JsonNode send = events.stream()
.filter(e -> "Send".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
JsonNode tags = send.path("mail").path("tags");
assertEquals(CS, tags.path("ses:configuration-set").get(0).asText());
assertEquals("launch", tags.path("campaign").get(0).asText());
assertEquals("prod", tags.path("env").get(0).asText());
}
@Test
@Order(10)
void v1SendEmail_messageTagsPropagateIntoMailTags() throws Exception {
drainQueue();
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SES_AUTH)
.body("Action=SendEmail"
+ "&Source=" + java.net.URLEncoder.encode(SENDER, java.nio.charset.StandardCharsets.UTF_8)
+ "&Destination.ToAddresses.member.1="
+ java.net.URLEncoder.encode("success@simulator.amazonses.com",
java.nio.charset.StandardCharsets.UTF_8)
+ "&Message.Subject.Data=v1tagged"
+ "&Message.Body.Text.Data=hi"
+ "&Tags.member.1.Name=campaign&Tags.member.1.Value=v1launch"
+ "&Tags.member.2.Name=env&Tags.member.2.Value=staging"
+ "&ConfigurationSetName=" + CS
+ "&Version=2010-12-01")
.when()
.post("/")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
JsonNode send = events.stream()
.filter(e -> "Send".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
JsonNode tags = send.path("mail").path("tags");
assertEquals("v1launch", tags.path("campaign").get(0).asText());
assertEquals("staging", tags.path("env").get(0).asText());
}
@Test
@Order(11)
void sendEmail_simpleHeadersAppearInEventMailHeaders() throws Exception {
drainQueue();
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["success@simulator.amazonses.com"]},
"ConfigurationSetName": "%s",
"Content": {
"Simple": {
"Subject": {"Data": "hdr"},
"Body": {"Text": {"Data": "hi"}},
"Headers": [
{"Name": "X-Mailer", "Value": "floci"},
{"Name": "List-Unsubscribe", "Value": "<mailto:u@example.com>"}
]
}
}
}
""".formatted(SENDER, CS))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
JsonNode send = events.stream()
.filter(e -> "Send".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
JsonNode headers = send.path("mail").path("headers");
boolean hasXMailer = false;
boolean hasUnsubscribe = false;
for (JsonNode h : headers) {
if ("X-Mailer".equals(h.path("name").asText())
&& "floci".equals(h.path("value").asText())) {
hasXMailer = true;
}
if ("List-Unsubscribe".equals(h.path("name").asText())) {
hasUnsubscribe = true;
}
}
assertTrue(hasXMailer, "expected X-Mailer header in event mail.headers");
assertTrue(hasUnsubscribe, "expected List-Unsubscribe header in event mail.headers");
}
private void sendEmail(String to) {
given()
.contentType("application/json")
.header("Authorization", SES_AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["%s"]},
"ConfigurationSetName": "%s",
"Content": {
"Simple": {
"Subject": {"Data": "evt"},
"Body": {"Text": {"Data": "hi"}}
}
}
}
""".formatted(SENDER, to, CS))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(200);
}
private void drainQueue() {
for (int i = 0; i < 5; i++) {
Response r = given()
.contentType(SQS_CONTENT_TYPE)
.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<String> handles = r.jsonPath().getList("Messages.ReceiptHandle");
if (handles == null || handles.isEmpty()) {
return;
}
deleteMessages(handles);
}
}
private List<JsonNode> receiveSesEvents(int expectedAtLeast) throws Exception {
List<JsonNode> events = new ArrayList<>();
// When we're confirming "no event arrives", a couple of long-poll attempts is
// enough — SES → SNS → SQS propagates in seconds locally. Keep 10 attempts only
// when we're actually waiting for events to appear.
int maxAttempts = expectedAtLeast > 0 ? 10 : 2;
for (int attempt = 0; attempt < maxAttempts; attempt++) {
if (expectedAtLeast > 0 && events.size() >= expectedAtLeast) {
break;
}
Response r = given()
.contentType(SQS_CONTENT_TYPE)
.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<String> bodies = r.jsonPath().getList("Messages.Body");
List<String> handles = r.jsonPath().getList("Messages.ReceiptHandle");
if (bodies == null || bodies.isEmpty()) {
continue;
}
for (String body : bodies) {
JsonNode snsWrapper = MAPPER.readTree(body);
JsonNode sesEvent = MAPPER.readTree(snsWrapper.path("Message").asText());
events.add(sesEvent);
}
deleteMessages(handles);
}
return events;
}
private void deleteMessages(List<String> 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(SQS_CONTENT_TYPE)
.header("Authorization", SQS_AUTH)
.header("X-Amz-Target", "AmazonSQS.DeleteMessageBatch")
.body("{\"QueueUrl\":\"" + queueUrl + "\",\"Entries\":[" + entries + "]}")
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.MessageTag;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Covers {@link SesService#mergeEmailTags(List, List)} — the per-entry tag merge used by
* V2 {@code SendBulkEmail} (DefaultEmailTags + per-entry ReplacementTags) and the V1 Query
* equivalent (DefaultTags + Destinations.member.N.ReplacementTags). AWS replaces by tag
* name: a per-entry tag with the same name as a default tag overrides the default value.
*/
class SesServiceMergeEmailTagsTest {
@Test
void mergeEmailTags_nullsAndEmptiesReturnEmpty() {
assertTrue(SesService.mergeEmailTags(null, null).isEmpty());
assertTrue(SesService.mergeEmailTags(List.of(), null).isEmpty());
assertTrue(SesService.mergeEmailTags(null, List.of()).isEmpty());
assertTrue(SesService.mergeEmailTags(List.of(), List.of()).isEmpty());
}
@Test
void mergeEmailTags_replacementOverridesByName() {
List<MessageTag> defaults = List.of(
new MessageTag("env", "prod"),
new MessageTag("campaign", "launch"));
List<MessageTag> replacement = List.of(new MessageTag("campaign", "vip"));
List<MessageTag> merged = SesService.mergeEmailTags(defaults, replacement);
assertEquals(2, merged.size());
assertEquals("prod", findValue(merged, "env"));
assertEquals("vip", findValue(merged, "campaign"));
}
@Test
void mergeEmailTags_replacementOnlyNamesAreAdded() {
List<MessageTag> defaults = List.of(new MessageTag("env", "prod"));
List<MessageTag> replacement = List.of(new MessageTag("locale", "ja-JP"));
List<MessageTag> merged = SesService.mergeEmailTags(defaults, replacement);
assertEquals(2, merged.size());
assertEquals("prod", findValue(merged, "env"));
assertEquals("ja-JP", findValue(merged, "locale"));
}
private static String findValue(List<MessageTag> tags, String name) {
return tags.stream().filter(t -> name.equals(t.name())).findFirst()
.orElseThrow().value();
}
}
@@ -0,0 +1,72 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Covers {@link SesService#mergeHeaders(List, List)} — the per-entry header merge used by
* V2 {@code SendBulkEmail} (DefaultContent.Template.Headers + per-entry
* ReplacementHeaders). AWS replaces by header name: a per-entry header with the same Name
* as a default header overrides the default value.
*/
class SesServiceMergeHeadersTest {
@Test
void mergeHeaders_nullsAndEmptiesReturnEmpty() {
assertTrue(SesService.mergeHeaders(null, null).isEmpty());
assertTrue(SesService.mergeHeaders(List.of(), null).isEmpty());
assertTrue(SesService.mergeHeaders(null, List.of()).isEmpty());
assertTrue(SesService.mergeHeaders(List.of(), List.of()).isEmpty());
}
@Test
void mergeHeaders_replacementOverridesByName() {
List<MessageHeader> defaults = List.of(
new MessageHeader("X-Mailer", "floci-default"),
new MessageHeader("List-Unsubscribe", "<mailto:default@example.com>"));
List<MessageHeader> replacement = List.of(
new MessageHeader("X-Mailer", "floci-override"));
List<MessageHeader> merged = SesService.mergeHeaders(defaults, replacement);
assertEquals(2, merged.size());
assertEquals("floci-override", findValue(merged, "X-Mailer"));
assertEquals("<mailto:default@example.com>", findValue(merged, "List-Unsubscribe"));
}
@Test
void mergeHeaders_caseInsensitiveOverrideKeepsReplacementCasing() {
// RFC 5322 makes header field names case-insensitive, so a per-entry
// lowercase "x-mailer" should override a default "X-Mailer".
List<MessageHeader> defaults = List.of(new MessageHeader("X-Mailer", "floci-default"));
List<MessageHeader> replacement = List.of(new MessageHeader("x-mailer", "floci-override"));
List<MessageHeader> merged = SesService.mergeHeaders(defaults, replacement);
assertEquals(1, merged.size(), "case differences should not produce duplicate entries");
assertEquals("x-mailer", merged.get(0).name(), "replacement's casing wins on override");
assertEquals("floci-override", merged.get(0).value());
}
@Test
void mergeHeaders_replacementOnlyNamesAreAdded() {
List<MessageHeader> defaults = List.of(new MessageHeader("X-Mailer", "floci"));
List<MessageHeader> replacement = List.of(new MessageHeader("X-Custom", "v1"));
List<MessageHeader> merged = SesService.mergeHeaders(defaults, replacement);
assertEquals(2, merged.size());
assertEquals("floci", findValue(merged, "X-Mailer"));
assertEquals("v1", findValue(merged, "X-Custom"));
}
private static String findValue(List<MessageHeader> headers, String name) {
return headers.stream().filter(h -> name.equals(h.name())).findFirst()
.orElseThrow().value();
}
}
@@ -49,7 +49,7 @@ class SesServiceSmtpTest {
List.of("cc@example.com"),
List.of("bcc@example.com"),
List.of("reply@example.com"),
"Subject", "text body", "<p>html</p>", "us-east-1");
"Subject", "text body", "<p>html</p>", null, List.of(), List.of(), "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
@@ -64,7 +64,7 @@ class SesServiceSmtpTest {
void sendEmail_storesAndRelays() {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
"Subject", "text", null, "us-east-1");
"Subject", "text", null, null, List.of(), List.of(), "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
@@ -74,7 +74,7 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_callsRelayRaw() {
service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", "us-east-1");
List.of("to@example.com"), "raw MIME", null, List.of(), "us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
@@ -85,7 +85,7 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_storesAndRelays() {
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw", "us-east-1");
List.of("to@example.com"), "raw", null, List.of(), "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
@@ -97,7 +97,7 @@ class SesServiceSmtpTest {
service.sendEmail("from@example.com",
List.of("to@example.com"),
null, null, null,
"Subject", null, "<p>html only</p>", "us-east-1");
"Subject", null, "<p>html only</p>", null, List.of(), List.of(), "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.services.ses;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SimulatorAddressesTest {
@Test
void recognisesSuccess() {
assertTrue(SimulatorAddresses.isSuccess("success@simulator.amazonses.com"));
assertTrue(SimulatorAddresses.isSuccess("SUCCESS@SIMULATOR.AMAZONSES.COM"));
assertTrue(SimulatorAddresses.isSuccess(" success@simulator.amazonses.com "));
}
@Test
void recognisesBounce() {
assertTrue(SimulatorAddresses.isBounce("bounce@simulator.amazonses.com"));
}
@Test
void recognisesComplaint() {
assertTrue(SimulatorAddresses.isComplaint("complaint@simulator.amazonses.com"));
}
@Test
void recognisesSuppressionList() {
assertTrue(SimulatorAddresses.isSuppressionList("suppressionlist@simulator.amazonses.com"));
}
@Test
void rejectsRegularAddresses() {
assertFalse(SimulatorAddresses.isSuccess("user@example.com"));
assertFalse(SimulatorAddresses.isBounce("user@example.com"));
assertFalse(SimulatorAddresses.isComplaint("user@example.com"));
assertFalse(SimulatorAddresses.isSuppressionList("user@example.com"));
}
@Test
void handlesNullSafely() {
assertFalse(SimulatorAddresses.isSuccess(null));
assertFalse(SimulatorAddresses.isBounce(null));
assertFalse(SimulatorAddresses.isComplaint(null));
assertFalse(SimulatorAddresses.isSuppressionList(null));
}
}
@@ -275,4 +275,62 @@ class SmtpRelayTest {
assertDoesNotThrow(() -> relay.relayRaw("from@example.com",
List.of("to@example.com"), "Subject: X\r\n\r\nBody"));
}
@Test
void parseRawRecipients_extractsToCcBcc() {
String raw = "From: sender@example.com\r\n"
+ "To: to1@example.com, to2@example.com\r\n"
+ "Cc: cc@example.com\r\n"
+ "Bcc: bcc@example.com\r\n"
+ "Subject: test\r\n\r\nbody";
List<String> recipients = SmtpRelay.parseRawRecipients(raw);
assertEquals(List.of("to1@example.com", "to2@example.com", "cc@example.com", "bcc@example.com"),
recipients);
}
@Test
void parseRawRecipients_acceptsBase64Encoded() {
String raw = "From: a@example.com\r\nTo: only@example.com\r\nSubject: x\r\n\r\nbody";
String b64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
assertEquals(List.of("only@example.com"), SmtpRelay.parseRawRecipients(b64));
}
@Test
void parseRawRecipients_blankOrUnparseable_returnsEmpty() {
assertTrue(SmtpRelay.parseRawRecipients(null).isEmpty());
assertTrue(SmtpRelay.parseRawRecipients("").isEmpty());
assertTrue(SmtpRelay.parseRawRecipients(" ").isEmpty());
}
@Test
void parseRawRecipients_noRecipientHeaders_returnsEmpty() {
String raw = "From: a@example.com\r\nSubject: x\r\n\r\nbody";
assertTrue(SmtpRelay.parseRawRecipients(raw).isEmpty());
}
@Test
void parseRawHeaders_extractsSubjectAndStructuredRecipients() {
String raw = "From: sender@example.com\r\n"
+ "To: to1@example.com, to2@example.com\r\n"
+ "Cc: cc@example.com\r\n"
+ "Bcc: bcc@example.com\r\n"
+ "Subject: Hello world\r\n\r\nbody";
String b64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(b64);
assertEquals("Hello world", h.subject());
assertEquals(List.of("to1@example.com", "to2@example.com"), h.to());
assertEquals(List.of("cc@example.com"), h.cc());
assertEquals(List.of("bcc@example.com"), h.bcc());
}
@Test
void parseRawHeaders_blank_returnsEmptyRecord() {
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(null);
assertEquals("", h.subject());
assertTrue(h.to().isEmpty());
assertTrue(h.cc().isEmpty());
assertTrue(h.bcc().isEmpty());
}
}