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 index 07130e0ca6..78943fa60e 100644 --- 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 @@ -691,6 +691,29 @@ class SesEventPublishingTest { return events; } + @Test + @Order(9) + @DisplayName("suppressionlist@simulator publishes a General bounce, not a Reject") + void sendToSuppressionListSimulator_publishesABounce() throws Exception { + drainQueue(); + sendEmailTo("suppressionlist@simulator.amazonses.com"); + List events = receiveEvents(2); + + assertThat(events).hasSize(2); + assertThat(events).noneMatch(e -> "Reject".equals(e.path("eventType").asText())); + JsonNode bounce = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + // Verified against real SES on 2026-09-21: an ordinary hard bounce whose diagnostic names + // the suppression. + assertThat(bounce.path("bounce").path("bounceType").asText()).isEqualTo("Permanent"); + assertThat(bounce.path("bounce").path("bounceSubType").asText()).isEqualTo("General"); + JsonNode recipient = bounce.path("bounce").path("bouncedRecipients").get(0); + assertThat(recipient.path("emailAddress").asText()).isEqualTo("suppressionlist@simulator.amazonses.com"); + assertThat(recipient.path("status").asText()).isEqualTo("5.1.1"); + assertThat(recipient.path("diagnosticCode").asText()).contains("suppressed address: suppressionlist@"); + } + private void sendEmailTo(String to) { ses.sendEmail(SendEmailRequest.builder() .fromEmailAddress(identity) diff --git a/docs/services/ses.md b/docs/services/ses.md index bdc5406a57..e2bb5c9267 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -387,14 +387,17 @@ Floci recognises the AWS [mailbox simulator addresses](https://docs.aws.amazon.c | 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` | +| `bounce@simulator.amazonses.com`, `suppressionlist@simulator.amazonses.com` | `Bounce` | +| `complaint@simulator.amazonses.com` | `Delivery`, then `Complaint` | A `+label` subaddress is supported on any of these, so `bounce+order-123@simulator.amazonses.com` triggers a `Bounce` just like the bare address — the label lets senders distinguish test messages. Only `+` separates the label; `bounce-label@...` is not a simulator address. A successful send without a simulator-address recipient emits only the `Send` event. +A recipient on the [account-level suppression list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html) produces a `Bounce` with `bounceSubType: OnAccountSuppressionList` or a `Complaint` with `complaintSubType: OnAccountSuppressionList`, following the stored reason, and never a `Delivery`. Events are split by cause: a message that reaches both `bounce@simulator` and a suppressed address publishes two `Bounce` events, each listing only its own recipients, with `mail.destination` carrying the full envelope on both. These shapes were verified against real SES on 2026-09-21. + +`Reject` is emitted the way AWS documents it: a message carrying the [EICAR test file](https://www.eicar.org/download-anti-malware-testfile/) in its subject, a header or a body is accepted (the send returns a `MessageId`) and then rejected with a `Reject` event whose `reason` is `Bad content`. The message is not relayed, the stored record keeps only its source, its envelope and `RejectReason`, and its `Send` and `Reject` events carry the envelope but no subject or headers in `mail`, where SES would include them, so the signature reaches neither the mailbox store nor an event destination. The test string itself is deliberately not reproduced here. + Account-level VDM (Virtual Deliverability Manager) attributes are stored per region. `PutAccountVdmAttributes` sets `VdmEnabled` (opt-in, defaults `DISABLED`) plus the optional `DashboardAttributes.EngagementMetrics` and `GuardianAttributes.OptimizedSharedDelivery`. `GetAccount` omits `VdmAttributes` until VDM has been configured for the region, then returns `VdmEnabled`, adding the `DashboardAttributes`/`GuardianAttributes` sub-objects only while `VdmEnabled` is `ENABLED`. Floci stores the settings but does not run VDM analytics. Account provisioning details are stored per region. `PutAccountDetails` sets `MailType` (required, ∈ {`MARKETING`, `TRANSACTIONAL`}) and `WebsiteURL` (required, 1–1000 chars) plus the optional `ContactLanguage` (∈ {`EN`, `JA`}), `UseCaseDescription` (≤5000 chars), `AdditionalContactEmailAddresses` (1–4 entries, each 6–254 chars matching `^(.+)@(.+)$`), and `ProductionAccessEnabled`. Floci stores `ProductionAccessEnabled` as given but stays production-enabled regardless (it has no sandbox), so the flag has no functional effect. Like `VdmAttributes`, `GetAccount` omits `Details` until it has been configured for the region, then echoes the stored fields under `Details` with a `ReviewDetails` block. Matching AWS, all modeled-constraint violations (null / enum / length / list) are aggregated into a single `BadRequestException` reporting every failure; a malformed (but in-range) `WebsiteURL` is reported separately as `Url contains invalid format`. Floci has no sandbox and does not run a production-access review, so `ReviewDetails.Status` is always `GRANTED`. diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java index 897e1827fa..54131e3f29 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java @@ -657,9 +657,9 @@ public class SesContactService { /** * Resolves the recipients suppressed by SES V2 {@code SendEmail} {@code ListManagementOptions}: * for each envelope recipient that is opted out of the named contact list (or the given topic), - * returns a {@code BOUNCE} suppression reason so the shared send path drops the recipient from - * the relay and publishes a Bounce event, matching AWS ("SES will issue a bounce event for a - * message that is sent to an unsubscribed contact"). Returns an empty map when no + * marks the recipient with {@link SesRecipientEvents#REASON_LIST_OPT_OUT} so the shared send + * path drops it from the relay and the event classifier publishes a Bounce event, matching AWS + * ("SES will issue a bounce event for a message that is sent to an unsubscribed contact"). Returns an empty map when no * {@code ListManagementOptions} was supplied. The display-name stripping is the facade's shared * send helper, injected as {@code addressExtractor} so this service stays free of facade * dependencies. Throws when the contact list does not exist, so a @@ -696,7 +696,7 @@ public class SesContactService { } Contact contact = getOrAutoCreateContact(list, email, region); if (isListManagementOptedOut(contact, list, effectiveTopic)) { - optOuts.put(address, "BOUNCE"); + optOuts.put(address, SesRecipientEvents.REASON_LIST_OPT_OUT); } } return optOuts; diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContentScan.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContentScan.java new file mode 100644 index 0000000000..f04c6f932c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContentScan.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.services.ses; + +import java.util.Arrays; + +/** + * The content scan SES runs on every accepted message. Real SES scans for viruses and rejects the + * whole message with a {@code Reject} event; Floci reproduces that for the one input AWS documents + * for testing it, the EICAR test file, and nothing else. + * + *

The EICAR string is a signature that endpoint protection quarantines on sight, so it is never + * written out verbatim: it is assembled from fragments at class initialisation, must never be + * logged or persisted, and tests obtain it from {@link #signature()} rather than spelling it out. + */ +final class SesContentScan { + + private static final String[] FRAGMENTS = { + "X5O!P%@AP[4\\PZX54(P^)7CC)7}$", + "EICAR-STANDARD-", + "ANTIVIRUS-TEST-", + "FILE!$H+H*" + }; + private static final String SIGNATURE_TEXT = String.join("", FRAGMENTS); + + private SesContentScan() {} + + /** The assembled test string, for tests that need to send it. Never log or persist it. */ + static String signature() { + return SIGNATURE_TEXT; + } + + /** True when any of the given texts carries the test signature. Nulls are skipped. */ + static boolean containsTestVirus(String... texts) { + return containsTestVirus(Arrays.asList(texts)); + } + + /** True when any of the given texts carries the test signature. Nulls are skipped. */ + static boolean containsTestVirus(Iterable texts) { + for (String text : texts) { + if (text != null && text.contains(SIGNATURE_TEXT)) { + return true; + } + } + return false; + } +} 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 index fb4742cd32..849cdc646e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPayload.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPayload.java @@ -9,7 +9,6 @@ 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.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -32,18 +31,16 @@ final class SesEventPayload { private SesEventPayload() {} - static ObjectNode build(ObjectMapper mapper, String eventType, String messageId, String source, - String sourceArn, String sendingAccountId, String subject, + static ObjectNode build(ObjectMapper mapper, SesRecipientEvent event, String messageId, + String source, String sourceArn, String sendingAccountId, String subject, List toAddresses, List ccAddresses, List bccAddresses, List envelopeDestinations, - List suppressionBounceRecipients, - List suppressionComplaintRecipients, String configurationSetName, List emailTags, List additionalHeaders, Instant timestamp) { - return buildRoot(mapper, "eventType", eventType, messageId, source, sourceArn, + return buildRoot(mapper, "eventType", event, messageId, source, sourceArn, sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses, - envelopeDestinations, suppressionBounceRecipients, suppressionComplaintRecipients, - configurationSetName, emailTags, additionalHeaders, timestamp, true, true); + envelopeDestinations, configurationSetName, emailTags, additionalHeaders, timestamp, + true, true); } /** @@ -59,40 +56,33 @@ final class SesEventPayload { * the {@code BOUNCE}, {@code COMPLAINT}, and {@code DELIVERY} event types are ever published * through this path. */ - static ObjectNode buildIdentityNotification(ObjectMapper mapper, String eventType, + static ObjectNode buildIdentityNotification(ObjectMapper mapper, SesRecipientEvent event, String messageId, String source, String sourceArn, String sendingAccountId, String subject, List toAddresses, List ccAddresses, List bccAddresses, List envelopeDestinations, - List suppressionBounceRecipients, - List suppressionComplaintRecipients, List additionalHeaders, Instant timestamp, boolean includeHeaders) { - return buildRoot(mapper, "notificationType", eventType, messageId, source, sourceArn, + return buildRoot(mapper, "notificationType", event, messageId, source, sourceArn, sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses, - envelopeDestinations, suppressionBounceRecipients, suppressionComplaintRecipients, - null, null, additionalHeaders, timestamp, includeHeaders, false); + envelopeDestinations, null, null, additionalHeaders, timestamp, includeHeaders, false); } - private static ObjectNode buildRoot(ObjectMapper mapper, String typeField, String eventType, + private static ObjectNode buildRoot(ObjectMapper mapper, String typeField, SesRecipientEvent event, String messageId, String source, String sourceArn, String sendingAccountId, String subject, List toAddresses, List ccAddresses, List bccAddresses, List envelopeDestinations, - List suppressionBounceRecipients, - List suppressionComplaintRecipients, String configurationSetName, List emailTags, List additionalHeaders, Instant timestamp, boolean includeHeaders, boolean includeTags) { ObjectNode root = mapper.createObjectNode(); - root.put(typeField, eventTypeLabel(eventType)); + root.put(typeField, eventTypeLabel(event.eventType())); root.set("mail", buildMail(mapper, messageId, source, sourceArn, sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations, configurationSetName, emailTags, additionalHeaders, timestamp, includeHeaders, includeTags)); - root.set(blockName(eventType), - buildEventBlock(mapper, eventType, messageId, envelopeDestinations, - suppressionBounceRecipients, suppressionComplaintRecipients, timestamp)); + root.set(blockName(event.eventType()), buildEventBlock(mapper, event, messageId, timestamp)); return root; } @@ -199,42 +189,61 @@ final class SesEventPayload { headers.add(h); } - private static ObjectNode buildEventBlock(ObjectMapper mapper, String eventType, String messageId, - List destination, - List suppressionBounceRecipients, - List suppressionComplaintRecipients, - Instant timestamp) { + // Probed against real SES on 2026-09-21: an account-suppressed recipient bounces with this + // subtype and diagnostic, or is complained about with this subtype and no feedback type, while + // suppressionlist@simulator is an ordinary General bounce whose diagnostic names the suppression. + static final String ON_ACCOUNT_SUPPRESSION_LIST = "OnAccountSuppressionList"; + static final String ACCOUNT_SUPPRESSION_DIAGNOSTIC = "Amazon SES did not send the message to this " + + "address because it is on the suppression list for your account. For more information " + + "about removing addresses from the suppression list, see the Amazon SES Developer Guide " + + "at https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html"; + + private static ObjectNode buildEventBlock(ObjectMapper mapper, SesRecipientEvent event, + String messageId, Instant timestamp) { ObjectNode body = mapper.createObjectNode(); - switch (eventType) { + switch (event.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()); - } + for (String recipient : event.recipients()) { + recipients.add(recipient); } body.put("smtpResponse", "250 ok"); body.put("reportingMTA", "floci"); } case "BOUNCE" -> { + boolean suppressed = event.cause() == SesRecipientEvent.Cause.ACCOUNT_SUPPRESSION; body.put("bounceType", "Permanent"); - body.put("bounceSubType", "General"); - emitDedupedRecipientObjects(body.putArray("bouncedRecipients"), - destination, SimulatorAddresses::isBounce, - suppressionBounceRecipients); + body.put("bounceSubType", suppressed ? ON_ACCOUNT_SUPPRESSION_LIST : "General"); + ArrayNode bounced = body.putArray("bouncedRecipients"); + for (String recipient : event.recipients()) { + ObjectNode entry = bounced.addObject(); + entry.put("emailAddress", recipient); + // The shape of a list-management opt-out bounce has not been probed, so it + // carries only the address, as it did before the per-cause split. + if (event.cause() != SesRecipientEvent.Cause.LIST_MANAGEMENT) { + entry.put("action", "failed"); + entry.put("status", "5.1.1"); + entry.put("diagnosticCode", bounceDiagnosticCode(recipient, suppressed)); + } + } body.put("timestamp", ISO_MILLIS.format(timestamp)); - body.put("feedbackId", "feedback-" + messageId); + body.put("feedbackId", feedbackId(messageId, event)); } case "COMPLAINT" -> { - emitDedupedRecipientObjects(body.putArray("complainedRecipients"), - destination, SimulatorAddresses::isComplaint, - suppressionComplaintRecipients); + if (event.cause() == SesRecipientEvent.Cause.ACCOUNT_SUPPRESSION) { + body.put("complaintSubType", ON_ACCOUNT_SUPPRESSION_LIST); + } + ArrayNode complained = body.putArray("complainedRecipients"); + for (String recipient : event.recipients()) { + complained.addObject().put("emailAddress", recipient); + } body.put("timestamp", ISO_MILLIS.format(timestamp)); - body.put("feedbackId", "feedback-" + messageId); + body.put("arrivalDate", ISO_MILLIS.format(timestamp)); + body.put("feedbackId", feedbackId(messageId, event)); } - case "REJECT" -> body.put("reason", "Bad content"); + case "REJECT" -> body.put("reason", SesRecipientEvents.CONTENT_REJECT_REASON); default -> { // SEND and other not-yet-modelled event types: empty block. } @@ -242,31 +251,23 @@ final class SesEventPayload { return body; } - /** - * Emit `{emailAddress: ...}` objects into {@code arr} for every recipient that either - * matches {@code simulatorPredicate} in {@code envelope} or is listed in - * {@code suppressionRecipients}. Addresses are trimmed and deduplicated by trimmed - * form so the same address never appears twice when both inputs claim it. - */ - private static void emitDedupedRecipientObjects(ArrayNode arr, - List envelope, - java.util.function.Predicate simulatorPredicate, - List suppressionRecipients) { - LinkedHashSet emitted = new LinkedHashSet<>(); - if (envelope != null) { - for (String d : envelope) { - if (d != null && simulatorPredicate.test(d) && emitted.add(d.trim())) { - arr.addObject().put("emailAddress", d.trim()); - } - } + // SES gives every bounce and complaint notification its own id, so the events split from one + // send (a simulator bounce and a suppression bounce) never share one; the id is derived rather + // than random so the configuration-set event and the identity notification of one outcome agree. + private static String feedbackId(String messageId, SesRecipientEvent event) { + return "feedback-" + messageId + "-" + event.eventType().toLowerCase(Locale.ROOT) + "-" + + event.cause().name().toLowerCase(Locale.ROOT); + } + + private static String bounceDiagnosticCode(String recipient, boolean suppressed) { + if (suppressed) { + return ACCOUNT_SUPPRESSION_DIAGNOSTIC; } - if (suppressionRecipients != null) { - for (String d : suppressionRecipients) { - if (d != null && emitted.add(d.trim())) { - arr.addObject().put("emailAddress", d.trim()); - } - } + if (SimulatorAddresses.isSuppressionList(recipient)) { + return "smtp; 550 5.1.1 As requested: user unknown (suppressed address: " + recipient + ")"; } + // The simulator documents bounce@ as an SMTP 550 5.1.1 "Unknown User" response. + return "smtp; 550 5.1.1 user unknown"; } static String eventTypeLabel(String eventType) { 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 index e90909444c..180ebe2876 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java @@ -61,21 +61,19 @@ public class SesEventPublisher { this.objectMapper = objectMapper; } - public void publish(ConfigurationSet configurationSet, String eventType, String messageId, + public void publish(ConfigurationSet configurationSet, SesRecipientEvent event, String messageId, String source, String sourceArn, String sendingAccountId, String subject, List toAddresses, List ccAddresses, List bccAddresses, List envelopeDestinations, - List suppressionBounceRecipients, - List suppressionComplaintRecipients, List emailTags, List additionalHeaders, Instant timestamp, String defaultRegion) { if (configurationSet == null || configurationSet.getEventDestinations().isEmpty()) { return; } - ObjectNode payload = SesEventPayload.build(objectMapper, eventType, messageId, source, + String eventType = event.eventType(); + ObjectNode payload = SesEventPayload.build(objectMapper, event, messageId, source, sourceArn, sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations, - suppressionBounceRecipients, suppressionComplaintRecipients, configurationSet.getName(), emailTags, additionalHeaders, timestamp); String payloadJson = payload.toString(); for (EventDestination ed : configurationSet.getEventDestinations()) { @@ -105,20 +103,18 @@ public class SesEventPublisher { * {@code mail.tags}, and includes the original headers only when {@code includeHeaders} is set * (i.e. the identity has headers-in-notifications enabled for the type). */ - public void publishIdentityNotification(String topicArn, boolean includeHeaders, String eventType, - String messageId, String source, String sourceArn, String sendingAccountId, - String subject, List toAddresses, List ccAddresses, - List bccAddresses, List envelopeDestinations, - List suppressionBounceRecipients, - List suppressionComplaintRecipients, - List additionalHeaders, Instant timestamp, String defaultRegion) { + public void publishIdentityNotification(String topicArn, boolean includeHeaders, + SesRecipientEvent event, String messageId, String source, String sourceArn, + String sendingAccountId, String subject, List toAddresses, + List ccAddresses, List bccAddresses, + List envelopeDestinations, List additionalHeaders, + Instant timestamp, String defaultRegion) { if (topicArn == null || topicArn.isBlank()) { return; } - ObjectNode payload = SesEventPayload.buildIdentityNotification(objectMapper, eventType, + ObjectNode payload = SesEventPayload.buildIdentityNotification(objectMapper, event, messageId, source, sourceArn, sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations, - suppressionBounceRecipients, suppressionComplaintRecipients, additionalHeaders, timestamp, includeHeaders); publishSns(topicArn, payload.toString(), defaultRegion); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java index 6f45332d97..439050202a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java @@ -55,6 +55,9 @@ public class SesInspectionController { node.putNull("Region"); } node.put("Source", email.getSource()); + if (email.getRejectReason() != null) { + node.put("RejectReason", email.getRejectReason()); + } if (email.getReturnPath() != null) { node.put("ReturnPath", email.getReturnPath()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesRecipientEvent.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecipientEvent.java new file mode 100644 index 0000000000..dc26a47af2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecipientEvent.java @@ -0,0 +1,26 @@ +package io.github.hectorvent.floci.services.ses; + +import java.util.List; + +/** + * One event to publish for a send: the SES event type, why it happened, and the recipients it + * concerns. A send yields one of these per (type, cause) pair, so a message that bounces for two + * different reasons publishes two {@code BOUNCE} events, as SES does. + */ +record SesRecipientEvent(String eventType, Cause cause, List recipients) { + + enum Cause { + /** A mailbox-simulator address, or the plain delivery of an ordinary recipient. */ + SIMULATOR, + /** The recipient was on the account-level suppression list and never left Floci. */ + ACCOUNT_SUPPRESSION, + /** The recipient had opted out through list management and never left Floci. */ + LIST_MANAGEMENT, + /** The whole message failed the content scan and was rejected after acceptance. */ + CONTENT_REJECTED + } + + static SesRecipientEvent of(String eventType, Cause cause, List recipients) { + return new SesRecipientEvent(eventType, cause, List.copyOf(recipients)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesRecipientEvents.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecipientEvents.java new file mode 100644 index 0000000000..c1aed8155e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecipientEvents.java @@ -0,0 +1,95 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.services.ses.SesRecipientEvent.Cause; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The one place that decides which SES events a send produces, per recipient. Configuration-set + * event publishing and the identity notifications both consume this, and anything else that + * derives a per-recipient outcome from a send should too, so the mailbox-simulator and + * suppression semantics have a single home. + * + *

A recipient on the account suppression list is dropped before the relay, so its outcome is + * the suppression reason regardless of its address; a list-management opt-out is dropped the same + * way but bounces under its own cause, since it is not on the suppression list. Otherwise the + * mailbox simulator decides: + * {@code success@} is delivered, {@code bounce@} and {@code suppressionlist@} both hard-bounce + * (probed 2026-09-21: the latter is an ordinary {@code General} bounce whose diagnostic text names + * the suppression, not a {@code Reject}), and {@code complaint@} is delivered and then complained + * about. An ordinary recipient produces nothing beyond {@code SEND} here; whether it counts as + * delivered is the caller's question. A rejected message publishes only {@code SEND} and + * {@code REJECT}, since SES accepts it and then refuses the whole message. + */ +final class SesRecipientEvents { + + static final String REASON_BOUNCE = "BOUNCE"; + static final String REASON_COMPLAINT = "COMPLAINT"; + static final String REASON_LIST_OPT_OUT = "LIST_MANAGEMENT"; + // The reason SES reports on a Reject event; also the marker stored on the rejected record. + static final String CONTENT_REJECT_REASON = "Bad content"; + + private SesRecipientEvents() {} + + static List classify(List envelope, Map suppressedReasons, + boolean contentRejected) { + List events = new ArrayList<>(); + events.add(SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of())); + if (contentRejected) { + events.add(SesRecipientEvent.of("REJECT", Cause.CONTENT_REJECTED, List.of())); + return events; + } + // Insertion order fixes the publish order: simulator outcomes, then suppression, then opt-outs. + Map> groups = new LinkedHashMap<>(); + for (String key : List.of(key("DELIVERY", Cause.SIMULATOR), key("BOUNCE", Cause.SIMULATOR), + key("COMPLAINT", Cause.SIMULATOR), key("BOUNCE", Cause.ACCOUNT_SUPPRESSION), + key("COMPLAINT", Cause.ACCOUNT_SUPPRESSION), key("BOUNCE", Cause.LIST_MANAGEMENT))) { + groups.put(key, new ArrayList<>()); + } + if (envelope != null) { + for (String recipient : envelope) { + if (recipient == null || recipient.isBlank()) { + continue; + } + String reason = suppressedReasons == null ? null : suppressedReasons.get(recipient); + if (REASON_BOUNCE.equals(reason)) { + add(groups, "BOUNCE", Cause.ACCOUNT_SUPPRESSION, recipient); + } else if (REASON_COMPLAINT.equals(reason)) { + add(groups, "COMPLAINT", Cause.ACCOUNT_SUPPRESSION, recipient); + } else if (REASON_LIST_OPT_OUT.equals(reason)) { + add(groups, "BOUNCE", Cause.LIST_MANAGEMENT, recipient); + } else if (SimulatorAddresses.isSuccess(recipient)) { + add(groups, "DELIVERY", Cause.SIMULATOR, recipient); + } else if (SimulatorAddresses.isBounce(recipient) || SimulatorAddresses.isSuppressionList(recipient)) { + add(groups, "BOUNCE", Cause.SIMULATOR, recipient); + } else if (SimulatorAddresses.isComplaint(recipient)) { + add(groups, "DELIVERY", Cause.SIMULATOR, recipient); + add(groups, "COMPLAINT", Cause.SIMULATOR, recipient); + } + } + } + for (Map.Entry> group : groups.entrySet()) { + if (group.getValue().isEmpty()) { + continue; + } + String[] parts = group.getKey().split("/"); + events.add(SesRecipientEvent.of(parts[0], Cause.valueOf(parts[1]), group.getValue())); + } + return events; + } + + private static String key(String eventType, Cause cause) { + return eventType + "/" + cause; + } + + private static void add(Map> groups, String eventType, Cause cause, String recipient) { + List recipients = groups.get(key(eventType, cause)); + String trimmed = recipient.trim(); + if (!recipients.contains(trimmed)) { + recipients.add(trimmed); + } + } +} 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 87211742bb..a8f1a56584 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 @@ -235,7 +235,7 @@ public class SesService { Map suppressedReasons = new LinkedHashMap<>( collectSuppressedReasons(envelope, effectiveConfigSet, region)); // putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins - // over the list-management BOUNCE and keeps its synthetic event type. + // over the list-management opt-out and keeps its synthetic event type. contactService.collectListManagementOptOuts(envelope, listManagement, region, SesService::extractEmailAddress).forEach(suppressedReasons::putIfAbsent); @@ -259,18 +259,25 @@ public class SesService { String messageId = UUID.randomUUID().toString(); String effectiveReturnPath = firstNonBlank(returnPath, source); + // SES accepts the message and then rejects it as a whole when the content scan trips, so + // the send still succeeds and a REJECT event is published in place of any delivery. + boolean rejected = SesContentScan.containsTestVirus(subject, bodyText, bodyHtml) + || SesContentScan.containsTestVirus(headerText(additionalHeaders)); SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, subject, bodyText, bodyHtml); email.setReturnPath(effectiveReturnPath); if (additionalHeaders != null && !additionalHeaders.isEmpty()) { email.setHeaders(additionalHeaders); } + if (rejected) { + email.discardContent(SesRecipientEvents.CONTENT_REJECT_REASON); + } sentEmailService.record(region, messageId, email); List relayedTo = filterUnsuppressed(toAddresses, suppressedReasons); List relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons); List relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons); - if (sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) { + if (!rejected && sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) { smtpRelay.relay(SmtpRelay.RelayMessage.builder(source) .returnPath(effectiveReturnPath) .to(relayedTo) @@ -284,15 +291,17 @@ public class SesService { .messageId(messageId) .build()); } else { - LOG.infov("SES email accepted but not relayed (all recipients suppressed): messageId={0}", - messageId); + LOG.infov("SES email accepted but not relayed ({0}): messageId={1}", + rejected ? "content rejected" : "all recipients suppressed", messageId); } - LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}", - source, toAddresses, subject, messageId); + if (!rejected) { + LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}", + source, toAddresses, subject, messageId); + } publishSendEvents(effectiveConfigSet, messageId, source, subject, toAddresses, ccAddresses, bccAddresses, envelope, - suppressedReasons, emailTags, additionalHeaders, region); + suppressedReasons, rejected, emailTags, additionalHeaders, region); return messageId; } @@ -349,7 +358,7 @@ public class SesService { Map suppressedReasons = new LinkedHashMap<>( collectSuppressedReasons(effectiveDestinations, effectiveConfigSet, region)); // putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins - // over the list-management BOUNCE and keeps its synthetic event type. + // over the list-management opt-out and keeps its synthetic event type. contactService.collectListManagementOptOuts(effectiveDestinations, listManagement, region, SesService::extractEmailAddress) .forEach(suppressedReasons::putIfAbsent); @@ -375,7 +384,7 @@ public class SesService { publishSendEvents(effectiveConfigSet, messageId, effectiveSource, headers.subject(), headers.to(), headers.cc(), headers.bcc(), effectiveDestinations, - suppressedReasons, effectiveTags, List.of(), region); + suppressedReasons, false, effectiveTags, List.of(), region); return messageId; } @@ -397,7 +406,7 @@ public class SesService { String subject, List toAddresses, List ccAddresses, List bccAddresses, List envelopeDestinations, - Map suppressedReasons, + Map suppressedReasons, boolean contentRejected, List emailTags, List additionalHeaders, String region) { if (eventPublisher == null || messageId == null) { @@ -430,30 +439,26 @@ public class SesService { : AwsArnUtils.Arn.of("ses", region, sendingAccountId, "identity/" + extractEmailAddress(source)).toString(); - List suppressionBounceRecipients = new ArrayList<>(); - List suppressionComplaintRecipients = new ArrayList<>(); - for (Map.Entry e : suppressedReasons.entrySet()) { - if ("BOUNCE".equals(e.getValue())) { - suppressionBounceRecipients.add(e.getKey()); - } else if ("COMPLAINT".equals(e.getValue())) { - suppressionComplaintRecipients.add(e.getKey()); - } - } - - for (String eventType : determineSendEventTypes(envelope, - suppressionBounceRecipients, suppressionComplaintRecipients)) { + // One event per (type, cause): a message that bounces both at the simulator and on the + // suppression list publishes two BOUNCE events, each naming only its own recipients. + // A rejected message publishes none of the scanned content: its Send and Reject events + // carry the envelope but no subject and no headers, where SES would include them, so the + // string reaches no event destination either. + String publishedSubject = contentRejected ? null : subject; + List publishedHeaders = contentRejected ? List.of() : additionalHeaders; + for (SesRecipientEvent event : SesRecipientEvents.classify(envelope, suppressedReasons, + contentRejected)) { if (configSetActive) { - eventPublisher.publish(cs, eventType, messageId, source, sourceArn, sendingAccountId, - subject, toAddresses, ccAddresses, bccAddresses, envelope, - suppressionBounceRecipients, suppressionComplaintRecipients, - emailTags, additionalHeaders, timestamp, region); + eventPublisher.publish(cs, event, messageId, source, sourceArn, sendingAccountId, + publishedSubject, toAddresses, ccAddresses, bccAddresses, envelope, + emailTags, publishedHeaders, timestamp, region); } - IdentityNotificationTarget target = identityTargets.get(eventType); + IdentityNotificationTarget target = identityTargets.get(event.eventType()); if (target != null) { eventPublisher.publishIdentityNotification(target.topicArn(), target.includeHeaders(), - eventType, messageId, source, sourceArn, sendingAccountId, subject, - toAddresses, ccAddresses, bccAddresses, envelope, suppressionBounceRecipients, - suppressionComplaintRecipients, additionalHeaders, timestamp, region); + event, messageId, source, sourceArn, sendingAccountId, publishedSubject, + toAddresses, ccAddresses, bccAddresses, envelope, publishedHeaders, + timestamp, region); } } } @@ -464,7 +469,7 @@ public class SesService { * domain identity's topic, per notification type; the headers-in-notifications flag is read from * whichever identity supplied the topic. Returns a map keyed by the {@code SEND}-style event name * ({@code BOUNCE}/{@code COMPLAINT}/{@code DELIVERY}) so it can be looked up directly against - * {@link #determineSendEventTypes}. + * the event types {@link SesRecipientEvents#classify} produces. */ private Map resolveIdentityNotificationTargets(String source, String region) { @@ -519,34 +524,6 @@ public class SesService { return source.trim(); } - private static List determineSendEventTypes(List destinations, - List suppressionBounceRecipients, - List suppressionComplaintRecipients) { - 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"); - } - } - if (!suppressionBounceRecipients.isEmpty() && !events.contains("BOUNCE")) { - events.add("BOUNCE"); - } - if (!suppressionComplaintRecipients.isEmpty() && !events.contains("COMPLAINT")) { - events.add("COMPLAINT"); - } - return events; - } - public void setEmailIdentityConfigurationSet(String identityValue, String configurationSetName, String region) { Identity identity = identityService.find(identityValue, region) @@ -1494,6 +1471,18 @@ public class SesService { return results; } + private static List headerText(List headers) { + if (headers == null) { + return List.of(); + } + List texts = new ArrayList<>(headers.size() * 2); + for (MessageHeader header : headers) { + texts.add(header.name()); + texts.add(header.value()); + } + return texts; + } + private static int sizeOf(List list) { return list == null ? 0 : list.size(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java index aaaf5f9679..e044a6ea3a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java @@ -55,6 +55,14 @@ public class SentEmail { @JsonProperty("SentAt") private Instant sentAt; + /** + * Set when the content scan rejected the message after acceptance. A rejected record keeps only + * its sender, its envelope and this reason, since the content is by definition something no + * store should hold. + */ + @JsonProperty("RejectReason") + private String rejectReason; + public SentEmail() {} /** Constructor for Simple / Template content. */ @@ -129,4 +137,21 @@ public class SentEmail { public Instant getSentAt() { return sentAt; } public void setSentAt(Instant sentAt) { this.sentAt = sentAt; } + + public String getRejectReason() { return rejectReason; } + public void setRejectReason(String rejectReason) { this.rejectReason = rejectReason; } + + /** + * Drops everything but the sender, the envelope and the reason; used when the content scan + * rejects the message. + */ + public void discardContent(String reason) { + this.rejectReason = reason; + this.replyToAddresses = null; + this.subject = null; + this.headers = null; + this.bodyText = null; + this.bodyHtml = null; + this.rawData = null; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java index f0e44cd200..97ebf20eda 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java @@ -81,7 +81,8 @@ class SesContactServiceTest { new ListManagementOptions(LIST, "Sports"), REGION, address -> address.substring(address.indexOf('<') + 1, address.indexOf('>'))); // The ORIGINAL envelope strings key the result; the extractor only feeds the contact lookup. - assertEquals(Map.of("Alice ", "BOUNCE", "Bob ", "BOUNCE"), + assertEquals(Map.of("Alice ", SesRecipientEvents.REASON_LIST_OPT_OUT, + "Bob ", SesRecipientEvents.REASON_LIST_OPT_OUT), optOuts); AwsException e = assertThrows(AwsException.class, () -> service.collectListManagementOptOuts( diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContentScanTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContentScanTest.java new file mode 100644 index 0000000000..f6f15d6984 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContentScanTest.java @@ -0,0 +1,31 @@ +package io.github.hectorvent.floci.services.ses; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The test signature is obtained from {@link SesContentScan#signature()} and never spelled out + * here, so this source file is as safe to check out as the production one. + */ +class SesContentScanTest { + + private static final String SIGNATURE = SesContentScan.signature(); + + @Test + void assembledSignatureHasTheDocumentedLength() { + assertEquals(68, SIGNATURE.length()); + } + + @Test + void cleanTextIsNotFlagged() { + assertFalse(SesContentScan.containsTestVirus("hello", "

hello

", null)); + } + + @Test + void signatureInsideATextBodyIsFlagged() { + assertTrue(SesContentScan.containsTestVirus(null, "prefix " + SIGNATURE + " suffix")); + } +} 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 index cb3b41c108..0fec434140 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPayloadTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPayloadTest.java @@ -3,6 +3,7 @@ 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.SesRecipientEvent.Cause; import io.github.hectorvent.floci.services.ses.model.MessageHeader; import io.github.hectorvent.floci.services.ses.model.MessageTag; import org.junit.jupiter.api.Test; @@ -12,6 +13,7 @@ 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.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,10 +29,7 @@ class SesEventPayloadTest { @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"), List.of(), List.of(), "my-cs", List.of(), List.of(), ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "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")); @@ -65,10 +64,7 @@ class SesEventPayloadTest { @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"), List.of(), List.of(), "cs", List.of(), List.of(), ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("DELIVERY", Cause.SIMULATOR, List.of("success@simulator.amazonses.com")), "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"); @@ -80,10 +76,7 @@ class SesEventPayloadTest { @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"), List.of(), List.of(), "cs", List.of(), List.of(), ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("BOUNCE", Cause.SIMULATOR, List.of("bounce@simulator.amazonses.com")), "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"); @@ -95,74 +88,18 @@ class SesEventPayloadTest { @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"), List.of(), List.of(), "cs", List.of(), List.of(), ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("COMPLAINT", Cause.SIMULATOR, List.of("complaint@simulator.amazonses.com")), "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"), - List.of(), List.of(), "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"), - List.of(), List.of(), "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"), - List.of(), List.of(), "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()); + assertEquals(node.get("complaint").get("timestamp").asText(), + node.get("complaint").get("arrivalDate").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"), - List.of(), List.of(), - "my-cs", - List.of(new MessageTag("campaign", "launch"), new MessageTag("env", "prod")), - List.of(), - ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "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()); @@ -172,15 +109,7 @@ class SesEventPayloadTest { @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"), - List.of(), List.of(), - "cs", - List.of(new MessageTag("k", null), new MessageTag("k", "v2")), - List.of(), - ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "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"); @@ -190,17 +119,9 @@ class SesEventPayloadTest { @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"), - List.of(), List.of(), - "cs", - List.of(), - List.of( + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "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); + new MessageHeader("List-Unsubscribe", "")), ts); ArrayNode headers = (ArrayNode) node.get("mail").get("headers"); // From, To, Subject auto-emitted first; then user headers in order. @@ -214,18 +135,10 @@ class SesEventPayloadTest { @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"), - List.of(), List.of(), - "cs", - List.of(), - List.of( + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "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); + 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. @@ -241,69 +154,78 @@ class SesEventPayloadTest { } @Test - void bounce_unionsSimulatorAndSuppressionRecipients() { - // simulator-bounce@... is detected from the envelope, while - // suppressed-bounce@... comes from the suppression-list group. - // The emitted bouncedRecipients list contains both, deduplicated. - ObjectNode node = SesEventPayload.build(mapper, "BOUNCE", "msg-1", "from@example.com", - null, "000000000000", "", + void bounce_forAccountSuppression_rendersOnlyItsOwnRecipientsWithTheSuppressionSubtype() { + // The envelope carries both a simulator bounce and a suppressed address, but this event is + // the suppression one: the simulator recipient belongs to a separate BOUNCE event. + ObjectNode node = SesEventPayload.build(mapper, + SesRecipientEvent.of("BOUNCE", Cause.ACCOUNT_SUPPRESSION, List.of("suppressed-bounce@example.com")), + "msg-1", "from@example.com", null, "000000000000", "", + List.of("bounce@simulator.amazonses.com", "suppressed-bounce@example.com"), List.of(), List.of(), List.of("bounce@simulator.amazonses.com", "suppressed-bounce@example.com"), - List.of(), List.of(), - List.of("bounce@simulator.amazonses.com", "suppressed-bounce@example.com"), - List.of("suppressed-bounce@example.com"), - List.of(), "cs", List.of(), List.of(), ts); - var bounced = node.get("bounce").get("bouncedRecipients"); - assertEquals(2, bounced.size()); - assertEquals("bounce@simulator.amazonses.com", - bounced.get(0).get("emailAddress").asText()); - assertEquals("suppressed-bounce@example.com", - bounced.get(1).get("emailAddress").asText()); + ObjectNode bounce = (ObjectNode) node.get("bounce"); + assertEquals("OnAccountSuppressionList", bounce.get("bounceSubType").asText()); + assertEquals(1, bounce.get("bouncedRecipients").size()); + ObjectNode recipient = (ObjectNode) bounce.get("bouncedRecipients").get(0); + assertEquals("suppressed-bounce@example.com", recipient.get("emailAddress").asText()); + assertEquals("failed", recipient.get("action").asText()); + assertEquals("5.1.1", recipient.get("status").asText()); + assertEquals(SesEventPayload.ACCOUNT_SUPPRESSION_DIAGNOSTIC, recipient.get("diagnosticCode").asText()); + assertEquals(2, node.get("mail").get("destination").size(), "mail.destination keeps the full envelope"); } @Test - void complaint_unionsSimulatorAndSuppressionRecipients() { - ObjectNode node = SesEventPayload.build(mapper, "COMPLAINT", "msg-1", "from@example.com", - null, "000000000000", "", + void complaint_forAccountSuppression_rendersOnlyItsOwnRecipientsWithTheSuppressionSubtype() { + ObjectNode node = SesEventPayload.build(mapper, + SesRecipientEvent.of("COMPLAINT", Cause.ACCOUNT_SUPPRESSION, List.of("suppressed-complaint@example.com")), + "msg-1", "from@example.com", null, "000000000000", "", + List.of("complaint@simulator.amazonses.com", "suppressed-complaint@example.com"), List.of(), List.of(), List.of("complaint@simulator.amazonses.com", "suppressed-complaint@example.com"), - List.of(), List.of(), - List.of("complaint@simulator.amazonses.com", "suppressed-complaint@example.com"), - List.of(), - List.of("suppressed-complaint@example.com"), "cs", List.of(), List.of(), ts); - var complained = node.get("complaint").get("complainedRecipients"); - assertEquals(2, complained.size()); - assertEquals("complaint@simulator.amazonses.com", - complained.get(0).get("emailAddress").asText()); + ObjectNode complaint = (ObjectNode) node.get("complaint"); + assertEquals("OnAccountSuppressionList", complaint.get("complaintSubType").asText()); + assertEquals(1, complaint.get("complainedRecipients").size()); assertEquals("suppressed-complaint@example.com", - complained.get(1).get("emailAddress").asText()); + complaint.get("complainedRecipients").get(0).get("emailAddress").asText()); } @Test - void bounce_simulatorAndSuppressionSameAddressNotDuplicated() { - // If an address is both a bounce simulator AND on the suppression list with - // reason BOUNCE, it should appear once in bouncedRecipients. - 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"), - List.of("bounce@simulator.amazonses.com"), - List.of(), - "cs", List.of(), List.of(), ts); + void bounce_listManagementOptOutIsAGeneralBounceCarryingOnlyTheAddress() { + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("BOUNCE", Cause.LIST_MANAGEMENT, List.of("unsub@example.com")), "msg-1", "from@example.com", null, "000000000000", "", List.of("unsub@example.com"), List.of(), List.of(), List.of("unsub@example.com"), "cs", List.of(), List.of(), ts); - var bounced = node.get("bounce").get("bouncedRecipients"); - assertEquals(1, bounced.size()); + ObjectNode bounce = (ObjectNode) node.get("bounce"); + assertEquals("General", bounce.get("bounceSubType").asText()); + ObjectNode entry = (ObjectNode) bounce.get("bouncedRecipients").get(0); + assertEquals("unsub@example.com", entry.get("emailAddress").asText()); + assertFalse(entry.has("diagnosticCode")); + } + + @Test + void feedbackIdsDifferBetweenTheEventsOfOneSend() { + List envelope = List.of("bounce@simulator.amazonses.com", "blocked@example.com"); + ObjectNode simulator = SesEventPayload.build(mapper, SesRecipientEvent.of("BOUNCE", Cause.SIMULATOR, List.of("bounce@simulator.amazonses.com")), "msg-1", "from@example.com", null, "000000000000", "", envelope, List.of(), List.of(), envelope, "cs", List.of(), List.of(), ts); + ObjectNode suppressed = SesEventPayload.build(mapper, SesRecipientEvent.of("BOUNCE", Cause.ACCOUNT_SUPPRESSION, List.of("blocked@example.com")), "msg-1", "from@example.com", null, "000000000000", "", envelope, List.of(), List.of(), envelope, "cs", List.of(), List.of(), ts); + + assertNotEquals(simulator.get("bounce").get("feedbackId").asText(), + suppressed.get("bounce").get("feedbackId").asText()); + } + + @Test + void feedbackIdIsTheSameOnTheEventAndOnTheIdentityNotificationOfOneOutcome() { + SesRecipientEvent bounce = SesRecipientEvent.of("BOUNCE", Cause.SIMULATOR, List.of("bounce@simulator.amazonses.com")); + List envelope = List.of("bounce@simulator.amazonses.com"); + ObjectNode event = SesEventPayload.build(mapper, bounce, "msg-1", "from@example.com", null, "000000000000", "", envelope, List.of(), List.of(), envelope, "cs", List.of(), List.of(), ts); + ObjectNode notification = SesEventPayload.buildIdentityNotification(mapper, bounce, "msg-1", "from@example.com", null, "000000000000", "", envelope, List.of(), List.of(), envelope, List.of(), ts, false); + + assertEquals(event.get("bounce").get("feedbackId").asText(), + notification.get("bounce").get("feedbackId").asText()); } @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"), List.of(), List.of(), "cs", List.of(), List.of(), ts); + ObjectNode node = SesEventPayload.build(mapper, SesRecipientEvent.of("REJECT", Cause.CONTENT_REJECTED, List.of()), "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/SesEventPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java index f203cc1157..19e6b13c2d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.firehose.FirehoseService; +import io.github.hectorvent.floci.services.ses.SesRecipientEvent.Cause; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.EventBridgeDestination; import io.github.hectorvent.floci.services.ses.model.EventDestination; @@ -72,10 +73,7 @@ class SesEventPublisherTest { when(eventBridgeService.putEvents(any(), anyString())) .thenReturn(new EventBridgeService.PutEventsResult(0, List.of())); - publisher.publish(configurationSetWithEventBridgeDestination(DEFAULT_BUS_ARN), - "SEND", "msg-1", null, null, "000000000000", "subj", - List.of("to@example.com"), null, null, List.of("to@example.com"), - null, null, null, null, Instant.now(), "us-east-1"); + publisher.publish(configurationSetWithEventBridgeDestination(DEFAULT_BUS_ARN), SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "msg-1", null, null, "000000000000", "subj", List.of("to@example.com"), null, null, List.of("to@example.com"), null, null, Instant.now(), "us-east-1"); Map entry = captureSingleEntry(); assertTrue(entry.containsKey("Resources"), @@ -94,10 +92,7 @@ class SesEventPublisherTest { when(eventBridgeService.putEvents(any(), anyString())) .thenReturn(new EventBridgeService.PutEventsResult(0, List.of())); - publisher.publish(configurationSetWithEventBridgeDestination(DEFAULT_BUS_ARN), - "SEND", "msg-1", "sender@example.com", arn, "000000000000", "subj", - List.of("to@example.com"), null, null, List.of("to@example.com"), - null, null, null, null, Instant.now(), "us-east-1"); + publisher.publish(configurationSetWithEventBridgeDestination(DEFAULT_BUS_ARN), SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "msg-1", "sender@example.com", arn, "000000000000", "subj", List.of("to@example.com"), null, null, List.of("to@example.com"), null, null, Instant.now(), "us-east-1"); Map entry = captureSingleEntry(); Object resources = entry.get("Resources"); 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 index 7f567908bb..3bbbceff44 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublishingV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublishingV2IntegrationTest.java @@ -19,9 +19,14 @@ import org.junit.jupiter.api.TestMethodOrder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -535,6 +540,11 @@ class SesEventPublishingV2IntegrationTest { .findFirst().orElseThrow(); assertEquals(suppressed, bounce.path("bounce").path("bouncedRecipients").get(0).path("emailAddress").asText()); + // Probed 2026-09-21: an account-suppressed recipient carries the suppression subtype + // and SES's own diagnostic text, not the simulator's SMTP response. + assertEquals("OnAccountSuppressionList", bounce.path("bounce").path("bounceSubType").asText()); + assertTrue(bounce.path("bounce").path("bouncedRecipients").get(0).path("diagnosticCode").asText() + .startsWith("Amazon SES did not send the message to this address")); } finally { // Always run cleanup so the suppression list doesn't leak into subsequent tests. given() @@ -638,6 +648,7 @@ class SesEventPublishingV2IntegrationTest { .findFirst().orElseThrow(); assertEquals(suppressed, complaint.path("complaint").path("complainedRecipients").get(0).path("emailAddress").asText()); + assertEquals("OnAccountSuppressionList", complaint.path("complaint").path("complaintSubType").asText()); } finally { given() .header("Authorization", SES_AUTH) @@ -1578,6 +1589,145 @@ class SesEventPublishingV2IntegrationTest { .statusCode(200); } + @Test + @Order(32) + void suppressionListSimulator_publishesAGeneralBounceNotAReject() throws Exception { + drainQueue(); + sendEmail("suppressionlist@simulator.amazonses.com"); + + List events = receiveSesEvents(2); + assertEquals(2, events.size(), "expected Send and Bounce events"); + assertTrue(events.stream().noneMatch(e -> "Reject".equals(e.path("eventType").asText()))); + JsonNode bounce = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + // Probed 2026-09-21: an ordinary hard bounce whose diagnostic names the suppression. + assertEquals("General", bounce.path("bounce").path("bounceSubType").asText()); + JsonNode recipient = bounce.path("bounce").path("bouncedRecipients").get(0); + assertEquals("suppressionlist@simulator.amazonses.com", recipient.path("emailAddress").asText()); + assertEquals("5.1.1", recipient.path("status").asText()); + assertTrue(recipient.path("diagnosticCode").asText().contains("suppressed address: suppressionlist@")); + } + + @Test + @Order(33) + void simulatorAndSuppressedBounces_arePublishedAsSeparateEvents() throws Exception { + String suppressed = "split-suppressed-" + System.nanoTime() + "@example.com"; + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"EmailAddress\":\"" + suppressed + "\",\"Reason\":\"BOUNCE\"}") + .when().put("/v2/email/suppression/addresses").then().statusCode(200); + try { + drainQueue(); + given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + { + "FromEmailAddress": "%s", + "Destination": {"ToAddresses": ["bounce@simulator.amazonses.com", "%s"]}, + "ConfigurationSetName": "%s", + "Content": {"Simple": {"Subject": {"Data": "split"}, + "Body": {"Text": {"Data": "hi"}}}} + } + """.formatted(SENDER, suppressed, CS)) + .when().post("/v2/email/outbound-emails").then().statusCode(200); + + List events = receiveSesEvents(3); + assertEquals(3, events.size(), "expected Send plus one Bounce per cause"); + List bounces = events.stream() + .filter(e -> "Bounce".equals(e.path("eventType").asText())).toList(); + assertEquals(2, bounces.size()); + for (JsonNode bounce : bounces) { + JsonNode recipients = bounce.path("bounce").path("bouncedRecipients"); + assertEquals(1, recipients.size(), "each Bounce lists only its own cause's recipients"); + String subtype = bounce.path("bounce").path("bounceSubType").asText(); + String address = recipients.get(0).path("emailAddress").asText(); + assertEquals(address.equals(suppressed) ? "OnAccountSuppressionList" : "General", subtype); + assertEquals(2, bounce.path("mail").path("destination").size(), + "mail.destination carries the full envelope on every event"); + } + } finally { + given().header("Authorization", SES_AUTH) + .when().delete("/v2/email/suppression/addresses/" + suppressed); + } + } + + @Test + @Order(35) + void eicarInSimpleBody_isAcceptedThenRejectedAndStoredWithoutItsContent() throws Exception { + drainQueue(); + String messageId = given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + {"FromEmailAddress": "%s", + "Destination": {"ToAddresses": ["success@simulator.amazonses.com"]}, + "ConfigurationSetName": "%s", + "Content": {"Simple": {"Subject": {"Data": "scan"}, + "Body": {"Text": {"Data": "%s"}, + "Html": {"Data": "

clean

"}}}}} + """.formatted(SENDER, CS, SesContentScan.signature().replace("\\", "\\\\"))) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .extract().jsonPath().getString("MessageId"); + + List events = receiveSesEvents(2); + assertEquals(2, events.size(), "expected Send and Reject, and no Delivery"); + assertTrue(events.stream().anyMatch(e -> "Reject".equals(e.path("eventType").asText()))); + assertTrue(events.stream().noneMatch(e -> "Delivery".equals(e.path("eventType").asText()))); + + // The record keeps the reason and the envelope, but none of the scanned content. + given().header("Authorization", SES_AUTH) + .when().get("/_aws/ses?id=" + messageId).then().statusCode(200) + .body("messages[0].RejectReason", equalTo("Bad content")) + .body("messages[0].Subject", nullValue()) + .body("messages[0].Body.text_part", nullValue()) + .body("messages[0].Body.html_part", nullValue()) + .body("messages[0]", not(hasKey("Headers"))); + } + + @Test + @Order(36) + void eicarInSimpleSubjectOrHeader_isRejectedLikeARawSend() throws Exception { + // The signature can sit in the subject or in a caller-supplied header name or value as + // well as in a body, so the simple path scans all of them, and the record keeps none. + String signature = SesContentScan.signature().replace("\\", "\\\\"); + for (String content : new String[] { + "\"Subject\": {\"Data\": \"" + signature + "\"}, \"Body\": {\"Text\": {\"Data\": \"clean\"}}", + "\"Subject\": {\"Data\": \"clean\"}, \"Body\": {\"Text\": {\"Data\": \"clean\"}}, " + + "\"Headers\": [{\"Name\": \"X-Probe\", \"Value\": \"" + signature + "\"}]", + "\"Subject\": {\"Data\": \"clean\"}, \"Body\": {\"Text\": {\"Data\": \"clean\"}}, " + + "\"Headers\": [{\"Name\": \"" + signature + "\", \"Value\": \"x\"}]"}) { + drainQueue(); + String messageId = given().contentType("application/json").header("Authorization", SES_AUTH) + .body(""" + {"FromEmailAddress": "%s", + "Destination": {"ToAddresses": ["success@simulator.amazonses.com"]}, + "ConfigurationSetName": "%s", + "Content": {"Simple": {%s}}} + """.formatted(SENDER, CS, content)) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .extract().jsonPath().getString("MessageId"); + + List events = receiveSesEvents(2); + assertTrue(events.stream().anyMatch(e -> "Reject".equals(e.path("eventType").asText())), + "expected a Reject for: " + content.substring(0, 30)); + assertTrue(events.stream().noneMatch(e -> "Delivery".equals(e.path("eventType").asText()))); + // Neither the Send nor the Reject event carries the scanned subject or headers. + for (JsonNode event : events) { + JsonNode mail = event.path("mail"); + assertTrue(mail.path("commonHeaders").path("subject").isMissingNode(), + event.path("eventType").asText() + " must not carry the subject"); + for (JsonNode header : mail.path("headers")) { + String name = header.path("name").asText(); + assertTrue(name.equals("From") || name.equals("To") || name.equals("Cc"), + event.path("eventType").asText() + " must not carry header " + name); + } + } + + given().header("Authorization", SES_AUTH) + .when().get("/_aws/ses?id=" + messageId).then().statusCode(200) + .body("messages[0].RejectReason", equalTo("Bad content")) + .body("messages[0].Subject", nullValue()) + .body("messages[0]", not(hasKey("Headers"))); + } + } + private void sendEmail(String to) { given() .contentType("application/json") diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesRecipientEventsTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecipientEventsTest.java new file mode 100644 index 0000000000..25e78be3ad --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecipientEventsTest.java @@ -0,0 +1,174 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.services.ses.SesRecipientEvent.Cause; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SesRecipientEventsTest { + + private static List types(List events) { + return events.stream().map(SesRecipientEvent::eventType).toList(); + } + + private static SesRecipientEvent find(List events, String type, Cause cause) { + return events.stream().filter(e -> e.eventType().equals(type) && e.cause() == cause) + .findFirst().orElseThrow(); + } + + @Test + void ordinaryRecipientProducesOnlySend() { + assertEquals(List.of("SEND"), + types(SesRecipientEvents.classify(List.of("user@example.com"), Map.of(), false))); + } + + @Test + void successSimulatorIsDelivered() { + List events = SesRecipientEvents.classify( + List.of("success@simulator.amazonses.com"), Map.of(), false); + + assertEquals(List.of("SEND", "DELIVERY"), types(events)); + assertEquals(List.of("success@simulator.amazonses.com"), + find(events, "DELIVERY", Cause.SIMULATOR).recipients()); + } + + @Test + void bounceAndSuppressionListSimulatorsShareOneGeneralBounce() { + // Probed 2026-09-21: suppressionlist@ is an ordinary hard bounce, not a Reject. + List events = SesRecipientEvents.classify( + List.of("bounce@simulator.amazonses.com", "suppressionlist@simulator.amazonses.com"), + Map.of(), false); + + assertEquals(List.of("SEND", "BOUNCE"), types(events)); + assertEquals(List.of("bounce@simulator.amazonses.com", "suppressionlist@simulator.amazonses.com"), + find(events, "BOUNCE", Cause.SIMULATOR).recipients()); + } + + @Test + void complaintSimulatorIsDeliveredThenComplainedAbout() { + List events = SesRecipientEvents.classify( + List.of("complaint@simulator.amazonses.com"), Map.of(), false); + + assertEquals(List.of("SEND", "DELIVERY", "COMPLAINT"), types(events)); + } + + @Test + void suppressedRecipientsBounceOrComplainUnderTheirReason() { + List events = SesRecipientEvents.classify( + List.of("a@example.com", "b@example.com"), + Map.of("a@example.com", "BOUNCE", "b@example.com", "COMPLAINT"), false); + + assertEquals(List.of("SEND", "BOUNCE", "COMPLAINT"), types(events)); + assertEquals(List.of("a@example.com"), find(events, "BOUNCE", Cause.ACCOUNT_SUPPRESSION).recipients()); + assertEquals(List.of("b@example.com"), find(events, "COMPLAINT", Cause.ACCOUNT_SUPPRESSION).recipients()); + } + + @Test + void simulatorAndSuppressionBouncesAreSeparateEvents() { + List events = SesRecipientEvents.classify( + List.of("bounce@simulator.amazonses.com", "blocked@example.com"), + Map.of("blocked@example.com", "BOUNCE"), false); + + assertEquals(List.of("SEND", "BOUNCE", "BOUNCE"), types(events)); + assertEquals(List.of("bounce@simulator.amazonses.com"), + find(events, "BOUNCE", Cause.SIMULATOR).recipients()); + assertEquals(List.of("blocked@example.com"), + find(events, "BOUNCE", Cause.ACCOUNT_SUPPRESSION).recipients()); + } + + @Test + void suppressionWinsOverTheSimulatorAddress() { + List events = SesRecipientEvents.classify( + List.of("bounce@simulator.amazonses.com"), + Map.of("bounce@simulator.amazonses.com", "COMPLAINT"), false); + + assertEquals(List.of("SEND", "COMPLAINT"), types(events)); + assertEquals(Cause.ACCOUNT_SUPPRESSION, events.get(1).cause()); + } + + @Test + void labelledSimulatorAddressKeepsItsScenarioAndItsSpelling() { + List events = SesRecipientEvents.classify( + List.of("bounce+order-1@simulator.amazonses.com"), Map.of(), false); + + assertEquals(List.of("bounce+order-1@simulator.amazonses.com"), + find(events, "BOUNCE", Cause.SIMULATOR).recipients()); + } + + @Test + void recipientsAreTrimmedAndDeduplicated() { + List events = SesRecipientEvents.classify( + List.of(" bounce@simulator.amazonses.com", "bounce@simulator.amazonses.com "), Map.of(), false); + + assertEquals(List.of("bounce@simulator.amazonses.com"), + find(events, "BOUNCE", Cause.SIMULATOR).recipients()); + } + + @Test + void rejectedMessagePublishesOnlySendAndReject() { + List events = SesRecipientEvents.classify( + List.of("success@simulator.amazonses.com", "blocked@example.com"), + Map.of("blocked@example.com", "BOUNCE"), true); + + assertEquals(List.of("SEND", "REJECT"), types(events)); + assertEquals(Cause.CONTENT_REJECTED, events.get(1).cause()); + } + + @Test + void nullEnvelopeAndNullReasonsAreTolerated() { + assertEquals(List.of("SEND"), types(SesRecipientEvents.classify(null, null, false))); + } + + @Test + void ordinaryAndSimulatorRecipientsShareTheSendButNotTheOutcome() { + List events = SesRecipientEvents.classify( + List.of("user@example.com", "bounce@simulator.amazonses.com"), Map.of(), false); + + assertEquals(List.of("SEND", "BOUNCE"), types(events)); + assertEquals(List.of("bounce@simulator.amazonses.com"), + find(events, "BOUNCE", Cause.SIMULATOR).recipients()); + } + + @Test + void bounceSimulatorSuppressedForBouncesBouncesOnceUnderTheSuppression() { + List events = SesRecipientEvents.classify( + List.of("bounce@simulator.amazonses.com"), + Map.of("bounce@simulator.amazonses.com", "BOUNCE"), false); + + assertEquals(List.of("SEND", "BOUNCE"), types(events)); + assertEquals(List.of("bounce@simulator.amazonses.com"), + find(events, "BOUNCE", Cause.ACCOUNT_SUPPRESSION).recipients()); + } + + @Test + void complaintSimulatorAndSuppressedComplaintAreSeparateEvents() { + List events = SesRecipientEvents.classify( + List.of("complaint@simulator.amazonses.com", "blocked@example.com"), + Map.of("blocked@example.com", "COMPLAINT"), false); + + assertEquals(List.of("SEND", "DELIVERY", "COMPLAINT", "COMPLAINT"), types(events)); + assertEquals(List.of("complaint@simulator.amazonses.com"), + find(events, "DELIVERY", Cause.SIMULATOR).recipients()); + assertEquals(List.of("complaint@simulator.amazonses.com"), + find(events, "COMPLAINT", Cause.SIMULATOR).recipients()); + assertEquals(List.of("blocked@example.com"), + find(events, "COMPLAINT", Cause.ACCOUNT_SUPPRESSION).recipients()); + } + + @Test + void listManagementOptOutBouncesUnderItsOwnCause() { + List events = SesRecipientEvents.classify( + List.of("unsub@example.com", "blocked@example.com"), + Map.of("unsub@example.com", SesRecipientEvents.REASON_LIST_OPT_OUT, + "blocked@example.com", "BOUNCE"), false); + + assertEquals(List.of("SEND", "BOUNCE", "BOUNCE"), types(events)); + assertEquals(List.of("blocked@example.com"), + find(events, "BOUNCE", Cause.ACCOUNT_SUPPRESSION).recipients()); + assertEquals(List.of("unsub@example.com"), + find(events, "BOUNCE", Cause.LIST_MANAGEMENT).recipients()); + } +}