diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java new file mode 100644 index 0000000000..97e7a2fc99 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java @@ -0,0 +1,352 @@ +package com.floci.test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.Body; +import software.amazon.awssdk.services.sesv2.model.BulkEmailContent; +import software.amazon.awssdk.services.sesv2.model.BulkEmailEntry; +import software.amazon.awssdk.services.sesv2.model.Content; +import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetEventDestinationRequest; +import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetEventDestinationRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.Destination; +import software.amazon.awssdk.services.sesv2.model.EmailContent; +import software.amazon.awssdk.services.sesv2.model.EmailTemplateContent; +import software.amazon.awssdk.services.sesv2.model.EventDestinationDefinition; +import software.amazon.awssdk.services.sesv2.model.EventType; +import software.amazon.awssdk.services.sesv2.model.Message; +import software.amazon.awssdk.services.sesv2.model.MessageHeader; +import software.amazon.awssdk.services.sesv2.model.MessageTag; +import software.amazon.awssdk.services.sesv2.model.SendBulkEmailRequest; +import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; +import software.amazon.awssdk.services.sesv2.model.SnsDestination; +import software.amazon.awssdk.services.sesv2.model.Template; + +import software.amazon.awssdk.services.sns.SnsClient; +import software.amazon.awssdk.services.sns.model.CreateTopicRequest; +import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; +import software.amazon.awssdk.services.sns.model.SubscribeRequest; +import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; + +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; +import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest; +import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry; +import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; +import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; +import software.amazon.awssdk.services.sqs.model.QueueAttributeName; +import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; +import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * SES event-publishing compatibility tests using the AWS SDK for Java v2. + * + * Drives the entire flow through real SDK clients (SesV2Client / SnsClient / + * SqsClient): create a configuration set + SNS event destination, send via + * SesV2Client.SendEmail with ConfigurationSetName, then receive the resulting + * SES event JSON from a subscribed SQS queue and assert the AWS-format shape. + */ +@DisplayName("SES Event Publishing") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesEventPublishingTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String EVENT_DEST_NAME = "ed-sns"; + + private static SesV2Client ses; + private static SnsClient sns; + private static SqsClient sqs; + private static String csName; + private static String identity; + private static String queueUrl; + private static String queueArn; + private static String topicArn; + private static String subscriptionArn; + + @BeforeAll + static void setup() { + ses = TestFixtures.sesV2Client(); + sns = TestFixtures.snsClient(); + sqs = TestFixtures.sqsClient(); + String suffix = TestFixtures.uniqueName(); + csName = "sdk-evt-cs-" + suffix; + identity = "sdk-evt-from-" + suffix + "@floci.test"; + + queueUrl = sqs.createQueue(CreateQueueRequest.builder() + .queueName("sdk-evt-q-" + suffix) + .build()) + .queueUrl(); + queueArn = sqs.getQueueAttributes(GetQueueAttributesRequest.builder() + .queueUrl(queueUrl) + .attributeNames(QueueAttributeName.QUEUE_ARN) + .build()) + .attributes().get(QueueAttributeName.QUEUE_ARN); + + topicArn = sns.createTopic(CreateTopicRequest.builder() + .name("sdk-evt-t-" + suffix) + .build()) + .topicArn(); + + subscriptionArn = sns.subscribe(SubscribeRequest.builder() + .topicArn(topicArn) + .protocol("sqs") + .endpoint(queueArn) + .build()) + .subscriptionArn(); + + ses.createEmailIdentity(CreateEmailIdentityRequest.builder() + .emailIdentity(identity) + .build()); + + ses.createConfigurationSet(CreateConfigurationSetRequest.builder() + .configurationSetName(csName) + .build()); + + ses.createConfigurationSetEventDestination(CreateConfigurationSetEventDestinationRequest.builder() + .configurationSetName(csName) + .eventDestinationName(EVENT_DEST_NAME) + .eventDestination(EventDestinationDefinition.builder() + .enabled(true) + .matchingEventTypes(EventType.SEND, EventType.DELIVERY, EventType.BOUNCE, + EventType.COMPLAINT, EventType.REJECT) + .snsDestination(SnsDestination.builder().topicArn(topicArn).build()) + .build()) + .build()); + } + + @AfterAll + static void cleanup() { + if (ses != null) { + try { + ses.deleteConfigurationSetEventDestination(DeleteConfigurationSetEventDestinationRequest.builder() + .configurationSetName(csName) + .eventDestinationName(EVENT_DEST_NAME) + .build()); + } catch (Exception ignored) {} + try { + ses.deleteConfigurationSet(DeleteConfigurationSetRequest.builder() + .configurationSetName(csName) + .build()); + } catch (Exception ignored) {} + try { + ses.deleteEmailIdentity(DeleteEmailIdentityRequest.builder() + .emailIdentity(identity) + .build()); + } catch (Exception ignored) {} + ses.close(); + } + if (sns != null) { + try { + sns.unsubscribe(UnsubscribeRequest.builder().subscriptionArn(subscriptionArn).build()); + } catch (Exception ignored) {} + try { + sns.deleteTopic(DeleteTopicRequest.builder().topicArn(topicArn).build()); + } catch (Exception ignored) {} + sns.close(); + } + if (sqs != null) { + try { + sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build()); + } catch (Exception ignored) {} + sqs.close(); + } + } + + @Test + @Order(1) + void sendToSuccessSimulator_publishesSendAndDelivery() throws Exception { + drainQueue(); + sendEmailTo("success@simulator.amazonses.com"); + List events = receiveEvents(2); + + assertThat(events).hasSize(2); + assertThat(events).anyMatch(e -> "Send".equals(e.path("eventType").asText())); + JsonNode delivery = events.stream() + .filter(e -> "Delivery".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + assertThat(delivery.path("mail").path("source").asText()).isEqualTo(identity); + assertThat(delivery.path("delivery").path("recipients").get(0).asText()) + .isEqualTo("success@simulator.amazonses.com"); + JsonNode tags = delivery.path("mail").path("tags"); + assertThat(tags.path("ses:configuration-set").get(0).asText()).isEqualTo(csName); + assertThat(tags.path("campaign").get(0).asText()).isEqualTo("launch"); + assertThat(tags.path("env").get(0).asText()).isEqualTo("prod"); + assertThat(delivery.path("mail").path("commonHeaders").path("subject").asText()) + .isEqualTo("evt"); + assertThat(delivery.path("mail").path("commonHeaders").path("to").get(0).asText()) + .isEqualTo("success@simulator.amazonses.com"); + assertThat(delivery.path("mail").path("commonHeaders").path("date").asText()).isNotEmpty(); + boolean hasXMailer = false; + boolean hasUnsubscribe = false; + for (JsonNode h : delivery.path("mail").path("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; + } + } + assertThat(hasXMailer).as("X-Mailer header in event mail.headers").isTrue(); + assertThat(hasUnsubscribe).as("List-Unsubscribe header in event mail.headers").isTrue(); + } + + @Test + @Order(2) + void sendToBounceSimulator_publishesSendAndBounce() throws Exception { + drainQueue(); + sendEmailTo("bounce@simulator.amazonses.com"); + List events = receiveEvents(2); + + assertThat(events).hasSize(2); + assertThat(events).anyMatch(e -> "Send".equals(e.path("eventType").asText())); + JsonNode bounce = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + assertThat(bounce.path("bounce").path("bounceType").asText()).isEqualTo("Permanent"); + assertThat(bounce.path("bounce").path("bouncedRecipients").get(0).path("emailAddress").asText()) + .isEqualTo("bounce@simulator.amazonses.com"); + } + + @Test + @Order(3) + void sendToRegularAddress_publishesSendOnly() throws Exception { + drainQueue(); + sendEmailTo("recipient@example.com"); + List events = receiveEvents(1); + + assertThat(events).hasSize(1); + assertThat(events.get(0).path("eventType").asText()).isEqualTo("Send"); + } + + @Test + @Order(4) + void sendBulkEmail_perEntryReplacementHeadersOverrideDefault() throws Exception { + drainQueue(); + ses.sendBulkEmail(SendBulkEmailRequest.builder() + .fromEmailAddress(identity) + .configurationSetName(csName) + .defaultContent(BulkEmailContent.builder() + .template(Template.builder() + .templateContent(EmailTemplateContent.builder() + .subject("bulk-subject") + .text("bulk body") + .build()) + .headers(MessageHeader.builder() + .name("X-Mailer").value("default").build()) + .build()) + .build()) + .bulkEmailEntries(BulkEmailEntry.builder() + .destination(Destination.builder() + .toAddresses("success@simulator.amazonses.com").build()) + .replacementHeaders(MessageHeader.builder() + .name("X-Mailer").value("override").build()) + .build()) + .build()); + + List events = receiveEvents(2); + JsonNode send = events.stream() + .filter(e -> "Send".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + String xMailer = null; + for (JsonNode h : send.path("mail").path("headers")) { + if ("X-Mailer".equals(h.path("name").asText())) { + xMailer = h.path("value").asText(); + } + } + assertThat(xMailer).as("X-Mailer in event mail.headers (per-entry should override default)") + .isEqualTo("override"); + } + + private void sendEmailTo(String to) { + ses.sendEmail(SendEmailRequest.builder() + .fromEmailAddress(identity) + .destination(Destination.builder().toAddresses(to).build()) + .configurationSetName(csName) + .emailTags( + MessageTag.builder().name("campaign").value("launch").build(), + MessageTag.builder().name("env").value("prod").build()) + .content(EmailContent.builder() + .simple(Message.builder() + .subject(Content.builder().data("evt").build()) + .body(Body.builder() + .text(Content.builder().data("hi").build()) + .build()) + .headers( + MessageHeader.builder().name("X-Mailer").value("floci").build(), + MessageHeader.builder().name("List-Unsubscribe") + .value("").build()) + .build()) + .build()) + .build()); + } + + private void drainQueue() { + for (int i = 0; i < 5; i++) { + ReceiveMessageResponse r = sqs.receiveMessage(ReceiveMessageRequest.builder() + .queueUrl(queueUrl) + .maxNumberOfMessages(10) + .waitTimeSeconds(0) + .build()); + if (r.messages().isEmpty()) { + return; + } + deleteBatch(r); + } + } + + private List receiveEvents(int expectedAtLeast) throws Exception { + List events = new ArrayList<>(); + for (int attempt = 0; attempt < 10; attempt++) { + if (expectedAtLeast > 0 && events.size() >= expectedAtLeast) { + break; + } + ReceiveMessageResponse r = sqs.receiveMessage(ReceiveMessageRequest.builder() + .queueUrl(queueUrl) + .maxNumberOfMessages(10) + .waitTimeSeconds(1) + .build()); + if (r.messages().isEmpty()) { + continue; + } + for (var m : r.messages()) { + JsonNode wrapper = MAPPER.readTree(m.body()); + JsonNode event = MAPPER.readTree(wrapper.path("Message").asText()); + events.add(event); + } + deleteBatch(r); + } + return events; + } + + private void deleteBatch(ReceiveMessageResponse r) { + List entries = new ArrayList<>(); + for (int i = 0; i < r.messages().size(); i++) { + entries.add(DeleteMessageBatchRequestEntry.builder() + .id("m" + i) + .receiptHandle(r.messages().get(i).receiptHandle()) + .build()); + } + sqs.deleteMessageBatch(DeleteMessageBatchRequest.builder() + .queueUrl(queueUrl) + .entries(entries) + .build()); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index 852d587e55..0490d3d015 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -195,7 +195,20 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `DELETE` | `/v2/email/tags?ResourceArn=...&TagKeys=...` | `UntagResource` | | `GET` | `/v2/email/tags?ResourceArn=...` | `ListTagsForResource` | -Configuration set event destinations are stored as configuration only. The target (SNS, CloudWatch, Kinesis Firehose, EventBridge, or Pinpoint) is not validated for existence, and Floci does not emit send/bounce/delivery events to it. Each event destination must specify exactly one destination type and at least one matching event type. A CloudWatch destination requires a non-empty dimension configuration list, and a Pinpoint destination requires an application ARN. +Configuration set event destinations are stored as configuration. The target is not validated for existence; missing targets cause Floci to log a warning and skip that destination. Each event destination must specify exactly one destination type and at least one matching event type. A CloudWatch destination requires a non-empty dimension configuration list, and a Pinpoint destination requires an application ARN. + +Floci publishes SES events to `SnsDestination` only in this version (`KinesisFirehoseDestination` / `EventBridgeDestination` / `CloudWatchDestination` / `PinpointDestination` log a warning and skip). The published payload matches the AWS SES SNS notification format with an outer `eventType` plus `mail` and event-type-specific blocks. Events fire whenever a configuration set has at least one event destination matching the event type — disable per-destination via `EventDestination.Enabled=false`, or remove the destination entirely. + +Floci recognises the AWS [mailbox simulator addresses](https://docs.aws.amazon.com/ses/latest/dg/send-an-email-from-console.html#send-email-simulator) for deterministic event-type emission: + +| Recipient address | Events emitted (in addition to `Send`) | +|---|---| +| `success@simulator.amazonses.com` | `Delivery` | +| `bounce@simulator.amazonses.com` | `Bounce` | +| `complaint@simulator.amazonses.com` | `Complaint` | +| `suppressionlist@simulator.amazonses.com` | `Reject` | + +A successful send without a simulator-address recipient emits only the `Send` event. Suppression list entries are stored per region. `Reason` is `BOUNCE` or `COMPLAINT`. `SendEmail` is not yet integrated with the suppression list, so suppressed addresses are still delivered locally. 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 d009477cfb..7d0ae7fd96 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 @@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.EventDestination; import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.services.ses.model.MessageHeader; +import io.github.hectorvent.floci.services.ses.model.MessageTag; import io.github.hectorvent.floci.services.ses.model.SuppressedDestination; import io.github.hectorvent.floci.services.ses.model.Tag; import com.fasterxml.jackson.databind.JsonNode; @@ -271,6 +273,9 @@ public class SesController { List ccAddresses = jsonArrayToList(destination.path("CcAddresses")); List bccAddresses = jsonArrayToList(destination.path("BccAddresses")); List replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses")); + List allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses); + String configurationSetName = request.path("ConfigurationSetName").asText(null); + List emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags"); JsonNode content = request.path("Content"); String messageId; @@ -281,19 +286,21 @@ public class SesController { throw new AwsException("BadRequestException", "Content.Raw.Data is required.", 400); } - List allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses); if (allDestinations.isEmpty()) { throw new AwsException("BadRequestException", "At least one destination address is required.", 400); } - messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData, region); + messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData, + configurationSetName, emailTags, region); } else if (content.has("Simple")) { JsonNode simple = content.path("Simple"); String subject = simple.path("Subject").path("Data").asText(""); String bodyText = simple.path("Body").path("Text").path("Data").asText(null); String bodyHtml = simple.path("Body").path("Html").path("Data").asText(null); + List additionalHeaders = parseHeadersArray(simple.path("Headers")); messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, subject, bodyText, bodyHtml, region); + bccAddresses, replyToAddresses, subject, bodyText, bodyHtml, + configurationSetName, emailTags, additionalHeaders, region); } else if (content.has("Template")) { JsonNode template = content.path("Template"); String templateName = template.path("TemplateName").asText(null); @@ -312,12 +319,14 @@ public class SesController { "Content.Template requires TemplateName, TemplateArn, or TemplateContent.", 400); } JsonNode templateData = parseTemplateData(template, "TemplateData"); + List additionalHeaders = parseHeadersArray(template.path("Headers")); if (hasName || hasArn) { String resolvedName = hasName ? templateName : SesService.templateNameFromArn(templateArn); messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, resolvedName, templateData, region); + bccAddresses, replyToAddresses, resolvedName, templateData, + configurationSetName, emailTags, additionalHeaders, region); } else { JsonNode inline = template.path("TemplateContent"); String subject = inline.path("Subject").asText(null); @@ -325,7 +334,8 @@ public class SesController { String html = inline.path("Html").asText(null); messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses, bccAddresses, replyToAddresses, - subject, text, html, templateData, region); + subject, text, html, templateData, + configurationSetName, emailTags, additionalHeaders, region); } } else { throw new AwsException("BadRequestException", @@ -363,6 +373,7 @@ public class SesController { "FromEmailAddress is required.", 400); } List replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses")); + String configurationSetName = request.path("ConfigurationSetName").asText(null); JsonNode template = request.path("DefaultContent").path("Template"); if (template.isMissingNode() || template.isNull()) { @@ -404,6 +415,8 @@ public class SesController { } JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData"); + List defaultEmailTags = parseEmailTagsArray(request.path("DefaultEmailTags"), "DefaultEmailTags"); + List defaultHeaders = parseHeadersArray(template.path("Headers")); JsonNode bulkEntries = request.path("BulkEmailEntries"); if (!bulkEntries.isArray() || bulkEntries.isEmpty()) { @@ -424,12 +437,15 @@ public class SesController { JsonNode replacementContent = requireObjectOrAbsent(node, "ReplacementEmailContent"); JsonNode replacementTemplate = requireObjectOrAbsent(replacementContent, "ReplacementTemplate"); JsonNode replacementData = parseTemplateData(replacementTemplate, "ReplacementTemplateData"); - entries.add(new BulkEmailEntry(to, cc, bcc, replacementData)); + List replacementTags = parseEmailTagsArray(node.path("ReplacementTags"), "ReplacementTags"); + List entryReplacementHeaders = parseHeadersArray(node.path("ReplacementHeaders")); + entries.add(new BulkEmailEntry(to, cc, bcc, replacementData, replacementTags, entryReplacementHeaders)); } List results = sesService.sendBulkTemplatedEmail(fromEmailAddress, replyToAddresses, subject, text, html, - defaultTemplateData, entries, region); + defaultTemplateData, entries, configurationSetName, + defaultEmailTags, defaultHeaders, region); ObjectNode response = objectMapper.createObjectNode(); ArrayNode arr = response.putArray("BulkEmailEntryResults"); @@ -1179,6 +1195,69 @@ public class SesController { return out; } + /** + * Parse a V2 SES {@code Content.Simple.Headers} / {@code Content.Template.Headers} array + * (additional message headers, elements use {@code Name}/{@code Value}). Returns an empty + * list when the node is absent so callers can pass it through unconditionally. + */ + private List parseHeadersArray(JsonNode headersNode) { + if (headersNode.isMissingNode() || headersNode.isNull()) { + return List.of(); + } + if (!headersNode.isArray()) { + throw new AwsException("BadRequestException", "Headers must be an array.", 400); + } + List out = new ArrayList<>(); + for (JsonNode h : headersNode) { + if (!h.isObject()) { + throw new AwsException("BadRequestException", + "Headers entries must be JSON objects.", 400); + } + String name = h.path("Name").asText(null); + String value = h.path("Value").asText(null); + if (name == null || name.isBlank()) { + throw new AwsException("BadRequestException", + "The header name must be specified.", 400); + } + out.add(new MessageHeader(name, value)); + } + return out; + } + + /** + * Parse a V2 SES {@code EmailTags} / {@code DefaultEmailTags} / {@code ReplacementTags} + * array (per-message {@link MessageTag} list whose elements use {@code Name}/{@code Value}, + * distinct from the resource-tag {@link Tag} {@code Key}/{@code Value} shape). Note that + * the per-entry name is {@code ReplacementTags} on the wire — only the top-level field + * carries the {@code EmailTags} suffix. Returns an empty list when the node is absent so + * callers can pass it through unconditionally. + * The {@code fieldName} parameter is reported in the error message when the node is + * present but not an array. + */ + private List parseEmailTagsArray(JsonNode tagsNode, String fieldName) { + if (tagsNode.isMissingNode() || tagsNode.isNull()) { + return List.of(); + } + if (!tagsNode.isArray()) { + throw new AwsException("BadRequestException", fieldName + " must be an array.", 400); + } + List out = new ArrayList<>(); + for (JsonNode t : tagsNode) { + if (!t.isObject()) { + throw new AwsException("BadRequestException", + fieldName + " entries must be JSON objects.", 400); + } + String name = t.path("Name").asText(null); + String value = t.path("Value").asText(null); + if (name == null || name.isBlank()) { + throw new AwsException("BadRequestException", + "The tag name must be specified.", 400); + } + out.add(new MessageTag(name, value)); + } + return out; + } + private static AwsException remapV1Exception(AwsException e) { return switch (e.getErrorCode()) { case "InvalidParameterValue", "InvalidTemplate", diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPayload.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPayload.java new file mode 100644 index 0000000000..cef427f00f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPayload.java @@ -0,0 +1,224 @@ +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 java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Locale; + +/** + * Builds the AWS SES event-publishing JSON for a single sent message. + * + *

The output shape matches the SES SNS notification format documented at + * https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-contents.html + * — an outer {@code eventType} plus a {@code mail} object and an event-type + * specific body block. + */ +final class SesEventPayload { + + private static final DateTimeFormatter ISO_MILLIS = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + + private static final DateTimeFormatter RFC_5322_DATE = + DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH) + .withZone(ZoneOffset.UTC); + + private SesEventPayload() {} + + static ObjectNode build(ObjectMapper mapper, String eventType, String messageId, String source, + String sourceArn, String sendingAccountId, String subject, + List toAddresses, List ccAddresses, + List bccAddresses, List envelopeDestinations, + String configurationSetName, List emailTags, + List additionalHeaders, Instant timestamp) { + ObjectNode root = mapper.createObjectNode(); + root.put("eventType", eventTypeLabel(eventType)); + root.set("mail", buildMail(mapper, messageId, source, sourceArn, sendingAccountId, + subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations, + configurationSetName, emailTags, additionalHeaders, timestamp)); + root.set(blockName(eventType), + buildEventBlock(mapper, eventType, messageId, envelopeDestinations, timestamp)); + return root; + } + + private static ObjectNode buildMail(ObjectMapper mapper, String messageId, String source, + String sourceArn, String sendingAccountId, + String subject, List toAddresses, + List ccAddresses, List bccAddresses, + List envelopeDestinations, + String configurationSetName, List emailTags, + List additionalHeaders, + Instant timestamp) { + ObjectNode mail = mapper.createObjectNode(); + mail.put("timestamp", ISO_MILLIS.format(timestamp)); + if (source != null && !source.isBlank()) { + mail.put("source", source); + } + if (sourceArn != null) { + mail.put("sourceArn", sourceArn); + } + mail.put("sendingAccountId", sendingAccountId); + mail.put("messageId", messageId); + ArrayNode dest = mail.putArray("destination"); + for (String d : envelopeDestinations) { + dest.add(d); + } + mail.put("headersTruncated", false); + ArrayNode headers = mail.putArray("headers"); + if (source != null && !source.isBlank()) { + addHeader(headers, mapper, "From", source); + } + if (toAddresses != null && !toAddresses.isEmpty()) { + addHeader(headers, mapper, "To", String.join(", ", toAddresses)); + } + if (ccAddresses != null && !ccAddresses.isEmpty()) { + addHeader(headers, mapper, "Cc", String.join(", ", ccAddresses)); + } + if (subject != null && !subject.isEmpty()) { + addHeader(headers, mapper, "Subject", subject); + } + if (additionalHeaders != null) { + for (MessageHeader h : additionalHeaders) { + if (h == null || h.name() == null || h.name().isBlank()) { + continue; + } + addHeader(headers, mapper, h.name(), h.value() == null ? "" : h.value()); + } + } + ObjectNode common = mail.putObject("commonHeaders"); + common.put("messageId", messageId); + common.put("date", RFC_5322_DATE.format(timestamp)); + ArrayNode fromArr = common.putArray("from"); + if (source != null && !source.isBlank()) { + fromArr.add(source); + } + ArrayNode toArr = common.putArray("to"); + if (toAddresses != null) { + for (String a : toAddresses) { + toArr.add(a); + } + } + if (ccAddresses != null && !ccAddresses.isEmpty()) { + ArrayNode ccArr = common.putArray("cc"); + for (String a : ccAddresses) { + ccArr.add(a); + } + } + if (bccAddresses != null && !bccAddresses.isEmpty()) { + ArrayNode bccArr = common.putArray("bcc"); + for (String a : bccAddresses) { + bccArr.add(a); + } + } + if (subject != null && !subject.isEmpty()) { + common.put("subject", subject); + } + ObjectNode tags = mail.putObject("tags"); + if (configurationSetName != null) { + ArrayNode csTag = tags.putArray("ses:configuration-set"); + csTag.add(configurationSetName); + } + if (emailTags != null) { + for (MessageTag t : emailTags) { + if (t == null || t.name() == null) { + continue; + } + ArrayNode arr = tags.has(t.name()) + ? (ArrayNode) tags.get(t.name()) + : tags.putArray(t.name()); + arr.add(t.value() == null ? "" : t.value()); + } + } + return mail; + } + + private static void addHeader(ArrayNode headers, ObjectMapper mapper, String name, String value) { + ObjectNode h = mapper.createObjectNode(); + h.put("name", name); + h.put("value", value); + headers.add(h); + } + + private static ObjectNode buildEventBlock(ObjectMapper mapper, String eventType, String messageId, + List destination, Instant timestamp) { + ObjectNode body = mapper.createObjectNode(); + switch (eventType) { + case "DELIVERY" -> { + body.put("timestamp", ISO_MILLIS.format(timestamp)); + body.put("processingTimeMillis", 0); + ArrayNode recipients = body.putArray("recipients"); + for (String d : destination) { + if (SimulatorAddresses.isSuccess(d)) { + recipients.add(d.trim()); + } + } + body.put("smtpResponse", "250 ok"); + body.put("reportingMTA", "floci"); + } + case "BOUNCE" -> { + body.put("bounceType", "Permanent"); + body.put("bounceSubType", "General"); + ArrayNode bounced = body.putArray("bouncedRecipients"); + for (String d : destination) { + if (SimulatorAddresses.isBounce(d)) { + ObjectNode br = bounced.addObject(); + br.put("emailAddress", d.trim()); + } + } + body.put("timestamp", ISO_MILLIS.format(timestamp)); + body.put("feedbackId", "feedback-" + messageId); + } + case "COMPLAINT" -> { + ArrayNode complained = body.putArray("complainedRecipients"); + for (String d : destination) { + if (SimulatorAddresses.isComplaint(d)) { + ObjectNode cr = complained.addObject(); + cr.put("emailAddress", d.trim()); + } + } + body.put("timestamp", ISO_MILLIS.format(timestamp)); + body.put("feedbackId", "feedback-" + messageId); + } + case "REJECT" -> body.put("reason", "Bad content"); + default -> { + // SEND and other not-yet-modelled event types: empty block. + } + } + return body; + } + + private static String eventTypeLabel(String eventType) { + return switch (eventType) { + case "SEND" -> "Send"; + case "REJECT" -> "Reject"; + case "BOUNCE" -> "Bounce"; + case "COMPLAINT" -> "Complaint"; + case "DELIVERY" -> "Delivery"; + case "OPEN" -> "Open"; + case "CLICK" -> "Click"; + case "RENDERING_FAILURE" -> "Rendering Failure"; + case "DELIVERY_DELAY" -> "DeliveryDelay"; + case "SUBSCRIPTION" -> "Subscription"; + default -> eventType; + }; + } + + private static String blockName(String eventType) { + return switch (eventType) { + case "SEND" -> "send"; + case "REJECT" -> "reject"; + case "BOUNCE" -> "bounce"; + case "COMPLAINT" -> "complaint"; + case "DELIVERY" -> "delivery"; + case "RENDERING_FAILURE" -> "failure"; + case "DELIVERY_DELAY" -> "deliveryDelay"; + default -> eventType.toLowerCase(Locale.ROOT); + }; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java new file mode 100644 index 0000000000..679cc65fdd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java @@ -0,0 +1,104 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; +import io.github.hectorvent.floci.services.ses.model.EventDestination; +import io.github.hectorvent.floci.services.ses.model.MessageHeader; +import io.github.hectorvent.floci.services.ses.model.MessageTag; +import io.github.hectorvent.floci.services.sns.SnsService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.List; + +/** + * Publishes SES event-publishing notifications to the event destinations attached + * to a {@link ConfigurationSet}. This MVP only delivers to {@code SnsDestination}; + * Firehose, EventBridge, CloudWatch, and Pinpoint destinations are logged and skipped. + */ +@ApplicationScoped +public class SesEventPublisher { + + private static final Logger LOG = Logger.getLogger(SesEventPublisher.class); + + private final SnsService snsService; + private final ObjectMapper objectMapper; + + @Inject + public SesEventPublisher(SnsService snsService, ObjectMapper objectMapper) { + this.snsService = snsService; + this.objectMapper = objectMapper; + } + + public void publish(ConfigurationSet configurationSet, String eventType, String messageId, + String source, String sourceArn, String sendingAccountId, + String subject, List toAddresses, List ccAddresses, + List bccAddresses, List envelopeDestinations, + List emailTags, List additionalHeaders, + Instant timestamp, String defaultRegion) { + if (configurationSet == null || configurationSet.getEventDestinations().isEmpty()) { + return; + } + ObjectNode payload = SesEventPayload.build(objectMapper, eventType, messageId, source, + sourceArn, sendingAccountId, subject, + toAddresses, ccAddresses, bccAddresses, envelopeDestinations, + configurationSet.getName(), emailTags, additionalHeaders, timestamp); + String payloadJson = payload.toString(); + for (EventDestination ed : configurationSet.getEventDestinations()) { + if (!ed.isEnabled()) { + continue; + } + if (ed.getMatchingEventTypes() == null + || !ed.getMatchingEventTypes().contains(eventType)) { + continue; + } + try { + dispatch(ed, eventType, payloadJson, defaultRegion); + } catch (Exception e) { + LOG.warnf(e, "Failed to publish SES event %s to destination %s", + eventType, ed.getName()); + } + } + } + + private void dispatch(EventDestination ed, String eventType, String payloadJson, String defaultRegion) { + if (ed.getSnsDestination() != null) { + String topicArn = ed.getSnsDestination().getTopicArn(); + if (topicArn == null || topicArn.isBlank()) { + LOG.warnf("SES SNS destination %s: event %s not delivered (TopicArn is missing).", + ed.getName(), eventType); + return; + } + publishSns(topicArn, payloadJson, defaultRegion); + return; + } + if (ed.getPinpointDestination() != null) { + LOG.warnf("SES Pinpoint destination %s: event %s not delivered (Pinpoint service not implemented in Floci).", + ed.getName(), eventType); + return; + } + if (ed.getKinesisFirehoseDestination() != null + || ed.getEventBridgeDestination() != null + || ed.getCloudWatchDestination() != null) { + LOG.warnf("SES destination %s: event %s not delivered (only SNS publishing is implemented).", + ed.getName(), eventType); + return; + } + LOG.warnf("SES destination %s: event %s not delivered (no destination target configured).", + ed.getName(), eventType); + } + + private void publishSns(String topicArn, String payload, String defaultRegion) { + String region = AwsArnUtils.regionOrDefault(topicArn, defaultRegion); + try { + snsService.publish(topicArn, null, payload, null, region); + } catch (AwsException e) { + LOG.warnf(e, "SES event publish to SNS topic %s skipped", topicArn); + } + } +} 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 8ddfc44b96..5fbefb842a 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 @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.services.ses.model.MessageTag; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.enterprise.context.ApplicationScoped; @@ -158,9 +159,12 @@ public class SesQueryHandler { String subject = getParam(params, "Message.Subject.Data"); String bodyText = getParam(params, "Message.Body.Text.Data"); String bodyHtml = getParam(params, "Message.Body.Html.Data"); + String configurationSetName = getParam(params, "ConfigurationSetName"); + List emailTags = extractMessageTags(params, "Tags"); String messageId = sesService.sendEmail(source, toAddresses, ccAddresses, bccAddresses, - replyToAddresses, subject, bodyText, bodyHtml, region); + replyToAddresses, subject, bodyText, bodyHtml, configurationSetName, + emailTags, List.of(), region); String result = new XmlBuilder().elem("MessageId", messageId).build(); return Response.ok(AwsQueryResponse.envelope("SendEmail", AwsNamespaces.SES, result)).build(); @@ -174,8 +178,11 @@ public class SesQueryHandler { String source = getParam(params, "Source"); List destinations = extractMembers(params, "Destinations"); String rawMessage = getParam(params, "RawMessage.Data"); + String configurationSetName = getParam(params, "ConfigurationSetName"); + List emailTags = extractMessageTags(params, "Tags"); - String messageId = sesService.sendRawEmail(source, destinations, rawMessage, region); + String messageId = sesService.sendRawEmail(source, destinations, rawMessage, + configurationSetName, emailTags, region); String result = new XmlBuilder().elem("MessageId", messageId).build(); return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build(); @@ -436,8 +443,11 @@ public class SesQueryHandler { String resolvedName = hasName ? templateName : SesService.templateNameFromArn(templateArn); JsonNode templateData = parseTemplateData(templateDataRaw); + String configurationSetName = getParam(params, "ConfigurationSetName"); + List emailTags = extractMessageTags(params, "Tags"); String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, resolvedName, templateData, region); + bccAddresses, replyToAddresses, resolvedName, templateData, + configurationSetName, emailTags, List.of(), region); String result = new XmlBuilder().elem("MessageId", messageId).build(); return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build(); @@ -485,19 +495,25 @@ public class SesQueryHandler { List cc = extractMembers(params, destPrefix + ".Destination.CcAddresses"); List bcc = extractMembers(params, destPrefix + ".Destination.BccAddresses"); String replacementRaw = getParam(params, destPrefix + ".ReplacementTemplateData"); - if (to.isEmpty() && cc.isEmpty() && bcc.isEmpty() && replacementRaw == null) { + List replacementTags = extractMessageTags(params, destPrefix + ".ReplacementTags"); + if (to.isEmpty() && cc.isEmpty() && bcc.isEmpty() + && replacementRaw == null && replacementTags.isEmpty()) { break; } - entries.add(new BulkEmailEntry(to, cc, bcc, parseTemplateData(replacementRaw))); + entries.add(new BulkEmailEntry(to, cc, bcc, + parseTemplateData(replacementRaw), replacementTags, List.of())); } if (entries.isEmpty()) { throw new AwsException("InvalidParameterValue", "At least one destination is required.", 400); } + String configurationSetName = getParam(params, "ConfigurationSetName"); + List defaultEmailTags = extractMessageTags(params, "DefaultTags"); List results = sesService.sendBulkTemplatedEmail(source, replyToAddresses, template.getSubject(), template.getTextPart(), template.getHtmlPart(), - defaultTemplateData, entries, region); + defaultTemplateData, entries, configurationSetName, + defaultEmailTags, List.of(), region); XmlBuilder xml = new XmlBuilder().start("Status"); for (BulkEmailEntryResult result : results) { @@ -594,6 +610,26 @@ public class SesQueryHandler { return members; } + /** + * Parse a V1 SES {@code MessageTag} list ({@code .member.N.Name} / + * {@code .Value}) into a list of {@link MessageTag} records. Returns an empty list when + * no members are present. + */ + private List extractMessageTags(MultivaluedMap params, String prefix) { + List tags = new ArrayList<>(); + for (int i = 1; ; i++) { + String name = getParam(params, prefix + ".member." + i + ".Name"); + String value = getParam(params, prefix + ".member." + i + ".Value"); + if (name == null && value == null) break; + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", + "The tag name must be specified.", 400); + } + tags.add(new MessageTag(name, value)); + } + return tags; + } + private String getParam(MultivaluedMap params, String name) { return params.getFirst(name); } 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 c9d6369b19..663509c5a7 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.ses; +import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -11,6 +12,8 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.EventDestination; import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.services.ses.model.MessageHeader; +import io.github.hectorvent.floci.services.ses.model.MessageTag; import io.github.hectorvent.floci.services.ses.model.SentEmail; import io.github.hectorvent.floci.services.ses.model.SuppressedDestination; import io.github.hectorvent.floci.services.ses.model.Tag; @@ -34,6 +37,7 @@ import java.util.HexFormat; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -61,9 +65,12 @@ public class SesService { private final StorageBackend accountSuppressionStore; private final SmtpRelay smtpRelay; private final ObjectMapper objectMapper; + private final SesEventPublisher eventPublisher; + private final String defaultAccountId; @Inject - public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper) { + public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper, + SesEventPublisher eventPublisher, EmulatorConfig config) { this.identityStore = storageFactory.create("ses", "ses-identities.json", new TypeReference>() {}); this.emailStore = storageFactory.create("ses", "ses-emails.json", @@ -80,6 +87,8 @@ public class SesService { new TypeReference>() {}); this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; + this.eventPublisher = eventPublisher; + this.defaultAccountId = config.defaultAccountId(); } SesService(StorageBackend identityStore, @@ -100,6 +109,8 @@ public class SesService { this.accountSuppressionStore = accountSuppressionStore; this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; + this.eventPublisher = null; + this.defaultAccountId = "000000000000"; } public Identity verifyEmailIdentity(String emailAddress, String region) { @@ -171,7 +182,9 @@ public class SesService { public String sendEmail(String source, List toAddresses, List ccAddresses, List bccAddresses, List replyToAddresses, - String subject, String bodyText, String bodyHtml, String region) { + String subject, String bodyText, String bodyHtml, + String configurationSetName, List emailTags, + List additionalHeaders, String region) { if (source == null || source.isBlank()) { throw new AwsException("InvalidParameterValue", "Source email is required.", 400); } @@ -181,6 +194,7 @@ public class SesService { if (!hasRecipient) { throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400); } + validateConfigurationSet(configurationSetName, region); String messageId = UUID.randomUUID().toString(); SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses, @@ -192,25 +206,138 @@ 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, + toAddresses, ccAddresses, bccAddresses, + allRecipients(toAddresses, ccAddresses, bccAddresses), + emailTags, additionalHeaders, region); return messageId; } - public String sendRawEmail(String source, List destinations, String rawMessage, String region) { + public String sendRawEmail(String source, List destinations, String rawMessage, + String configurationSetName, List emailTags, + String region) { if (rawMessage == null || rawMessage.isBlank()) { throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400); } + validateConfigurationSet(configurationSetName, region); + boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty(); + boolean willPublishEvents = configurationSetName != null && !configurationSetName.isBlank(); + SmtpRelay.RawMessageHeaders headers = (hasExplicitDestinations && !willPublishEvents) + ? null + : SmtpRelay.parseRawHeaders(rawMessage); + List effectiveDestinations = hasExplicitDestinations + ? destinations + : allRecipients(headers.to(), headers.cc(), headers.bcc()); + if (effectiveDestinations.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "At least one destination address is required.", 400); + } String messageId = UUID.randomUUID().toString(); - SentEmail email = new SentEmail(messageId, region, source, - destinations != null ? destinations : Collections.emptyList(), - rawMessage); + SentEmail email = new SentEmail(messageId, region, source, effectiveDestinations, rawMessage); emailStore.put("email::" + region + "::" + messageId, email); - smtpRelay.relayRaw(source, destinations, rawMessage); + smtpRelay.relayRaw(source, effectiveDestinations, rawMessage); LOG.infov("SES raw email sent: from={0}, messageId={1}", source, messageId); + publishSendEvents(configurationSetName, messageId, source, + headers != null ? headers.subject() : "", + headers != null ? headers.to() : List.of(), + headers != null ? headers.cc() : List.of(), + headers != null ? headers.bcc() : List.of(), + effectiveDestinations, + emailTags, List.of(), region); return messageId; } + private static List allRecipients(List to, List cc, List bcc) { + List all = new ArrayList<>(); + if (to != null) { + all.addAll(to); + } + if (cc != null) { + all.addAll(cc); + } + if (bcc != null) { + all.addAll(bcc); + } + return all; + } + + /** + * Validate that a non-blank {@code ConfigurationSetName} refers to a configuration set + * that exists in the given region. Always raises {@code ConfigurationSetDoesNotExist} + * with {@code httpStatus = 400}; the V2 REST controller's {@code remapV1Exception} + * then translates that into a {@code NotFoundException 404}, while V1 Query keeps the + * original code/status. Mirrors AWS SES behaviour: invalid set name fails fast instead + * of silently storing/relaying the message and skipping event publishing later. + */ + private void validateConfigurationSet(String configurationSetName, String region) { + if (configurationSetName == null || configurationSetName.isBlank()) { + return; + } + if (configSetStore.get(configSetKey(region, configurationSetName)).isEmpty()) { + throw new AwsException("ConfigurationSetDoesNotExist", + "Configuration set <" + configurationSetName + "> does not exist.", 400); + } + } + + private void publishSendEvents(String configurationSetName, String messageId, String source, + String subject, List toAddresses, + List ccAddresses, List bccAddresses, + List envelopeDestinations, + List emailTags, + List additionalHeaders, String region) { + if (eventPublisher == null) { + return; + } + if (configurationSetName == null || configurationSetName.isBlank() || messageId == null) { + return; + } + ConfigurationSet cs = configSetStore.get(configSetKey(region, configurationSetName)).orElse(null); + if (cs == null) { + LOG.warnv("SES send references unknown ConfigurationSet <{0}>; events not published.", + configurationSetName); + return; + } + if (cs.getEventDestinations().isEmpty()) { + return; + } + + List envelope = envelopeDestinations != null + ? envelopeDestinations : Collections.emptyList(); + Instant timestamp = Instant.now(); + String sendingAccountId = defaultAccountId; + String sourceArn = (source == null || source.isBlank()) + ? null + : AwsArnUtils.Arn.of("ses", region, sendingAccountId, "identity/" + source).toString(); + + for (String eventType : determineSendEventTypes(envelope)) { + eventPublisher.publish(cs, eventType, messageId, source, sourceArn, sendingAccountId, + subject, toAddresses, ccAddresses, bccAddresses, envelope, + emailTags, additionalHeaders, timestamp, region); + } + } + + private static List determineSendEventTypes(List destinations) { + List events = new ArrayList<>(); + events.add("SEND"); + for (String d : destinations) { + if (SimulatorAddresses.isSuccess(d) && !events.contains("DELIVERY")) { + events.add("DELIVERY"); + } + if (SimulatorAddresses.isBounce(d) && !events.contains("BOUNCE")) { + events.add("BOUNCE"); + } + if (SimulatorAddresses.isComplaint(d) && !events.contains("COMPLAINT")) { + events.add("COMPLAINT"); + } + if (SimulatorAddresses.isSuppressionList(d) && !events.contains("REJECT")) { + events.add("REJECT"); + } + } + return events; + } + public long getSentEmailCount(String region) { String prefix = "email::" + region + "::"; return emailStore.scan(k -> k.startsWith(prefix)).size(); @@ -981,11 +1108,14 @@ public class SesService { public String sendTemplatedEmail(String source, List toAddresses, List ccAddresses, List bccAddresses, List replyToAddresses, - String templateName, JsonNode templateData, String region) { + String templateName, JsonNode templateData, + String configurationSetName, List emailTags, + List additionalHeaders, String region) { EmailTemplate template = getTemplate(templateName, region); return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, template.getSubject(), template.getTextPart(), - template.getHtmlPart(), templateData, region); + template.getHtmlPart(), templateData, + configurationSetName, emailTags, additionalHeaders, region); } public String renderTestTemplate(String templateName, String templateDataRaw, String region) { @@ -1104,7 +1234,10 @@ public class SesService { public String sendInlineTemplatedEmail(String source, List toAddresses, List ccAddresses, List bccAddresses, List replyToAddresses, String subject, String textPart, String htmlPart, - JsonNode templateData, String region) { + JsonNode templateData, + String configurationSetName, List emailTags, + List additionalHeaders, + String region) { boolean hasSubject = subject != null && !subject.isBlank(); boolean hasText = textPart != null && !textPart.isBlank(); boolean hasHtml = htmlPart != null && !htmlPart.isBlank(); @@ -1116,7 +1249,7 @@ public class SesService { applyTemplateData(subject, templateData), applyTemplateData(textPart, templateData), applyTemplateData(htmlPart, templateData), - region); + configurationSetName, emailTags, additionalHeaders, region); } public List sendBulkTemplatedEmail(String source, @@ -1124,6 +1257,9 @@ public class SesService { String subject, String textPart, String htmlPart, JsonNode defaultTemplateData, List entries, + String configurationSetName, + List defaultEmailTags, + List defaultHeaders, String region) { if (source == null || source.isBlank()) { throw new AwsException("InvalidParameterValue", "Source email is required.", 400); @@ -1139,6 +1275,7 @@ public class SesService { throw new AwsException("InvalidParameterValue", "At least one destination entry is required.", 400); } + validateConfigurationSet(configurationSetName, region); if (entries.size() > MAX_BULK_DESTINATIONS) { throw new AwsException("MessageRejected", "Number of destinations (" + entries.size() + ") exceeds the maximum of " @@ -1159,13 +1296,15 @@ public class SesService { for (BulkEmailEntry entry : entries) { try { JsonNode merged = mergeTemplateData(defaultTemplateData, entry.replacementTemplateData()); + List mergedTags = mergeEmailTags(defaultEmailTags, entry.replacementEmailTags()); + List mergedHeaders = mergeHeaders(defaultHeaders, entry.replacementHeaders()); String messageId = sendEmail(source, entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(), replyToAddresses, applyTemplateData(subject, merged), applyTemplateData(textPart, merged), applyTemplateData(htmlPart, merged), - region); + configurationSetName, mergedTags, mergedHeaders, region); results.add(BulkEmailEntryResult.success(messageId)); } catch (AwsException e) { results.add(BulkEmailEntryResult.failure( @@ -1190,6 +1329,57 @@ public class SesService { return BulkEmailEntryResult.Status.FAILED; } + static List mergeHeaders(List defaults, List replacement) { + boolean hasDefault = defaults != null && !defaults.isEmpty(); + boolean hasReplacement = replacement != null && !replacement.isEmpty(); + if (!hasDefault && !hasReplacement) { + return List.of(); + } + // RFC 5322 header field names are case-insensitive, so the merge key is the + // lowercased name. The header itself is stored verbatim, so the replacement's + // original casing wins when it overrides a default. + LinkedHashMap byLowerName = new LinkedHashMap<>(); + if (hasDefault) { + for (MessageHeader h : defaults) { + if (h != null && h.name() != null && !h.name().isBlank()) { + byLowerName.put(h.name().toLowerCase(Locale.ROOT), h); + } + } + } + if (hasReplacement) { + for (MessageHeader h : replacement) { + if (h != null && h.name() != null && !h.name().isBlank()) { + byLowerName.put(h.name().toLowerCase(Locale.ROOT), h); + } + } + } + return new ArrayList<>(byLowerName.values()); + } + + static List mergeEmailTags(List defaults, List replacement) { + boolean hasDefault = defaults != null && !defaults.isEmpty(); + boolean hasReplacement = replacement != null && !replacement.isEmpty(); + if (!hasDefault && !hasReplacement) { + return List.of(); + } + LinkedHashMap byName = new LinkedHashMap<>(); + if (hasDefault) { + for (MessageTag t : defaults) { + if (t != null && t.name() != null && !t.name().isBlank()) { + byName.put(t.name(), t); + } + } + } + if (hasReplacement) { + for (MessageTag t : replacement) { + if (t != null && t.name() != null && !t.name().isBlank()) { + byName.put(t.name(), t); + } + } + } + return new ArrayList<>(byName.values()); + } + static JsonNode mergeTemplateData(JsonNode defaults, JsonNode replacement) { boolean hasDefault = defaults != null && defaults.isObject(); boolean hasReplacement = replacement != null && replacement.isObject(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SimulatorAddresses.java b/src/main/java/io/github/hectorvent/floci/services/ses/SimulatorAddresses.java new file mode 100644 index 0000000000..9eac8bc06d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SimulatorAddresses.java @@ -0,0 +1,36 @@ +package io.github.hectorvent.floci.services.ses; + +/** + * Recognises the AWS Amazon SES mailbox simulator addresses + * (see https://docs.aws.amazon.com/ses/latest/dg/send-an-email-from-console.html#send-email-simulator) + * so Floci can deterministically emit the matching event types. + */ +final class SimulatorAddresses { + + static final String SUCCESS = "success@simulator.amazonses.com"; + static final String BOUNCE = "bounce@simulator.amazonses.com"; + static final String COMPLAINT = "complaint@simulator.amazonses.com"; + static final String SUPPRESSION_LIST = "suppressionlist@simulator.amazonses.com"; + + private SimulatorAddresses() {} + + static boolean isSuccess(String address) { + return SUCCESS.equalsIgnoreCase(strip(address)); + } + + static boolean isBounce(String address) { + return BOUNCE.equalsIgnoreCase(strip(address)); + } + + static boolean isComplaint(String address) { + return COMPLAINT.equalsIgnoreCase(strip(address)); + } + + static boolean isSuppressionList(String address) { + return SUPPRESSION_LIST.equalsIgnoreCase(strip(address)); + } + + private static String strip(String address) { + return address == null ? null : address.trim(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java b/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java index e654e422ef..d5f9021412 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java @@ -278,6 +278,56 @@ public class SmtpRelay { } } + /** + * Structured headers extracted from a raw RFC 5322 MIME message: + * subject and separate To / Cc / Bcc address lists. Empty fields when the + * corresponding header is missing. + */ + public record RawMessageHeaders(String subject, List to, List cc, List bcc) { + public static RawMessageHeaders empty() { + return new RawMessageHeaders("", List.of(), List.of(), List.of()); + } + } + + /** + * Parses a raw RFC 5322 MIME message (plain or base64-encoded) into + * {@link RawMessageHeaders}. Returns an empty result when the input is blank + * or unparseable. + */ + public static RawMessageHeaders parseRawHeaders(String rawMessage) { + if (rawMessage == null || rawMessage.isBlank()) { + return RawMessageHeaders.empty(); + } + try { + byte[] mimeBytes = tryBase64Decode(rawMessage); + var builder = new DefaultMessageBuilder(); + var message = builder.parseMessage(new ByteArrayInputStream(mimeBytes)); + String subject = message.getSubject() != null ? message.getSubject() : ""; + List to = message.getTo() != null + ? toMailboxAddresses(message.getTo().flatten()) : List.of(); + List cc = message.getCc() != null + ? toMailboxAddresses(message.getCc().flatten()) : List.of(); + List bcc = message.getBcc() != null + ? toMailboxAddresses(message.getBcc().flatten()) : List.of(); + return new RawMessageHeaders(subject, to, cc, bcc); + } catch (Exception e) { + return RawMessageHeaders.empty(); + } + } + + /** + * Returns the flat list of recipients (To + Cc + Bcc) parsed from a raw RFC 5322 + * MIME message. Convenience wrapper around {@link #parseRawHeaders}. + */ + public static List parseRawRecipients(String rawMessage) { + RawMessageHeaders h = parseRawHeaders(rawMessage); + List all = new ArrayList<>(); + all.addAll(h.to()); + all.addAll(h.cc()); + all.addAll(h.bcc()); + return all; + } + private static List toMailboxAddresses(MailboxList list) { List addresses = new ArrayList<>(); for (Mailbox mailbox : list) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/BulkEmailEntry.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/BulkEmailEntry.java index 453699af1e..e6d9c67bcc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/BulkEmailEntry.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/BulkEmailEntry.java @@ -10,5 +10,7 @@ public record BulkEmailEntry( List toAddresses, List ccAddresses, List bccAddresses, - JsonNode replacementTemplateData + JsonNode replacementTemplateData, + List replacementEmailTags, + List replacementHeaders ) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/MessageHeader.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/MessageHeader.java new file mode 100644 index 0000000000..5b0406d0cc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/MessageHeader.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * Represents one entry of the SES V2 {@code Content.Simple.Headers} / + * {@code Content.Template.Headers} list — a user-supplied additional header to attach to + * an outgoing message. + */ +@RegisterForReflection +public record MessageHeader( + @JsonProperty("Name") String name, + @JsonProperty("Value") String value) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/MessageTag.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/MessageTag.java new file mode 100644 index 0000000000..0354a70910 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/MessageTag.java @@ -0,0 +1,21 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * Represents one entry of an AWS SES {@code EmailTags} / {@code DefaultEmailTags} / + * {@code ReplacementTags} list — also known as a {@code MessageTag} in the SES API. + * Used to attach name/value pairs to a single sent message for analytics and event + * publishing (the values surface in {@code mail.tags} on published events). + * + *

Distinct from {@link Tag}, which models the resource tags applied to a + * {@code ConfigurationSet} / {@code EmailTemplate} / {@code Identity} via the + * {@code TagResource} / {@code UntagResource} APIs — those use {@code Key}/{@code Value}, + * not {@code Name}/{@code Value}. + */ +@RegisterForReflection +public record MessageTag( + @JsonProperty("Name") String name, + @JsonProperty("Value") String value) { +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPayloadTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPayloadTest.java new file mode 100644 index 0000000000..afa2ffc38f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPayloadTest.java @@ -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", "")), + 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")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublishingV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublishingV2IntegrationTest.java new file mode 100644 index 0000000000..381a109dbd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublishingV2IntegrationTest.java @@ -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 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 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 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 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 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 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 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 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": ""} + ] + } + } + } + """.formatted(SENDER, CS)) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200); + + List 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 handles = r.jsonPath().getList("Messages.ReceiptHandle"); + if (handles == null || handles.isEmpty()) { + return; + } + deleteMessages(handles); + } + } + + private List receiveSesEvents(int expectedAtLeast) throws Exception { + List 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 bodies = r.jsonPath().getList("Messages.Body"); + List 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 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceMergeEmailTagsTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceMergeEmailTagsTest.java new file mode 100644 index 0000000000..80c197699c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceMergeEmailTagsTest.java @@ -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 defaults = List.of( + new MessageTag("env", "prod"), + new MessageTag("campaign", "launch")); + List replacement = List.of(new MessageTag("campaign", "vip")); + + List merged = SesService.mergeEmailTags(defaults, replacement); + + assertEquals(2, merged.size()); + assertEquals("prod", findValue(merged, "env")); + assertEquals("vip", findValue(merged, "campaign")); + } + + @Test + void mergeEmailTags_replacementOnlyNamesAreAdded() { + List defaults = List.of(new MessageTag("env", "prod")); + List replacement = List.of(new MessageTag("locale", "ja-JP")); + + List 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 tags, String name) { + return tags.stream().filter(t -> name.equals(t.name())).findFirst() + .orElseThrow().value(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceMergeHeadersTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceMergeHeadersTest.java new file mode 100644 index 0000000000..885d3c7002 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceMergeHeadersTest.java @@ -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 defaults = List.of( + new MessageHeader("X-Mailer", "floci-default"), + new MessageHeader("List-Unsubscribe", "")); + List replacement = List.of( + new MessageHeader("X-Mailer", "floci-override")); + + List merged = SesService.mergeHeaders(defaults, replacement); + + assertEquals(2, merged.size()); + assertEquals("floci-override", findValue(merged, "X-Mailer")); + assertEquals("", 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 defaults = List.of(new MessageHeader("X-Mailer", "floci-default")); + List replacement = List.of(new MessageHeader("x-mailer", "floci-override")); + + List 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 defaults = List.of(new MessageHeader("X-Mailer", "floci")); + List replacement = List.of(new MessageHeader("X-Custom", "v1")); + + List 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 headers, String name) { + return headers.stream().filter(h -> name.equals(h.name())).findFirst() + .orElseThrow().value(); + } +} 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 8ec07d4e66..fca8961c3c 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 @@ -49,7 +49,7 @@ class SesServiceSmtpTest { List.of("cc@example.com"), List.of("bcc@example.com"), List.of("reply@example.com"), - "Subject", "text body", "

html

", "us-east-1"); + "Subject", "text body", "

html

", 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, "

html only

", "us-east-1"); + "Subject", null, "

html only

", null, List.of(), List.of(), "us-east-1"); verify(smtpRelay).relay( "from@example.com", diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SimulatorAddressesTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SimulatorAddressesTest.java new file mode 100644 index 0000000000..c7fa42d818 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SimulatorAddressesTest.java @@ -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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java index 2692aa5150..d6096d90b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java @@ -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 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()); + } }