refactor(ses): model SES sends as an envelope plus content, like the v2 SDK (#4529)

* refactor(ses): model SES sends as an envelope plus content, like the v2 SDK

The five SES send methods took up to 15 positional parameters, and every
new send field cascaded through all of them and their callers. Sends now
follow the v2 SDK shape: a SendEmailRequest envelope carrying a sealed
EmailContent (Simple, Template, InlineTemplate or Raw), and a
SendBulkEmailRequest for bulk. SesService exposes sendEmail, which
switches on the content, and sendBulkEmail.

The controllers keep their validation, error codes and tenant gates;
each maps its wire input onto the envelope and picks the content
variant. The request always carries the content being sent: rendering
and header sanitizing rebuild it rather than holding a second copy.

No wire behaviour changes.

* refactor(ses): share the recipient join between the request and MIME headers
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-28 21:40:58 -04:00
1 parent 11b762d08b
commit 673c8838cf
15 files changed
+866 -316

No files matched your search

@@ -17,6 +17,8 @@ import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.ses.SesService;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
@@ -45,7 +47,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -148,6 +149,18 @@ class CognitoLambdaTriggersTest {
}
}
private static void assertVerificationEmail(SesService ses, String to, String subject, String body) {
ArgumentCaptor<SendEmailRequest> captor = ArgumentCaptor.forClass(SendEmailRequest.class);
verify(ses).sendEmail(captor.capture());
SendEmailRequest sent = captor.getValue();
assertEquals(SendEmailRequest.builder()
.source(sent.source())
.toAddresses(List.of(to))
.region("us-east-1")
.content(new EmailContent.Simple(subject, body, null, List.of()))
.build(), sent);
}
private static InvokeResult rawPayload(String payload) {
return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "req-id");
}
@@ -1396,12 +1409,7 @@ class CognitoLambdaTriggersTest {
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
verify(ses).sendEmail(
anyString(), eq(List.of("spike@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()), isNull(),
eq("TRIGGER-FIRED"),
eq("TRIGGER-FIRED code=246962"),
any(), any(), eq(List.of()), eq(List.of()), any(), isNull(), anyString());
assertVerificationEmail(ses, "spike@example.com", "TRIGGER-FIRED", "TRIGGER-FIRED code=246962");
}
@Test
@@ -1453,12 +1461,8 @@ class CognitoLambdaTriggersTest {
// SignUp must still succeed and deliver the default message when CustomMessage errors.
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
verify(ses).sendEmail(
anyString(), eq(List.of("spike@example.com")),
any(), any(), any(), isNull(),
eq("Your verification code"),
eq("Your verification code is 246962."),
any(), any(), any(), any(), any(), isNull(), anyString());
assertVerificationEmail(ses, "spike@example.com", "Your verification code",
"Your verification code is 246962.");
}
@Test
@@ -1477,12 +1481,8 @@ class CognitoLambdaTriggersTest {
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
verify(ses).sendEmail(
anyString(), eq(List.of("spike@example.com")),
any(), any(), any(), isNull(),
eq("Your verification code"),
eq("Your verification code is 246962."),
any(), any(), any(), any(), any(), isNull(), anyString());
assertVerificationEmail(ses, "spike@example.com", "Your verification code",
"Your verification code is 246962.");
}
@Test
@@ -3,15 +3,20 @@ package io.github.hectorvent.floci.services.cognito.verification;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.ses.SesService;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.sns.SnsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -43,14 +48,13 @@ class CognitoMessageDispatcherTest {
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"));
verify(ses).sendEmail(
anyString(),
eq(List.of("alice@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()), isNull(),
eq("Verify your account"),
eq("Hi! Your code is 123456."),
isNull(), isNull(), eq(List.of()), eq(List.of()),
isNull(), isNull(), eq("us-east-1"));
SendEmailRequest sent = sentEmail();
assertEquals(SendEmailRequest.builder()
.source(sent.source())
.toAddresses(List.of("alice@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Verify your account", "Hi! Your code is 123456.", null, List.of()))
.build(), sent);
verifyNoInteractions(sns);
}
@@ -118,12 +122,14 @@ class CognitoMessageDispatcherTest {
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"111222", List.of("EMAIL"));
verify(ses).sendEmail(
anyString(), eq(List.of("alice@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()), isNull(),
eq("Your verification code"),
eq("Your verification code is 111222."),
isNull(), isNull(), eq(List.of()), eq(List.of()), isNull(), isNull(), eq("us-east-1"));
SendEmailRequest sent = sentEmail();
assertEquals(SendEmailRequest.builder()
.source(sent.source())
.toAddresses(List.of("alice@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Your verification code", "Your verification code is 111222.",
null, List.of()))
.build(), sent);
}
@Test
@@ -134,12 +140,14 @@ class CognitoMessageDispatcherTest {
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"999000", List.of("EMAIL"));
verify(ses).sendEmail(
anyString(), eq(List.of("alice@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()), isNull(),
anyString(),
eq("Welcome, please verify.\nCode: 999000"),
isNull(), isNull(), eq(List.of()), eq(List.of()), isNull(), isNull(), eq("us-east-1"));
SendEmailRequest sent = sentEmail();
assertNotNull(subject(sent));
assertEquals(SendEmailRequest.builder()
.source(sent.source())
.toAddresses(List.of("alice@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple(subject(sent), "Welcome, please verify.\nCode: 999000", null, List.of()))
.build(), sent);
}
@Test
@@ -150,9 +158,15 @@ class CognitoMessageDispatcherTest {
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"444555", List.of());
verify(ses).sendEmail(anyString(), eq(List.of("alice@example.com")),
any(), any(), any(), isNull(), anyString(), anyString(), isNull(), isNull(), any(), any(),
isNull(), isNull(), anyString());
SendEmailRequest sent = sentEmail();
assertNotNull(subject(sent));
assertNotNull(bodyText(sent));
assertEquals(SendEmailRequest.builder()
.source(sent.source())
.toAddresses(List.of("alice@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple(subject(sent), bodyText(sent), null, List.of()))
.build(), sent);
verifyNoInteractions(sns);
}
@@ -169,6 +183,20 @@ class CognitoMessageDispatcherTest {
verifyNoInteractions(ses);
}
private SendEmailRequest sentEmail() {
ArgumentCaptor<SendEmailRequest> captor = ArgumentCaptor.forClass(SendEmailRequest.class);
verify(ses).sendEmail(captor.capture());
return captor.getValue();
}
private static String subject(SendEmailRequest sent) {
return assertInstanceOf(EmailContent.Simple.class, sent.content()).subject();
}
private static String bodyText(SendEmailRequest sent) {
return assertInstanceOf(EmailContent.Simple.class, sent.content()).bodyText();
}
private UserPool pool(Map<String, Object> template) {
UserPool p = new UserPool();
p.setVerificationMessageTemplate(new HashMap<>(template));
@@ -155,7 +155,7 @@ class SesBulkV1IntegrationTest {
@Test
@Order(6)
void sendBulkTemplatedEmail_perEntryMissingDestination_mapsToInvalidParameterValue() {
// An entry with only ReplacementTemplateData (no recipient) reaches sendEmail,
// An entry with only ReplacementTemplateData (no recipient) reaches the per-entry send,
// which throws AwsException("InvalidParameterValue", ...). Expected per-entry
// Status string in v1 is "InvalidParameterValue", not "Failed" or "InvalidParameter".
// DefaultTemplateData supplies team so rendering succeeds before the recipient check.
@@ -4,8 +4,10 @@ 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.Contact;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
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.SendEmailRequest;
import io.github.hectorvent.floci.services.ses.model.Topic;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import org.junit.jupiter.api.BeforeEach;
@@ -64,8 +66,13 @@ class SesServiceListManagementTest {
}
private void send(List<String> to, String topicName) {
service.sendEmail(FROM, to, null, null, null, null, "Subject", "body", null,
null, List.of(), List.of(), new ListManagementOptions(LIST, topicName), null, REGION);
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(to)
.listManagement(new ListManagementOptions(LIST, topicName))
.region(REGION)
.content(new EmailContent.Simple("Subject", "body", null, List.of()))
.build());
}
private SmtpRelay.RelayMessage capturedRelay() {
@@ -122,9 +129,13 @@ class SesServiceListManagementTest {
@Test
void nonExistentContactList_failsTheSend() {
AwsException ex = assertThrows(AwsException.class, () ->
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null, null,
"Subject", "body", null, null, List.of(), List.of(),
new ListManagementOptions("ghost-list", null), null, REGION));
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("sportsin@example.com"))
.listManagement(new ListManagementOptions("ghost-list", null))
.region(REGION)
.content(new EmailContent.Simple("Subject", "body", null, List.of()))
.build()));
assertEquals(404, ex.getHttpStatus());
}
@@ -132,9 +143,13 @@ class SesServiceListManagementTest {
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, null,
"Subject", "body", null, null, List.of(), List.of(),
new ListManagementOptions(LIST, "GhostTopic"), null, REGION));
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("sportsin@example.com"))
.listManagement(new ListManagementOptions(LIST, "GhostTopic"))
.region(REGION)
.content(new EmailContent.Simple("Subject", "body", null, List.of()))
.build()));
assertEquals(400, ex.getHttpStatus());
}
@@ -142,17 +157,26 @@ class SesServiceListManagementTest {
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, null,
"Subject", "body", null, null, List.of(), List.of(), null, null, REGION);
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("unsub@example.com"))
.region(REGION)
.content(new EmailContent.Simple("Subject", "body", null, List.of()))
.build());
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, null,
"Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), null, REGION);
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("newbie@example.com"))
.listManagement(new ListManagementOptions(LIST, "Sports"))
.region(REGION)
.content(new EmailContent.Simple("Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
List.of()))
.build());
String html = capturedRelayBodyHtml();
assertTrue(html.contains("http://localhost:4566/_aws/ses/unsubscribe?"), html);
assertTrue(html.contains("contactList=" + LIST), html);
@@ -162,9 +186,14 @@ class SesServiceListManagementTest {
@Test
void multiRecipient_doesNotReplacePlaceholder() {
service.sendEmail(FROM, List.of("newbie@example.com", "sportsin@example.com"), null, null, null,
null, "Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), null, REGION);
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("newbie@example.com", "sportsin@example.com"))
.listManagement(new ListManagementOptions(LIST, "Sports"))
.region(REGION)
.content(new EmailContent.Simple("Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
List.of()))
.build());
assertTrue(capturedRelayBodyHtml().contains("{{amazonSESUnsubscribeUrl}}"),
"multi-recipient send must not inject the unsubscribe link");
}
@@ -215,9 +244,13 @@ class SesServiceListManagementTest {
@Test
void singleRecipient_addsListUnsubscribeHeadersToRelay() {
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null,
"Subject", "text", "<p>x</p>", null, List.of(), List.of(),
new ListManagementOptions(LIST, "Sports"), null, REGION);
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("newbie@example.com"))
.listManagement(new ListManagementOptions(LIST, "Sports"))
.region(REGION)
.content(new EmailContent.Simple("Subject", "text", "<p>x</p>", List.of()))
.build());
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");
@@ -227,10 +260,14 @@ class SesServiceListManagementTest {
@Test
void callerSuppliedUnsubscribeHeader_isOverriddenNotDuplicated() {
service.sendEmail(FROM, List.of("newbie@example.com"), null, 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"), null, REGION);
service.sendEmail(SendEmailRequest.builder()
.source(FROM)
.toAddresses(List.of("newbie@example.com"))
.listManagement(new ListManagementOptions(LIST, "Sports"))
.region(REGION)
.content(new EmailContent.Simple("Subject", "text", "<p>x</p>",
List.of(new MessageHeader("List-Unsubscribe", "<https://caller.example/u>"))))
.build());
long count = capturedRelayHeaders().stream()
.filter(h -> "List-Unsubscribe".equalsIgnoreCase(h.name())).count();
assertEquals(1L, count);
@@ -4,7 +4,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.InsightsEvent;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -123,13 +125,15 @@ class SesServiceSmtpTest {
@Test
void sendEmail_callsRelayWithAllFields() {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"),
List.of("cc@example.com"),
List.of("bcc@example.com"),
List.of("reply@example.com"),
null,
"Subject", "text body", "<p>html</p>", null, List.of(), List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.ccAddresses(List.of("cc@example.com"))
.bccAddresses(List.of("bcc@example.com"))
.replyToAddresses(List.of("reply@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text body", "<p>html</p>", List.of()))
.build());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals("from@example.com", relayed.from());
@@ -146,9 +150,12 @@ class SesServiceSmtpTest {
@Test
void sendEmail_storesAndRelays() {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null, null,
"Subject", "text", null, null, List.of(), List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text", null, List.of()))
.build());
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
@@ -157,18 +164,25 @@ class SesServiceSmtpTest {
@Test
void sendEmail_noReturnPath_fallsBackToSource() {
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null, null,
"Subject", "text", null, null, List.of(), List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text", null, List.of()))
.build());
assertEquals("from@example.com", capturedRelay().returnPath());
}
@Test
void sendEmail_explicitReturnPath_isRelayedAndStored() {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null, "bounces@example.com",
"Subject", "text", null, null, List.of(), List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.returnPath("bounces@example.com")
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text", null, List.of()))
.build());
assertEquals("bounces@example.com", capturedRelay().returnPath());
assertEquals("bounces@example.com", storedEmail(messageId).getReturnPath());
@@ -181,8 +195,13 @@ class SesServiceSmtpTest {
String raw = "From: from@example.com\r\nTo: to@example.com\r\nReturn-Path: <bounces@evil.example>\r\n"
+ "Subject: " + SesContentScan.signature() + "\r\n\r\nbody\r\n";
String messageId = service.sendRawEmail("from@example.com", List.of("to@example.com"), raw,
"bounces@example.com", null, List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.returnPath("bounces@example.com")
.region("us-east-1")
.content(new EmailContent.Raw(raw))
.build());
assertEquals("bounces@example.com", storedEmail(messageId).getReturnPath());
assertEquals("Bad content", storedEmail(messageId).getRejectReason());
@@ -195,8 +214,12 @@ class SesServiceSmtpTest {
// rather than recorded and relayed unseen.
String raw = "Content-Type: message/rfc822\r\n\r\n".repeat(100_000) + "Subject: deep\r\n\r\nx\r\n";
AwsException e = assertThrows(AwsException.class, () -> service.sendRawEmail("from@example.com",
List.of("to@example.com"), raw, null, null, List.of(), null, null, "us-east-1"));
AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Raw(raw))
.build()));
assertEquals(400, e.getHttpStatus());
assertTrue(sentEmails.listAll().isEmpty());
@@ -205,8 +228,12 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_callsRelayRaw() {
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, null, List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Raw("raw MIME"))
.build());
SmtpRelay.RawRelayMessage relayed = capturedRawRelay();
assertEquals("from@example.com", relayed.from());
@@ -222,8 +249,13 @@ class SesServiceSmtpTest {
+ "Return-Path: <mime-bounces@example.com>\r\n"
+ "Subject: x\r\n\r\nbody";
String messageId = service.sendRawEmail("from@example.com", List.of("to@example.com"), raw,
"request-bounces@example.com", null, List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.returnPath("request-bounces@example.com")
.region("us-east-1")
.content(new EmailContent.Raw(raw))
.build());
assertEquals("mime-bounces@example.com", capturedRawRelay().returnPath());
assertEquals("mime-bounces@example.com", storedEmail(messageId).getReturnPath());
@@ -233,28 +265,64 @@ class SesServiceSmtpTest {
void sendRawEmail_noReturnPathHeader_usesRequestField() {
String raw = "From: from@example.com\r\nTo: to@example.com\r\nSubject: x\r\n\r\nbody";
service.sendRawEmail("from@example.com", List.of("to@example.com"), raw,
"request-bounces@example.com", null, List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.returnPath("request-bounces@example.com")
.region("us-east-1")
.content(new EmailContent.Raw(raw))
.build());
assertEquals("request-bounces@example.com", capturedRawRelay().returnPath());
}
@Test
void sendRawEmail_storesAndRelays() {
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw", null, null, List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Raw("raw"))
.build());
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
verify(smtpRelay).relayRaw(any(SmtpRelay.RawRelayMessage.class));
}
// Template errors (a missing stored template, empty inline content) are reported before the
// envelope checks, so envelope validation must not move ahead of the content switch.
@Test
void sendEmail_unknownTemplate_reportedBeforeMissingSource() {
AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(SendEmailRequest.builder()
.region("us-east-1")
.content(new EmailContent.Template("ghost", null, List.of()))
.build()));
assertEquals("TemplateDoesNotExist", e.getErrorCode());
}
@Test
void sendEmail_emptyInlineTemplate_reportedBeforeMissingSource() {
AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(SendEmailRequest.builder()
.region("us-east-1")
.content(new EmailContent.InlineTemplate(null, null, null, null, List.of()))
.build()));
assertEquals("InvalidTemplate", e.getErrorCode());
}
@Test
void sendEmail_relayReceivesCorrectFieldsWithNulls() {
service.sendEmail("from@example.com",
List.of("to@example.com"),
null, null, null, null,
"Subject", null, "<p>html only</p>", null, List.of(), List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.ccAddresses(null)
.bccAddresses(null)
.replyToAddresses(null)
.region("us-east-1")
.content(new EmailContent.Simple("Subject", null, "<p>html only</p>", List.of()))
.build());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals(List.of("to@example.com"), relayed.to());
@@ -270,11 +338,13 @@ class SesServiceSmtpTest {
suppression.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE");
suppression.putSuppressedDestination("us-east-1", "cc@example.com", "COMPLAINT");
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"),
List.of("cc@example.com"),
null, null, null,
"Subject", "text body", null, null, List.of(), List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.ccAddresses(List.of("cc@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text body", null, List.of()))
.build());
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty(),
@@ -287,11 +357,13 @@ class SesServiceSmtpTest {
// Only suppress one of the To recipients; the other should still reach the relay.
suppression.putSuppressedDestination("us-east-1", "suppressed@example.com", "BOUNCE");
service.sendEmail("from@example.com",
List.of("to@example.com", "suppressed@example.com"),
List.of("cc-keep@example.com"),
null, null, null,
"Subject", "text body", null, null, List.of(), List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com", "suppressed@example.com"))
.ccAddresses(List.of("cc-keep@example.com"))
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text body", null, List.of()))
.build());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals(List.of("to@example.com"), relayed.to());
@@ -302,8 +374,12 @@ class SesServiceSmtpTest {
void sendRawEmail_allRecipientsSuppressed_skipsRelayRawButStillStores() {
suppression.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE");
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, null, List.of(), null, null, "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.region("us-east-1")
.content(new EmailContent.Raw("raw MIME"))
.build());
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
@@ -314,9 +390,12 @@ class SesServiceSmtpTest {
void sendRawEmail_partialSuppression_relayRawCalledWithFilteredRecipients() {
suppression.putSuppressedDestination("us-east-1", "suppressed@example.com", "COMPLAINT");
service.sendRawEmail("from@example.com",
List.of("to@example.com", "suppressed@example.com"),
"raw MIME", null, null, List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com", "suppressed@example.com"))
.region("us-east-1")
.content(new EmailContent.Raw("raw MIME"))
.build());
assertEquals(List.of("to@example.com"), capturedRawRelay().destinations());
}
@@ -333,9 +412,13 @@ class SesServiceSmtpTest {
service.createConfigurationSet(new ConfigurationSet("cs-no-suppression"), "us-east-1");
configSets.putSuppressionOptions("cs-no-suppression", List.of(), "us-east-1");
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null, null,
"Subject", "text body", null, "cs-no-suppression", List.of(), List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.configurationSetName("cs-no-suppression")
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text body", null, List.of()))
.build());
assertEquals(List.of("to@example.com"), capturedRelay().to());
}
@@ -349,9 +432,13 @@ class SesServiceSmtpTest {
service.createConfigurationSet(new ConfigurationSet("cs-bounce-only"), "us-east-1");
configSets.putSuppressionOptions("cs-bounce-only", List.of("BOUNCE"), "us-east-1");
service.sendEmail("from@example.com",
List.of("complainer@example.com"), null, null, null, null,
"Subject", "text body", null, "cs-bounce-only", List.of(), List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("complainer@example.com"))
.configurationSetName("cs-bounce-only")
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text body", null, List.of()))
.build());
assertEquals(List.of("complainer@example.com"), capturedRelay().to());
}
@@ -364,9 +451,13 @@ class SesServiceSmtpTest {
suppression.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE");
service.createConfigurationSet(new ConfigurationSet("cs-default"), "us-east-1");
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null, null,
"Subject", "text body", null, "cs-default", List.of(), List.of(), null, null, "us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.configurationSetName("cs-default")
.region("us-east-1")
.content(new EmailContent.Simple("Subject", "text body", null, List.of()))
.build());
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
}
@@ -377,9 +468,13 @@ class SesServiceSmtpTest {
service.createConfigurationSet(new ConfigurationSet("cs-no-suppression-raw"), "us-east-1");
configSets.putSuppressionOptions("cs-no-suppression-raw", List.of(), "us-east-1");
service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, "cs-no-suppression-raw", List.of(), null, null,
"us-east-1");
service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
.configurationSetName("cs-no-suppression-raw")
.region("us-east-1")
.content(new EmailContent.Raw("raw MIME"))
.build());
assertEquals(List.of("to@example.com"), capturedRawRelay().destinations());
}
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.ses.model;
import org.junit.jupiter.api.Test;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EmailContentTest {
@Test
void withSafeHeaders_dropsUnsafeHeadersAndKeepsTheRestInOrder() {
EmailContent.Simple content = new EmailContent.Simple("Subject", "text", "<p>html</p>", List.of(
new MessageHeader("X-First", "one"),
new MessageHeader(" ", "blank name"),
new MessageHeader("X-Injected\r\nBcc", "value"),
new MessageHeader("X-Split", "line\nBcc: victim@example.com"),
new MessageHeader("X-Null", null),
new MessageHeader("X-Second", "two")));
EmailContent.Simple safe = content.withSafeHeaders();
assertEquals(new EmailContent.Simple("Subject", "text", "<p>html</p>", List.of(
new MessageHeader("X-First", "one"),
new MessageHeader("X-Second", "two"))), safe);
}
@Test
void withSafeHeaders_nullHeaders_returnsTheSameContent() {
EmailContent.Simple content = new EmailContent.Simple("Subject", "text", null, null);
assertSame(content, content.withSafeHeaders());
}
@Test
void withSafeHeaders_emptyHeaders_returnsTheSameContent() {
EmailContent.Simple content = new EmailContent.Simple("Subject", "text", null, List.of());
assertSame(content, content.withSafeHeaders());
}
@Test
void hasHeaders_falseForNullOrEmptyAndTrueOtherwise() {
assertFalse(new EmailContent.Simple("Subject", "text", null, null).hasHeaders());
assertFalse(new EmailContent.Simple("Subject", "text", null, List.of()).hasHeaders());
assertTrue(new EmailContent.Simple("Subject", "text", null,
List.of(new MessageHeader("X-Header", "value"))).hasHeaders());
}
}
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.services.ses.model;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.RecordComponent;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class SendEmailRequestTest {
// Iterates the record components so a field added to the record but not to toBuilder() fails
// here instead of silently resetting to its default whenever SesService rebuilds the request
// around rendered or sanitized content.
@Test
void toBuilderCopiesEveryComponent() throws Exception {
SendEmailRequest.Builder builder = SendEmailRequest.builder();
for (RecordComponent component : SendEmailRequest.class.getRecordComponents()) {
Method setter = SendEmailRequest.Builder.class.getMethod(component.getName(), component.getType());
setter.invoke(builder, sampleValue(component));
}
SendEmailRequest original = builder.build();
SendEmailRequest defaults = SendEmailRequest.builder().content(new EmailContent.Raw("raw")).build();
for (RecordComponent component : SendEmailRequest.class.getRecordComponents()) {
assertNotEquals(component.getAccessor().invoke(defaults), component.getAccessor().invoke(original),
component.getName() + " must differ from its default for the round trip to prove anything");
}
assertEquals(original, original.toBuilder().build());
}
@Test
void buildWithoutContent_fails() {
NullPointerException e = assertThrows(NullPointerException.class,
() -> SendEmailRequest.builder().source("from@example.com").build());
assertEquals("content", e.getMessage());
}
@Test
void recipients_concatenatesToCcBccAndSkipsNullLists() {
SendEmailRequest request = SendEmailRequest.builder()
.toAddresses(List.of("to@example.com"))
.ccAddresses(null)
.bccAddresses(List.of("bcc1@example.com", "bcc2@example.com"))
.content(new EmailContent.Raw("raw"))
.build();
assertEquals(List.of("to@example.com", "bcc1@example.com", "bcc2@example.com"), request.recipients());
assertTrue(request.hasRecipients());
}
@Test
void hasRecipients_falseWhenEveryListIsNullOrEmpty() {
SendEmailRequest request = SendEmailRequest.builder()
.toAddresses(null)
.ccAddresses(List.of())
.bccAddresses(null)
.content(new EmailContent.Raw("raw"))
.build();
assertEquals(List.of(), request.recipients());
assertFalse(request.hasRecipients());
}
private static Object sampleValue(RecordComponent component) {
if (component.getType() == String.class) {
return component.getName() + "-value";
}
if (component.getType() == ListManagementOptions.class) {
return new ListManagementOptions("list", "topic");
}
if (component.getType() == EmailContent.class) {
return new EmailContent.Simple("subject", "text", "<p>html</p>", List.of());
}
if (component.getType() == List.class) {
Object element = ((ParameterizedType) component.getGenericType()).getActualTypeArguments()[0];
if (element == String.class) {
return List.of(component.getName() + "@example.com");
}
if (element == MessageTag.class) {
return List.of(new MessageTag("tag", "value"));
}
}
return fail("no sample value for component " + component.getName() + " of type " + component.getGenericType());
}
}