feat(ses): add v2 GetMessageInsights (#4157)

* feat(ses): add v2 GetMessageInsights

Serves the per-recipient event timeline for a sent message. The timeline is
derived at send time from the events SesRecipientEvents classifies for the
send, the same classification that drives configuration-set event publishing
and identity notifications, then stored on the SentEmail record, so the read
path is a plain lookup and no new event store is needed. SentEmail also gains
the EmailTags the operation returns, and a raw send now stores its parsed MIME
subject, when present, as a simple send does.

Insights additionally report DELIVERY for an ordinary recipient so a plain
send does not look stuck at SEND; a suppressed recipient never gets DELIVERY,
since it is dropped before the relay, and a message the content scan rejected
ends every recipient's timeline at REJECT. What gets published is unchanged.

Probed against real SES in us-east-1: the operation is gated on Virtual
Deliverability Manager and reports that before it looks at the message id, a
missing message names the account alongside the id, Isp carries the literal
UNKNOWN_ISP when the provider cannot be identified, BounceType is the
upper-case enum member, and an account-suppressed recipient is reported with
BounceSubType ON_ACCOUNT_SUPPRESSION_LIST and SES's own suppression text as
the diagnostic, the upper snake spelling this operation uses where the
published events say OnAccountSuppressionList. Floci deliberately records the
mailbox-simulator sends and the multi-recipient mail that VDM drops, because
dropping both would leave insights permanently empty, and returns one entry
per envelope recipient where an AWS response carries at most one.

* test(ses): pin the message-insights VDM gate to one account

The gate reads the account VDM attributes, which are account-scoped like
every other SES store, but no test said so: the isolation test enables VDM
for both of its accounts. An account that never enabled it now has to meet
the gate while others in the same region are past it.

* feat(ses): report a content-rejected raw send in message insights

The raw send path classified its recipients with a hardcoded false, because
the content scan did not exist on this branch's base. It does now, so the
real scan result reaches the timeline: a rejected raw send reports SEND then
REJECT instead of a delivery it never had.

Its stored tags follow the same rule the published events already use, the
request's own tags only, so tags read off a refused message's headers cannot
resurface through GetMessageInsights.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-23 00:17:28 -04:00
1 parent a0cb86cc13
commit e947b6a2a1
17 files changed
+1328 -4

No files matched your search

@@ -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, "sender@example.com",
List.of("user@example.com"), 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("sender@example.com", 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");
}
}
@@ -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("user@example.com"), Map.of());
assertEquals(1, insights.size());
assertEquals("user@example.com", insights.get(0).destination());
assertEquals(List.of("SEND", "DELIVERY"), types(insights.get(0)));
}
@Test
void eachRecipientGetsItsOwnTimeline() {
List<EmailInsights> insights = build(List.of("bounce@simulator.amazonses.com", "user@example.com"), 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("to@example.com", "cc@example.com", "bcc@example.com"), Map.of());
assertEquals(List.of("to@example.com", "cc@example.com", "bcc@example.com"),
insights.stream().map(EmailInsights::destination).toList());
}
@Test
void duplicateRecipientsAreCollapsed() {
List<EmailInsights> insights = build(List.of("dup@example.com", "dup@example.com"), Map.of());
assertEquals(1, insights.size());
}
@Test
void blankAndNullRecipientsAreSkipped() {
List<String> addresses = new ArrayList<>();
addresses.add("user@example.com");
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("complaint@simulator.amazonses.com"), Map.of());
assertEquals(List.of("SEND", "DELIVERY", "COMPLAINT"), types(insights.get(0)));
}
@Test
void suppressionListSimulatorBouncesWithTheSuppressionDiagnostic() {
List<EmailInsights> insights = build(List.of("suppressionlist@simulator.amazonses.com"), 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: suppressionlist@simulator.amazonses.com"));
}
@Test
void rejectedMessageEndsEveryTimelineAtReject() {
List<String> envelope = List.of("user@example.com", "success@simulator.amazonses.com");
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("unsub@example.com"),
Map.of("unsub@example.com", 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("bounce+order-1@simulator.amazonses.com"), Map.of());
assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));
}
@Test
void suppressedRecipientBouncesInsteadOfDelivering() {
List<EmailInsights> insights = build(List.of("blocked@example.com"), Map.of("blocked@example.com", "BOUNCE"));
assertEquals(List.of("SEND", "BOUNCE"), types(insights.get(0)));
}
@Test
void suppressionReasonWinsOverTheSimulatorScenario() {
List<EmailInsights> insights = build(List.of("bounce@simulator.amazonses.com"),
Map.of("bounce@simulator.amazonses.com", "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("blocked@example.com"),
Map.of("blocked@example.com", "COMPLAINT"));
assertEquals(List.of("SEND", "COMPLAINT"), types(insights.get(0)));
}
@Test
void bounceCarriesTheSimulatorDiagnosticCode() {
List<EmailInsights> insights = build(List.of("bounce@simulator.amazonses.com"), 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("complaint@simulator.amazonses.com"), 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("blocked@example.com"), Map.of("blocked@example.com", "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("blocked@example.com"),
Map.of("blocked@example.com", "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("user@example.com"), 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("complaint@simulator.amazonses.com"), 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("user@example.com"), Map.of());
assertEquals("UNKNOWN_ISP", insights.get(0).isp());
}
}
@@ -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 = "insights-sender@example.com";
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\": [\"user@example.com\"]}", "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("user@example.com"))
.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\": [\"bounce@simulator.amazonses.com\"]}", "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\": [\"complaint@simulator.amazonses.com\"]}", "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\": [\"to@example.com\"], \"CcAddresses\": [\"cc@example.com\"]}",
"multi");
given().header("Authorization", AUTH)
.when().get("/v2/email/insights/" + messageId).then().statusCode(200)
.body("Insights", hasSize(2))
.body("Insights.Destination", contains("to@example.com", "cc@example.com"))
.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\": [\"slash@example.com\"]}", "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: raw@example.com\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": ["raw@example.com"]},
"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("raw@example.com"));
// The MIME parser yields "" for a missing Subject header; the member must stay absent.
String noSubject = "From: " + SENDER + "\r\nTo: raw@example.com\r\n\r\nhi\r\n";
String noSubjectId = given().contentType("application/json").header("Authorization", AUTH)
.body("""
{"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["raw@example.com"]},
"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[] {"suppressed@example.com:COMPLAINT", "bounced@example.com: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\": [\"suppressed@example.com\", \"bounced@example.com\"]}", "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("suppressed@example.com"))
.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("bounced@example.com"))
.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[] {"suppressed@example.com", "bounced@example.com"}) {
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\": [\"user@example.com\"]}", "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: raw@example.com\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": ["raw@example.com"]},
"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("raw@example.com"))
.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);
}
}