feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2) (#1875)

* feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2)

SendEmail now honors ListManagementOptions (ContactListName / TopicName):

Opt-out suppression — recipients opted out of the named contact list are
suppressed as a Bounce, reusing the existing relay-exclusion and Bounce-event
path. A contact is opted out when UnsubscribeAll is set; with a TopicName, an
explicit OPT_OUT preference (or the topic's OPT_OUT DefaultSubscriptionStatus
when no explicit preference) suppresses; without a TopicName, only
UnsubscribeAll contacts are suppressed. A recipient that is not yet a contact
is created on the list automatically; an unknown contact list fails the send.

Unsubscribe handling — a single-recipient list-managed send gets a functional
unsubscribe link: the {{amazonSESUnsubscribeUrl}} body placeholder is replaced
and List-Unsubscribe / List-Unsubscribe-Post headers are added. The link points
at Floci's own /_aws/ses/unsubscribe endpoint (GET/POST), which applies the
opt-out (topic -> OPT_OUT, no topic -> UnsubscribeAll), auto-creating the
contact if needed. The link uses readable query parameters rather than AWS's
opaque token, and its scheme follows Floci's base URL. Raw sends do not get
link injection yet.

* fix(ses): apply list-management unsubscribe headers to relay + inspection, override duplicates, preserve placeholder in templates

Addresses three review findings on the unsubscribe handling:

- The List-Unsubscribe / List-Unsubscribe-Post headers now reach the SMTP relay
  message (relay() takes the additional headers and applies them) and are stored
  on SentEmail so GET /_aws/ses surfaces them under Headers — previously they
  only appeared in published events.
- withUnsubscribeHeaders now overrides a caller-supplied List-Unsubscribe /
  List-Unsubscribe-Post rather than appending a duplicate, matching AWS.
- applyTemplateData leaves the reserved {{amazonSESUnsubscribeUrl}} placeholder
  intact instead of failing with MissingRenderingAttribute, so a templated body
  can carry it (replacement still happens post-render in the send path).

* fix(ses): sanitize relayed headers against SMTP injection and avoid double-slash unsubscribe URLs

User-supplied SendEmail Headers reach the SMTP relay, where a name or value containing
CR/LF could inject extra headers (e.g. Bcc) into the delivered message. Skip any header
with a blank name or CR/LF in its name/value before adding it to the relay message, and
log the drop. Also trim a trailing slash from the configured base URL when building the
List-Unsubscribe URL so a base-url ending in "/" no longer yields "//_aws/...".

* fix(ses): make the unsubscribe GET a no-mutation confirmation page

The unsubscribe endpoint applied the opt-out on both GET and POST. A GET is a browser
click that AWS answers with a landing page, and treating it as a mutation is the RFC 8058
prefetch hazard: mail clients, scanners and link-preview bots that fetch the URL would
silently unsubscribe the contact. GET now renders a confirmation form that POSTs back;
only the POST (the RFC 8058 one-click request) applies the opt-out. Adds GET test
coverage and updates the docs.

* test(ses): add an SDK compat test for SendEmail with ListManagementOptions

Send with ListManagementOptions through the SES v2 SDK client to prove the nested structure
(ContactListName + optional TopicName) marshals as a real client sends it, and that Floci
actually applies it — an absent recipient is auto-created as a contact on the list. Also note
in the docs that {{amazonSESUnsubscribeUrl}} is left verbatim on a send without
ListManagementOptions (Floci behavior, not verified against real SES).

* fix(ses): harden the unsubscribe confirmation page and document its trust model

Escape '&' as '&' in the confirmation form's action attribute (valid HTML), and add the
RFC 8058 one-click hidden field so the form's POST body matches the advertised
List-Unsubscribe-Post header. Also document — in the controller Javadoc and the SES docs — that
the endpoint carries the target in readable query parameters and, like the rest of Floci, is
unauthenticated, so it is only safe on a trusted dev/test network.

* fix(ses): filter unsafe headers once so all send surfaces stay consistent

The SMTP relay dropped user-supplied headers with a blank name or CR/LF, but the stored
SentEmail (GET /_aws/ses) and published events kept the raw list — so inspection and events
could show headers the relay dropped and retain CR/LF injection payloads. Move the safety
check to MessageHeader.isSafe(), filter the headers once in the send path, and use that
sanitized list for storage, relay, and event publishing alike.

* fix(ses): reject SES v2 message headers that omit a required Name or Value

Content.Simple.Headers / Content.Template.Headers entries declare Name and
Value as required members. A header object missing either member was parsed
leniently and later silently dropped, which is surprising when the request is
otherwise accepted. Reject it at parse time the way AWS does — BadRequestException
with the Smithy "Member must not be null" constraint message anchored at the
offending header path and 1-based index.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-08-08 21:33:35 -05:00
1 parent 66fd109ad6
commit fa9ed9100e
17 files changed
+1269 -64

No files matched your search

@@ -50,7 +50,7 @@ class CognitoMessageDispatcherTest {
eq("Verify your account"),
eq("Hi! Your code is 123456."),
isNull(), isNull(), eq(List.of()), eq(List.of()),
eq("us-east-1"));
isNull(), eq("us-east-1"));
verifyNoInteractions(sns);
}
@@ -105,7 +105,7 @@ class CognitoMessageDispatcherTest {
eq(List.of()), eq(List.of()), eq(List.of()),
eq("Your verification code"),
eq("Your verification code is 111222."),
isNull(), isNull(), eq(List.of()), eq(List.of()), eq("us-east-1"));
isNull(), isNull(), eq(List.of()), eq(List.of()), isNull(), eq("us-east-1"));
}
@Test
@@ -121,7 +121,7 @@ class CognitoMessageDispatcherTest {
eq(List.of()), eq(List.of()), eq(List.of()),
anyString(),
eq("Welcome, please verify.\nCode: 999000"),
isNull(), isNull(), eq(List.of()), eq(List.of()), eq("us-east-1"));
isNull(), isNull(), eq(List.of()), eq(List.of()), isNull(), eq("us-east-1"));
}
@Test
@@ -133,7 +133,7 @@ class CognitoMessageDispatcherTest {
"444555", List.of());
verify(ses).sendEmail(anyString(), eq(List.of("alice@example.com")),
any(), any(), any(), anyString(), anyString(), isNull(), isNull(), any(), any(), anyString());
any(), any(), any(), anyString(), anyString(), isNull(), isNull(), any(), any(), isNull(), anyString());
verifyNoInteractions(sns);
}
@@ -0,0 +1,268 @@
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Integration tests for the SES V2 {@code SendEmail} {@code ListManagementOptions} wiring through the
* REST controller: an absent recipient is auto-created as a contact, an unknown contact list fails
* the send, and a malformed {@code ListManagementOptions} is rejected. Uses an isolated region so the
* one-contact-list-per-account limit does not collide with other SES tests.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesListManagementOptionsV2IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/ses/aws4_request";
private static final String LIST = "lmo-newsletter";
private static final String FROM = "lmo-sender@floci.test";
@Test
@Order(0)
void setup_contactList() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"ContactListName": "%s",
"Topics": [
{"TopicName": "Sports", "DisplayName": "Sports",
"DefaultSubscriptionStatus": "OPT_IN", "Description": "d"}
]
}
""".formatted(LIST))
.when().post("/v2/email/contact-lists").then().statusCode(200);
}
@Test
@Order(1)
void sendWithListManagementOptions_autoCreatesAbsentRecipient() {
String recipient = "lmo-newcontact@floci.test";
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["%s"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "b"}}}},
"ListManagementOptions": {"ContactListName": "%s"}
}
""".formatted(FROM, recipient, LIST))
.when().post("/v2/email/outbound-emails").then().statusCode(200);
// AWS auto-creates a contact on the list for a recipient that isn't one yet.
given().header("Authorization", AUTH)
.when().get("/v2/email/contact-lists/" + LIST + "/contacts/" + recipient)
.then().statusCode(200)
.body("EmailAddress", equalTo(recipient));
}
@Test
@Order(2)
void sendWithUnknownContactList_returns404() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["lmo-x@floci.test"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "b"}}}},
"ListManagementOptions": {"ContactListName": "lmo-ghost-list"}
}
""".formatted(FROM))
.when().post("/v2/email/outbound-emails").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
@Order(3)
void listManagementOptionsWithoutContactListName_returns400() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["lmo-x@floci.test"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "b"}}}},
"ListManagementOptions": {"TopicName": "Sports"}
}
""".formatted(FROM))
.when().post("/v2/email/outbound-emails").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
@Test
@Order(4)
void listManagementOptionsWithNonStringTopicName_returns400() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["lmo-x@floci.test"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "b"}}}},
"ListManagementOptions": {"ContactListName": "%s", "TopicName": 123}
}
""".formatted(FROM, LIST))
.when().post("/v2/email/outbound-emails").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
@Test
@Order(5)
void singleRecipientSend_replacesUnsubscribePlaceholderWithFunctionalUrl() {
String recipient = "lmo-unsub-body@floci.test";
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["%s"]},
"Content": {"Simple": {"Subject": {"Data": "hi"},
"Body": {"Html": {"Data": "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>"}}}},
"ListManagementOptions": {"ContactListName": "%s", "TopicName": "Sports"}
}
""".formatted(FROM, recipient, LIST))
.when().post("/v2/email/outbound-emails").then().statusCode(200);
// The stored message body has the placeholder replaced with a functional Floci unsubscribe URL.
given().header("Authorization", AUTH).queryParam("email", recipient)
.when().get("/_aws/ses").then().statusCode(200)
.body(org.hamcrest.Matchers.containsString("/_aws/ses/unsubscribe?"))
.body(org.hamcrest.Matchers.containsString("contactList=" + LIST))
.body(org.hamcrest.Matchers.containsString("topic=Sports"))
.body(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("amazonSESUnsubscribeUrl")))
// the stored message also carries the List-Unsubscribe header
.body(org.hamcrest.Matchers.containsString("List-Unsubscribe"));
}
@Test
@Order(6)
void unsubscribeEndpoint_optsContactOutOfTopic() {
String recipient = "lmo-endpoint@floci.test";
given().header("Authorization", AUTH)
.queryParam("region", "us-west-2").queryParam("contactList", LIST)
.queryParam("topic", "Sports").queryParam("address", recipient)
.when().post("/_aws/ses/unsubscribe").then().statusCode(200);
given().header("Authorization", AUTH)
.when().get("/v2/email/contact-lists/" + LIST + "/contacts/" + recipient)
.then().statusCode(200)
.body("TopicPreferences.find { it.TopicName == 'Sports' }.SubscriptionStatus",
equalTo("OPT_OUT"));
}
@Test
@Order(7)
void unsubscribeEndpoint_missingRegion_returns400() {
given().header("Authorization", AUTH)
.queryParam("contactList", LIST).queryParam("address", "lmo-x@floci.test")
.when().post("/_aws/ses/unsubscribe").then().statusCode(400);
}
@Test
@Order(8)
void unsubscribeEndpoint_get_rendersConfirmationWithoutOptingOut() {
String recipient = "lmo-get@floci.test";
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"EmailAddress\":\"" + recipient + "\",\"TopicPreferences\":["
+ "{\"TopicName\":\"Sports\",\"SubscriptionStatus\":\"OPT_IN\"}]}")
.when().post("/v2/email/contact-lists/" + LIST + "/contacts").then().statusCode(200);
// A browser click (GET) only renders a confirmation form; it must not opt the contact out,
// so a client or bot that prefetches the link cannot silently unsubscribe the contact.
given().header("Authorization", AUTH)
.queryParam("region", "us-west-2").queryParam("contactList", LIST)
.queryParam("topic", "Sports").queryParam("address", recipient)
.when().get("/_aws/ses/unsubscribe").then().statusCode(200)
.body(org.hamcrest.Matchers.containsString("<form method=\"post\""))
.body(org.hamcrest.Matchers.containsString("Unsubscribe"))
// The form action escapes '&' as '&amp;' for valid HTML, and carries the RFC 8058
// one-click parameter so its POST body matches the advertised header.
.body(org.hamcrest.Matchers.containsString("&amp;contactList="))
.body(org.hamcrest.Matchers.containsString(
"<input type=\"hidden\" name=\"List-Unsubscribe\" value=\"One-Click\">"));
given().header("Authorization", AUTH)
.when().get("/v2/email/contact-lists/" + LIST + "/contacts/" + recipient)
.then().statusCode(200)
.body("TopicPreferences.find { it.TopicName == 'Sports' }.SubscriptionStatus",
equalTo("OPT_IN"));
}
@Test
@Order(9)
void send_unsafeHeader_isDroppedFromStoredMessage() {
String recipient = "lmo-unsafe-hdr@floci.test";
// A user-supplied header whose value carries CR/LF must not survive on any surface: the SMTP
// relay already drops it, and the stored SentEmail (GET /_aws/ses) must not retain it either.
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["%s"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "hi"}},
"Headers": [
{"Name": "X-Safe", "Value": "ok"},
{"Name": "X-Evil", "Value": "bad\\r\\nBcc: attacker@evil.com"}
]}}
}
""".formatted(FROM, recipient))
.when().post("/v2/email/outbound-emails").then().statusCode(200);
given().header("Authorization", AUTH).queryParam("email", recipient)
.when().get("/_aws/ses").then().statusCode(200)
.body(org.hamcrest.Matchers.containsString("X-Safe"))
.body(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("X-Evil")))
.body(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("attacker@evil.com")));
}
@Test
@Order(10)
void send_headerMissingValue_isRejectedLikeAws() {
// AWS enforces Content.Simple.Headers[].Value as a required member: a header object that omits
// Value is rejected with BadRequestException and a Smithy constraint message, rather than being
// silently dropped.
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["lmo-x@floci.test"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "b"}},
"Headers": [{"Name": "X-Foo"}]}}
}
""".formatted(FROM))
.when().post("/v2/email/outbound-emails").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", org.hamcrest.Matchers.containsString(
"content.simple.headers.1.member.value"))
.body("message", org.hamcrest.Matchers.containsString("Member must not be null"));
}
@Test
@Order(11)
void send_headerMissingName_isRejectedLikeAws() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["lmo-x@floci.test"]},
"Content": {"Simple": {"Subject": {"Data": "hi"}, "Body": {"Text": {"Data": "b"}},
"Headers": [{"Value": "bar"}]}}
}
""".formatted(FROM))
.when().post("/v2/email/outbound-emails").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", org.hamcrest.Matchers.containsString(
"content.simple.headers.1.member.name"))
.body("message", org.hamcrest.Matchers.containsString("Member must not be null"));
}
@Test
@Order(99)
void cleanup_deleteContactList() {
given().header("Authorization", AUTH)
.when().delete("/v2/email/contact-lists/" + LIST).then().statusCode(200);
}
}
@@ -0,0 +1,269 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes;
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
import io.github.hectorvent.floci.services.ses.model.Contact;
import io.github.hectorvent.floci.services.ses.model.ContactList;
import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.Identity;
import io.github.hectorvent.floci.services.ses.model.ListManagementOptions;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
import io.github.hectorvent.floci.services.ses.model.Topic;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Clock;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Unit tests for SES V2 {@code SendEmail} {@code ListManagementOptions} suppression: opted-out
* contacts on the named list are dropped from the SMTP relay (surfaced here via the relay mock),
* absent recipients are auto-created, and an unknown contact list fails the send. Uses the relay
* mock to observe exactly which recipients survive suppression.
*/
@ExtendWith(MockitoExtension.class)
class SesServiceListManagementTest {
private static final String REGION = "us-east-1";
private static final String LIST = "newsletter";
private static final String FROM = "from@example.com";
@Mock SmtpRelay smtpRelay;
private SesService service;
private InMemoryStorage<String, Contact> contactStore;
@BeforeEach
void setUp() {
contactStore = new InMemoryStorage<>();
service = new SesService(
new InMemoryStorage<String, Identity>(),
new InMemoryStorage<String, SentEmail>(),
new InMemoryStorage<String, Boolean>(),
new InMemoryStorage<String, EmailTemplate>(),
new InMemoryStorage<String, ConfigurationSet>(),
new InMemoryStorage<String, SuppressedDestination>(),
new InMemoryStorage<String, AccountSuppressionAttributes>(),
new InMemoryStorage<String, DedicatedIpPool>(),
new InMemoryStorage<String, ContactList>(),
contactStore,
new InMemoryStorage<String, String>(),
new InMemoryStorage<String, ReceiptRuleSet>(),
smtpRelay,
new ObjectMapper(),
Clock.systemUTC());
// Sports defaults OPT_IN, Promos defaults OPT_OUT.
service.createContactList(LIST, "desc", List.of(
new Topic("Sports", "Sports", "OPT_IN", "d"),
new Topic("Promos", "Promos", "OPT_OUT", "d")), List.of(), REGION);
service.createContact(LIST, "unsub@example.com", List.of(), true, null, REGION);
service.createContact(LIST, "sportsout@example.com",
List.of(new TopicPreference("Sports", "OPT_OUT")), false, null, REGION);
service.createContact(LIST, "sportsin@example.com",
List.of(new TopicPreference("Sports", "OPT_IN")), false, null, REGION);
service.createContact(LIST, "noprefs@example.com", List.of(), false, null, REGION);
}
private void send(List<String> to, String topicName) {
service.sendEmail(FROM, to, null, null, null, "Subject", "body", null,
null, List.of(), List.of(), new ListManagementOptions(LIST, topicName), REGION);
}
@SuppressWarnings("unchecked")
private List<String> capturedRelayTo() {
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
verify(smtpRelay).relay(any(), captor.capture(), any(), any(), any(), any(), any(), any(), any());
return captor.getValue();
}
@Test
void unsubscribeAll_isSuppressed_evenWithNoTopic() {
send(List.of("unsub@example.com", "sportsin@example.com"), null);
assertEquals(List.of("sportsin@example.com"), capturedRelayTo());
}
@Test
void noTopic_onlyUnsubscribeAllSuppressed_topicOptOutStillSent() {
// Without a topic, a contact opted out of a single topic (but not UnsubscribeAll) still gets it.
send(List.of("unsub@example.com", "sportsout@example.com"), null);
assertEquals(List.of("sportsout@example.com"), capturedRelayTo());
}
@Test
void topicExplicitOptOut_isSuppressed() {
send(List.of("sportsout@example.com", "sportsin@example.com"), "Sports");
assertEquals(List.of("sportsin@example.com"), capturedRelayTo());
}
@Test
void topicDefaultOptOut_suppressesContactWithNoExplicitPreference() {
// Promos defaults OPT_OUT and noprefs has no explicit Promos preference -> suppressed.
send(List.of("noprefs@example.com"), "Promos");
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void topicDefaultOptIn_sendsContactWithNoExplicitPreference() {
send(List.of("noprefs@example.com"), "Sports");
assertEquals(List.of("noprefs@example.com"), capturedRelayTo());
}
@Test
void recipientNotAContact_isAutoCreatedAndSent() {
send(List.of("brandnew@example.com"), null);
assertEquals(List.of("brandnew@example.com"), capturedRelayTo());
assertTrue(contactStore.get("contact::" + REGION + "::" + LIST + "::brandnew@example.com").isPresent(),
"an absent recipient must be auto-created as a contact on the list");
}
@Test
void nonExistentContactList_failsTheSend() {
AwsException ex = assertThrows(AwsException.class, () ->
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null,
"Subject", "body", null, null, List.of(), List.of(),
new ListManagementOptions("ghost-list", null), REGION));
assertEquals(404, ex.getHttpStatus());
}
@Test
void unknownTopic_failsTheSend() {
// A TopicName not defined on the list is rejected rather than silently skipping suppression.
AwsException ex = assertThrows(AwsException.class, () ->
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null,
"Subject", "body", null, null, List.of(), List.of(),
new ListManagementOptions(LIST, "GhostTopic"), REGION));
assertEquals(400, ex.getHttpStatus());
}
@Test
void noListManagementOptions_leavesRecipientsUntouched() {
// Without ListManagementOptions the contact list is never consulted: an unsubscribed contact
// is not suppressed and no contact is auto-created.
service.sendEmail(FROM, List.of("unsub@example.com"), null, null, null,
"Subject", "body", null, null, List.of(), List.of(), null, REGION);
assertEquals(List.of("unsub@example.com"), capturedRelayTo());
}
@Test
void singleRecipient_replacesUnsubscribePlaceholder() {
// newbie is not a contact (auto-created, Sports defaults OPT_IN) so the send reaches the relay.
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
"Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), REGION);
String html = capturedRelayBodyHtml();
assertTrue(html.contains("http://localhost:4566/_aws/ses/unsubscribe?"), html);
assertTrue(html.contains("contactList=" + LIST), html);
assertTrue(html.contains("topic=Sports"), html);
assertFalse(html.contains("{{amazonSESUnsubscribeUrl}}"), "placeholder must be replaced");
}
@Test
void multiRecipient_doesNotReplacePlaceholder() {
service.sendEmail(FROM, List.of("newbie@example.com", "sportsin@example.com"), null, null, null,
"Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), REGION);
assertTrue(capturedRelayBodyHtml().contains("{{amazonSESUnsubscribeUrl}}"),
"multi-recipient send must not inject the unsubscribe link");
}
@Test
void unsubscribeContact_withTopic_setsOptOut() {
service.unsubscribeContact(LIST, "sportsin@example.com", "Sports", REGION);
Contact c = contact("sportsin@example.com");
assertTrue(c.getTopicPreferences().stream()
.anyMatch(p -> "Sports".equals(p.getTopicName()) && "OPT_OUT".equals(p.getSubscriptionStatus())));
}
@Test
void unsubscribeContact_withoutTopic_setsUnsubscribeAll() {
service.unsubscribeContact(LIST, "sportsin@example.com", null, REGION);
assertTrue(contact("sportsin@example.com").isUnsubscribeAll());
}
@Test
void unsubscribeContact_absentContact_autoCreatesAndOptsOut() {
service.unsubscribeContact(LIST, "ghost@example.com", null, REGION);
assertTrue(contact("ghost@example.com").isUnsubscribeAll());
}
@Test
void unsubscribeContact_withImmutablePreferences_addsTopicWithoutThrowing() {
Contact c = new Contact("immutable@example.com");
c.setTopicPreferences(List.of(new TopicPreference("Sports", "OPT_IN")));
contactStore.put("contact::" + REGION + "::" + LIST + "::immutable@example.com", c);
service.unsubscribeContact(LIST, "immutable@example.com", "Promos", REGION);
assertTrue(contact("immutable@example.com").getTopicPreferences().stream()
.anyMatch(p -> "Promos".equals(p.getTopicName()) && "OPT_OUT".equals(p.getSubscriptionStatus())));
}
private Contact contact(String email) {
return contactStore.get("contact::" + REGION + "::" + LIST + "::" + email).orElseThrow();
}
@SuppressWarnings("unchecked")
private String capturedRelayBodyHtml() {
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), captor.capture(), any());
return captor.getValue();
}
@SuppressWarnings("unchecked")
private List<MessageHeader> capturedRelayHeaders() {
ArgumentCaptor<List<MessageHeader>> captor = ArgumentCaptor.forClass(List.class);
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), any(), captor.capture());
return captor.getValue();
}
@Test
void singleRecipient_addsListUnsubscribeHeadersToRelay() {
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
"Subject", "text", "<p>x</p>", null, List.of(), List.of(),
new ListManagementOptions(LIST, "Sports"), REGION);
List<MessageHeader> headers = capturedRelayHeaders();
assertTrue(headers.stream().anyMatch(h -> "List-Unsubscribe".equals(h.name())
&& h.value().contains("/_aws/ses/unsubscribe")), "List-Unsubscribe header must reach the relay");
assertTrue(headers.stream().anyMatch(h -> "List-Unsubscribe-Post".equals(h.name())
&& "List-Unsubscribe=One-Click".equals(h.value())));
}
@Test
void callerSuppliedUnsubscribeHeader_isOverriddenNotDuplicated() {
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
"Subject", "text", "<p>x</p>", null, List.of(),
List.of(new MessageHeader("List-Unsubscribe", "<https://caller.example/u>")),
new ListManagementOptions(LIST, "Sports"), REGION);
long count = capturedRelayHeaders().stream()
.filter(h -> "List-Unsubscribe".equalsIgnoreCase(h.name())).count();
assertEquals(1L, count);
}
@Test
void applyTemplateData_leavesUnsubscribePlaceholderIntact() {
String rendered = SesService.applyTemplateData("<p>{{amazonSESUnsubscribeUrl}} {{name}}</p>",
new ObjectMapper().createObjectNode().put("name", "Bob"));
assertEquals("<p>{{amazonSESUnsubscribeUrl}} Bob</p>", rendered);
}
}
@@ -60,7 +60,7 @@ class SesServiceSmtpTest {
List.of("cc@example.com"),
List.of("bcc@example.com"),
List.of("reply@example.com"),
"Subject", "text body", "<p>html</p>", null, List.of(), List.of(), "us-east-1");
"Subject", "text body", "<p>html</p>", null, List.of(), List.of(), null, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
@@ -68,24 +68,24 @@ class SesServiceSmtpTest {
List.of("cc@example.com"),
List.of("bcc@example.com"),
List.of("reply@example.com"),
"Subject", "text body", "<p>html</p>");
"Subject", "text body", "<p>html</p>", List.of());
}
@Test
void sendEmail_storesAndRelays() {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
"Subject", "text", null, null, List.of(), List.of(), "us-east-1");
"Subject", "text", null, null, List.of(), List.of(), null, "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), any());
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void sendRawEmail_callsRelayRaw() {
service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, List.of(), "us-east-1");
List.of("to@example.com"), "raw MIME", null, List.of(), null, "us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
@@ -96,7 +96,7 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_storesAndRelays() {
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw", null, List.of(), "us-east-1");
List.of("to@example.com"), "raw", null, List.of(), null, "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
@@ -108,13 +108,13 @@ class SesServiceSmtpTest {
service.sendEmail("from@example.com",
List.of("to@example.com"),
null, null, null,
"Subject", null, "<p>html only</p>", null, List.of(), List.of(), "us-east-1");
"Subject", null, "<p>html only</p>", null, List.of(), List.of(), null, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
List.of("to@example.com"),
null, null, null,
"Subject", null, "<p>html only</p>");
"Subject", null, "<p>html only</p>", List.of());
}
@Test
@@ -126,12 +126,12 @@ class SesServiceSmtpTest {
List.of("to@example.com"),
List.of("cc@example.com"),
null, null,
"Subject", "text body", null, null, List.of(), List.of(), "us-east-1");
"Subject", "text body", null, null, List.of(), List.of(), null, "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty(),
"stored SentEmail should still record the original recipient list");
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any());
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -143,7 +143,7 @@ class SesServiceSmtpTest {
List.of("to@example.com", "suppressed@example.com"),
List.of("cc-keep@example.com"),
null, null,
"Subject", "text body", null, null, List.of(), List.of(), "us-east-1");
"Subject", "text body", null, null, List.of(), List.of(), null, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
@@ -151,7 +151,7 @@ class SesServiceSmtpTest {
List.of("cc-keep@example.com"),
null,
null,
"Subject", "text body", null);
"Subject", "text body", null, List.of());
}
@Test
@@ -159,7 +159,7 @@ class SesServiceSmtpTest {
service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE");
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, List.of(), "us-east-1");
List.of("to@example.com"), "raw MIME", null, List.of(), null, "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
@@ -172,7 +172,7 @@ class SesServiceSmtpTest {
service.sendRawEmail("from@example.com",
List.of("to@example.com", "suppressed@example.com"),
"raw MIME", null, List.of(), "us-east-1");
"raw MIME", null, List.of(), null, "us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
@@ -194,13 +194,13 @@ class SesServiceSmtpTest {
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
"Subject", "text body", null, "cs-no-suppression", List.of(), List.of(), "us-east-1");
"Subject", "text body", null, "cs-no-suppression", List.of(), List.of(), null, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
List.of("to@example.com"),
null, null, null,
"Subject", "text body", null);
"Subject", "text body", null, List.of());
}
@Test
@@ -214,13 +214,13 @@ class SesServiceSmtpTest {
service.sendEmail("from@example.com",
List.of("complainer@example.com"), null, null, null,
"Subject", "text body", null, "cs-bounce-only", List.of(), List.of(), "us-east-1");
"Subject", "text body", null, "cs-bounce-only", List.of(), List.of(), null, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
List.of("complainer@example.com"),
null, null, null,
"Subject", "text body", null);
"Subject", "text body", null, List.of());
}
@Test
@@ -233,9 +233,9 @@ class SesServiceSmtpTest {
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
"Subject", "text body", null, "cs-default", List.of(), List.of(), "us-east-1");
"Subject", "text body", null, "cs-default", List.of(), List.of(), null, "us-east-1");
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any());
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -245,7 +245,7 @@ class SesServiceSmtpTest {
service.putConfigurationSetSuppressionOptions("cs-no-suppression-raw", List.of(), "us-east-1");
service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", "cs-no-suppression-raw", List.of(), "us-east-1");
List.of("to@example.com"), "raw MIME", "cs-no-suppression-raw", List.of(), null, "us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.vertx.core.Future;
import io.vertx.ext.mail.MailClient;
import io.vertx.ext.mail.MailMessage;
@@ -33,7 +34,7 @@ class SmtpRelayTest {
assertFalse(relay.isEnabled());
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "text", null);
null, null, null, "Subject", "text", null, List.of());
verify(mailClient, never()).sendMail(any(MailMessage.class));
}
@@ -49,7 +50,7 @@ class SmtpRelayTest {
List.of("reply@example.com"),
"Test Subject",
"plain text",
"<p>html</p>");
"<p>html</p>", List.of());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -70,19 +71,43 @@ class SmtpRelayTest {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "text", null);
null, null, null, "Subject", "text", null, List.of());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
assertNull(captor.getValue().getHeaders());
}
@Test
void relay_dropsHeadersWithCrlfOrBlankName_preventingInjection() {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "text", null, List.of(
new MessageHeader("X-Safe", "ok"),
new MessageHeader("X-Evil", "value\r\nBcc: attacker@evil.com"),
new MessageHeader("Injected\r\nBcc", "x"),
new MessageHeader("", "no-name")));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
MailMessage sent = captor.getValue();
assertEquals("ok", sent.getHeaders().get("X-Safe"));
// The CR/LF-bearing and blank-name headers are dropped entirely, so no smuggled header
// (e.g. Bcc) reaches the relayed message and no header name/value carries a line break.
assertFalse(sent.getHeaders().contains("X-Evil"));
assertNull(sent.getHeaders().get("Bcc"));
assertTrue(sent.getHeaders().names().stream()
.noneMatch(n -> n.isBlank() || n.indexOf('\r') >= 0 || n.indexOf('\n') >= 0));
}
@Test
void relay_textOnly_setsTextWithoutHtml() {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "only text", null);
null, null, null, "Subject", "only text", null, List.of());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -95,7 +120,7 @@ class SmtpRelayTest {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", null, "<b>html</b>");
null, null, null, "Subject", null, "<b>html</b>", List.of());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -110,7 +135,7 @@ class SmtpRelayTest {
.thenReturn(Future.failedFuture(new RuntimeException("SMTP refused")));
assertDoesNotThrow(() -> relay.relay("from@example.com",
List.of("to@example.com"), null, null, null, "Subject", "text", null));
List.of("to@example.com"), null, null, null, "Subject", "text", null, List.of()));
}
// ── Raw relay ──