feat(ses): preserve raw message fidelity and envelope sender in the SMTP relay (#3522)

* feat(ses): preserve raw messages, envelope sender, and X-SES headers in SMTP relay

The raw relay reparsed each MIME message and rebuilt it from the text and
HTML parts alone, dropping every attachment and custom header. It now walks
the Mime4j tree and maps it onto the outgoing message: the first text/plain
and text/html parts become the body, every other leaf becomes an attachment
(inline when it carries a Content-ID, so cid: references still resolve), an
embedded message/rfc822 part is relayed whole, and display names on addresses
survive. Top-level headers are copied through apart from the MIME structural
ones, which the encoder regenerates for the re-built message.

Wire the envelope sender through to MAIL FROM, resolved in AWS's order: the
Return-Path MIME header, then the ReturnPath request field (v1) or
FeedbackForwardingEmailAddress (v2), then the source. The resolved value is
recorded on SentEmail so the inspection endpoint shows it.

Stamp relayed messages with <{MessageId}@{region}.amazonses.com>, matching the
MessageId returned to the caller, leaving a caller-supplied Message-ID alone.

Honour the X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS control headers on
raw sends, which previously parsed to nothing and left event publishing
silently inert for callers using the header form. Both are stripped from the
relayed message, as AWS consumes rather than forwards them. The tenant send
gate sees the same resolved configuration set, so one named only by header
cannot slip past the association check.

Fix tryBase64Decode, which decoded every raw message with the MIME decoder and
only fell back to plain text when it threw. That decoder skips characters
outside the base64 alphabet rather than rejecting them, so a plain-text RFC
5322 message decoded into garbage whenever the surviving alphabet characters
happened to form a valid length, wiping its headers. The alphabet is now
checked before decoding.

Replace the nine-argument SmtpRelay.relay with a RelayMessage record, and add
a ServerSocket-based SMTP test that drives a real MailClient end to end and
asserts on the negotiated envelope and the bytes on the wire, covering the
authentication and STARTTLS-OPTIONAL configuration branches.

* fix(ses): align SMTP relay with documented AWS header and tag semantics

Verified the relay against the SES documentation and corrected four
deviations.

AWS overrides a caller-supplied Message-ID with the id it assigned, and
rejects Message-ID outright as a custom header on Simple and Templated
content (SES header fields reference). The relay preserved a caller's value
instead; it now always stamps the id returned by the API.

AWS likewise overrides a caller-supplied Date with the time it accepted the
message. The relay copied the caller's Date through, so a stale timestamp
reached the recipient. Date is now regenerated with the rest of the headers
SES sets.

AWS uses only the request field's message tags when tags are supplied both
as a request field and as an X-SES-MESSAGE-TAGS header, and explicitly does
not join the two sets. The relay merged them, letting a header-only tag
survive a request that supplied its own. Header tags now apply only when the
request passes none.

The stamped Message-ID domain was region-scoped, which no AWS documentation
or observed output supports. Use the observed email.amazonses.com instead,
and record in the docs that only the local part, which is the returned
MessageId, is documented behaviour.

Also document that AWS delivers a Return-Path differing from the one
supplied, because it routes bounces through its own address, whereas Floci
has no bounce pipeline and puts the resolved address directly in MAIL FROM.

* fix(ses): align mime4j artifacts to unbreak the native build

The raw relay's new DefaultMessageWriter path failed GraalVM analysis with
an unresolved reference to Field.getSafeRaw(). apache-mime4j-dom was pinned
to 0.8.14 while the Quarkus BOM manages apache-mime4j-core at 0.8.12, so the
writer was compiled against a Field API the resolved core does not declare.
Nothing reached the writer before this branch, which is why the skew only
surfaced now, and only in native builds.

Drop the hardcoded -dom version so both artifacts track the BOM together,
and cover the embedded message/rfc822 branch that exercises the writer.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-12 23:27:38 -05:00
1 parent 325bdfb30e
commit 505b5d286e
17 files changed
+1790 -266

No files matched your search

@@ -39,6 +39,7 @@ 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;
@@ -941,7 +942,7 @@ class CognitoLambdaTriggersTest {
verify(ses).sendEmail(
anyString(), eq(List.of("spike@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()),
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(), anyString());
@@ -998,7 +999,7 @@ class CognitoLambdaTriggersTest {
verify(ses).sendEmail(
anyString(), eq(List.of("spike@example.com")),
any(), any(), any(),
any(), any(), any(), isNull(),
eq("Your verification code"),
eq("Your verification code is 246962."),
any(), any(), any(), any(), any(), anyString());
@@ -1022,7 +1023,7 @@ class CognitoLambdaTriggersTest {
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
verify(ses).sendEmail(
anyString(), eq(List.of("spike@example.com")),
any(), any(), any(),
any(), any(), any(), isNull(),
eq("Your verification code"),
eq("Your verification code is 246962."),
any(), any(), any(), any(), any(), anyString());
@@ -46,7 +46,7 @@ class CognitoMessageDispatcherTest {
verify(ses).sendEmail(
anyString(),
eq(List.of("alice@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()),
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()),
@@ -102,7 +102,7 @@ class CognitoMessageDispatcherTest {
verify(ses).sendEmail(
anyString(), eq(List.of("alice@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()),
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(), eq("us-east-1"));
@@ -118,7 +118,7 @@ class CognitoMessageDispatcherTest {
verify(ses).sendEmail(
anyString(), eq(List.of("alice@example.com")),
eq(List.of()), eq(List.of()), eq(List.of()),
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(), eq("us-east-1"));
@@ -133,7 +133,8 @@ class CognitoMessageDispatcherTest {
"444555", List.of());
verify(ses).sendEmail(anyString(), eq(List.of("alice@example.com")),
any(), any(), any(), anyString(), anyString(), isNull(), isNull(), any(), any(), isNull(), anyString());
any(), any(), any(), isNull(), anyString(), anyString(), isNull(), isNull(), any(), any(),
isNull(), anyString());
verifyNoInteractions(sns);
}
@@ -1677,4 +1677,77 @@ class SesEventPublishingV2IntegrationTest {
.then()
.statusCode(200);
}
@Test
@Order(30)
void v1SendRawEmail_xSesControlHeaders_selectConfigurationSetAndSupplyTags() throws Exception {
drainQueue();
// Neither ConfigurationSetName nor Tags is sent as a request field: AWS reads both from the
// message itself on a raw send, so the events only reach the topic if the headers are honoured.
String raw = "From: " + SENDER + "\r\n"
+ "To: success@simulator.amazonses.com\r\n"
+ "Subject: header-driven\r\n"
+ "X-SES-CONFIGURATION-SET: " + CS + "\r\n"
+ "X-SES-MESSAGE-TAGS: campaign=headercampaign, env=headerenv\r\n"
+ "\r\nbody";
String rawB64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SES_AUTH)
.body("Action=SendRawEmail"
+ "&Source=" + java.net.URLEncoder.encode(SENDER, java.nio.charset.StandardCharsets.UTF_8)
+ "&RawMessage.Data=" + java.net.URLEncoder.encode(rawB64, java.nio.charset.StandardCharsets.UTF_8)
+ "&Version=2010-12-01")
.when()
.post("/")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
JsonNode send = events.stream()
.filter(e -> "Send".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
JsonNode tags = send.path("mail").path("tags");
assertEquals(CS, tags.path("ses:configuration-set").get(0).asText());
assertEquals("headercampaign", tags.path("campaign").get(0).asText());
assertEquals("headerenv", tags.path("env").get(0).asText());
}
@Test
@Order(31)
void v1SendRawEmail_requestTagsReplaceTheHeaderTagsEntirely() throws Exception {
drainQueue();
String raw = "From: " + SENDER + "\r\n"
+ "To: success@simulator.amazonses.com\r\n"
+ "Subject: header-vs-request\r\n"
+ "X-SES-MESSAGE-TAGS: campaign=fromheader, only=inheader\r\n"
+ "\r\nbody";
String rawB64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SES_AUTH)
.body("Action=SendRawEmail"
+ "&Source=" + java.net.URLEncoder.encode(SENDER, java.nio.charset.StandardCharsets.UTF_8)
+ "&RawMessage.Data=" + java.net.URLEncoder.encode(rawB64, java.nio.charset.StandardCharsets.UTF_8)
+ "&Tags.member.1.Name=campaign&Tags.member.1.Value=fromrequest"
+ "&ConfigurationSetName=" + CS
+ "&Version=2010-12-01")
.when()
.post("/")
.then()
.statusCode(200);
List<JsonNode> events = receiveSesEvents(2);
JsonNode send = events.stream()
.filter(e -> "Send".equals(e.path("eventType").asText()))
.findFirst().orElseThrow();
JsonNode tags = send.path("mail").path("tags");
assertEquals("fromrequest", tags.path("campaign").get(0).asText());
// AWS uses only the API parameter's tags when both are given and does not join the two
// sets, so a header-only tag is dropped rather than merged in.
assertTrue(tags.path("only").isMissingNode() || tags.path("only").isEmpty(),
"header tags must be discarded entirely when the request supplies tags: " + tags);
}
}
@@ -446,6 +446,65 @@ class SesIntegrationTest {
.body("messages[0].ReplyToAddresses", hasItem("reply@example.com"));
}
@Test
@Order(21)
void sendEmailV1_returnPathStoredInInspection() {
given().delete("/_aws/ses").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
.formParam("Action", "SendEmail")
.formParam("Source", "sender@example.com")
.formParam("Destination.ToAddresses.member.1", "recipient@example.com")
.formParam("ReturnPath", "bounces@example.com")
.formParam("Message.Subject.Data", "V1 ReturnPath")
.formParam("Message.Body.Text.Data", "body")
.when()
.post("/")
.then()
.statusCode(200);
given()
.when()
.get("/_aws/ses")
.then()
.statusCode(200)
.body("messages[0].ReturnPath", equalTo("bounces@example.com"));
}
@Test
@Order(21)
void sendRawEmailV1_returnPathHeaderStoredInInspection() {
given().delete("/_aws/ses").then().statusCode(200);
String raw = "From: sender@example.com\r\n"
+ "To: recipient@example.com\r\n"
+ "Return-Path: <mime-bounces@example.com>\r\n"
+ "Subject: raw-return-path\r\n\r\nbody";
String rawB64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
.formParam("Action", "SendRawEmail")
.formParam("Source", "sender@example.com")
.formParam("Destinations.member.1", "recipient@example.com")
.formParam("RawMessage.Data", rawB64)
.when()
.post("/")
.then()
.statusCode(200);
given()
.when()
.get("/_aws/ses")
.then()
.statusCode(200)
.body("messages[0].ReturnPath", equalTo("mime-bounces@example.com"));
}
@Test
@Order(22)
void deleteDomainIdentity() {
@@ -62,17 +62,21 @@ class SesServiceListManagementTest {
}
private void send(List<String> to, String topicName) {
service.sendEmail(FROM, to, null, null, null, "Subject", "body", null,
service.sendEmail(FROM, to, null, 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());
private SmtpRelay.RelayMessage capturedRelay() {
ArgumentCaptor<SmtpRelay.RelayMessage> captor =
ArgumentCaptor.forClass(SmtpRelay.RelayMessage.class);
verify(smtpRelay).relay(captor.capture());
return captor.getValue();
}
private List<String> capturedRelayTo() {
return capturedRelay().to();
}
@Test
void unsubscribeAll_isSuppressed_evenWithNoTopic() {
send(List.of("unsub@example.com", "sportsin@example.com"), null);
@@ -96,7 +100,7 @@ class SesServiceListManagementTest {
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());
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
}
@Test
@@ -116,7 +120,7 @@ class SesServiceListManagementTest {
@Test
void nonExistentContactList_failsTheSend() {
AwsException ex = assertThrows(AwsException.class, () ->
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null,
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), REGION));
assertEquals(404, ex.getHttpStatus());
@@ -126,7 +130,7 @@ 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,
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null, null,
"Subject", "body", null, null, List.of(), List.of(),
new ListManagementOptions(LIST, "GhostTopic"), REGION));
assertEquals(400, ex.getHttpStatus());
@@ -136,7 +140,7 @@ 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,
service.sendEmail(FROM, List.of("unsub@example.com"), null, null, null, null,
"Subject", "body", null, null, List.of(), List.of(), null, REGION);
assertEquals(List.of("unsub@example.com"), capturedRelayTo());
}
@@ -144,7 +148,7 @@ class SesServiceListManagementTest {
@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,
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"), REGION);
String html = capturedRelayBodyHtml();
@@ -157,7 +161,7 @@ class SesServiceListManagementTest {
@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, "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");
@@ -199,23 +203,17 @@ class SesServiceListManagementTest {
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();
return capturedRelay().bodyHtml();
}
@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();
return capturedRelay().headers();
}
@Test
void singleRecipient_addsListUnsubscribeHeadersToRelay() {
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
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"), REGION);
List<MessageHeader> headers = capturedRelayHeaders();
@@ -227,7 +225,7 @@ class SesServiceListManagementTest {
@Test
void callerSuppliedUnsubscribeHeader_isOverriddenNotDuplicated() {
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
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"), REGION);
@@ -9,6 +9,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -29,68 +31,140 @@ class SesServiceSmtpTest {
service = builder.build();
}
private SentEmail storedEmail(String messageId) {
return service.getEmails().stream()
.filter(e -> messageId.equals(e.getMessageId()))
.findFirst()
.orElseThrow();
}
private SmtpRelay.RelayMessage capturedRelay() {
ArgumentCaptor<SmtpRelay.RelayMessage> captor =
ArgumentCaptor.forClass(SmtpRelay.RelayMessage.class);
verify(smtpRelay).relay(captor.capture());
return captor.getValue();
}
private SmtpRelay.RawRelayMessage capturedRawRelay() {
ArgumentCaptor<SmtpRelay.RawRelayMessage> captor =
ArgumentCaptor.forClass(SmtpRelay.RawRelayMessage.class);
verify(smtpRelay).relayRaw(captor.capture());
return captor.getValue();
}
@Test
void sendEmail_callsRelayWithAllFields() {
service.sendEmail("from@example.com",
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, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
List.of("to@example.com"),
List.of("cc@example.com"),
List.of("bcc@example.com"),
List.of("reply@example.com"),
"Subject", "text body", "<p>html</p>", List.of());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals("from@example.com", relayed.from());
assertEquals(List.of("to@example.com"), relayed.to());
assertEquals(List.of("cc@example.com"), relayed.cc());
assertEquals(List.of("bcc@example.com"), relayed.bcc());
assertEquals(List.of("reply@example.com"), relayed.replyTo());
assertEquals("Subject", relayed.subject());
assertEquals("text body", relayed.bodyText());
assertEquals("<p>html</p>", relayed.bodyHtml());
assertEquals(List.of(), relayed.headers());
assertEquals(messageId, relayed.messageId());
}
@Test
void sendEmail_storesAndRelays() {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
List.of("to@example.com"), null, null, null, null,
"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(), any());
verify(smtpRelay).relay(any(SmtpRelay.RelayMessage.class));
}
@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, "us-east-1");
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, "us-east-1");
assertEquals("bounces@example.com", capturedRelay().returnPath());
assertEquals("bounces@example.com", storedEmail(messageId).getReturnPath());
}
@Test
void sendRawEmail_callsRelayRaw() {
service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, List.of(), null, "us-east-1");
String messageId = service.sendRawEmail("from@example.com",
List.of("to@example.com"), "raw MIME", null, null, List.of(), null, "us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
List.of("to@example.com"),
"raw MIME");
SmtpRelay.RawRelayMessage relayed = capturedRawRelay();
assertEquals("from@example.com", relayed.from());
assertEquals(List.of("to@example.com"), relayed.destinations());
assertEquals("raw MIME", relayed.rawMessage());
assertEquals(messageId, relayed.messageId());
}
@Test
void sendRawEmail_returnPathHeader_winsOverRequestField() {
String raw = "From: from@example.com\r\n"
+ "To: to@example.com\r\n"
+ "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, "us-east-1");
assertEquals("mime-bounces@example.com", capturedRawRelay().returnPath());
assertEquals("mime-bounces@example.com", storedEmail(messageId).getReturnPath());
}
@Test
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, "us-east-1");
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, List.of(), null, "us-east-1");
List.of("to@example.com"), "raw", null, null, List.of(), null, "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
verify(smtpRelay).relayRaw(any(), any(), any());
verify(smtpRelay).relayRaw(any(SmtpRelay.RawRelayMessage.class));
}
@Test
void sendEmail_relayReceivesCorrectFieldsWithNulls() {
service.sendEmail("from@example.com",
List.of("to@example.com"),
null, null, null,
null, null, null, null,
"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>", List.of());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals(List.of("to@example.com"), relayed.to());
assertNull(relayed.cc());
assertNull(relayed.bcc());
assertNull(relayed.replyTo());
assertNull(relayed.bodyText());
assertEquals("<p>html only</p>", relayed.bodyHtml());
}
@Test
@@ -101,13 +175,13 @@ class SesServiceSmtpTest {
String messageId = service.sendEmail("from@example.com",
List.of("to@example.com"),
List.of("cc@example.com"),
null, null,
null, null, null,
"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(), any());
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
}
@Test
@@ -118,16 +192,12 @@ class SesServiceSmtpTest {
service.sendEmail("from@example.com",
List.of("to@example.com", "suppressed@example.com"),
List.of("cc-keep@example.com"),
null, null,
null, null, null,
"Subject", "text body", null, null, List.of(), List.of(), null, "us-east-1");
verify(smtpRelay).relay(
"from@example.com",
List.of("to@example.com"),
List.of("cc-keep@example.com"),
null,
null,
"Subject", "text body", null, List.of());
SmtpRelay.RelayMessage relayed = capturedRelay();
assertEquals(List.of("to@example.com"), relayed.to());
assertEquals(List.of("cc-keep@example.com"), relayed.cc());
}
@Test
@@ -135,11 +205,11 @@ 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(), null, "us-east-1");
List.of("to@example.com"), "raw MIME", null, null, List.of(), null, "us-east-1");
assertNotNull(messageId);
assertFalse(emailStore.scan(k -> true).isEmpty());
verify(smtpRelay, never()).relayRaw(any(), any(), any());
verify(smtpRelay, never()).relayRaw(any(SmtpRelay.RawRelayMessage.class));
}
@Test
@@ -148,12 +218,9 @@ class SesServiceSmtpTest {
service.sendRawEmail("from@example.com",
List.of("to@example.com", "suppressed@example.com"),
"raw MIME", null, List.of(), null, "us-east-1");
"raw MIME", null, null, List.of(), null, "us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
List.of("to@example.com"),
"raw MIME");
assertEquals(List.of("to@example.com"), capturedRawRelay().destinations());
}
// ─────────── Per-CS SuppressionOptions override at send time ───────────
@@ -169,14 +236,10 @@ class SesServiceSmtpTest {
service.putConfigurationSetSuppressionOptions("cs-no-suppression", List.of(), "us-east-1");
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
List.of("to@example.com"), null, null, null, null,
"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, List.of());
assertEquals(List.of("to@example.com"), capturedRelay().to());
}
@Test
@@ -189,14 +252,10 @@ class SesServiceSmtpTest {
service.putConfigurationSetSuppressionOptions("cs-bounce-only", List.of("BOUNCE"), "us-east-1");
service.sendEmail("from@example.com",
List.of("complainer@example.com"), null, null, null,
List.of("complainer@example.com"), null, null, null, null,
"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, List.of());
assertEquals(List.of("complainer@example.com"), capturedRelay().to());
}
@Test
@@ -208,10 +267,10 @@ class SesServiceSmtpTest {
service.createConfigurationSet(new ConfigurationSet("cs-default"), "us-east-1");
service.sendEmail("from@example.com",
List.of("to@example.com"), null, null, null,
List.of("to@example.com"), null, null, null, null,
"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(), any());
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
}
@Test
@@ -221,11 +280,9 @@ 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(), null, "us-east-1");
List.of("to@example.com"), "raw MIME", null, "cs-no-suppression-raw", List.of(), null,
"us-east-1");
verify(smtpRelay).relayRaw(
"from@example.com",
List.of("to@example.com"),
"raw MIME");
assertEquals(List.of("to@example.com"), capturedRawRelay().destinations());
}
}
@@ -0,0 +1,345 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.vertx.core.Vertx;
import io.vertx.ext.mail.MailClient;
import io.vertx.ext.mail.MailConfig;
import io.vertx.ext.mail.StartTLSOptions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Drives the relay through a real Vert.x {@link MailClient} against an in-process SMTP server, so
* the assertions cover what a mocked client cannot: the SMTP envelope actually negotiated, and the
* bytes the encoder puts on the wire.
*/
class SmtpRelayServerTest {
private static StubSmtpServer server;
private static Vertx vertx;
private final List<MailClient> clients = new ArrayList<>();
@BeforeAll
static void startServer() throws IOException {
server = new StubSmtpServer();
vertx = Vertx.vertx();
}
@AfterEach
void closeClients() {
// Vert.x pools SMTP connections, so an unclosed client keeps its socket open and the next
// test would assert against a stale session.
clients.forEach(MailClient::close);
clients.clear();
}
@AfterAll
static void stopServer() throws IOException {
server.close();
vertx.close();
}
/**
* Builds the relay the way CDI would, then swaps in the synchronous-executor constructor so the
* assertions run after delivery rather than racing it. The authentication and STARTTLS-OPTIONAL
* branches of {@link SmtpRelay#buildMailConfig} are exercised on the way through.
*/
private SmtpRelay relayAgainstServer() {
MailConfig mailConfig = SmtpRelay.buildMailConfig(
config("relay-user", "relay-pass", "OPTIONAL"),
server.host(), server.port());
MailClient client = MailClient.create(vertx, mailConfig);
clients.add(client);
return new SmtpRelay(client, true);
}
private static EmulatorConfig config(String user, String pass, String starttls) {
EmulatorConfig config = mock(EmulatorConfig.class, org.mockito.Mockito.RETURNS_DEEP_STUBS);
when(config.services().ses().smtpUser()).thenReturn(Optional.ofNullable(user));
when(config.services().ses().smtpPass()).thenReturn(Optional.ofNullable(pass));
when(config.services().ses().smtpStarttls()).thenReturn(starttls);
return config;
}
@Test
void rawRelay_deliversEnvelopeHeadersAndAttachmentOverSmtp() throws Exception {
server.reset();
String attachmentBody = Base64.getEncoder().encodeToString(
"PDF-PAYLOAD".getBytes(StandardCharsets.UTF_8));
String rawMime = "From: Alice Sender <sender@example.com>\r\n"
+ "To: Bob <to@example.com>\r\n"
+ "Subject: Real SMTP\r\n"
+ "Return-Path: <bounces@example.com>\r\n"
+ "X-Custom: keep-me\r\n"
+ "X-SES-CONFIGURATION-SET: my-config-set\r\n"
+ "MIME-Version: 1.0\r\n"
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n"
+ "\r\n"
+ "--outer\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "the real body\r\n"
+ "--outer\r\n"
+ "Content-Type: application/pdf\r\n"
+ "Content-Disposition: attachment; filename=\"report.pdf\"\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "\r\n"
+ attachmentBody + "\r\n"
+ "--outer--";
relayAgainstServer().relayRaw(new SmtpRelay.RawRelayMessage("sender@example.com",
"bounces@example.com", List.of("dest@example.com"), rawMime, "msg-42"));
assertTrue(server.awaitDelivery(), "the stub server should have accepted a message");
assertEquals("bounces@example.com", server.mailFrom(),
"the Return-Path must become the SMTP envelope sender");
assertEquals(List.of("dest@example.com"), server.recipients());
String data = server.data();
assertTrue(data.contains("Message-ID: <msg-42@email.amazonses.com>"), data);
assertTrue(data.contains("From: Alice Sender <sender@example.com>"),
"the display name must survive the relay: " + data);
assertTrue(data.contains("X-Custom: keep-me"), data);
assertTrue(data.contains("the real body"), data);
assertTrue(data.contains("report.pdf"), data);
assertTrue(data.contains(attachmentBody), "the attachment payload must survive the relay");
// AWS consumes the X-SES-* control headers rather than forwarding them.
assertFalse(data.contains("X-SES-CONFIGURATION-SET"), data);
// The caller's Content-Type described the original tree, which the encoder has rebuilt.
assertFalse(data.contains("boundary=\"outer\""), data);
}
@Test
void structuredRelay_usesReturnPathAsEnvelopeSenderAndStampsMessageId() throws Exception {
server.reset();
relayAgainstServer().relay(SmtpRelay.RelayMessage.builder("sender@example.com")
.returnPath("bounces@example.com")
.to(List.of("to@example.com"))
.cc(List.of("cc@example.com"))
.subject("Structured")
.bodyText("plain body")
.headers(List.of(new MessageHeader("X-Custom", "kept")))
.messageId("msg-7")
.build());
assertTrue(server.awaitDelivery(), "the stub server should have accepted a message");
assertEquals("bounces@example.com", server.mailFrom());
assertEquals(List.of("to@example.com", "cc@example.com"), server.recipients());
String data = server.data();
assertTrue(data.contains("Message-ID: <msg-7@email.amazonses.com>"), data);
assertTrue(data.contains("X-Custom: kept"), data);
assertTrue(data.contains("plain body"), data);
}
@Test
void relay_authenticatesWithTheConfiguredCredentials() throws Exception {
server.reset();
relayAgainstServer().relay(SmtpRelay.RelayMessage.builder("sender@example.com")
.to(List.of("to@example.com"))
.subject("Auth")
.bodyText("body")
.build());
assertTrue(server.awaitDelivery());
String auth = server.authCommand();
assertNotNull(auth, "the relay should authenticate when smtp-user is configured");
String credentials = new String(Base64.getDecoder().decode(auth.substring("AUTH PLAIN ".length())),
StandardCharsets.UTF_8);
assertEquals("\0relay-user\0relay-pass", credentials);
}
@Test
void buildMailConfig_mapsStarttlsModesAndFallsBackToDisabled() {
assertEquals(StartTLSOptions.REQUIRED,
SmtpRelay.buildMailConfig(config(null, null, "required"), "h", 25).getStarttls());
assertEquals(StartTLSOptions.OPTIONAL,
SmtpRelay.buildMailConfig(config(null, null, "OPTIONAL"), "h", 25).getStarttls());
assertEquals(StartTLSOptions.DISABLED,
SmtpRelay.buildMailConfig(config(null, null, "DISABLED"), "h", 25).getStarttls());
assertEquals(StartTLSOptions.DISABLED,
SmtpRelay.buildMailConfig(config(null, null, "nonsense"), "h", 25).getStarttls());
}
@Test
void buildMailConfig_withoutAUsername_leavesCredentialsUnset() {
MailConfig mailConfig = SmtpRelay.buildMailConfig(config(" ", "pass", "DISABLED"), "h", 25);
assertNull(mailConfig.getUsername());
assertNull(mailConfig.getPassword());
}
/**
* A minimal SMTP server: enough of the protocol for a real {@link MailClient} to complete a
* session, capturing the envelope and the DATA payload.
*/
private static final class StubSmtpServer implements AutoCloseable {
private final ServerSocket serverSocket;
private final Thread acceptThread;
private volatile java.util.concurrent.CountDownLatch delivered =
new java.util.concurrent.CountDownLatch(1);
private volatile String mailFrom;
private volatile String authCommand;
private volatile String data;
private volatile List<String> recipients = new ArrayList<>();
StubSmtpServer() throws IOException {
serverSocket = new ServerSocket(0, 16, InetAddress.getLoopbackAddress());
acceptThread = new Thread(this::acceptLoop, "stub-smtp");
acceptThread.setDaemon(true);
acceptThread.start();
}
String host() {
return serverSocket.getInetAddress().getHostAddress();
}
int port() {
return serverSocket.getLocalPort();
}
void reset() {
delivered = new java.util.concurrent.CountDownLatch(1);
mailFrom = null;
authCommand = null;
data = null;
recipients = new ArrayList<>();
}
boolean awaitDelivery() throws InterruptedException {
return delivered.await(20, java.util.concurrent.TimeUnit.SECONDS);
}
String mailFrom() {
return mailFrom;
}
List<String> recipients() {
return recipients;
}
String data() {
return data;
}
String authCommand() {
return authCommand;
}
private void acceptLoop() {
while (!serverSocket.isClosed()) {
try {
Socket socket = serverSocket.accept();
// Vert.x keeps the connection pooled after a send, so the session is handled off
// the accept loop: otherwise the first idle connection blocks every later test.
Thread worker = new Thread(() -> {
try (socket) {
converse(socket);
} catch (IOException e) {
// The client closed the pooled connection; nothing left to serve.
}
}, "stub-smtp-session");
worker.setDaemon(true);
worker.start();
} catch (IOException e) {
if (!serverSocket.isClosed()) {
throw new IllegalStateException("stub SMTP server failed", e);
}
return;
}
}
}
private void converse(Socket socket) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
reply(out, "220 floci-stub ESMTP");
String line;
while ((line = in.readLine()) != null) {
String command = line.toUpperCase(Locale.ROOT);
if (command.startsWith("EHLO")) {
reply(out, "250-floci-stub");
reply(out, "250 AUTH PLAIN");
} else if (command.startsWith("HELO")) {
reply(out, "250 floci-stub");
} else if (command.startsWith("AUTH")) {
authCommand = line;
reply(out, "235 2.7.0 Authentication successful");
} else if (command.startsWith("MAIL FROM")) {
mailFrom = address(line);
reply(out, "250 OK");
} else if (command.startsWith("RCPT TO")) {
recipients.add(address(line));
reply(out, "250 OK");
} else if (command.startsWith("DATA")) {
reply(out, "354 End data with <CR><LF>.<CR><LF>");
data = readData(in);
reply(out, "250 OK: queued");
delivered.countDown();
} else if (command.startsWith("QUIT")) {
reply(out, "221 Bye");
return;
} else if (command.startsWith("RSET") || command.startsWith("NOOP")) {
reply(out, "250 OK");
} else {
reply(out, "500 Unrecognized command");
}
}
}
private static String readData(BufferedReader in) throws IOException {
StringBuilder body = new StringBuilder();
String line;
while ((line = in.readLine()) != null && !".".equals(line)) {
// Undo the dot-stuffing the client applies to lines starting with a period.
body.append(line.startsWith("..") ? line.substring(1) : line).append("\r\n");
}
return body.toString();
}
private static String address(String line) {
int start = line.indexOf('<');
int end = line.indexOf('>', start + 1);
return start >= 0 && end > start ? line.substring(start + 1, end) : "";
}
private static void reply(BufferedWriter out, String response) throws IOException {
out.write(response);
out.write("\r\n");
out.flush();
}
@Override
public void close() throws IOException {
serverSocket.close();
}
}
}
@@ -1,7 +1,9 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
import io.github.hectorvent.floci.services.ses.model.MessageTag;
import io.vertx.core.Future;
import io.vertx.ext.mail.MailAttachment;
import io.vertx.ext.mail.MailClient;
import io.vertx.ext.mail.MailMessage;
import io.vertx.ext.mail.MailResult;
@@ -22,6 +24,19 @@ class SmtpRelayTest {
@Mock MailClient mailClient;
private static SmtpRelay.RelayMessage simple(String text) {
return SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyText(text)
.headers(List.of())
.build();
}
private static SmtpRelay.RawRelayMessage raw(String from, List<String> destinations, String rawMessage) {
return new SmtpRelay.RawRelayMessage(from, null, destinations, rawMessage, null);
}
private SmtpRelay enabledRelay() {
when(mailClient.sendMail(any(MailMessage.class)))
.thenReturn(Future.succeededFuture(new MailResult()));
@@ -33,8 +48,7 @@ class SmtpRelayTest {
SmtpRelay relay = new SmtpRelay(mailClient, false);
assertFalse(relay.isEnabled());
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "text", null, List.of());
relay.relay(simple("text"));
verify(mailClient, never()).sendMail(any(MailMessage.class));
}
@@ -43,14 +57,16 @@ class SmtpRelayTest {
void relay_whenEnabled_sendsMail() {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com",
List.of("to@example.com"),
List.of("cc@example.com"),
List.of("bcc@example.com"),
List.of("reply@example.com"),
"Test Subject",
"plain text",
"<p>html</p>", List.of());
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.cc(List.of("cc@example.com"))
.bcc(List.of("bcc@example.com"))
.replyTo(List.of("reply@example.com"))
.subject("Test Subject")
.bodyText("plain text")
.bodyHtml("<p>html</p>")
.headers(List.of())
.build());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -70,8 +86,7 @@ class SmtpRelayTest {
void relay_noReplyTo_omitsHeader() {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "text", null, List.of());
relay.relay(simple("text"));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -82,12 +97,16 @@ class SmtpRelayTest {
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(
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyText("text")
.headers(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")));
new MessageHeader("", "no-name")))
.build());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -106,8 +125,7 @@ class SmtpRelayTest {
void relay_textOnly_setsTextWithoutHtml() {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", "only text", null, List.of());
relay.relay(simple("only text"));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -119,8 +137,11 @@ class SmtpRelayTest {
void relay_htmlOnly_setsHtmlWithoutText() {
SmtpRelay relay = enabledRelay();
relay.relay("from@example.com", List.of("to@example.com"),
null, null, null, "Subject", null, "<b>html</b>", List.of());
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyHtml("<b>html</b>")
.build());
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -134,8 +155,7 @@ class SmtpRelayTest {
when(mailClient.sendMail(any(MailMessage.class)))
.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()));
assertDoesNotThrow(() -> relay.relay(simple("text")));
}
// ── Raw relay ──
@@ -144,7 +164,7 @@ class SmtpRelayTest {
void relayRaw_whenDisabled_doesNotSend() {
SmtpRelay relay = new SmtpRelay(mailClient, false);
relay.relayRaw("from@example.com", List.of("to@example.com"), "raw");
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), "raw"));
verify(mailClient, never()).sendMail(any(MailMessage.class));
}
@@ -159,7 +179,7 @@ class SmtpRelayTest {
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "Raw body content";
relay.relayRaw("envelope@example.com", List.of("dest@example.com"), rawMime);
relay.relayRaw(raw("envelope@example.com", List.of("dest@example.com"), rawMime));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -178,7 +198,7 @@ class SmtpRelayTest {
String rawMime = "From: s@example.com\r\nTo: t@example.com\r\nSubject: B64\r\n\r\nDecoded body";
String encoded = java.util.Base64.getEncoder().encodeToString(
rawMime.getBytes(java.nio.charset.StandardCharsets.UTF_8));
relay.relayRaw("from@example.com", List.of("to@example.com"), encoded);
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), encoded));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -192,7 +212,7 @@ class SmtpRelayTest {
String rawMime = "From: s@example.com\r\nTo: t@example.com\r\nSubject: HTML\r\n"
+ "Content-Type: text/html; charset=UTF-8\r\n\r\n<h1>Hello</h1>";
relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime);
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -212,7 +232,7 @@ class SmtpRelayTest {
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "body";
relay.relayRaw("envelope@example.com", null, rawMime);
relay.relayRaw(raw("envelope@example.com", null, rawMime));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -227,7 +247,7 @@ class SmtpRelayTest {
SmtpRelay relay = enabledRelay();
String rawMime = "Subject: NoAddr\r\n\r\nBody";
relay.relayRaw("envelope@example.com", List.of("dest@example.com"), rawMime);
relay.relayRaw(raw("envelope@example.com", List.of("dest@example.com"), rawMime));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -257,7 +277,7 @@ class SmtpRelayTest {
+ "<p>html</p>\r\n"
+ "--inner--\r\n"
+ "--outer--";
relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime);
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -284,7 +304,7 @@ class SmtpRelayTest {
+ "\r\n"
+ "attachment content that must not clobber body\r\n"
+ "--outer--";
relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime);
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
@@ -297,8 +317,8 @@ class SmtpRelayTest {
when(mailClient.sendMail(any(MailMessage.class)))
.thenReturn(Future.failedFuture(new RuntimeException("SMTP timeout")));
assertDoesNotThrow(() -> relay.relayRaw("from@example.com",
List.of("to@example.com"), "Subject: X\r\n\r\nBody"));
assertDoesNotThrow(() -> relay.relayRaw(raw("from@example.com",
List.of("to@example.com"), "Subject: X\r\n\r\nBody")));
}
@Test
@@ -321,6 +341,25 @@ class SmtpRelayTest {
assertEquals(List.of("only@example.com"), SmtpRelay.parseRawRecipients(b64));
}
@Test
void tryBase64Decode_plainTextMime_isNotTreatedAsBase64() {
// The MIME decoder skips characters outside the base64 alphabet, so a plain-text message
// whose remaining alphabet characters happen to form a valid length would otherwise decode
// into garbage.
String raw = "From: s@example.com\r\nMessage-ID: <caller@example.com>\r\nSubject: x\r\n\r\nbody";
assertEquals(raw, new String(SmtpRelay.tryBase64Decode(raw),
java.nio.charset.StandardCharsets.UTF_8));
}
@Test
void tryBase64Decode_base64Payload_isDecoded() {
String raw = "From: s@example.com\r\nSubject: x\r\n\r\nbody";
String encoded = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
assertEquals(raw, new String(SmtpRelay.tryBase64Decode(encoded),
java.nio.charset.StandardCharsets.UTF_8));
}
@Test
void parseRawRecipients_blankOrUnparseable_returnsEmpty() {
assertTrue(SmtpRelay.parseRawRecipients(null).isEmpty());
@@ -358,4 +397,392 @@ class SmtpRelayTest {
assertTrue(h.cc().isEmpty());
assertTrue(h.bcc().isEmpty());
}
@Test
void parseRawHeaders_extractsReturnPathAndSesControlHeaders() {
String raw = "From: sender@example.com\r\n"
+ "To: to@example.com\r\n"
+ "Return-Path: <bounces@example.com>\r\n"
+ "X-SES-CONFIGURATION-SET: my-config-set\r\n"
+ "X-SES-MESSAGE-TAGS: campaign=spring, tier=gold\r\n"
+ "Subject: x\r\n\r\nbody";
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(raw);
assertEquals("bounces@example.com", h.returnPath());
assertEquals("my-config-set", h.configurationSet());
assertEquals(List.of(new MessageTag("campaign", "spring"), new MessageTag("tier", "gold")),
h.messageTags());
}
@Test
void parseRawHeaders_withoutSesHeaders_returnsBlanksAndNoTags() {
String raw = "From: sender@example.com\r\nTo: to@example.com\r\nSubject: x\r\n\r\nbody";
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(raw);
assertEquals("", h.returnPath());
assertEquals("", h.configurationSet());
assertTrue(h.messageTags().isEmpty());
}
@Test
void parseMessageTagsHeader_skipsEntriesWithoutAName() {
assertEquals(List.of(new MessageTag("ok", "1")),
SmtpRelay.parseMessageTagsHeader("ok=1, =2, novalueseparator"));
assertTrue(SmtpRelay.parseMessageTagsHeader(null).isEmpty());
assertTrue(SmtpRelay.parseMessageTagsHeader(" ").isEmpty());
}
@Test
void formatMessageId_usesTheReturnedMessageIdAsTheLocalPart() {
assertEquals("<abc-123@email.amazonses.com>", SmtpRelay.formatMessageId("abc-123"));
assertNull(SmtpRelay.formatMessageId(null));
assertNull(SmtpRelay.formatMessageId(" "));
}
// ── Envelope sender and Message-ID ──
@Test
void relay_returnPath_becomesTheEnvelopeSender() {
SmtpRelay relay = enabledRelay();
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.returnPath("bounces@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyText("text")
.build());
assertEquals("bounces@example.com", captureSent().getBounceAddress());
}
@Test
void relay_noReturnPath_envelopeSenderFallsBackToFrom() {
SmtpRelay relay = enabledRelay();
relay.relay(simple("text"));
assertEquals("from@example.com", captureSent().getBounceAddress());
}
@Test
void relay_stampsMessageIdInTheAwsFormat() {
SmtpRelay relay = enabledRelay();
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyText("text")
.messageId("msg-1")
.build());
assertEquals("<msg-1@email.amazonses.com>",
captureSent().getHeaders().get("Message-ID"));
}
@Test
void relay_callerSuppliedMessageIdHeader_isOverridden() {
SmtpRelay relay = enabledRelay();
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
.to(List.of("to@example.com"))
.subject("Subject")
.bodyText("text")
.headers(List.of(new MessageHeader("Message-ID", "<caller@example.com>")))
.messageId("msg-1")
.build());
// AWS overrides a caller-supplied Message-ID with the id it assigned.
assertEquals(List.of("<msg-1@email.amazonses.com>"),
captureSent().getHeaders().getAll("Message-ID"));
}
@Test
void relayRaw_returnPath_becomesTheEnvelopeSender() {
SmtpRelay relay = enabledRelay();
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", "bounces@example.com",
List.of("to@example.com"), "From: s@example.com\r\nSubject: x\r\n\r\nbody",
"msg-1"));
assertEquals("bounces@example.com", captureSent().getBounceAddress());
}
@Test
void relayRaw_stampsMessageIdWhenTheMessageHasNone() {
SmtpRelay relay = enabledRelay();
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", null,
List.of("to@example.com"), "From: s@example.com\r\nSubject: x\r\n\r\nbody",
"msg-1"));
assertEquals("<msg-1@email.amazonses.com>",
captureSent().getHeaders().get("Message-ID"));
}
@Test
void relayRaw_overridesACallerSuppliedMessageId() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "Message-ID: <caller-supplied@example.com>\r\n"
+ "Subject: x\r\n\r\nbody";
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", null,
List.of("to@example.com"), rawMime, "msg-1"));
// AWS overrides a caller-supplied Message-ID with the id it assigned.
assertEquals(List.of("<msg-1@email.amazonses.com>"),
captureSent().getHeaders().getAll("Message-ID"));
}
@Test
void relayRaw_dropsACallerSuppliedDate() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "Date: Mon, 08 Oct 2018 14:05:45 +0000\r\n"
+ "Subject: x\r\n\r\nbody";
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", null,
List.of("to@example.com"), rawMime, "msg-1"));
// AWS replaces the caller's Date with the time it accepted the message, so the stale value
// must not be carried onto the relayed message; the encoder generates the send-time Date.
MailMessage sent = captureSent();
assertNull(sent.getHeaders().get("Date"));
assertEquals("<msg-1@email.amazonses.com>", sent.getHeaders().get("Message-ID"));
}
// ── Raw relay fidelity: headers and attachments ──
@Test
void relayRaw_copiesCustomHeadersButNotStructuralOrSesOnes() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: Headers\r\n"
+ "Reply-To: reply@example.com\r\n"
+ "X-Custom: keep-me\r\n"
+ "X-SES-CONFIGURATION-SET: cs\r\n"
+ "X-SES-MESSAGE-TAGS: a=b\r\n"
+ "Return-Path: <bounces@example.com>\r\n"
+ "MIME-Version: 1.0\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "body";
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
MailMessage sent = captureSent();
assertEquals("keep-me", sent.getHeaders().get("X-Custom"));
assertEquals("reply@example.com", sent.getHeaders().get("Reply-To"));
// AWS consumes the X-SES-* control headers rather than forwarding them, and the MIME
// structural headers are regenerated for the re-built message.
assertFalse(sent.getHeaders().contains("X-SES-CONFIGURATION-SET"));
assertFalse(sent.getHeaders().contains("X-SES-MESSAGE-TAGS"));
assertFalse(sent.getHeaders().contains("Content-Type"));
assertFalse(sent.getHeaders().contains("MIME-Version"));
assertFalse(sent.getHeaders().contains("Return-Path"));
assertFalse(sent.getHeaders().contains("Date"));
assertFalse(sent.getHeaders().contains("Subject"));
assertFalse(sent.getHeaders().contains("From"));
}
@Test
void relayRaw_keepsDisplayNamesOnAddresses() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: Alice Sender <alice@example.com>\r\n"
+ "To: Bob Recipient <bob@example.com>\r\n"
+ "Cc: Carol <carol@example.com>\r\n"
+ "Subject: Names\r\n\r\nbody";
relay.relayRaw(raw("envelope@example.com", null, rawMime));
MailMessage sent = captureSent();
assertEquals("Alice Sender <alice@example.com>", sent.getFrom());
assertEquals(List.of("Bob Recipient <bob@example.com>"), sent.getTo());
assertEquals(List.of("Carol <carol@example.com>"), sent.getCc());
}
@Test
void parseRawRecipients_stripsDisplayNames() {
// The envelope, suppression checks and published events all work with bare addresses.
String raw = "From: Alice <alice@example.com>\r\n"
+ "To: Bob Recipient <bob@example.com>\r\n"
+ "Subject: x\r\n\r\nbody";
assertEquals(List.of("bob@example.com"), SmtpRelay.parseRawRecipients(raw));
assertEquals("alice@example.com", SmtpRelay.parseRawHeaders(raw).from());
}
@Test
void relayRaw_preservesAttachments() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: WithAttachment\r\n"
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n"
+ "\r\n"
+ "--outer\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "the body\r\n"
+ "--outer\r\n"
+ "Content-Type: application/pdf\r\n"
+ "Content-Disposition: attachment; filename=\"report.pdf\"\r\n"
+ "Content-Description: Quarterly report\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "\r\n"
+ java.util.Base64.getEncoder().encodeToString("PDF-BYTES".getBytes(
java.nio.charset.StandardCharsets.UTF_8)) + "\r\n"
+ "--outer--";
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
MailMessage sent = captureSent();
assertEquals("the body", sent.getText().trim());
assertNotNull(sent.getAttachment());
assertEquals(1, sent.getAttachment().size());
MailAttachment attachment = sent.getAttachment().get(0);
assertEquals("report.pdf", attachment.getName());
assertEquals("application/pdf", attachment.getContentType());
assertEquals("attachment", attachment.getDisposition());
assertEquals("Quarterly report", attachment.getDescription());
assertEquals("PDF-BYTES", attachment.getData().toString());
}
@Test
void relayRaw_embeddedRfc822Part_isReserializedWhole() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: Fwd: original\r\n"
+ "Content-Type: multipart/mixed; boundary=\"fwd\"\r\n"
+ "\r\n"
+ "--fwd\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "see the forwarded note\r\n"
+ "--fwd\r\n"
+ "Content-Type: message/rfc822\r\n"
+ "Content-Disposition: attachment; filename=\"original.eml\"\r\n"
+ "\r\n"
+ "From: inner@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: original\r\n"
+ "\r\n"
+ "inner body\r\n"
+ "--fwd--";
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
MailMessage sent = captureSent();
assertEquals("see the forwarded note", sent.getText().trim());
assertNotNull(sent.getAttachment());
assertEquals(1, sent.getAttachment().size());
MailAttachment forwarded = sent.getAttachment().get(0);
assertEquals("original.eml", forwarded.getName());
assertEquals("message/rfc822", forwarded.getContentType());
// The embedded message is written back out as a complete RFC 822 stream, headers and all,
// which is the DefaultMessageWriter path that needs mime4j -core and -dom to agree.
String reserialized = forwarded.getData().toString();
assertTrue(reserialized.contains("From: inner@example.com"),
"forwarded headers should survive, got: " + reserialized);
assertTrue(reserialized.contains("Subject: original"),
"forwarded headers should survive, got: " + reserialized);
assertTrue(reserialized.contains("inner body"),
"forwarded body should survive, got: " + reserialized);
}
@Test
void relayRaw_contentIdPart_becomesAnInlineAttachment() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: Inline\r\n"
+ "Content-Type: multipart/related; boundary=\"rel\"\r\n"
+ "\r\n"
+ "--rel\r\n"
+ "Content-Type: text/html; charset=UTF-8\r\n"
+ "\r\n"
+ "<img src=\"cid:logo\">\r\n"
+ "--rel\r\n"
+ "Content-Type: image/png\r\n"
+ "Content-ID: <logo>\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "\r\n"
+ java.util.Base64.getEncoder().encodeToString("PNG".getBytes(
java.nio.charset.StandardCharsets.UTF_8)) + "\r\n"
+ "--rel--";
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
MailMessage sent = captureSent();
assertNull(sent.getAttachment());
assertNotNull(sent.getInlineAttachment());
assertEquals(1, sent.getInlineAttachment().size());
MailAttachment inline = sent.getInlineAttachment().get(0);
assertEquals("<logo>", inline.getContentId());
assertEquals("image/png", inline.getContentType());
assertEquals("PNG", inline.getData().toString());
}
@Test
void relayRaw_inlineAttachmentWithoutHtmlBody_isRelayedAsARegularAttachment() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: InlineNoHtml\r\n"
+ "Content-Type: multipart/related; boundary=\"rel\"\r\n"
+ "\r\n"
+ "--rel\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "plain only\r\n"
+ "--rel\r\n"
+ "Content-Type: image/png\r\n"
+ "Content-ID: <logo>\r\n"
+ "\r\n"
+ "PNG\r\n"
+ "--rel--";
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
MailMessage sent = captureSent();
assertNull(sent.getInlineAttachment());
assertNotNull(sent.getAttachment());
assertEquals(1, sent.getAttachment().size());
}
@Test
void relayRaw_textAttachmentDoesNotClobberTheBody() {
SmtpRelay relay = enabledRelay();
String rawMime = "From: s@example.com\r\n"
+ "To: t@example.com\r\n"
+ "Subject: Mixed\r\n"
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n"
+ "\r\n"
+ "--outer\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "\r\n"
+ "real body\r\n"
+ "--outer\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "Content-Disposition: attachment; filename=\"notes.txt\"\r\n"
+ "\r\n"
+ "attachment content\r\n"
+ "--outer--";
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
MailMessage sent = captureSent();
assertEquals("real body", sent.getText().trim());
assertEquals(1, sent.getAttachment().size());
assertEquals("notes.txt", sent.getAttachment().get(0).getName());
}
private MailMessage captureSent() {
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
verify(mailClient).sendMail(captor.capture());
return captor.getValue();
}
}