diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java index c386f2d851..8c44927a9a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java @@ -21,6 +21,8 @@ import software.amazon.awssdk.services.ses.model.ListConfigurationSetsResponse; import software.amazon.awssdk.services.sesv2.SesV2Client; import software.amazon.awssdk.services.sesv2.model.GetConfigurationSetRequest; import software.amazon.awssdk.services.sesv2.model.GetConfigurationSetResponse; +import software.amazon.awssdk.services.sesv2.model.PutConfigurationSetSuppressionOptionsRequest; +import software.amazon.awssdk.services.sesv2.model.SuppressionListReason; import software.amazon.awssdk.services.sesv2.model.Tag; import static org.assertj.core.api.Assertions.assertThat; @@ -38,6 +40,7 @@ class SesConfigurationSetTest { private static SesV2Client sesV2; private static String v1Name; private static String v2Name; + private static String suppressionCsName; @BeforeAll static void setup() { @@ -46,6 +49,7 @@ class SesConfigurationSetTest { String suffix = TestFixtures.uniqueName(); v1Name = "sdk-v1-cs-" + suffix; v2Name = "sdk-v2-cs-" + suffix; + suppressionCsName = "sdk-v2-cs-supp-" + suffix; } @AfterAll @@ -56,6 +60,7 @@ class SesConfigurationSetTest { } if (sesV2 != null) { safelyDeleteV2(v2Name); + safelyDeleteV2(suppressionCsName); sesV2.close(); } } @@ -208,6 +213,99 @@ class SesConfigurationSetTest { .isEqualTo(400); } + // ─────────────────── V2 SuppressionOptions (per-CS) ─────────────────── + + @Test + @Order(30) + void v2SuppressionOptions_setup_createsSuppressionConfigurationSet() { + sesV2.createConfigurationSet(software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest.builder() + .configurationSetName(suppressionCsName) + .build()); + + // Before any PutSuppressionOptions, the response has no SuppressionOptions block. + GetConfigurationSetResponse before = sesV2.getConfigurationSet(GetConfigurationSetRequest.builder() + .configurationSetName(suppressionCsName) + .build()); + assertThat(before.suppressionOptions()).isNull(); + } + + @Test + @Order(31) + void v2PutSuppressionOptions_bounceOnly_visibleOnGet() { + sesV2.putConfigurationSetSuppressionOptions(PutConfigurationSetSuppressionOptionsRequest.builder() + .configurationSetName(suppressionCsName) + .suppressedReasons(SuppressionListReason.BOUNCE) + .build()); + + GetConfigurationSetResponse after = sesV2.getConfigurationSet(GetConfigurationSetRequest.builder() + .configurationSetName(suppressionCsName) + .build()); + assertThat(after.suppressionOptions()).isNotNull(); + assertThat(after.suppressionOptions().suppressedReasons()) + .containsExactly(SuppressionListReason.BOUNCE); + } + + @Test + @Order(32) + void v2PutSuppressionOptions_bothReasons() { + sesV2.putConfigurationSetSuppressionOptions(PutConfigurationSetSuppressionOptionsRequest.builder() + .configurationSetName(suppressionCsName) + .suppressedReasons(SuppressionListReason.BOUNCE, SuppressionListReason.COMPLAINT) + .build()); + + GetConfigurationSetResponse after = sesV2.getConfigurationSet(GetConfigurationSetRequest.builder() + .configurationSetName(suppressionCsName) + .build()); + assertThat(after.suppressionOptions().suppressedReasons()) + .containsExactlyInAnyOrder(SuppressionListReason.BOUNCE, SuppressionListReason.COMPLAINT); + } + + @Test + @Order(33) + void v2PutSuppressionOptions_emptyList_explicitlyDisablesFiltering() { + // Per the AWS V2 contract, an empty SuppressedReasons list is the documented way + // to disable suppression filtering for a configuration set. + sesV2.putConfigurationSetSuppressionOptions(PutConfigurationSetSuppressionOptionsRequest.builder() + .configurationSetName(suppressionCsName) + .suppressedReasons(java.util.Collections.emptyList()) + .build()); + + GetConfigurationSetResponse after = sesV2.getConfigurationSet(GetConfigurationSetRequest.builder() + .configurationSetName(suppressionCsName) + .build()); + assertThat(after.suppressionOptions()).isNotNull(); + assertThat(after.suppressionOptions().suppressedReasons()).isEmpty(); + } + + @Test + @Order(34) + void v2PutSuppressionOptions_invalidReason_rejectedAt400() { + // The typed enum (SuppressionListReason) prevents passing an unknown value through + // the SDK, so use the WithStrings variant to round-trip the literal "INVALID" to + // the wire and exercise server-side validation. + assertThatThrownBy(() -> sesV2.putConfigurationSetSuppressionOptions( + PutConfigurationSetSuppressionOptionsRequest.builder() + .configurationSetName(suppressionCsName) + .suppressedReasonsWithStrings("BOUNCE", "INVALID") + .build())) + .isInstanceOf(AwsServiceException.class) + .extracting(e -> ((AwsServiceException) e).statusCode()) + .isEqualTo(400); + } + + @Test + @Order(35) + void v2PutSuppressionOptions_unknownConfigurationSet_rejectedAt404() { + assertThatThrownBy(() -> sesV2.putConfigurationSetSuppressionOptions( + PutConfigurationSetSuppressionOptionsRequest.builder() + .configurationSetName(suppressionCsName + "-does-not-exist") + .suppressedReasons(SuppressionListReason.BOUNCE) + .build())) + .isInstanceOf(AwsServiceException.class) + .extracting(e -> ((AwsServiceException) e).statusCode()) + .isEqualTo(404); + } + // ─────────────────────────── Helpers ─────────────────────────── private static void safelyDeleteV1(String name) { diff --git a/docs/services/ses.md b/docs/services/ses.md index 0490d3d015..49f1d9cd22 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -187,6 +187,7 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `GET` | `/v2/email/configuration-sets/{name}/event-destinations` | `GetConfigurationSetEventDestinations` | | `PUT` | `/v2/email/configuration-sets/{name}/event-destinations/{eventDestinationName}` | `UpdateConfigurationSetEventDestination` | | `DELETE` | `/v2/email/configuration-sets/{name}/event-destinations/{eventDestinationName}` | `DeleteConfigurationSetEventDestination` | +| `PUT` | `/v2/email/configuration-sets/{name}/suppression-options` | `PutConfigurationSetSuppressionOptions` | | `PUT` | `/v2/email/suppression/addresses` | `PutSuppressedDestination` | | `GET` | `/v2/email/suppression/addresses/{EmailAddress}` | `GetSuppressedDestination` | | `DELETE` | `/v2/email/suppression/addresses/{EmailAddress}` | `DeleteSuppressedDestination` | @@ -210,7 +211,9 @@ Floci recognises the AWS [mailbox simulator addresses](https://docs.aws.amazon.c 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. +Suppression list entries are stored per region with `Reason` ∈ {`BOUNCE`, `COMPLAINT`}. At send time, a recipient is suppressed when it appears on the suppression list AND its stored `Reason` is contained in the **effective** `SuppressedReasons` for the send. The effective list is the configuration set's `SuppressionOptions.SuppressedReasons` (set via `PutConfigurationSetSuppressionOptions`) when present — an **empty list is preserved as an explicit "no suppression filtering for this configuration set"** — otherwise it falls back to the account-level `AccountSuppressionAttributes.SuppressedReasons` (set via `PutAccountSuppressionAttributes`, default `[BOUNCE, COMPLAINT]`). Following the AWS V2 contract, there is no dedicated `GetConfigurationSetSuppressionOptions` action; once set, the block is read back through `GetConfigurationSet`'s response (the field is omitted when the configuration set has no override). + +Suppressed recipients are filtered out of the SMTP relay step (non-suppressed recipients on the same send still reach the relay normally), and the configuration set's event destinations receive a synthetic `Bounce` or `Complaint` event alongside the always-emitted `Send` event. The `SendEmail` API response (`200` + `MessageId`), the stored `SentEmail` visible at `GET /_aws/ses`, and the published event's `mail.destination` all retain the original recipient list — matching the AWS contract that the message is "accepted, just not sent" for suppressed addresses. Tag operations support these ARN forms: `arn:aws:ses:::configuration-set/`, `arn:aws:ses:::template/`, and `arn:aws:ses:::identity/`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, and `CreateEmailIdentity` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` does not modify tags. Other resource types return `NotFoundException`. 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 7d0ae7fd96..05fd55fdc3 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 @@ -648,12 +648,55 @@ public class SesController { tagNode.put("Value", t.value()); tags.add(tagNode); } + if (cs.getSuppressionOptions() != null) { + ObjectNode suppressionNode = result.putObject("SuppressionOptions"); + ArrayNode reasons = suppressionNode.putArray("SuppressedReasons"); + for (String r : cs.getSuppressionOptions().getSuppressedReasons()) { + reasons.add(r); + } + } return Response.ok(result).build(); } catch (AwsException e) { throw remapV1Exception(e); } } + @PUT + @Path("/configuration-sets/{configurationSetName}/suppression-options") + public Response putConfigurationSetSuppressionOptions(@Context HttpHeaders headers, + @PathParam("configurationSetName") String name, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = (body == null || body.isBlank()) + ? objectMapper.createObjectNode() + : objectMapper.readTree(body); + requireJsonObject(request); + JsonNode reasonsNode = request.path("SuppressedReasons"); + List reasons = new ArrayList<>(); + if (!reasonsNode.isMissingNode() && !reasonsNode.isNull()) { + if (!reasonsNode.isArray()) { + throw new AwsException("BadRequestException", + "SuppressedReasons must be an array.", 400); + } + for (JsonNode r : reasonsNode) { + if (r.isNull() || !r.isTextual()) { + throw new AwsException("BadRequestException", + "SuppressedReasons entries must be strings.", 400); + } + reasons.add(r.asText()); + } + } + sesService.putConfigurationSetSuppressionOptions(name, reasons, region); + LOG.infov("SES V2 PutConfigurationSetSuppressionOptions: {0} on {1}", reasons, name); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + @DELETE @Path("/configuration-sets/{configurationSetName}") public Response deleteConfigurationSet(@Context HttpHeaders headers, 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 cef427f00f..0948fcb4c5 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,6 +9,7 @@ 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; @@ -35,6 +36,8 @@ final class SesEventPayload { 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) { ObjectNode root = mapper.createObjectNode(); @@ -43,7 +46,8 @@ final class SesEventPayload { subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations, configurationSetName, emailTags, additionalHeaders, timestamp)); root.set(blockName(eventType), - buildEventBlock(mapper, eventType, messageId, envelopeDestinations, timestamp)); + buildEventBlock(mapper, eventType, messageId, envelopeDestinations, + suppressionBounceRecipients, suppressionComplaintRecipients, timestamp)); return root; } @@ -146,7 +150,10 @@ final class SesEventPayload { } private static ObjectNode buildEventBlock(ObjectMapper mapper, String eventType, String messageId, - List destination, Instant timestamp) { + List destination, + List suppressionBounceRecipients, + List suppressionComplaintRecipients, + Instant timestamp) { ObjectNode body = mapper.createObjectNode(); switch (eventType) { case "DELIVERY" -> { @@ -164,24 +171,16 @@ final class SesEventPayload { 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()); - } - } + emitDedupedRecipientObjects(body.putArray("bouncedRecipients"), + destination, SimulatorAddresses::isBounce, + suppressionBounceRecipients); 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()); - } - } + emitDedupedRecipientObjects(body.putArray("complainedRecipients"), + destination, SimulatorAddresses::isComplaint, + suppressionComplaintRecipients); body.put("timestamp", ISO_MILLIS.format(timestamp)); body.put("feedbackId", "feedback-" + messageId); } @@ -193,6 +192,33 @@ 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()); + } + } + } + if (suppressionRecipients != null) { + for (String d : suppressionRecipients) { + if (d != null && emitted.add(d.trim())) { + arr.addObject().put("emailAddress", d.trim()); + } + } + } + } + private static String eventTypeLabel(String eventType) { return switch (eventType) { case "SEND" -> "Send"; 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 679cc65fdd..f561d52c20 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 @@ -39,6 +39,8 @@ public class SesEventPublisher { 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()) { @@ -47,6 +49,7 @@ public class SesEventPublisher { ObjectNode payload = SesEventPayload.build(objectMapper, eventType, 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()) { 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 13b204d4ca..e88088c110 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 @@ -17,6 +17,7 @@ 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.SuppressionOptions; import io.github.hectorvent.floci.services.ses.model.Tag; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; @@ -32,6 +33,7 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HexFormat; @@ -202,15 +204,25 @@ public class SesService { bccAddresses, replyToAddresses, subject, bodyText, bodyHtml); emailStore.put("email::" + region + "::" + messageId, email); - smtpRelay.relay(source, toAddresses, ccAddresses, bccAddresses, - replyToAddresses, subject, bodyText, bodyHtml); + List envelope = allRecipients(toAddresses, ccAddresses, bccAddresses); + Map suppressedReasons = collectSuppressedReasons(envelope, configurationSetName, region); + + List relayedTo = filterUnsuppressed(toAddresses, suppressedReasons); + List relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons); + List relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons); + if (sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) { + smtpRelay.relay(source, relayedTo, relayedCc, relayedBcc, + replyToAddresses, subject, bodyText, bodyHtml); + } else { + LOG.infov("SES email accepted but not relayed (all recipients suppressed): messageId={0}", + messageId); + } 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); + toAddresses, ccAddresses, bccAddresses, envelope, + suppressedReasons, emailTags, additionalHeaders, region); return messageId; } @@ -237,7 +249,15 @@ public class SesService { SentEmail email = new SentEmail(messageId, region, source, effectiveDestinations, rawMessage); emailStore.put("email::" + region + "::" + messageId, email); - smtpRelay.relayRaw(source, effectiveDestinations, rawMessage); + Map suppressedReasons = collectSuppressedReasons(effectiveDestinations, configurationSetName, region); + + List relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons); + if (!relayedDestinations.isEmpty()) { + smtpRelay.relayRaw(source, relayedDestinations, rawMessage); + } else { + LOG.infov("SES raw email accepted but not relayed (all recipients suppressed): messageId={0}", + messageId); + } LOG.infov("SES raw email sent: from={0}, messageId={1}", source, messageId); publishSendEvents(configurationSetName, messageId, source, @@ -246,7 +266,7 @@ public class SesService { headers != null ? headers.cc() : List.of(), headers != null ? headers.bcc() : List.of(), effectiveDestinations, - emailTags, List.of(), region); + suppressedReasons, emailTags, List.of(), region); return messageId; } @@ -286,6 +306,7 @@ public class SesService { String subject, List toAddresses, List ccAddresses, List bccAddresses, List envelopeDestinations, + Map suppressedReasons, List emailTags, List additionalHeaders, String region) { if (eventPublisher == null) { @@ -312,14 +333,28 @@ public class SesService { ? null : AwsArnUtils.Arn.of("ses", region, sendingAccountId, "identity/" + source).toString(); - for (String eventType : determineSendEventTypes(envelope)) { + 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)) { eventPublisher.publish(cs, eventType, messageId, source, sourceArn, sendingAccountId, subject, toAddresses, ccAddresses, bccAddresses, envelope, + suppressionBounceRecipients, suppressionComplaintRecipients, emailTags, additionalHeaders, timestamp, region); } } - private static List determineSendEventTypes(List destinations) { + private static List determineSendEventTypes(List destinations, + List suppressionBounceRecipients, + List suppressionComplaintRecipients) { List events = new ArrayList<>(); events.add("SEND"); for (String d : destinations) { @@ -336,6 +371,12 @@ public class SesService { events.add("REJECT"); } } + if (!suppressionBounceRecipients.isEmpty() && !events.contains("BOUNCE")) { + events.add("BOUNCE"); + } + if (!suppressionComplaintRecipients.isEmpty() && !events.contains("COMPLAINT")) { + events.add("COMPLAINT"); + } return events; } @@ -686,6 +727,53 @@ public class SesService { eventDestinationName, configSetName, region); } + /** + * Stores per-configuration-set suppression overrides. Mirrors the AWS V2 + * {@code PutConfigurationSetSuppressionOptions} contract: {@code reasons} may + * be {@code null} or empty (explicit "no filtering" for this set) or a subset + * of {@code [BOUNCE, COMPLAINT]}. Once set, the value is returned through + * {@link #getConfigurationSet}; downstream callers can resolve the effective + * reasons for a given send via {@link #getEffectiveSuppressedReasons}. + */ + public void putConfigurationSetSuppressionOptions(String configSetName, + List reasons, String region) { + List sanitized = new ArrayList<>(); + if (reasons != null) { + for (String r : reasons) { + validateConfigSetSuppressionReason(r); + sanitized.add(r); + } + } + ConfigurationSet cs = getConfigurationSet(configSetName, region); + SuppressionOptions options = new SuppressionOptions(); + options.setSuppressedReasons(sanitized); + cs.setSuppressionOptions(options); + configSetStore.put(configSetKey(region, configSetName), cs); + LOG.infov("Updated SuppressionOptions on configuration set {0} in region {1}: {2}", + configSetName, region, sanitized); + } + + /** + * Returns the effective suppression reasons for a send that is using + * {@code configurationSetName}. Per the AWS V2 contract, a configuration + * set's {@code SuppressionOptions} (when present) overrides the + * account-level reasons — including an empty list, which explicitly + * disables suppression filtering for that set. Falls back to the + * account-level reasons when the configuration set has no override, or + * when {@code configurationSetName} is null/blank (i.e. the caller didn't + * specify a configuration set). + */ + public List getEffectiveSuppressedReasons(String configurationSetName, String region) { + if (configurationSetName != null && !configurationSetName.isBlank()) { + ConfigurationSet cs = getConfigurationSet(configurationSetName, region); + SuppressionOptions options = cs.getSuppressionOptions(); + if (options != null) { + return List.copyOf(options.getSuppressedReasons()); + } + } + return List.copyOf(getAccountSuppressionAttributes(region).getSuppressedReasons()); + } + private static int indexOfEventDestination(List destinations, String name) { for (int i = 0; i < destinations.size(); i++) { if (name != null && name.equals(destinations.get(i).getName())) { @@ -1100,6 +1188,101 @@ public class SesService { return "suppression::" + region + "::" + emailAddress; } + /** + * Resolve the effective suppression reason for each address in a single pass over the + * store and the effective settings. The returned map only contains entries for + * addresses that ARE suppressed (i.e., on the list AND whose reason matches the + * effective {@code suppressedReasons} — the configuration set's + * {@code SuppressionOptions} override if present, else the account-level reasons). + * Callers reuse this map for both the SMTP relay filter and the event-publishing + * partitioning so the store is read once per send regardless of the number of + * consumers. + */ + Map collectSuppressedReasons(Collection addresses, + String configurationSetName, String region) { + if (addresses == null || addresses.isEmpty()) { + return Map.of(); + } + List effectiveReasons = getEffectiveSuppressedReasons(configurationSetName, region); + if (effectiveReasons == null || effectiveReasons.isEmpty()) { + return Map.of(); + } + Set reasonFilter = Set.copyOf(effectiveReasons); + Map result = new LinkedHashMap<>(); + for (String address : addresses) { + if (address == null || address.isBlank() || result.containsKey(address)) { + continue; + } + String normalized = normalizeSuppressionEmail(address); + SuppressedDestination entry = suppressionStore.get(suppressionKey(region, normalized)) + .orElse(null); + if (entry != null && entry.getReason() != null + && reasonFilter.contains(entry.getReason())) { + result.put(address, entry.getReason()); + } + } + return result; + } + + /** + * Filter out recipients whose effective suppression reason is non-null. Returns a new + * list containing only the addresses that should reach the SMTP relay, mirroring AWS + * SES's "accept the message, but doesn't send it" behaviour for suppressed addresses. + * Returns the original reference when {@code addresses} is {@code null} or empty. + */ + static List filterUnsuppressed(List addresses, Map suppressedReasons) { + if (addresses == null || addresses.isEmpty()) { + return addresses; + } + if (suppressedReasons.isEmpty()) { + return addresses; + } + List kept = new ArrayList<>(addresses.size()); + for (String a : addresses) { + if (!suppressedReasons.containsKey(a)) { + kept.add(a); + } + } + return kept; + } + + /** + * Resolve the suppression reason that applies to a given recipient in the given region + * for sends using {@code configurationSetName}, or {@code null} if the recipient is not + * suppressed. The recipient is suppressed only when it appears in the address-level + * suppression list AND its stored reason intersects the effective {@code suppressedReasons} + * — the configuration set's {@code SuppressionOptions} override if present, else the + * account-level reasons. {@code configurationSetName} may be {@code null} or blank to + * scope the check to account-level reasons only. + * + *

The returned value is one of {@code "BOUNCE"} / {@code "COMPLAINT"}, allowing + * callers (publishSendEvents) to map the recipient to a synthetic Bounce / Complaint + * event without consulting the store again. Both the per-address suppression entries + * and the account-level / per-CS {@code suppressedReasons} go through + * {@link #validateSuppressionReason} / {@link #validateConfigSetSuppressionReason}, + * which enforce exact case-sensitive equality with the two canonical values, so + * {@code entry.getReason()} is guaranteed to be canonical and downstream + * {@code .equals("BOUNCE")} / {@code .equals("COMPLAINT")} checks are safe. + */ + String resolveSuppressionReason(String emailAddress, String configurationSetName, String region) { + if (emailAddress == null || emailAddress.isBlank()) { + return null; + } + // Share the same normalization used when entries are stored + // (`normalizeSuppressionEmail`) so lookups can't drift apart from inserts. + String normalized = normalizeSuppressionEmail(emailAddress); + SuppressedDestination entry = suppressionStore.get(suppressionKey(region, normalized)) + .orElse(null); + if (entry == null || entry.getReason() == null) { + return null; + } + List effective = getEffectiveSuppressedReasons(configurationSetName, region); + if (effective == null || effective.isEmpty()) { + return null; + } + return effective.contains(entry.getReason()) ? entry.getReason() : null; + } + private static String normalizeSuppressionEmail(String emailAddress) { if (emailAddress == null || emailAddress.isBlank()) { throw new AwsException("BadRequestException", "EmailAddress is required.", 400); @@ -1108,6 +1291,17 @@ public class SesService { return emailAddress.trim(); } + /** + * Validation message used by PutAccountSuppressionAttributes, + * PutSuppressedDestination, and ListSuppressedDestinations — all three + * return the AWS "1 validation error detected: Value at '' + * failed to satisfy constraint: ..." V1-style nested message verbatim. + * (Verified against real AWS V2 SES on 2026-06-03.) The {@code nested} + * flag controls whether the inner enum constraint is wrapped in + * {@code Member must satisfy constraint: [...]} — PutSuppressedDestination + * (single Reason field) returns the unwrapped form; the two list-bearing + * APIs return the wrapped form. + */ private static void validateSuppressionReason(String reason, String fieldName, boolean nested) { if (reason == null || (!"BOUNCE".equals(reason) && !"COMPLAINT".equals(reason))) { String constraint = nested @@ -1119,6 +1313,20 @@ public class SesService { } } + /** + * Validation message used by PutConfigurationSetSuppressionOptions. AWS + * V2 SES uses a different, simpler natural-language sentence on this + * endpoint than on the three older suppression APIs above: + * "Reason is invalid, must be one of [BOUNCE, COMPLAINT]." + * (Verified against real AWS V2 SES on 2026-06-03.) + */ + private static void validateConfigSetSuppressionReason(String reason) { + if (reason == null || (!"BOUNCE".equals(reason) && !"COMPLAINT".equals(reason))) { + throw new AwsException("BadRequestException", + "Reason " + reason + " is invalid, must be one of [BOUNCE, COMPLAINT].", 400); + } + } + static void validateTag(Tag tag) { if (tag == null) { throw new AwsException("InvalidParameterValue", "Tag must not be null.", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/ConfigurationSet.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/ConfigurationSet.java index 619ca66b01..25f0728531 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/ConfigurationSet.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ConfigurationSet.java @@ -24,6 +24,9 @@ public class ConfigurationSet { @JsonProperty("EventDestinations") private List eventDestinations = new ArrayList<>(); + @JsonProperty("SuppressionOptions") + private SuppressionOptions suppressionOptions; + public ConfigurationSet() {} public ConfigurationSet(String name) { @@ -44,4 +47,9 @@ public class ConfigurationSet { public void setEventDestinations(List eventDestinations) { this.eventDestinations = eventDestinations != null ? eventDestinations : new ArrayList<>(); } + + public SuppressionOptions getSuppressionOptions() { return suppressionOptions; } + public void setSuppressionOptions(SuppressionOptions suppressionOptions) { + this.suppressionOptions = suppressionOptions; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/SuppressionOptions.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/SuppressionOptions.java new file mode 100644 index 0000000000..07d87a2482 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/SuppressionOptions.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; + +/** + * Per-configuration-set override of the account-level suppression reasons. + * Mirrors the AWS SES V2 {@code SuppressionOptions} shape. When present on a + * {@link ConfigurationSet}, its {@code SuppressedReasons} take precedence over + * the account-level {@link AccountSuppressionAttributes} for any send using + * that configuration set; an empty list explicitly disables suppression + * filtering for the set. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SuppressionOptions { + + @JsonProperty("SuppressedReasons") + private List suppressedReasons = new ArrayList<>(); + + public SuppressionOptions() {} + + public List getSuppressedReasons() { return suppressedReasons; } + public void setSuppressedReasons(List suppressedReasons) { + this.suppressedReasons = suppressedReasons != null ? suppressedReasons : new ArrayList<>(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetSuppressionOptionsV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetSuppressionOptionsV2IntegrationTest.java new file mode 100644 index 0000000000..71dcb6cf2e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetSuppressionOptionsV2IntegrationTest.java @@ -0,0 +1,280 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +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.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration test for the SES V2 per-configuration-set SuppressionOptions + * endpoint: PUT /v2/email/configuration-sets/{name}/suppression-options and the + * matching GET /v2/email/configuration-sets/{name} response shape. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesConfigurationSetSuppressionOptionsV2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String REGION = "us-east-1"; + private static final String CS = "cs-suppression-options"; + + @Inject + SesService sesService; + + @Test + @Order(1) + void createConfigurationSet() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"ConfigurationSetName\":\"" + CS + "\"}") + .when() + .post("/v2/email/configuration-sets") + .then() + .statusCode(200); + } + + @Test + @Order(2) + void getConfigurationSetBeforePut_doesNotIncludeSuppressionOptions() { + given() + .header("Authorization", AUTH) + .when() + .get("/v2/email/configuration-sets/" + CS) + .then() + .statusCode(200) + .body("ConfigurationSetName", equalTo(CS)) + .body("SuppressionOptions", nullValue()); + } + + @Test + @Order(3) + void putSuppressionOptions_bounceOnly() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"SuppressedReasons\":[\"BOUNCE\"]}") + .when() + .put("/v2/email/configuration-sets/" + CS + "/suppression-options") + .then() + .statusCode(200); + } + + @Test + @Order(4) + void getConfigurationSet_afterPut_reflectsSuppressionOptions() { + given() + .header("Authorization", AUTH) + .when() + .get("/v2/email/configuration-sets/" + CS) + .then() + .statusCode(200) + .body("SuppressionOptions.SuppressedReasons", contains("BOUNCE")) + .body("SuppressionOptions.SuppressedReasons", hasSize(1)); + } + + @Test + @Order(5) + void putSuppressionOptions_emptyList_explicitlyDisablesFiltering() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"SuppressedReasons\":[]}") + .when() + .put("/v2/email/configuration-sets/" + CS + "/suppression-options") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .when() + .get("/v2/email/configuration-sets/" + CS) + .then() + .statusCode(200) + .body("SuppressionOptions.SuppressedReasons", empty()); + } + + @Test + @Order(6) + void putSuppressionOptions_bothReasons() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"SuppressedReasons\":[\"BOUNCE\",\"COMPLAINT\"]}") + .when() + .put("/v2/email/configuration-sets/" + CS + "/suppression-options") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .when() + .get("/v2/email/configuration-sets/" + CS) + .then() + .statusCode(200) + .body("SuppressionOptions.SuppressedReasons", contains("BOUNCE", "COMPLAINT")); + } + + @Test + @Order(7) + void putSuppressionOptions_invalidReason_rejected() { + // Message verified against real AWS V2 SES on 2026-06-03: + // "Reason INVALID is invalid, must be one of [BOUNCE, COMPLAINT]." + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"SuppressedReasons\":[\"BOUNCE\",\"INVALID\"]}") + .when() + .put("/v2/email/configuration-sets/" + CS + "/suppression-options") + .then() + .statusCode(400) + .body("__type", org.hamcrest.Matchers.equalTo("BadRequestException")) + .body("message", org.hamcrest.Matchers.equalTo( + "Reason INVALID is invalid, must be one of [BOUNCE, COMPLAINT].")); + } + + @Test + @Order(8) + void putSuppressionOptions_nonArrayReasons_rejected() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"SuppressedReasons\":\"BOUNCE\"}") + .when() + .put("/v2/email/configuration-sets/" + CS + "/suppression-options") + .then() + .statusCode(400); + } + + @Test + @Order(9) + void putSuppressionOptions_unknownConfigSet_returns404() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"SuppressedReasons\":[\"BOUNCE\"]}") + .when() + .put("/v2/email/configuration-sets/does-not-exist/suppression-options") + .then() + .statusCode(404); + } + + @Test + @Order(10) + void putSuppressionOptions_omittedSuppressedReasons_treatedAsEmptyList() { + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{}") + .when() + .put("/v2/email/configuration-sets/" + CS + "/suppression-options") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .when() + .get("/v2/email/configuration-sets/" + CS) + .then() + .statusCode(200) + .body("SuppressionOptions.SuppressedReasons", empty()); + } + + // ─── getEffectiveSuppressedReasons helper (forward-looking integration with #1109) ─── + + @Test + @Order(20) + void effectiveReasons_csWithoutOverride_fallsBackToAccountLevel() { + String csNoOverride = "cs-suppression-no-override"; + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"ConfigurationSetName\":\"" + csNoOverride + "\"}") + .when() + .post("/v2/email/configuration-sets") + .then() + .statusCode(200); + + List effective = sesService.getEffectiveSuppressedReasons(csNoOverride, REGION); + // Account defaults to [BOUNCE, COMPLAINT]; matches account state when no per-CS override. + assertEquals(sesService.getAccountSuppressionAttributes(REGION).getSuppressedReasons(), effective); + } + + @Test + @Order(21) + void effectiveReasons_csWithBounceOverride_returnsBounceOnly() { + String csBounceOnly = "cs-suppression-bounce-only"; + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"ConfigurationSetName\":\"" + csBounceOnly + "\"}") + .when() + .post("/v2/email/configuration-sets") + .then() + .statusCode(200); + + sesService.putConfigurationSetSuppressionOptions(csBounceOnly, List.of("BOUNCE"), REGION); + + List effective = sesService.getEffectiveSuppressedReasons(csBounceOnly, REGION); + assertEquals(List.of("BOUNCE"), effective); + } + + @Test + @Order(22) + void effectiveReasons_csWithEmptyOverride_explicitlyDisablesFiltering() { + String csEmpty = "cs-suppression-empty"; + given() + .contentType("application/json") + .header("Authorization", AUTH) + .body("{\"ConfigurationSetName\":\"" + csEmpty + "\"}") + .when() + .post("/v2/email/configuration-sets") + .then() + .statusCode(200); + + sesService.putConfigurationSetSuppressionOptions(csEmpty, List.of(), REGION); + + List effective = sesService.getEffectiveSuppressedReasons(csEmpty, REGION); + assertTrue(effective.isEmpty(), + "An empty SuppressedReasons override must defeat the account-level reasons, " + + "matching the AWS V2 contract: \"If you specify an empty list, " + + "Amazon SES doesn't apply any suppression filtering ...\""); + } + + @Test + @Order(23) + void effectiveReasons_nullConfigSetName_returnsAccountLevel() { + List effective = sesService.getEffectiveSuppressedReasons(null, REGION); + assertEquals(sesService.getAccountSuppressionAttributes(REGION).getSuppressedReasons(), effective); + } + + @Test + @Order(24) + void effectiveReasons_blankConfigSetName_returnsAccountLevel() { + List effective = sesService.getEffectiveSuppressedReasons(" ", REGION); + assertEquals(sesService.getAccountSuppressionAttributes(REGION).getSuppressedReasons(), effective); + } + + @Test + @Order(25) + void effectiveReasons_nonExistentConfigSet_throws() { + assertThrows(AwsException.class, + () -> sesService.getEffectiveSuppressedReasons("never-created", REGION)); + } +} 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 afa2ffc38f..21f1bf99cb 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 @@ -30,7 +30,7 @@ class SesEventPayloadTest { 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); + List.of(), List.of("to@example.com", "cc@example.com"), List.of(), List.of(), "my-cs", List.of(), List.of(), ts); assertEquals("Send", node.get("eventType").asText()); assertTrue(node.has("send")); @@ -68,7 +68,7 @@ class SesEventPayloadTest { 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); + List.of("success@simulator.amazonses.com"), List.of(), List.of(), "cs", List.of(), List.of(), ts); assertEquals("Delivery", node.get("eventType").asText()); ObjectNode delivery = (ObjectNode) node.get("delivery"); @@ -83,7 +83,7 @@ class SesEventPayloadTest { 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); + List.of("bounce@simulator.amazonses.com"), List.of(), List.of(), "cs", List.of(), List.of(), ts); assertEquals("Bounce", node.get("eventType").asText()); ObjectNode bounce = (ObjectNode) node.get("bounce"); @@ -98,7 +98,7 @@ class SesEventPayloadTest { 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); + List.of("complaint@simulator.amazonses.com"), List.of(), List.of(), "cs", List.of(), List.of(), ts); assertEquals("Complaint", node.get("eventType").asText()); assertEquals("complaint@simulator.amazonses.com", @@ -112,7 +112,7 @@ class SesEventPayloadTest { 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); + List.of(), List.of(), "cs", List.of(), List.of(), ts); var bounced = (com.fasterxml.jackson.databind.node.ArrayNode) node.get("bounce").get("bouncedRecipients"); @@ -130,7 +130,7 @@ class SesEventPayloadTest { 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); + List.of(), List.of(), "cs", List.of(), List.of(), ts); var recipients = node.get("delivery").get("recipients"); assertEquals(1, recipients.size()); @@ -144,7 +144,7 @@ class SesEventPayloadTest { 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); + List.of(), List.of(), "cs", List.of(), List.of(), ts); var complained = node.get("complaint").get("complainedRecipients"); assertEquals(1, complained.size()); @@ -158,6 +158,7 @@ class SesEventPayloadTest { 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(), @@ -175,6 +176,7 @@ class SesEventPayloadTest { 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(), @@ -192,6 +194,7 @@ class SesEventPayloadTest { 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( @@ -215,6 +218,7 @@ class SesEventPayloadTest { 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( @@ -236,12 +240,70 @@ class SesEventPayloadTest { assertTrue(hasXReal); } + @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", "", + 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()); + } + + @Test + void complaint_unionsSimulatorAndSuppressionRecipients() { + ObjectNode node = SesEventPayload.build(mapper, "COMPLAINT", "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("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()); + assertEquals("suppressed-complaint@example.com", + complained.get(1).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); + + var bounced = node.get("bounce").get("bouncedRecipients"); + assertEquals(1, bounced.size()); + } + @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); + List.of("suppressionlist@simulator.amazonses.com"), List.of(), List.of(), "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 index 381a109dbd..0f5ad028b6 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 @@ -445,6 +445,111 @@ class SesEventPublishingV2IntegrationTest { assertTrue(hasUnsubscribe, "expected List-Unsubscribe header in event mail.headers"); } + @Test + @Order(12) + void sendToSuppressedAddress_withBounceReason_publishesSyntheticBounceEvent() throws Exception { + String suppressed = "bounce-suppressed-" + System.nanoTime() + "@example.com"; + // Pre-register the address in the account-level suppression list with reason BOUNCE. + 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": ["%s"]}, + "ConfigurationSetName": "%s", + "Content": { + "Simple": { + "Subject": {"Data": "evt"}, + "Body": {"Text": {"Data": "hi"}} + } + } + } + """.formatted(SENDER, suppressed, CS)) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200); + + List events = receiveSesEvents(2); + assertEquals(2, events.size(), "expected Send and synthetic 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(); + assertEquals(suppressed, + bounce.path("bounce").path("bouncedRecipients").get(0).path("emailAddress").asText()); + } finally { + // Always run cleanup so the suppression list doesn't leak into subsequent tests. + given() + .header("Authorization", SES_AUTH) + .when() + .delete("/v2/email/suppression/addresses/" + suppressed); + } + } + + @Test + @Order(13) + void sendToSuppressedAddress_withComplaintReason_publishesSyntheticComplaintEvent() throws Exception { + String suppressed = "complaint-suppressed-" + System.nanoTime() + "@example.com"; + given() + .contentType("application/json") + .header("Authorization", SES_AUTH) + .body("{\"EmailAddress\":\"" + suppressed + "\",\"Reason\":\"COMPLAINT\"}") + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + try { + drainQueue(); + 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, suppressed, CS)) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200); + + List events = receiveSesEvents(2); + assertEquals(2, events.size(), "expected Send and synthetic Complaint events"); + JsonNode complaint = events.stream() + .filter(e -> "Complaint".equals(e.path("eventType").asText())) + .findFirst().orElseThrow(); + assertEquals(suppressed, + complaint.path("complaint").path("complainedRecipients").get(0).path("emailAddress").asText()); + } finally { + given() + .header("Authorization", SES_AUTH) + .when() + .delete("/v2/email/suppression/addresses/" + suppressed); + } + } + private void sendEmail(String to) { given() .contentType("application/json") 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 fca8961c3c..bd9d46cbb4 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 @@ -105,4 +105,140 @@ class SesServiceSmtpTest { null, null, null, "Subject", null, "

html only

"); } + + @Test + void sendEmail_allRecipientsSuppressed_skipsRelayButStillStores() { + service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); + service.putSuppressedDestination("us-east-1", "cc@example.com", "COMPLAINT"); + + String messageId = service.sendEmail("from@example.com", + List.of("to@example.com"), + List.of("cc@example.com"), + null, null, + "Subject", "text body", null, null, List.of(), List.of(), "us-east-1"); + + assertNotNull(messageId); + assertFalse(emailStore.scan(k -> true).isEmpty(), + "stored SentEmail should still record the original recipient list"); + verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void sendEmail_partialSuppression_relayCalledWithFilteredRecipients() { + // Only suppress one of the To recipients; the other should still reach the relay. + service.putSuppressedDestination("us-east-1", "suppressed@example.com", "BOUNCE"); + + service.sendEmail("from@example.com", + List.of("to@example.com", "suppressed@example.com"), + List.of("cc-keep@example.com"), + null, null, + "Subject", "text body", null, null, List.of(), List.of(), "us-east-1"); + + verify(smtpRelay).relay( + "from@example.com", + List.of("to@example.com"), + List.of("cc-keep@example.com"), + null, + null, + "Subject", "text body", null); + } + + @Test + void sendRawEmail_allRecipientsSuppressed_skipsRelayRawButStillStores() { + service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); + + String messageId = service.sendRawEmail("from@example.com", + List.of("to@example.com"), "raw MIME", null, List.of(), "us-east-1"); + + assertNotNull(messageId); + assertFalse(emailStore.scan(k -> true).isEmpty()); + verify(smtpRelay, never()).relayRaw(any(), any(), any()); + } + + @Test + void sendRawEmail_partialSuppression_relayRawCalledWithFilteredRecipients() { + service.putSuppressedDestination("us-east-1", "suppressed@example.com", "COMPLAINT"); + + service.sendRawEmail("from@example.com", + List.of("to@example.com", "suppressed@example.com"), + "raw MIME", null, List.of(), "us-east-1"); + + verify(smtpRelay).relayRaw( + "from@example.com", + List.of("to@example.com"), + "raw MIME"); + } + + // ─────────── Per-CS SuppressionOptions override at send time ─────────── + + @Test + void sendEmail_csOverridesAccountToEmptyList_suppressionListIsIgnored() { + // Account defaults to [BOUNCE, COMPLAINT] suppression. The CS explicitly + // overrides to an empty list, which is the AWS V2 contract for "disable + // suppression filtering for this configuration set". A recipient on the + // suppression list with reason=BOUNCE should still reach the SMTP relay. + service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); + service.createConfigurationSet(new ConfigurationSet("cs-no-suppression"), "us-east-1"); + service.putConfigurationSetSuppressionOptions("cs-no-suppression", List.of(), "us-east-1"); + + service.sendEmail("from@example.com", + List.of("to@example.com"), null, null, null, + "Subject", "text body", null, "cs-no-suppression", List.of(), List.of(), "us-east-1"); + + verify(smtpRelay).relay( + "from@example.com", + List.of("to@example.com"), + null, null, null, + "Subject", "text body", null); + } + + @Test + void sendEmail_csOverridesAccountToBounceOnly_complaintSuppressedAddressStillRelayed() { + // Account-level reasons include both BOUNCE and COMPLAINT by default. + // The CS narrows the effective reasons to [BOUNCE] only — so a recipient + // suppressed for COMPLAINT is NOT filtered when sending through this CS. + service.putSuppressedDestination("us-east-1", "complainer@example.com", "COMPLAINT"); + service.createConfigurationSet(new ConfigurationSet("cs-bounce-only"), "us-east-1"); + service.putConfigurationSetSuppressionOptions("cs-bounce-only", List.of("BOUNCE"), "us-east-1"); + + service.sendEmail("from@example.com", + List.of("complainer@example.com"), null, null, null, + "Subject", "text body", null, "cs-bounce-only", List.of(), List.of(), "us-east-1"); + + verify(smtpRelay).relay( + "from@example.com", + List.of("complainer@example.com"), + null, null, null, + "Subject", "text body", null); + } + + @Test + void sendEmail_csWithoutOverride_fallsBackToAccountLevelSuppression() { + // A configuration set whose SuppressionOptions block was never PUT must + // fall back to account-level reasons — same filtering behaviour as a + // send without any configuration set. + service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); + service.createConfigurationSet(new ConfigurationSet("cs-default"), "us-east-1"); + + service.sendEmail("from@example.com", + List.of("to@example.com"), null, null, null, + "Subject", "text body", null, "cs-default", List.of(), List.of(), "us-east-1"); + + verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void sendRawEmail_csOverridesAccountToEmptyList_suppressionListIsIgnored() { + service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); + service.createConfigurationSet(new ConfigurationSet("cs-no-suppression-raw"), "us-east-1"); + service.putConfigurationSetSuppressionOptions("cs-no-suppression-raw", List.of(), "us-east-1"); + + service.sendRawEmail("from@example.com", + List.of("to@example.com"), "raw MIME", "cs-no-suppression-raw", List.of(), "us-east-1"); + + verify(smtpRelay).relayRaw( + "from@example.com", + List.of("to@example.com"), + "raw MIME"); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java new file mode 100644 index 0000000000..6341e7e94d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java @@ -0,0 +1,97 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; +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.SentEmail; +import io.github.hectorvent.floci.services.ses.model.SuppressedDestination; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; + +/** + * Covers {@link SesService#resolveSuppressionReason(String, String)} — the per-recipient + * lookup that publishSendEvents uses to map suppressed addresses to synthetic Bounce or + * Complaint events. + * + *

The helper returns a reason only when the address is on the suppression list AND + * the address's stored reason intersects {@link AccountSuppressionAttributes#getSuppressedReasons()}. + */ +class SesServiceSuppressionReasonTest { + + private static final String REGION = "us-east-1"; + + private SesService service; + private InMemoryStorage suppressionStore; + private InMemoryStorage accountSuppressionStore; + + @BeforeEach + void setUp() { + suppressionStore = new InMemoryStorage<>(); + accountSuppressionStore = new InMemoryStorage<>(); + service = new SesService( + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + suppressionStore, + accountSuppressionStore, + mock(SmtpRelay.class), + new ObjectMapper()); + } + + @Test + void notOnList_returnsNull() { + // Default fresh account: suppressedReasons defaults to [BOUNCE, COMPLAINT], but the + // address is not on the list, so resolution returns null. + assertNull(service.resolveSuppressionReason("unknown@example.com", null, REGION)); + } + + @Test + void onListAndReasonInAccountSettings_returnsReason() { + service.putSuppressedDestination(REGION, "bouncer@example.com", "BOUNCE"); + // Account-level suppressedReasons defaults to [BOUNCE, COMPLAINT]. + assertEquals("BOUNCE", service.resolveSuppressionReason("bouncer@example.com", null, REGION)); + } + + @Test + void onListButReasonNotInAccountSettings_returnsNull() { + service.putSuppressedDestination(REGION, "complainer@example.com", "COMPLAINT"); + // Narrow the account settings to BOUNCE only. + service.putAccountSuppressionAttributes(REGION, List.of("BOUNCE")); + assertNull(service.resolveSuppressionReason("complainer@example.com", null, REGION)); + } + + @Test + void accountSettingsEmpty_returnsNull() { + service.putSuppressedDestination(REGION, "bouncer@example.com", "BOUNCE"); + // Disable account-level suppression by passing an empty list. + service.putAccountSuppressionAttributes(REGION, new ArrayList<>()); + assertNull(service.resolveSuppressionReason("bouncer@example.com", null, REGION)); + } + + @Test + void leadingTrailingWhitespaceIsNormalized() { + service.putSuppressedDestination(REGION, "trim-me@example.com", "BOUNCE"); + // Caller may pass the recipient with surrounding whitespace (e.g. from a header). + assertEquals("BOUNCE", + service.resolveSuppressionReason(" trim-me@example.com ", null, REGION)); + } + + @Test + void nullOrBlankInput_returnsNull() { + assertNull(service.resolveSuppressionReason(null, null, REGION)); + assertNull(service.resolveSuppressionReason("", null, REGION)); + assertNull(service.resolveSuppressionReason(" ", null, REGION)); + } +}