Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ses): add v2 GetMessageInsights (#4157)
Kenshin Okinakae947b6a2a1b8
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesMessageInsightsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesMessageInsightsTest.javanew file mode 100644index 0000000000..fb937a6568--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesMessageInsightsTest.java@@ -0,0 +1,207 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import software.amazon.awssdk.services.sesv2.SesV2Client;+import software.amazon.awssdk.services.sesv2.model.Body;+import software.amazon.awssdk.services.sesv2.model.Content;+import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest;+import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest;+import software.amazon.awssdk.services.sesv2.model.Destination;+import software.amazon.awssdk.services.sesv2.model.EmailContent;+import software.amazon.awssdk.services.sesv2.model.EmailInsights;+import software.amazon.awssdk.services.sesv2.model.GetAccountRequest;+import software.amazon.awssdk.services.sesv2.model.GetAccountResponse;+import software.amazon.awssdk.services.sesv2.model.GetMessageInsightsRequest;+import software.amazon.awssdk.services.sesv2.model.GetMessageInsightsResponse;+import software.amazon.awssdk.services.sesv2.model.InsightsEvent;+import software.amazon.awssdk.services.sesv2.model.Message;+import software.amazon.awssdk.services.sesv2.model.MessageTag;+import software.amazon.awssdk.services.sesv2.model.NotFoundException;+import software.amazon.awssdk.services.sesv2.model.PutAccountVdmAttributesRequest;+import software.amazon.awssdk.services.sesv2.model.SendEmailRequest;+import software.amazon.awssdk.services.sesv2.model.VdmAttributes;++import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * SDK compatibility test for SES v2 GetMessageInsights: the Virtual Deliverability Manager gate,+ * the not-found shape, and the per-recipient event timeline a send produces, against a live Floci+ * instance. VDM is account and region scoped, so the original attributes are captured and restored.+ */+@DisplayName("SES v2 Message Insights")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesMessageInsightsTest {++ private static final String SENDER = "[email protected]";++ private static SesV2Client sesV2;+ private static VdmAttributes originalVdm;++ @BeforeAll+ static void setup() {+ sesV2 = TestFixtures.sesV2Client();+ GetAccountResponse account = sesV2.getAccount(GetAccountRequest.builder().build());+ originalVdm = account.vdmAttributes();+ // An interrupted earlier run can leave the identity behind; creating it again would fail+ // with AlreadyExistsException before any test ran.+ quietly(() -> sesV2.deleteEmailIdentity(+ DeleteEmailIdentityRequest.builder().emailIdentity(SENDER).build()));+ setVdmEnabled(false);+ sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(SENDER).build());+ }++ @AfterAll+ static void cleanup() {+ if (sesV2 == null) {+ return;+ }+ quietly(() -> sesV2.deleteEmailIdentity(+ DeleteEmailIdentityRequest.builder().emailIdentity(SENDER).build()));+ quietly(SesMessageInsightsTest::restoreVdm);+ sesV2.close();+ }++ @Test+ @Order(1)+ @DisplayName("reports the VDM gate before it looks at the message id")+ void vdmDisabledIsReportedFirst() {+ assertThatThrownBy(() -> sesV2.getMessageInsights(+ GetMessageInsightsRequest.builder().messageId("not-even-an-id").build()))+ .isInstanceOf(NotFoundException.class)+ .hasMessageContaining("Virtual Deliverability Manager");+ }++ @Test+ @Order(2)+ @DisplayName("an unknown message names the account alongside the id")+ void unknownMessageNamesTheAccount() {+ setVdmEnabled(true);++ assertThatThrownBy(() -> sesV2.getMessageInsights(+ GetMessageInsightsRequest.builder().messageId("no-such-message").build()))+ .isInstanceOf(NotFoundException.class)+ .hasMessageContaining("Message <no-such-message> not found for account <");+ }++ @Test+ @Order(3)+ @DisplayName("an ordinary recipient reports SEND then DELIVERY with the send's tags")+ void ordinaryRecipientTimeline() {+ String messageId = send("[email protected]", "compat-ordinary");++ GetMessageInsightsResponse insights = sesV2.getMessageInsights(+ GetMessageInsightsRequest.builder().messageId(messageId).build());++ assertThat(insights.messageId()).isEqualTo(messageId);+ assertThat(insights.fromEmailAddress()).isEqualTo(SENDER);+ assertThat(insights.subject()).isEqualTo("compat-ordinary");+ assertThat(insights.emailTags()).singleElement()+ .satisfies(tag -> {+ assertThat(tag.name()).isEqualTo("campaign");+ assertThat(tag.value()).isEqualTo("compat");+ });+ assertThat(insights.insights()).singleElement().satisfies(recipient -> {+ assertThat(recipient.destination()).isEqualTo("[email protected]");+ assertThat(recipient.isp()).isEqualTo("UNKNOWN_ISP");+ assertThat(recipient.events()).extracting(event -> event.type().toString())+ .containsExactly("SEND", "DELIVERY");+ assertThat(recipient.events()).allSatisfy(+ event -> assertThat(event.timestamp()).isNotNull());+ });+ }++ @Test+ @Order(4)+ @DisplayName("the bounce simulator carries the bounce details")+ void bounceSimulatorTimeline() {+ String messageId = send("[email protected]", "compat-bounce");++ GetMessageInsightsResponse insights = sesV2.getMessageInsights(+ GetMessageInsightsRequest.builder().messageId(messageId).build());++ List<InsightsEvent> events = insights.insights().get(0).events();+ assertThat(events).extracting(event -> event.type().toString())+ .containsExactly("SEND", "BOUNCE");+ assertThat(events.get(1).details().bounce().bounceTypeAsString()).isEqualTo("PERMANENT");+ assertThat(events.get(1).details().bounce().diagnosticCode()).contains("550 5.1.1");+ }++ @Test+ @Order(5)+ @DisplayName("Floci reports one timeline per recipient where AWS records nothing at all")+ void multipleRecipientsGetOneTimelineEach() {+ String messageId = sesV2.sendEmail(SendEmailRequest.builder()+ .fromEmailAddress(SENDER)+ .destination(Destination.builder()+ .toAddresses("[email protected]")+ .ccAddresses("[email protected]")+ .build())+ .content(content("compat-multi"))+ .build()).messageId();++ GetMessageInsightsResponse insights = sesV2.getMessageInsights(+ GetMessageInsightsRequest.builder().messageId(messageId).build());++ assertThat(insights.insights()).extracting(EmailInsights::destination)+ .containsExactly("[email protected]", "[email protected]");+ }++ private static String send(String recipient, String subject) {+ return sesV2.sendEmail(SendEmailRequest.builder()+ .fromEmailAddress(SENDER)+ .destination(Destination.builder().toAddresses(recipient).build())+ .emailTags(MessageTag.builder().name("campaign").value("compat").build())+ .content(content(subject))+ .build()).messageId();+ }++ private static EmailContent content(String subject) {+ return EmailContent.builder()+ .simple(Message.builder()+ .subject(Content.builder().data(subject).build())+ .body(Body.builder().text(Content.builder().data("hi").build()).build())+ .build())+ .build();+ }++ private static void setVdmEnabled(boolean enabled) {+ sesV2.putAccountVdmAttributes(PutAccountVdmAttributesRequest.builder()+ .vdmAttributes(VdmAttributes.builder()+ .vdmEnabled(enabled ? "ENABLED" : "DISABLED")+ .build())+ .build());+ }++ // VDM has no un-configure API, so a region that started unconfigured is left DISABLED rather+ // than restored to absent. Same compromise as SesAccountAttributesTest.+ private static void restoreVdm() {+ VdmAttributes.Builder vdm = VdmAttributes.builder();+ if (originalVdm != null && originalVdm.vdmEnabled() != null) {+ vdm.vdmEnabled(originalVdm.vdmEnabled())+ .dashboardAttributes(originalVdm.dashboardAttributes())+ .guardianAttributes(originalVdm.guardianAttributes());+ } else {+ vdm.vdmEnabled("DISABLED");+ }+ sesV2.putAccountVdmAttributes(+ PutAccountVdmAttributesRequest.builder().vdmAttributes(vdm.build()).build());+ }++ private static void quietly(Runnable action) {+ try {+ action.run();+ } catch (RuntimeException expected) {+ // Cleanup is best effort: a failed teardown must not mask the test result.+ }+ }+}diff --git a/docs/services/ses.md b/docs/services/ses.mdindex 26ded81726..14545fdce3 100644--- a/docs/services/ses.md+++ b/docs/services/ses.md@@ -377,6 +377,7 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS| `POST` | `/v2/email/import-jobs` | `CreateImportJob` || `GET` | `/v2/email/import-jobs/{JobId}` | `GetImportJob` || `POST` | `/v2/email/import-jobs/list` | `ListImportJobs` |+| `GET` | `/v2/email/insights/{MessageId}` | `GetMessageInsights` |Floci models no leased dedicated IPs: `GetDedicatedIps` is empty and IP-targeted operations return `NotFoundException`, as real AWS does for an account with no leased IPs, with required request members validated first (`BadRequestException`). `PutDedicatedIpPoolScalingAttributes` rejects downgrading a `MANAGED` pool to `STANDARD`, and `PutAccountDedicatedIpWarmupAttributes` stores the flag behind `GetAccount.DedicatedIpAutoWarmupEnabled` (default `true`).@@ -416,6 +417,8 @@ Suppression list entries are stored per region with `Reason` ∈ {`BOUNCE`, `COMSuppressed 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.+`GetMessageInsights` derives its per-recipient timeline at send time from the same classification as event publishing, adding `DELIVERY` for an ordinary recipient, and spells the suppression subtype `ON_ACCOUNT_SUPPRESSION_LIST` where the published events say `OnAccountSuppressionList` (bounce probed 2026-09-21, complaint by analogy). It is gated on Virtual Deliverability Manager as on AWS: 404 `NotFoundException`, checked before the message id. Deviations from AWS: Floci records the mailbox-simulator and multi-recipient sends that VDM drops (otherwise insights would stay empty here), serves a message immediately, returns only the caller's `EmailTags` without the injected `ses:*` entries, applies no 30-day retention cutoff, and derives a timeline whether or not VDM was enabled at send time. `Isp` is always `UNKNOWN_ISP`, AWS's own value for a provider it cannot identify. A message the content scan rejected reports `SEND` then `REJECT` and carries nothing read off it: no subject, and only the tags the request itself supplied.+Import jobs read their source from Floci's own S3 emulation, so the object has to be uploaded there rather than to real S3; the CSV and newline-delimited JSON record formats are AWS's own ([suppression list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html#sending-email-suppression-list-manual-add-bulk), [contact list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-list-management.html#configuring-list-management-bulk-import)). A job still running when the emulator restarts is marked `FAILED` on the next start. Not emulated: `FailureInfo.FailedRecordsS3Url` (Floci writes no failed-record file), the per-file record limits, the same-region bucket rule, and `ListImportJobs` pagination, which returns every job in one page.`SendEmail` honors `ListManagementOptions` (`ContactListName`, optional `TopicName`). When present, each recipient is matched against the named contact list and suppressed as a `Bounce` when opted out — reusing the same relay-exclusion and Bounce-event path as suppression-list filtering, matching AWS ("SES will issue a bounce event for a message that is sent to an unsubscribed contact"). A contact is opted out when `UnsubscribeAll` is set; with a `TopicName`, an explicit `OPT_OUT` preference for that topic (or, absent an explicit preference, the topic's `DefaultSubscriptionStatus` being `OPT_OUT`) suppresses; without a `TopicName`, only `UnsubscribeAll` contacts are suppressed. A recipient that is not yet a contact is created on the list automatically (as on AWS) and then evaluated. Referencing a contact list that does not exist fails the send with `NotFoundException`. The topic-default fallback at send time is an intentional deviation — it is not documented by AWS and mirrors the effective-status model AWS uses for `ListContacts`.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 50983709eb..cabd06b768 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -40,6 +40,7 @@ import io.github.hectorvent.floci.services.ses.SesCvetController;import io.github.hectorvent.floci.services.ses.SesDedicatedIpController;import io.github.hectorvent.floci.services.ses.SesIdentityController;import io.github.hectorvent.floci.services.ses.SesImportJobController;+import io.github.hectorvent.floci.services.ses.SesInsightsController;import io.github.hectorvent.floci.services.ses.SesSendController;import io.github.hectorvent.floci.services.ses.SesSuppressionController;import io.github.hectorvent.floci.services.ses.SesTagController;@@ -300,9 +301,10 @@ public class ResolvedServiceCatalog {Set.of(SesAccountController.class, SesConfigurationSetController.class,SesContactController.class, SesCvetController.class,SesDedicatedIpController.class, SesIdentityController.class,- SesSendController.class, SesSuppressionController.class,- SesTagController.class, SesTemplateController.class,- SesImportJobController.class, SesTenantController.class)),+ SesInsightsController.class, SesSendController.class,+ SesSuppressionController.class, SesTagController.class,+ SesTemplateController.class, SesImportJobController.class,+ SesTenantController.class)),descriptor("es", "opensearch", config.services().opensearch().enabled(), true,"opensearch", storageMode(config.storage().services().opensearch().mode(), config.storage().mode()),config.storage().services().opensearch().flushIntervalMs(), null, ServiceProtocol.REST_JSON,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.javaindex 849cdc646e..c42a11c3e2 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@@ -259,7 +259,7 @@ final class SesEventPayload {+ event.cause().name().toLowerCase(Locale.ROOT);}- private static String bounceDiagnosticCode(String recipient, boolean suppressed) {+ static String bounceDiagnosticCode(String recipient, boolean suppressed) {if (suppressed) {return ACCOUNT_SUPPRESSION_DIAGNOSTIC;}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesInsightsController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesInsightsController.javanew file mode 100644index 0000000000..66f1026f2e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesInsightsController.java@@ -0,0 +1,155 @@+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.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes;+import io.github.hectorvent.floci.services.ses.model.EmailInsights;+import io.github.hectorvent.floci.services.ses.model.InsightsBounce;+import io.github.hectorvent.floci.services.ses.model.InsightsComplaint;+import io.github.hectorvent.floci.services.ses.model.InsightsEvent;+import io.github.hectorvent.floci.services.ses.model.InsightsEventDetails;+import io.github.hectorvent.floci.services.ses.model.MessageTag;+import io.github.hectorvent.floci.services.ses.model.SentEmail;+import jakarta.inject.Inject;+import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.core.Context;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++import java.util.List;+import java.util.Optional;++/**+ * SES V2 message insights ({@code /v2/email/insights/{MessageId}/}), the read side of the+ * per-recipient timelines {@link SesMessageInsights} derives at send time.+ *+ * <p>Two behaviours are probe-confirmed against real SES (2026-09-21, us-east-1). The operation is+ * gated on Virtual Deliverability Manager and the gate is checked before the message id, so an+ * unparseable id in a VDM-disabled region still reports the VDM error. A message that is absent+ * reports the account id alongside the id.+ */+@Path("/v2/email")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class SesInsightsController {++ private static final String VDM_DISABLED_MESSAGE =+ "To use this feature you must enable Virtual Deliverability Manager";++ private final SesSentEmailService sentEmailService;+ private final SesAccountService accountService;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public SesInsightsController(SesSentEmailService sentEmailService, SesAccountService accountService,+ RegionResolver regionResolver, ObjectMapper objectMapper) {+ this.sentEmailService = sentEmailService;+ this.accountService = accountService;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ @GET+ @Path("/insights/{messageId}")+ public Response getMessageInsights(@Context HttpHeaders headers,+ @PathParam("messageId") String messageId) {+ String region = regionResolver.resolveRegion(headers);+ requireVdmEnabled(region);+ SentEmail email = sentEmailService.find(region, messageId)+ .orElseThrow(() -> new AwsException("NotFoundException",+ "Message <" + messageId + "> not found for account <"+ + regionResolver.getAccountId() + ">", 404));+ return Response.ok(render(email)).build();+ }++ private void requireVdmEnabled(String region) {+ Optional<AccountVdmAttributes> vdm = accountService.findAccountVdmAttributes(region);+ if (vdm.isEmpty() || !vdm.get().vdmEnabled()) {+ throw new AwsException("NotFoundException", VDM_DISABLED_MESSAGE, 404);+ }+ }++ private ObjectNode render(SentEmail email) {+ ObjectNode result = objectMapper.createObjectNode();+ result.put("MessageId", email.getMessageId());+ if (email.getSource() != null) {+ result.put("FromEmailAddress", email.getSource());+ }+ if (email.getSubject() != null) {+ result.put("Subject", email.getSubject());+ }+ ArrayNode tags = result.putArray("EmailTags");+ for (MessageTag tag : orEmpty(email.getEmailTags())) {+ ObjectNode node = tags.addObject();+ node.put("Name", tag.name());+ node.put("Value", tag.value());+ }+ ArrayNode insights = result.putArray("Insights");+ for (EmailInsights recipient : orEmpty(email.getInsights())) {+ insights.add(renderRecipient(recipient));+ }+ return result;+ }++ private ObjectNode renderRecipient(EmailInsights recipient) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Destination", recipient.destination());+ if (recipient.isp() != null) {+ node.put("Isp", recipient.isp());+ }+ ArrayNode events = node.putArray("Events");+ for (InsightsEvent event : orEmpty(recipient.events())) {+ events.add(renderEvent(event));+ }+ return node;+ }++ private ObjectNode renderEvent(InsightsEvent event) {+ ObjectNode node = objectMapper.createObjectNode();+ if (event.timestamp() != null) {+ node.put("Timestamp", event.timestamp().toEpochMilli() / 1000.0);+ }+ node.put("Type", event.type());+ InsightsEventDetails details = event.details();+ if (details == null) {+ return node;+ }+ ObjectNode rendered = objectMapper.createObjectNode();+ InsightsBounce bounce = details.bounce();+ if (bounce != null) {+ ObjectNode node2 = rendered.putObject("Bounce");+ putIfPresent(node2, "BounceType", bounce.bounceType());+ putIfPresent(node2, "BounceSubType", bounce.bounceSubType());+ putIfPresent(node2, "DiagnosticCode", bounce.diagnosticCode());+ }+ InsightsComplaint complaint = details.complaint();+ if (complaint != null) {+ ObjectNode node2 = rendered.putObject("Complaint");+ putIfPresent(node2, "ComplaintSubType", complaint.complaintSubType());+ putIfPresent(node2, "ComplaintFeedbackType", complaint.complaintFeedbackType());+ }+ if (!rendered.isEmpty()) {+ node.set("Details", rendered);+ }+ return node;+ }++ private static void putIfPresent(ObjectNode node, String field, String value) {+ if (value != null) {+ node.put(field, value);+ }+ }++ private static <T> List<T> orEmpty(List<T> values) {+ return values == null ? List.of() : values;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesMessageInsights.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesMessageInsights.javanew file mode 100644index 0000000000..925bb3a1a1--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesMessageInsights.java@@ -0,0 +1,146 @@+package io.github.hectorvent.floci.services.ses;++import io.github.hectorvent.floci.services.ses.SesRecipientEvent.Cause;+import io.github.hectorvent.floci.services.ses.model.EmailInsights;+import io.github.hectorvent.floci.services.ses.model.InsightsBounce;+import io.github.hectorvent.floci.services.ses.model.InsightsComplaint;+import io.github.hectorvent.floci.services.ses.model.InsightsEvent;+import io.github.hectorvent.floci.services.ses.model.InsightsEventDetails;++import java.time.Duration;+import java.time.Instant;+import java.util.ArrayList;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;++/**+ * Derives the per-recipient event timelines that {@code GetMessageInsights} serves from the events+ * {@link SesRecipientEvents#classify} produced for the send, so the simulator and suppression+ * semantics have the same home as event publishing.+ *+ * <p>Insights add one thing publishing does not: {@code DELIVERY} for an ordinary recipient that+ * was neither suppressed nor a simulator address, so a plain send does not look stuck at+ * {@code SEND}. Floci hands such a message to the SMTP relay or drops it, and either way nothing+ * downstream can report a real outcome.+ *+ * <p>Floci tracks more messages than real SES does, deliberately. AWS documents that Virtual+ * Deliverability Manager ignores mail sent to the mailbox simulator, mail with more than one+ * recipient, and mail from a delegate sender. Both of the first two would gut the operation here:+ * simulator addresses are the only sends Floci can derive bounce and complaint events for, and+ * dropping multi-recipient mail would leave most local test traffic invisible. Floci therefore+ * records every send and returns one entry per recipient, where an AWS response in practice carries+ * exactly one. Both exclusions are probe-confirmed (2026-09-21): three simulator sends and one+ * two-recipient send were still absent from GetMessageInsights an hour later, while a+ * single-recipient send made in the middle of that window was already being served, which rules+ * out a merely slow indexing pipeline.+ */+final class SesMessageInsights {++ // Events within one recipient's timeline are one millisecond apart, the finest step the+ // epoch-seconds rendering keeps, so a client that sorts by timestamp keeps the order SES would+ // have produced while no event is stamped later than the send call that returns them. A single+ // instant for every event, which is what the data really supports, would make the ordering+ // arbitrary.+ private static final Duration EVENT_SPACING = Duration.ofMillis(1);++ // What real SES reports when it cannot identify the recipient's provider, which is always the+ // case here: Floci never sees a receiving mail server.+ private static final String UNKNOWN_ISP = "UNKNOWN_ISP";++ // BounceType is an enum in the Smithy model (UNDETERMINED / TRANSIENT / PERMANENT), so it is+ // upper case, while BounceSubType and the complaint members are free strings. GetMessageInsights+ // spells the suppression subtype in upper snake case (probed 2026-09-21 for the bounce; the+ // complaint follows by analogy), unlike the OnAccountSuppressionList of the published events.+ static final String ON_ACCOUNT_SUPPRESSION_LIST = "ON_ACCOUNT_SUPPRESSION_LIST";+ // ComplaintSubType is null for an ordinary feedback-loop complaint; SES only sets it for a+ // complaint raised against an address already on the suppression list.+ private static final InsightsComplaint SIMULATED_COMPLAINT = new InsightsComplaint(null, "abuse");+ private static final InsightsComplaint SUPPRESSED_COMPLAINT =+ new InsightsComplaint(ON_ACCOUNT_SUPPRESSION_LIST, null);++ private SesMessageInsights() {}++ /**+ * Builds one {@link EmailInsights} per envelope recipient, in envelope order with blanks and+ * duplicates removed, from the events the classifier derived for that envelope.+ */+ static List<EmailInsights> build(List<String> envelope, List<SesRecipientEvent> events, Instant sentAt) {+ Set<String> recipients = new LinkedHashSet<>();+ if (envelope != null) {+ for (String address : envelope) {+ if (address != null && !address.isBlank()) {+ recipients.add(address);+ }+ }+ }+ List<EmailInsights> insights = new ArrayList<>(recipients.size());+ for (String recipient : recipients) {+ insights.add(new EmailInsights(recipient, UNKNOWN_ISP, eventsFor(recipient, events, sentAt)));+ }+ return insights;+ }++ private static List<InsightsEvent> eventsFor(String recipient, List<SesRecipientEvent> events,+ Instant sentAt) {+ List<InsightsEvent> timeline = new ArrayList<>();+ timeline.add(InsightsEvent.of(sentAt, "SEND"));+ String trimmed = recipient.trim();+ boolean outcome = false;+ for (SesRecipientEvent event : events) {+ switch (event.eventType()) {+ case "REJECT" -> {+ // The whole message is refused, so every recipient's timeline ends here.+ timeline.add(InsightsEvent.of(next(sentAt, timeline), "REJECT"));+ outcome = true;+ }+ case "DELIVERY" -> {+ if (event.recipients().contains(trimmed)) {+ timeline.add(InsightsEvent.of(next(sentAt, timeline), "DELIVERY"));+ outcome = true;+ }+ }+ case "BOUNCE" -> {+ if (event.recipients().contains(trimmed)) {+ timeline.add(new InsightsEvent(next(sentAt, timeline), "BOUNCE",+ InsightsEventDetails.ofBounce(bounceDetails(trimmed, event.cause()))));+ outcome = true;+ }+ }+ case "COMPLAINT" -> {+ if (event.recipients().contains(trimmed)) {+ timeline.add(new InsightsEvent(next(sentAt, timeline), "COMPLAINT",+ InsightsEventDetails.ofComplaint(complaintDetails(event.cause()))));+ outcome = true;+ }+ }+ default -> {+ // SEND is already on the timeline.+ }+ }+ }+ if (!outcome) {+ timeline.add(InsightsEvent.of(next(sentAt, timeline), "DELIVERY"));+ }+ return timeline;+ }++ private static Instant next(Instant sentAt, List<InsightsEvent> timeline) {+ return sentAt.plus(EVENT_SPACING.multipliedBy(timeline.size()));+ }++ private static InsightsBounce bounceDetails(String recipient, Cause cause) {+ return switch (cause) {+ case ACCOUNT_SUPPRESSION -> new InsightsBounce("PERMANENT", ON_ACCOUNT_SUPPRESSION_LIST,+ SesEventPayload.ACCOUNT_SUPPRESSION_DIAGNOSTIC);+ // The shape of a list-management opt-out has not been probed, so it carries no diagnostic.+ case LIST_MANAGEMENT -> new InsightsBounce("PERMANENT", "General", null);+ default -> new InsightsBounce("PERMANENT", "General",+ SesEventPayload.bounceDiagnosticCode(recipient, false));+ };+ }++ private static InsightsComplaint complaintDetails(Cause cause) {+ return cause == Cause.ACCOUNT_SUPPRESSION ? SUPPRESSED_COMPLAINT : SIMULATED_COMPLAINT;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.javaindex 767ced6018..6ffc15bb85 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java@@ -10,6 +10,7 @@ import org.jboss.logging.Logger;import java.util.List;import java.util.Map;+import java.util.Optional;/*** Sent-email records (the {@code emailStore}), extracted from {@link SesService} as part of the@@ -39,6 +40,17 @@ public class SesSentEmailService {emailStore.put(emailKey(region, messageId), email);}+ /**+ * One stored message, for {@code GetMessageInsights}. Empty when the region has no record under+ * that id; the caller owns the AWS-shaped error.+ */+ public Optional<SentEmail> find(String region, String messageId) {+ if (messageId == null || messageId.isBlank()) {+ return Optional.empty();+ }+ return emailStore.get(emailKey(region, messageId));+ }+public long countInRegion(String region) {String prefix = "email::" + region + "::";return emailStore.scan(k -> k.startsWith(prefix)).size();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.javaindex 8a33294ab8..91d164a731 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@@ -269,6 +269,9 @@ public class SesService {if (additionalHeaders != null && !additionalHeaders.isEmpty()) {email.setHeaders(additionalHeaders);}+ email.setEmailTags(emailTags);+ email.setInsights(SesMessageInsights.build(envelope,+ SesRecipientEvents.classify(envelope, suppressedReasons, rejected), email.getSentAt()));if (rejected) {email.discardContent(SesRecipientEvents.CONTENT_REJECT_REASON);}@@ -381,6 +384,16 @@ public class SesService {: firstNonBlank(headers.returnPath(), returnPath, effectiveSource);SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage);email.setReturnPath(effectiveReturnPath);+ // The MIME subject is already parsed for the published events; store it too so+ // GetMessageInsights reports it for a raw send as it does for a simple one. The parser+ // yields "" for a missing header, and an absent subject must stay absent.+ email.setSubject(firstNonBlank(headers.subject()));+ // A rejected message publishes only the tags that came with the request, so the stored+ // record keeps the same set: tags read off its headers must not resurface through insights.+ email.setEmailTags(rejected ? requestTags(emailTags) : effectiveTags);+ email.setInsights(SesMessageInsights.build(effectiveDestinations,+ SesRecipientEvents.classify(effectiveDestinations, suppressedReasons, rejected),+ email.getSentAt()));if (rejected) {email.discardContent(SesRecipientEvents.CONTENT_REJECT_REASON);}@@ -699,6 +712,9 @@ public class SesService {List.of(emailAddress), List.of(), List.of(), List.of(),template.getTemplateSubject(), null, renderedHtml);email.setReturnPath(template.getFromEmailAddress());+ email.setInsights(SesMessageInsights.build(List.of(emailAddress),+ SesRecipientEvents.classify(List.of(emailAddress), Map.of(), false),+ email.getSentAt()));sentEmailService.record(region, messageId, email);smtpRelay.relay(SmtpRelay.RelayMessage.builder(template.getFromEmailAddress()).returnPath(template.getFromEmailAddress())diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailInsights.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailInsights.javanew file mode 100644index 0000000000..48605afdd9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailInsights.java@@ -0,0 +1,23 @@+package io.github.hectorvent.floci.services.ses.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++/**+ * The per-recipient timeline returned by {@code GetMessageInsights}. One entry per envelope+ * recipient, carrying the events Floci derived for that address at send time.+ *+ * <p>{@code isp} is always {@code UNKNOWN_ISP}. Real SES reports the receiving provider it observed+ * and falls back to that literal when it cannot identify one (probe-confirmed 2026-09-21), which is+ * permanently Floci's situation, so the AWS-faithful value is also the honest one here.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public record EmailInsights(+ @JsonProperty("Destination") String destination,+ @JsonProperty("Isp") String isp,+ @JsonProperty("Events") List<InsightsEvent> events) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsBounce.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsBounce.javanew file mode 100644index 0000000000..f1e39ad659--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsBounce.java@@ -0,0 +1,16 @@+package io.github.hectorvent.floci.services.ses.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * The {@code Bounce} member of a {@code GetMessageInsights} event's {@code Details}.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public record InsightsBounce(+ @JsonProperty("BounceType") String bounceType,+ @JsonProperty("BounceSubType") String bounceSubType,+ @JsonProperty("DiagnosticCode") String diagnosticCode) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsComplaint.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsComplaint.javanew file mode 100644index 0000000000..8259cd983c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsComplaint.java@@ -0,0 +1,15 @@+package io.github.hectorvent.floci.services.ses.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * The {@code Complaint} member of a {@code GetMessageInsights} event's {@code Details}.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public record InsightsComplaint(+ @JsonProperty("ComplaintSubType") String complaintSubType,+ @JsonProperty("ComplaintFeedbackType") String complaintFeedbackType) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsEvent.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsEvent.javanew file mode 100644index 0000000000..8a91b13a72--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsEvent.java@@ -0,0 +1,23 @@+package io.github.hectorvent.floci.services.ses.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/**+ * One event in a {@code GetMessageInsights} recipient timeline. {@code type} is an SES+ * {@code EventType} name such as {@code SEND} or {@code DELIVERY}.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public record InsightsEvent(+ @JsonProperty("Timestamp") Instant timestamp,+ @JsonProperty("Type") String type,+ @JsonProperty("Details") InsightsEventDetails details) {++ public static InsightsEvent of(Instant timestamp, String type) {+ return new InsightsEvent(timestamp, type, null);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsEventDetails.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsEventDetails.javanew file mode 100644index 0000000000..7eccae4ffc--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/InsightsEventDetails.java@@ -0,0 +1,24 @@+package io.github.hectorvent.floci.services.ses.model;++import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * The {@code Details} member of a {@code GetMessageInsights} event. Only the member matching the+ * event type is populated, and an event with neither omits {@code Details} entirely.+ */+@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+public record InsightsEventDetails(+ @JsonProperty("Bounce") InsightsBounce bounce,+ @JsonProperty("Complaint") InsightsComplaint complaint) {++ public static InsightsEventDetails ofBounce(InsightsBounce bounce) {+ return new InsightsEventDetails(bounce, null);+ }++ public static InsightsEventDetails ofComplaint(InsightsComplaint complaint) {+ return new InsightsEventDetails(null, complaint);+ }+}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.javaindex e044a6ea3a..c358f0fcc7 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@@ -63,6 +63,15 @@ public class SentEmail {@JsonProperty("RejectReason")private String rejectReason;+ @JsonProperty("EmailTags")+ private List<MessageTag> emailTags;++ /**+ * Per-recipient event timelines, derived at send time and served by {@code GetMessageInsights}.+ */+ @JsonProperty("Insights")+ private List<EmailInsights> insights;+public SentEmail() {}/** Constructor for Simple / Template content. */@@ -154,4 +163,10 @@ public class SentEmail {this.bodyHtml = null;this.rawData = null;}++ public List<MessageTag> getEmailTags() { return emailTags; }+ public void setEmailTags(List<MessageTag> emailTags) { this.emailTags = emailTags; }++ public List<EmailInsights> getInsights() { return insights; }+ public void setInsights(List<EmailInsights> insights) { this.insights = insights; }}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesInsightsControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesInsightsControllerTest.javanew file mode 100644index 0000000000..6476344322--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesInsightsControllerTest.java@@ -0,0 +1,110 @@+package io.github.hectorvent.floci.services.ses;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes;+import io.github.hectorvent.floci.services.ses.model.SentEmail;+import jakarta.ws.rs.core.Response;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Optional;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++/**+ * Unit tests for the parts of {@link SesInsightsController} the integration test cannot pin down:+ * that the Virtual Deliverability Manager gate runs before the store is touched at all, and that a+ * message stored before insights existed still renders.+ */+class SesInsightsControllerTest {++ private static final String REGION = "eu-north-1";++ private final SesSentEmailService sentEmailService = mock(SesSentEmailService.class);+ private final SesAccountService accountService = mock(SesAccountService.class);+ private final RegionResolver regionResolver = mock(RegionResolver.class);+ private final ObjectMapper objectMapper = new ObjectMapper();+ private final SesInsightsController controller = new SesInsightsController(+ sentEmailService, accountService, regionResolver, objectMapper);++ @BeforeEach+ void stubRegion() {+ when(regionResolver.resolveRegion(any())).thenReturn(REGION);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ }++ private void vdmEnabled(boolean enabled) {+ when(accountService.findAccountVdmAttributes(REGION))+ .thenReturn(enabled ? Optional.of(new AccountVdmAttributes(true, false, false))+ : Optional.empty());+ }++ @Test+ void vdmGateRunsBeforeTheStoreIsTouched() {+ vdmEnabled(false);++ AwsException thrown = assertThrows(AwsException.class,+ () -> controller.getMessageInsights(null, "any-id"));++ assertEquals("NotFoundException", thrown.getErrorCode());+ assertTrue(thrown.getMessage().contains("Virtual Deliverability Manager"), thrown.getMessage());+ // The integration test can only infer the ordering from the response; this pins it.+ verifyNoInteractions(sentEmailService);+ }++ @Test+ void vdmConfiguredButDisabledIsStillGated() {+ when(accountService.findAccountVdmAttributes(REGION))+ .thenReturn(Optional.of(new AccountVdmAttributes(false, false, false)));++ AwsException thrown = assertThrows(AwsException.class,+ () -> controller.getMessageInsights(null, "any-id"));++ assertTrue(thrown.getMessage().contains("Virtual Deliverability Manager"), thrown.getMessage());+ verifyNoInteractions(sentEmailService);+ }++ @Test+ void unknownMessageNamesTheResolvedAccount() {+ vdmEnabled(true);+ when(sentEmailService.find(anyString(), anyString())).thenReturn(Optional.empty());++ AwsException thrown = assertThrows(AwsException.class,+ () -> controller.getMessageInsights(null, "missing"));++ assertEquals(404, thrown.getHttpStatus());+ assertEquals("Message <missing> not found for account <000000000000>", thrown.getMessage());+ }++ @Test+ void aMessageStoredBeforeInsightsExistedStillRenders() {+ // Records written by an older Floci carry no Insights and no EmailTags. The message is+ // still a real message, so it is served as an empty timeline rather than reported missing.+ SentEmail legacy = new SentEmail("legacy-id", REGION, "[email protected]",+ List.of("[email protected]"), List.of(), List.of(), List.of(), "old", "hi", null);+ legacy.setInsights(null);+ legacy.setEmailTags(null);+ vdmEnabled(true);+ when(sentEmailService.find(REGION, "legacy-id")).thenReturn(Optional.of(legacy));++ Response response = controller.getMessageInsights(null, "legacy-id");++ assertEquals(200, response.getStatus());+ ObjectNode body = (ObjectNode) response.getEntity();+ assertEquals("legacy-id", body.get("MessageId").asText());+ assertEquals("[email protected]", body.get("FromEmailAddress").asText());+ assertTrue(body.get("Insights").isEmpty(), "Insights should be an empty array");+ assertTrue(body.get("EmailTags").isEmpty(), "EmailTags should be an empty array");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesMessageInsightsTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesMessageInsightsTest.javanew file mode 100644index 0000000000..315751be50--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesMessageInsightsTest.java@@ -0,0 +1,220 @@+package io.github.hectorvent.floci.services.ses;++import io.github.hectorvent.floci.services.ses.model.EmailInsights;+import io.github.hectorvent.floci.services.ses.model.InsightsBounce;+import io.github.hectorvent.floci.services.ses.model.InsightsEvent;+import org.junit.jupiter.api.Test;++import java.time.Instant;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++class SesMessageInsightsTest {++ private static final Instant SENT_AT = Instant.parse("2026-09-21T10:00:00Z");++ private static List<EmailInsights> build(List<String> envelope, Map<String, String> suppressedReasons) {+ return SesMessageInsights.build(envelope,+ SesRecipientEvents.classify(envelope, suppressedReasons, false), SENT_AT);+ }++ private static List<String> types(EmailInsights insights) {+ return insights.events().stream().map(InsightsEvent::type).toList();+ }++ @Test+ void ordinaryRecipientIsReportedAsDelivered() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ assertEquals(1, insights.size());+ assertEquals("[email protected]", insights.get(0).destination());+ assertEquals(List.of("SEND", "DELIVERY"), types(insights.get(0)));+ }++ @Test+ void eachRecipientGetsItsOwnTimeline() {+ List<EmailInsights> insights = build(List.of("[email protected]", "[email protected]"), Map.of());++ assertEquals(2, insights.size());+ assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));+ assertEquals(List.of("SEND", "DELIVERY"), types(insights.get(1)));+ }++ @Test+ void ccAndBccRecipientsAreIncludedInEnvelopeOrder() {+ List<EmailInsights> insights = build(List.of("[email protected]", "[email protected]", "[email protected]"), Map.of());++ insights.stream().map(EmailInsights::destination).toList());+ }++ @Test+ void duplicateRecipientsAreCollapsed() {+ List<EmailInsights> insights = build(List.of("[email protected]", "[email protected]"), Map.of());++ assertEquals(1, insights.size());+ }++ @Test+ void blankAndNullRecipientsAreSkipped() {+ List<String> addresses = new ArrayList<>();+ addresses.add("[email protected]");+ addresses.add(null);+ addresses.add(" ");++ List<EmailInsights> insights = build(addresses, Map.of());++ assertEquals(1, insights.size());+ }++ @Test+ void complaintSimulatorIsDeliveredBeforeItComplains() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ assertEquals(List.of("SEND", "DELIVERY", "COMPLAINT"), types(insights.get(0)));+ }++ @Test+ void suppressionListSimulatorBouncesWithTheSuppressionDiagnostic() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));+ InsightsBounce bounce = insights.get(0).events().get(1).details().bounce();+ assertEquals("General", bounce.bounceSubType());+ assertTrue(bounce.diagnosticCode().contains("suppressed address: [email protected]"));+ }++ @Test+ void rejectedMessageEndsEveryTimelineAtReject() {+ List<String> envelope = List.of("[email protected]", "[email protected]");+ List<EmailInsights> insights = SesMessageInsights.build(envelope,+ SesRecipientEvents.classify(envelope, Map.of(), true), SENT_AT);++ assertEquals(2, insights.size());+ assertEquals(List.of("SEND", "REJECT"), types(insights.get(0)));+ assertEquals(List.of("SEND", "REJECT"), types(insights.get(1)));+ }++ @Test+ void listManagementOptOutBouncesWithoutADiagnostic() {+ List<EmailInsights> insights = build(List.of("[email protected]"),+ Map.of("[email protected]", SesRecipientEvents.REASON_LIST_OPT_OUT));++ assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));+ InsightsBounce bounce = insights.get(0).events().get(1).details().bounce();+ assertEquals("General", bounce.bounceSubType());+ assertNull(bounce.diagnosticCode());+ }++ @Test+ void labelledSimulatorAddressKeepsItsScenario() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));+ }++ @Test+ void suppressedRecipientBouncesInsteadOfDelivering() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of("[email protected]", "BOUNCE"));++ assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));+ }++ @Test+ void suppressionReasonWinsOverTheSimulatorScenario() {+ List<EmailInsights> insights = build(List.of("[email protected]"),+ Map.of("[email protected]", "COMPLAINT"));++ assertEquals(List.of("SEND", "COMPLAINT"), types(insights.get(0)));+ }++ @Test+ void suppressedComplaintRecipientIsNeverDelivered() {+ // The message is dropped before the relay, unlike complaint@simulator which is delivered+ // and then complained about.+ List<EmailInsights> insights = build(List.of("[email protected]"),+ Map.of("[email protected]", "COMPLAINT"));++ assertEquals(List.of("SEND", "COMPLAINT"), types(insights.get(0)));+ }++ @Test+ void bounceCarriesTheSimulatorDiagnosticCode() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ InsightsEvent bounce = insights.get(0).events().get(1);+ assertEquals("PERMANENT", bounce.details().bounce().bounceType());+ assertEquals("General", bounce.details().bounce().bounceSubType());+ assertEquals("smtp; 550 5.1.1 user unknown", bounce.details().bounce().diagnosticCode());+ assertNull(bounce.details().complaint());+ }++ @Test+ void complaintCarriesAFeedbackType() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ InsightsEvent complaint = insights.get(0).events().get(2);+ assertEquals("abuse", complaint.details().complaint().complaintFeedbackType());+ // SES leaves ComplaintSubType unset unless the address was already suppressed.+ assertNull(complaint.details().complaint().complaintSubType());+ assertNull(complaint.details().bounce());+ }++ @Test+ void suppressedBounceCarriesTheSuppressionSubtypeAndDiagnostic() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of("[email protected]", "BOUNCE"));++ InsightsEvent bounce = insights.get(0).events().get(1);+ assertEquals("BOUNCE", bounce.type());+ assertEquals("PERMANENT", bounce.details().bounce().bounceType());+ // GetMessageInsights spells the subtype in upper snake case and carries SES's own+ // suppression text as the diagnostic (probed 2026-09-21).+ assertEquals("ON_ACCOUNT_SUPPRESSION_LIST", bounce.details().bounce().bounceSubType());+ assertEquals(SesEventPayload.ACCOUNT_SUPPRESSION_DIAGNOSTIC, bounce.details().bounce().diagnosticCode());+ }++ @Test+ void suppressedComplaintCarriesTheSuppressionSubtypeAndNoFeedbackType() {+ List<EmailInsights> insights = build(List.of("[email protected]"),+ Map.of("[email protected]", "COMPLAINT"));++ InsightsEvent complaint = insights.get(0).events().get(1);+ assertEquals("COMPLAINT", complaint.type());+ assertEquals("ON_ACCOUNT_SUPPRESSION_LIST", complaint.details().complaint().complaintSubType());+ // No ISP feedback loop fired, so there is no feedback type to report.+ assertNull(complaint.details().complaint().complaintFeedbackType());+ }++ @Test+ void plainEventsCarryNoDetails() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ for (InsightsEvent event : insights.get(0).events()) {+ assertNull(event.details(), event.type() + " should have no Details");+ }+ }++ @Test+ void eventsAreOrderedInTimeSoAClientCanSortThem() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ List<InsightsEvent> events = insights.get(0).events();+ assertEquals(SENT_AT, events.get(0).timestamp());+ for (int i = 1; i < events.size(); i++) {+ assertTrue(events.get(i).timestamp().isAfter(events.get(i - 1).timestamp()),+ "event " + i + " must come after event " + (i - 1));+ }+ }++ @Test+ void ispIsAlwaysUnknownBecauseFlociCannotObserveIt() {+ List<EmailInsights> insights = build(List.of("[email protected]"), Map.of());++ assertEquals("UNKNOWN_ISP", insights.get(0).isp());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesMessageInsightsV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesMessageInsightsV2IntegrationTest.javanew file mode 100644index 0000000000..830fd34ae6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesMessageInsightsV2IntegrationTest.java@@ -0,0 +1,337 @@+package io.github.hectorvent.floci.services.ses;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.nio.charset.StandardCharsets;+import java.util.Base64;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.not;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * Integration tests for {@code GET /v2/email/insights/{MessageId}} (GetMessageInsights).+ *+ * <p>Two behaviours are probe-confirmed against real SES (2026-09-21, us-east-1): the operation is+ * gated on Virtual Deliverability Manager and reports that before it looks at the message id, and a+ * missing message names the account alongside the id. Uses an isolated region because VDM is+ * account and region scoped, and enables VDM as its own ordered step so the gate can be observed+ * first.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesMessageInsightsV2IntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-north-1/ses/aws4_request";+ private static final String SENDER = "[email protected]";+ private static final String ACCOUNT_A_AUTH =+ "AWS4-HMAC-SHA256 Credential=111122223333/20260101/eu-north-1/ses/aws4_request";+ private static final String ACCOUNT_B_AUTH =+ "AWS4-HMAC-SHA256 Credential=444455556666/20260101/eu-north-1/ses/aws4_request";+ private static final String ACCOUNT_C_AUTH =+ "AWS4-HMAC-SHA256 Credential=777788889999/20260101/eu-north-1/ses/aws4_request";++ private static String send(String destinationJson, String subject) {+ return send(AUTH, destinationJson, subject);+ }++ private static String send(String auth, String destinationJson, String subject) {+ return given().contentType("application/json").header("Authorization", auth)+ .body("""+ {+ "FromEmailAddress": "%s",+ "Destination": %s,+ "EmailTags": [{"Name": "campaign", "Value": "insights"}],+ "Content": {"Simple": {"Subject": {"Data": "%s"},+ "Body": {"Text": {"Data": "hi"}}}}+ }+ """.formatted(SENDER, destinationJson, subject))+ .when().post("/v2/email/outbound-emails").then().statusCode(200)+ .extract().jsonPath().getString("MessageId");+ }++ @Test+ @Order(0)+ void getMessageInsights_vdmDisabled_reportsTheVdmGateBeforeTheMessageId() {+ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/not-even-an-id").then().statusCode(404)+ .body("message", containsString(+ "To use this feature you must enable Virtual Deliverability Manager"));+ }++ @Test+ @Order(1)+ void enableVdmAndVerifyTheSender() {+ enableVdm(AUTH);++ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"EmailIdentity\":\"" + SENDER + "\"}")+ .when().post("/v2/email/identities").then().statusCode(200);+ }++ @Test+ @Order(2)+ void getMessageInsights_unknownMessage_namesTheAccount() {+ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/no-such-message").then().statusCode(404)+ .body("message", containsString("Message <no-such-message> not found for account <"));+ }++ @Test+ @Order(3)+ void getMessageInsights_ordinaryRecipient_reportsSendThenDelivery() {+ String messageId = send("{\"ToAddresses\": [\"[email protected]\"]}", "ordinary");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("MessageId", equalTo(messageId))+ .body("FromEmailAddress", equalTo(SENDER))+ .body("Subject", equalTo("ordinary"))+ .body("EmailTags", hasSize(1))+ .body("EmailTags[0].Name", equalTo("campaign"))+ .body("EmailTags[0].Value", equalTo("insights"))+ .body("Insights", hasSize(1))+ .body("Insights[0].Destination", equalTo("[email protected]"))+ .body("Insights[0].Events.Type", contains("SEND", "DELIVERY"))+ .body("Insights[0].Events[0].Timestamp", notNullValue())+ .body("Insights[0].Events[0].Details", nullValue())+ // AWS reports UNKNOWN_ISP when it cannot identify the provider, which is always+ // Floci's case.+ .body("Insights[0].Isp", equalTo("UNKNOWN_ISP"));+ }++ @Test+ @Order(4)+ void getMessageInsights_bounceSimulator_carriesTheBounceDetails() {+ String messageId = send("{\"ToAddresses\": [\"[email protected]\"]}", "bounced");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("Insights[0].Events.Type", contains("SEND", "BOUNCE"))+ .body("Insights[0].Events[1].Details.Bounce.BounceType", equalTo("PERMANENT"))+ .body("Insights[0].Events[1].Details.Bounce.BounceSubType", equalTo("General"))+ .body("Insights[0].Events[1].Details.Bounce.DiagnosticCode",+ containsString("550 5.1.1"))+ .body("Insights[0].Events[1].Details.Complaint", nullValue());+ }++ @Test+ @Order(5)+ void getMessageInsights_complaintSimulator_deliversBeforeItComplains() {+ String messageId = send("{\"ToAddresses\": [\"[email protected]\"]}", "complained");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("Insights[0].Events.Type", contains("SEND", "DELIVERY", "COMPLAINT"))+ .body("Insights[0].Events[2].Details.Complaint.ComplaintFeedbackType",+ equalTo("abuse"))+ .body("Insights[0].Events[2].Details.Complaint.ComplaintSubType", nullValue())+ .body("Insights[0].Events[2].Details.Bounce", nullValue());+ }++ @Test+ @Order(6)+ void getMessageInsights_multipleRecipients_reportsOneTimelineEach() {+ // Real SES tracks nothing for a multi-recipient message, so an AWS response here would be a+ // NotFoundException. Floci deliberately records every recipient instead, because dropping+ // these would leave most local test traffic invisible.+ String messageId = send(+ "{\"ToAddresses\": [\"[email protected]\"], \"CcAddresses\": [\"[email protected]\"]}",+ "multi");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("Insights", hasSize(2))+ .body("Insights.Destination", contains("[email protected]", "[email protected]"))+ .body("Insights[1].Events.Type", contains("SEND", "DELIVERY"));+ }++ @Test+ @Order(7)+ void getMessageInsights_trailingSlash_matchesTheSameRoute() {+ // The Smithy model's requestUri is /v2/email/insights/{MessageId}/ with a trailing slash,+ // so that is the form an SDK client sends.+ String messageId = send("{\"ToAddresses\": [\"[email protected]\"]}", "slash");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId + "/").then().statusCode(200)+ .body("MessageId", equalTo(messageId));+ }++ @Test+ @Order(8)+ void getMessageInsights_rawSend_reportsTheMimeSubject() {+ String raw = "From: " + SENDER + "\r\nTo: [email protected]\r\n"+ + "Subject: raw-mime-subject\r\n\r\nhi\r\n";+ String encoded = Base64.getEncoder()+ .encodeToString(raw.getBytes(StandardCharsets.UTF_8));++ String messageId = given().contentType("application/json").header("Authorization", AUTH)+ .body("""+ {"FromEmailAddress": "%s",+ "Destination": {"ToAddresses": ["[email protected]"]},+ "Content": {"Raw": {"Data": "%s"}}}+ """.formatted(SENDER, encoded))+ .when().post("/v2/email/outbound-emails").then().statusCode(200)+ .extract().jsonPath().getString("MessageId");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("Subject", equalTo("raw-mime-subject"))+ .body("Insights[0].Destination", equalTo("[email protected]"));++ // The MIME parser yields "" for a missing Subject header; the member must stay absent.+ String noSubject = "From: " + SENDER + "\r\nTo: [email protected]\r\n\r\nhi\r\n";+ String noSubjectId = given().contentType("application/json").header("Authorization", AUTH)+ .body("""+ {"FromEmailAddress": "%s",+ "Destination": {"ToAddresses": ["[email protected]"]},+ "Content": {"Raw": {"Data": "%s"}}}+ """.formatted(SENDER, Base64.getEncoder()+ .encodeToString(noSubject.getBytes(StandardCharsets.UTF_8))))+ .when().post("/v2/email/outbound-emails").then().statusCode(200)+ .extract().jsonPath().getString("MessageId");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + noSubjectId).then().statusCode(200)+ .body("$", not(hasKey("Subject")));+ }++ @Test+ @Order(9)+ void getMessageInsights_suppressedRecipient_isNeverDelivered() {+ // Account-level suppression defaults to [BOUNCE, COMPLAINT], so no configuration set is+ // needed for the entry to take effect on the send.+ for (String entry : new String[] {"[email protected]:COMPLAINT", "[email protected]:BOUNCE"}) {+ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"EmailAddress\":\"%s\",\"Reason\":\"%s\"}"+ .formatted(entry.split(":")[0], entry.split(":")[1]))+ .when().put("/v2/email/suppression/addresses").then().statusCode(200);+ }++ try {+ String messageId = send(+ "{\"ToAddresses\": [\"[email protected]\", \"[email protected]\"]}", "suppressed");++ // Neither recipient reached the relay, so the details are the suppression-specific+ // values SES reports for insights (upper snake case, unlike the published events).+ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("Insights[0].Destination", equalTo("[email protected]"))+ .body("Insights[0].Events.Type", contains("SEND", "COMPLAINT"))+ .body("Insights[0].Events[1].Details.Complaint.ComplaintSubType",+ equalTo("ON_ACCOUNT_SUPPRESSION_LIST"))+ .body("Insights[0].Events[1].Details.Complaint.ComplaintFeedbackType", nullValue())+ .body("Insights[1].Destination", equalTo("[email protected]"))+ .body("Insights[1].Events.Type", contains("SEND", "BOUNCE"))+ .body("Insights[1].Events[1].Details.Bounce.BounceType", equalTo("PERMANENT"))+ .body("Insights[1].Events[1].Details.Bounce.BounceSubType",+ equalTo("ON_ACCOUNT_SUPPRESSION_LIST"))+ .body("Insights[1].Events[1].Details.Bounce.DiagnosticCode",+ containsString("suppression list for your account"));+ } finally {+ // A failed assertion must not leave the entries on the shared region's list.+ for (String address : new String[] {"[email protected]", "[email protected]"}) {+ given().header("Authorization", AUTH)+ .when().delete("/v2/email/suppression/addresses/" + address);+ }+ }+ }++ @Test+ @Order(10)+ void getMessageInsights_isScopedToTheCallingAccount() {+ // A 12-digit access key id in the credential is the account id, so these are two accounts.+ // Both need VDM on, otherwise account B would be refused by the gate and the test would+ // pass without ever proving isolation.+ enableVdm(ACCOUNT_A_AUTH);+ enableVdm(ACCOUNT_B_AUTH);+ given().contentType("application/json").header("Authorization", ACCOUNT_A_AUTH)+ .body("{\"EmailIdentity\":\"" + SENDER + "\"}")+ .when().post("/v2/email/identities").then().statusCode(200);++ String messageId = send(ACCOUNT_A_AUTH, "{\"ToAddresses\": [\"[email protected]\"]}", "scoped");++ given().header("Authorization", ACCOUNT_A_AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("MessageId", equalTo(messageId));++ given().header("Authorization", ACCOUNT_B_AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(404)+ .body("message", containsString("not found for account <444455556666>"));+ }++ @Test+ @Order(11)+ void getMessageInsights_vdmGateIsPerAccount() {+ // Three accounts have VDM on in this region by now; one that never enabled it still meets+ // the gate, so the setting is not shared across the region.+ given().header("Authorization", ACCOUNT_C_AUTH)+ .when().get("/v2/email/insights/not-even-an-id").then().statusCode(404)+ .body("message", containsString(+ "To use this feature you must enable Virtual Deliverability Manager"));+ }++ @Test+ @Order(12)+ void getMessageInsights_rejectedRawSend_reportsRejectAndKeepsNothingReadOffTheMessage() {+ // The signature is assembled at run time so it never appears in the tree.+ String raw = "From: " + SENDER + "\r\nTo: [email protected]\r\n"+ + "Subject: rejected-mime-subject\r\n"+ + SmtpRelay.HEADER_MESSAGE_TAGS + ": campaign=fromheader\r\n\r\n"+ + SesContentScan.signature() + "\r\n";+ String messageId = given().contentType("application/json").header("Authorization", AUTH)+ .body("""+ {"FromEmailAddress": "%s",+ "Destination": {"ToAddresses": ["[email protected]"]},+ "Content": {"Raw": {"Data": "%s"}}}+ """.formatted(SENDER, Base64.getEncoder()+ .encodeToString(raw.getBytes(StandardCharsets.UTF_8))))+ .when().post("/v2/email/outbound-emails").then().statusCode(200)+ .extract().jsonPath().getString("MessageId");++ given().header("Authorization", AUTH)+ .when().get("/v2/email/insights/" + messageId).then().statusCode(200)+ .body("Insights[0].Destination", equalTo("[email protected]"))+ .body("Insights[0].Events.Type", contains("SEND", "REJECT"))+ // Everything read off the refused message stays out of the timeline: the subject+ // is gone and the header tags never become the record's tags.+ .body("$", not(hasKey("Subject")))+ .body("EmailTags", hasSize(0));+ }++ @Test+ @Order(13)+ void cleanUpVdmAndIdentities() {+ for (String auth : new String[] {AUTH, ACCOUNT_A_AUTH, ACCOUNT_B_AUTH}) {+ disableVdm(auth);+ // Account B never verified the sender; the delete is best effort so the status is not+ // asserted.+ given().header("Authorization", auth)+ .when().delete("/v2/email/identities/" + SENDER);+ }+ }++ private static void enableVdm(String auth) {+ given().contentType("application/json").header("Authorization", auth)+ .body("{\"VdmAttributes\":{\"VdmEnabled\":\"ENABLED\"}}")+ .when().put("/v2/email/account/vdm").then().statusCode(200);+ }++ private static void disableVdm(String auth) {+ given().contentType("application/json").header("Authorization", auth)+ .body("{\"VdmAttributes\":{\"VdmEnabled\":\"DISABLED\"}}")+ .when().put("/v2/email/account/vdm").then().statusCode(200);+ }+}