fix(ses): reject send addresses longer than 320 characters (#4749)

* fix(ses): reject send addresses longer than 320 characters

* fix(ses): ignore quotes and commas inside comments when splitting address headers
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-30 14:50:59 -04:00
1 parent b0f30ae94d
commit 0b53580969
6 files changed
+787 -17

No files matched your search

@@ -0,0 +1,167 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import org.apache.james.mime4j.dom.Header;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.stream.Field;
import java.util.ArrayList;
import java.util.List;
/**
* The 320-character limit AWS applies to every address of a send (probe-confirmed). AWS measures
* an address in UTF-16 units in the {@code name <address>} form that JavaMail's
* {@code InternetAddress.toUnicodeString()} prints: the display name is quoted only when it holds
* a non-ASCII character or an RFC 822 special, an encoded-word name is measured undecoded, and the
* error echoes that form. The v2 controller remaps the code to BadRequestException.
*/
final class SesAddressLength {
static final int MAX_LENGTH = 320;
private static final String PHRASE_SPECIALS = "()<>@,;:\\\".[]";
private static final List<String> RAW_RECIPIENT_HEADERS = List.of("To", "Cc", "Bcc", "Reply-To", "Return-Path");
private SesAddressLength() {
}
/**
* Checks the envelope fields in the order AWS reports them: the sender, To, Cc, Bcc, the return
* path (v2 FeedbackForwardingEmailAddress), then Reply-To.
*/
static void requireEnvelope(SendEmailRequest request) {
require(request.source());
requireRecipients(request);
}
/**
* Checks a raw send: the sender parameter, the From header, the envelope fields of the request,
* and then the remaining address headers of the MIME message. Header addresses are measured as
* written, like the request fields: an encoded-word name stays encoded and escaped quotes count
* (probe-confirmed). Each address of a header is checked on its own, so a header listing
* several short addresses passes however long it is.
*/
static void requireRaw(SendEmailRequest request, Message message) {
require(request.source());
requireHeader(message, "From");
requireRecipients(request);
for (String name : RAW_RECIPIENT_HEADERS) {
requireHeader(message, name);
}
}
static void require(String address) {
if (address == null || address.isBlank()) {
return;
}
String trimmed = address.trim();
int open = trimmed.lastIndexOf('<');
if (open < 0 || !trimmed.endsWith(">")) {
requireNormalized(trimmed);
return;
}
String name = trimmed.substring(0, open).trim();
if (name.length() >= 2 && name.startsWith("\"") && name.endsWith("\"")) {
name = name.substring(1, name.length() - 1);
}
requireNormalized(format(name, trimmed.substring(open + 1, trimmed.length() - 1).trim()));
}
private static void requireRecipients(SendEmailRequest request) {
requireAll(request.toAddresses());
requireAll(request.ccAddresses());
requireAll(request.bccAddresses());
require(request.returnPath());
requireAll(request.replyToAddresses());
}
private static void requireAll(List<String> addresses) {
if (addresses != null) {
addresses.forEach(SesAddressLength::require);
}
}
private static void requireHeader(Message message, String name) {
Header header = message == null ? null : message.getHeader();
if (header == null) {
return;
}
for (Field field : header.getFields(name)) {
if (field.getBody() != null) {
splitAddressList(field.getBody()).forEach(SesAddressLength::require);
}
}
}
/**
* Splits an RFC 5322 address-list header body at the commas that separate its addresses,
* ignoring commas inside a quoted display name, a comment or an angle-bracketed address. A
* quote inside a comment is literal. A group's {@code name:} prefix and closing semicolon are
* dropped, leaving its member addresses.
*/
static List<String> splitAddressList(String body) {
List<String> addresses = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean quoted = false;
boolean angled = false;
int commentDepth = 0;
for (int i = 0; i < body.length(); i++) {
char c = body.charAt(i);
if ((quoted || commentDepth > 0) && c == '\\' && i + 1 < body.length()) {
current.append(c).append(body.charAt(++i));
continue;
}
if (commentDepth > 0) {
if (c == '(') {
commentDepth++;
} else if (c == ')') {
commentDepth--;
}
} else if (c == '"') {
quoted = !quoted;
} else if (!quoted && c == '(') {
commentDepth = 1;
} else if (!quoted && c == '<') {
angled = true;
} else if (!quoted && c == '>') {
angled = false;
} else if (!quoted && !angled && c == ':') {
current.setLength(0);
continue;
} else if (!quoted && !angled && (c == ',' || c == ';')) {
addresses.add(current.toString());
current.setLength(0);
continue;
}
current.append(c);
}
addresses.add(current.toString());
addresses.removeIf(String::isBlank);
return addresses;
}
private static String format(String name, String address) {
if (name == null || name.isEmpty()) {
return address;
}
return (needsQuoting(name) ? "\"" + name + "\"" : name) + " <" + address + ">";
}
private static boolean needsQuoting(String name) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if ((c < 0x20 && c != '\t') || c >= 0x7f || PHRASE_SPECIALS.indexOf(c) >= 0) {
return true;
}
}
return false;
}
private static void requireNormalized(String address) {
if (address.length() > MAX_LENGTH) {
throw new AwsException("InvalidParameterValue",
"Address length is more than " + MAX_LENGTH + " characters long: '" + address + "'.", 400);
}
}
}
@@ -215,32 +215,48 @@ public class SesService {
}
public String sendEmail(SendEmailRequest request) {
return switch (request.content()) {
case EmailContent.Simple simple -> sendSimpleEmail(request, simple);
if (request.content() instanceof EmailContent.Raw raw) {
return sendRawEmail(request, raw);
}
if (request.content() instanceof EmailContent.InlineTemplate inline) {
requireInlineTemplateContent(inline.subject(), inline.textPart(), inline.htmlPart());
}
// AWS reports an unknown configuration set, then an over-long address, and only then a
// missing stored template (probe-confirmed), so the content is resolved after these checks.
String effectiveConfigSet = validateEnvelope(request);
SesAddressLength.requireEnvelope(request);
EmailContent.Simple content = switch (request.content()) {
case EmailContent.Simple simple -> simple;
case EmailContent.Template template ->
sendInlineTemplatedEmail(request, templateService.inline(template, request.region()));
case EmailContent.InlineTemplate inline -> sendInlineTemplatedEmail(request, inline);
case EmailContent.Raw raw -> sendRawEmail(request, raw);
renderInlineTemplate(templateService.inline(template, request.region()));
case EmailContent.InlineTemplate inline -> SesTemplateService.render(inline);
case EmailContent.Raw raw -> throw new IllegalStateException("Raw content is sent above");
};
return sendSimpleEmail(request.toBuilder().content(content).build(), content, effectiveConfigSet);
}
private String sendInlineTemplatedEmail(SendEmailRequest request, EmailContent.InlineTemplate template) {
private static EmailContent.Simple renderInlineTemplate(EmailContent.InlineTemplate template) {
requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart());
EmailContent.Simple rendered = SesTemplateService.render(template);
return sendSimpleEmail(request.toBuilder().content(rendered).build(), rendered);
return SesTemplateService.render(template);
}
private String sendSimpleEmail(SendEmailRequest request, EmailContent.Simple content) {
private String validateEnvelope(SendEmailRequest request) {
String source = request.source();
String region = request.region();
if (source == null || source.isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
if (!request.hasRecipients()) {
throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);
}
String effectiveConfigSet = resolveDefaultConfigurationSet(request.configurationSetName(), source, region);
configSetService.validateForSending(effectiveConfigSet, region);
String effectiveConfigSet = resolveDefaultConfigurationSet(request.configurationSetName(), source,
request.region());
configSetService.validateForSending(effectiveConfigSet, request.region());
return effectiveConfigSet;
}
private String sendSimpleEmail(SendEmailRequest request, EmailContent.Simple content, String effectiveConfigSet) {
String source = request.source();
String region = request.region();
// Resolve suppression before recording the message so a bad ListManagementOptions (e.g. an
// unknown contact list) fails the whole send without leaving an orphaned SentEmail record.
@@ -363,6 +379,7 @@ public class SesService {
// both with this message.
throw new AwsException("InvalidParameterValue", "Missing required header 'From'.", 400);
}
SesAddressLength.requireRaw(request, parsed.message());
// FromEmailAddress was omitted, so the configuration set couldn't be resolved from the
// sender until the MIME "From" was parsed. Re-resolve from the effective sender now so an
// email identity's default configuration set still applies to a Raw send without an
@@ -1499,7 +1516,10 @@ public class SesService {
.region(request.region())
.content(rendered)
.build();
String messageId = sendSimpleEmail(entryRequest, rendered);
// SesAddressLength is not applied: AWS rejects an over-long bulk sender as "Invalid
// email address", and an over-long destination did not fail the length check ahead
// of sender verification (probe-confirmed; the verified-sender case is unprobed).
String messageId = sendSimpleEmail(entryRequest, rendered, validateEnvelope(entryRequest));
results.add(BulkEmailEntryResult.success(messageId));
} catch (AwsException e) {
results.add(BulkEmailEntryResult.failure(
@@ -0,0 +1,179 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The normalization rules of {@link SesAddressLength#require(String)} and the header splitting of
* {@link SesAddressLength#splitAddressList(String)}. The ASCII, non-ASCII, RFC 822 special,
* quoted-name, UTF-16, encoded-word and escaped-quote cases are probe-confirmed; the remaining edge
* cases pin Floci's own handling of inputs that were not probed.
*/
class SesAddressLengthTest {
private static final String DOMAIN = "example.com";
private static final String SENDER = "sender@" + DOMAIN;
private static final String SUFFIX = " <" + SENDER + ">";
@Test
void nullAndBlankAreIgnored() {
assertDoesNotThrow(() -> SesAddressLength.require(null));
assertDoesNotThrow(() -> SesAddressLength.require(" "));
}
@Test
void bareAddressLimitIsInclusive() {
assertDoesNotThrow(() -> SesAddressLength.require(address(320)));
assertRejects(address(321), address(321));
}
@Test
void asciiNameIsMeasuredWithoutTheCallersQuotes() {
String name = "N".repeat(320 - SUFFIX.length());
assertDoesNotThrow(() -> SesAddressLength.require("\"" + name + "\"" + SUFFIX));
assertRejects("\"" + name + "N\"" + SUFFIX, name + "N" + SUFFIX);
}
@Test
void asciiNameExtraWhitespaceBeforeTheBracketDoesNotCount() {
String name = "N".repeat(320 - SUFFIX.length());
assertDoesNotThrow(() -> SesAddressLength.require(name + " <" + SENDER + ">"));
}
@Test
void nonAsciiNameIsMeasuredQuoted() {
String name = "山".repeat(320 - SUFFIX.length() - 2);
assertDoesNotThrow(() -> SesAddressLength.require(name + SUFFIX));
assertRejects(name + "山" + SUFFIX, "\"" + name + "山\"" + SUFFIX);
}
@Test
void nameWithSpecialIsMeasuredQuoted() {
String name = "N".repeat(320 - SUFFIX.length() - 3) + ",";
assertDoesNotThrow(() -> SesAddressLength.require(name + SUFFIX));
assertRejects("N" + name + SUFFIX, "\"N" + name + "\"" + SUFFIX);
}
@Test
void lengthIsCountedInUtf16Units() {
int emoji = (320 - SUFFIX.length() - 2) / 2;
assertDoesNotThrow(() -> SesAddressLength.require("😀".repeat(emoji) + SUFFIX));
assertRejects("😀".repeat(emoji + 1) + SUFFIX, "\"" + "😀".repeat(emoji + 1) + "\"" + SUFFIX);
}
@Test
void encodedWordNameIsMeasuredUndecoded() {
String encoded = "=?UTF-8?B?" + Base64.getEncoder().encodeToString(
"山".repeat(90).getBytes(StandardCharsets.UTF_8)) + "?=" + SUFFIX;
assertRejects(encoded, encoded);
}
@Test
void surroundingWhitespaceIsTrimmed() {
assertDoesNotThrow(() -> SesAddressLength.require(" " + address(320) + " "));
}
@Test
void angleOnlyAddressIsMeasuredWithoutTheBrackets() {
assertDoesNotThrow(() -> SesAddressLength.require("<" + address(320) + ">"));
assertRejects("<" + address(321) + ">", address(321));
}
@Test
void emptyAngleAddressKeepsTheName() {
String name = "N".repeat(321 - " <>".length());
assertRejects(name + " <>", name + " <>");
}
@Test
void unclosedAngleBracketIsMeasuredAsWritten() {
String input = "N".repeat(321 - SUFFIX.length() + 1) + " <" + SENDER;
assertRejects(input + " ", input);
}
@Test
void angleBracketInsideQuotedNameSplitsAtTheLastBracket() {
String name = "a<b" + "N".repeat(320 - SUFFIX.length() - 5);
assertDoesNotThrow(() -> SesAddressLength.require("\"" + name + "\"" + SUFFIX));
assertRejects("\"" + name + "N\"" + SUFFIX, "\"" + name + "N\"" + SUFFIX);
}
@Test
void escapedQuotesInNameAreKeptAsWritten() {
String name = "a \\\"b\\\" " + "N".repeat(321 - SUFFIX.length() - 10);
assertRejects("\"" + name + "\"" + SUFFIX, "\"" + name + "\"" + SUFFIX);
}
@Test
void tabInNameDoesNotForceQuoting() {
String name = "a\tb" + "N".repeat(320 - SUFFIX.length() - 3);
assertDoesNotThrow(() -> SesAddressLength.require(name + SUFFIX));
}
@Test
void controlCharacterInNameForcesQuoting() {
String name = "a\u0001b" + "N".repeat(320 - SUFFIX.length() - 3);
assertRejects(name + SUFFIX, "\"" + name + "\"" + SUFFIX);
}
@Test
void splitAddressListSeparatesAddressesAtTopLevelCommas() {
assertEquals(List.of("a@b.com", " \"Doe, John\" <c@d.com>", " \"x \\\"y, z\\\"\" <e@f.com>"),
SesAddressLength.splitAddressList("a@b.com, \"Doe, John\" <c@d.com>, \"x \\\"y, z\\\"\" <e@f.com>"));
}
@Test
void splitAddressListKeepsCommasInsideAngleBrackets() {
assertEquals(List.of("Name <a,b@c.com>"), SesAddressLength.splitAddressList("Name <a,b@c.com>"));
}
@Test
void splitAddressListIgnoresQuotesAndCommasInsideComments() {
assertEquals(List.of("a@b.com (it\"s, (nested)) ", " c@d.com"),
SesAddressLength.splitAddressList("a@b.com (it\"s, (nested)) , c@d.com"));
}
@Test
void splitAddressListKeepsParenthesesInsideQuotedNames() {
assertEquals(List.of("\"a (b\" <x@y.com>", " z@y.com"),
SesAddressLength.splitAddressList("\"a (b\" <x@y.com>, z@y.com"));
}
@Test
void splitAddressListDropsGroupSyntax() {
assertEquals(List.of(" a@b.com", " c@d.com"),
SesAddressLength.splitAddressList("team: a@b.com, c@d.com;"));
assertEquals(List.of(), SesAddressLength.splitAddressList("undisclosed-recipients:;"));
}
private static void assertRejects(String input, String reported) {
AwsException e = assertThrows(AwsException.class, () -> SesAddressLength.require(input));
assertEquals("InvalidParameterValue", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
assertEquals("Address length is more than 320 characters long: '" + reported + "'.", e.getMessage());
}
private static String address(int length) {
return "a".repeat(length - DOMAIN.length() - 1) + "@" + DOMAIN;
}
}
@@ -0,0 +1,120 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class SesSendAddressLengthIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String DOMAIN = "example.com";
private static final String TOO_LONG = "a".repeat(321 - DOMAIN.length() - 1) + "@" + DOMAIN;
private static final String EXPECTED_MESSAGE =
"Address length is more than 320 characters long: '" + TOO_LONG + "'.";
@Test
void v1SendEmail_sourceOverLimit_returnsInvalidParameterValue() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH)
.formParam("Action", "SendEmail")
.formParam("Source", TOO_LONG)
.formParam("Destination.ToAddresses.member.1", "success@simulator.amazonses.com")
.formParam("Message.Subject.Data", "Subject")
.formParam("Message.Body.Text.Data", "Body")
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo(EXPECTED_MESSAGE));
}
@Test
void v2SendEmail_fromOverLimit_returnsBadRequestException() {
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["success@simulator.amazonses.com"]},
"Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
}
""".formatted(TOO_LONG))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(EXPECTED_MESSAGE));
}
@Test
void v1SendRawEmail_destinationOverLimit_returnsInvalidParameterValue() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH)
.formParam("Action", "SendRawEmail")
.formParam("Source", "sender@example.com")
.formParam("Destinations.member.1", TOO_LONG)
.formParam("RawMessage.Data", Base64.getEncoder().encodeToString(
"From: sender@example.com\r\nSubject: s\r\n\r\nb".getBytes(StandardCharsets.UTF_8)))
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo(EXPECTED_MESSAGE));
}
@Test
void v2SendEmail_feedbackForwardingOverLimit_returnsBadRequestException() {
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "sender@example.com",
"FeedbackForwardingEmailAddress": "%s",
"Destination": {"ToAddresses": ["success@simulator.amazonses.com"]},
"Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
}
""".formatted(TOO_LONG))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(EXPECTED_MESSAGE));
}
@Test
void v2SendEmail_rawWithCcOverLimit_returnsBadRequestException() {
String raw = Base64.getEncoder().encodeToString(
"From: sender@example.com\r\nTo: success@simulator.amazonses.com\r\nSubject: s\r\n\r\nb"
.getBytes(StandardCharsets.UTF_8));
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body("""
{
"Destination": {"ToAddresses": ["success@simulator.amazonses.com"], "CcAddresses": ["%s"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(TOO_LONG, raw))
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(EXPECTED_MESSAGE));
}
}
@@ -0,0 +1,283 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
import io.github.hectorvent.floci.services.ses.model.EmailContent;
import io.github.hectorvent.floci.services.ses.model.SendBulkEmailRequest;
import io.github.hectorvent.floci.services.ses.model.SendEmailRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class SesServiceAddressLengthTest {
private static final String REGION = "us-east-1";
private static final String DOMAIN = "example.com";
private static final String SENDER = "sender@" + DOMAIN;
private static final String TO = "success@simulator.amazonses.com";
private static final EmailContent.Simple SIMPLE =
new EmailContent.Simple("Subject", "body", null, List.of());
private SesService service;
@BeforeEach
void setUp() {
service = SesServiceTestBuilder.create().build();
}
@Test
void simpleSend_sourceOverLimit_isRejectedWithAddressInMessage() {
String source = address(321, 'a');
AwsException e = assertThrows(AwsException.class,
() -> service.sendEmail(request(source).content(SIMPLE).build()));
assertEquals("InvalidParameterValue", e.getErrorCode());
assertEquals(400, e.getHttpStatus());
assertEquals(expectedMessage(source), e.getMessage());
}
@Test
void simpleSend_eachEnvelopeFieldIsChecked() {
String tooLong = address(321, 'a');
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.toAddresses(List.of(TO, tooLong)).content(SIMPLE).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.ccAddresses(List.of(tooLong)).content(SIMPLE).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.bccAddresses(List.of(tooLong)).content(SIMPLE).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.returnPath(tooLong).content(SIMPLE).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.replyToAddresses(List.of(tooLong)).content(SIMPLE).build()));
}
@Test
void simpleSend_fieldsAreReportedInAwsOrder() {
String source = address(400, 'b');
String to = address(390, 'c');
String cc = address(380, 'd');
String bcc = address(370, 'e');
String returnPath = address(360, 'f');
String replyTo = address(350, 'g');
assertRejects(source, () -> service.sendEmail(request(source).toAddresses(List.of(to))
.content(SIMPLE).build()));
assertRejects(to, () -> service.sendEmail(request(SENDER).toAddresses(List.of(to))
.ccAddresses(List.of(cc)).content(SIMPLE).build()));
assertRejects(cc, () -> service.sendEmail(request(SENDER).ccAddresses(List.of(cc))
.bccAddresses(List.of(bcc)).content(SIMPLE).build()));
assertRejects(bcc, () -> service.sendEmail(request(SENDER).bccAddresses(List.of(bcc))
.returnPath(returnPath).content(SIMPLE).build()));
assertRejects(returnPath, () -> service.sendEmail(request(SENDER).returnPath(returnPath)
.replyToAddresses(List.of(replyTo)).content(SIMPLE).build()));
}
@Test
void simpleSend_unknownConfigurationSetIsReportedBeforeLength() {
AwsException e = assertThrows(AwsException.class,
() -> service.sendEmail(request(address(321, 'a')).configurationSetName("missing")
.content(SIMPLE).build()));
assertEquals("ConfigurationSetDoesNotExist", e.getErrorCode());
}
@Test
void templatedSend_lengthIsReportedBeforeMissingTemplate() {
String replyTo = address(321, 'a');
assertRejects(replyTo, () -> service.sendEmail(request(SENDER).replyToAddresses(List.of(replyTo))
.content(new EmailContent.Template("missing", null, List.of())).build()));
}
@Test
void templatedSend_unknownConfigurationSetIsReportedBeforeMissingTemplate() {
AwsException e = assertThrows(AwsException.class,
() -> service.sendEmail(request(address(321, 'a')).configurationSetName("missing")
.content(new EmailContent.Template("missing", null, List.of())).build()));
assertEquals("ConfigurationSetDoesNotExist", e.getErrorCode());
}
@Test
void inlineTemplateSend_emptyContentIsReportedBeforeConfigurationSetAndLength() {
AwsException e = assertThrows(AwsException.class,
() -> service.sendEmail(request(address(321, 'a')).configurationSetName("missing")
.content(new EmailContent.InlineTemplate("", "", "", null, List.of())).build()));
assertEquals("InvalidTemplate", e.getErrorCode());
}
@Test
void rawSend_sourceParameterIsReportedBeforeFromHeader() {
String source = address(400, 'b');
assertRejects(source, () -> service.sendEmail(request(source)
.content(raw(address(330, 'c'), TO, "")).build()));
}
@Test
void rawSend_fromHeaderIsReportedBeforeDestinations() {
String from = address(330, 'c');
assertRejects(from, () -> service.sendEmail(request(null).toAddresses(List.of(address(500, 'd')))
.content(raw(from, TO, "")).build()));
}
@Test
void rawSend_destinationsAreReportedBeforeToHeader() {
String destination = address(500, 'd');
assertRejects(destination, () -> service.sendEmail(request(SENDER).toAddresses(List.of(destination))
.content(raw(SENDER, address(330, 'e'), "")).build()));
}
@Test
void rawSend_eachAddressHeaderIsChecked() {
String tooLong = address(330, 'a');
assertRejects(tooLong, () -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, tooLong, "")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, TO, "Cc: " + tooLong + "\r\n")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, TO, "Bcc: " + tooLong + "\r\n")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, TO, "Reply-To: " + tooLong + "\r\n")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, TO, "Return-Path: " + tooLong + "\r\n")).build()));
}
@Test
void rawSend_eachEnvelopeFieldOfTheRequestIsChecked() {
String tooLong = address(330, 'a');
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.ccAddresses(List.of(tooLong)).content(raw(SENDER, TO, "")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.bccAddresses(List.of(tooLong)).content(raw(SENDER, TO, "")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.returnPath(tooLong).content(raw(SENDER, TO, "")).build()));
assertRejects(tooLong, () -> service.sendEmail(request(SENDER)
.replyToAddresses(List.of(tooLong)).content(raw(SENDER, TO, "")).build()));
}
@Test
void rawSend_nonAsciiFromHeaderIsMeasuredQuoted() {
String suffix = " <" + SENDER + ">";
String fits = "山".repeat(320 - suffix.length() - 2) + suffix;
String tooLong = "山".repeat(321 - suffix.length() - 2) + suffix;
assertDoesNotThrow(() -> service.sendEmail(request(null).content(rawUtf8(fits)).build()));
assertRejects("\"" + tooLong.replace(suffix, "\"" + suffix),
() -> service.sendEmail(request(null).content(rawUtf8(tooLong)).build()));
}
@Test
void rawSend_headerAddressesAreMeasuredOneByOne() {
String toHeader = address(200, 'a') + ", " + address(200, 'b');
assertDoesNotThrow(() -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, toHeader, "")).build()));
}
@Test
void rawSend_quoteInsideCommentDoesNotJoinAddresses() {
String toHeader = address(200, 'a') + " (it\"s), " + address(200, 'b');
assertDoesNotThrow(() -> service.sendEmail(request(null).toAddresses(List.of())
.content(raw(SENDER, toHeader, "")).build()));
}
@Test
void rawSend_otherAddressHeadersAreNotChecked() {
String tooLong = address(330, 'a');
assertDoesNotThrow(() -> service.sendEmail(request(SENDER).content(raw(SENDER, TO,
"Sender: " + tooLong + "\r\nResent-To: " + tooLong + "\r\n")).build()));
}
@Test
void rawSend_fromHeaderDisplayNameIsMeasuredWithoutQuotes() {
assertDoesNotThrow(() -> service.sendEmail(request(null)
.content(raw(quotedName(320), TO, "")).build()));
assertRejects(quotedName(321).replace("\"", ""), () -> service.sendEmail(request(null)
.content(raw(quotedName(321), TO, "")).build()));
}
@Test
void rawSend_encodedWordHeaderNameIsMeasuredUndecoded() {
String from = "=?UTF-8?B?" + Base64.getEncoder().encodeToString(
"山".repeat(90).getBytes(StandardCharsets.UTF_8)) + "?= <" + SENDER + ">";
assertRejects(from, () -> service.sendEmail(request(null).content(raw(from, TO, "")).build()));
}
@Test
void rawSend_escapedQuotesInHeaderNameCount() {
String suffix = " <" + SENDER + ">";
String inner = "a \\\"b\\\" ";
String tooLong = "\"" + inner + "N".repeat(321 - suffix.length() - 2 - inner.length()) + "\"" + suffix;
assertRejects(tooLong, () -> service.sendEmail(request(null).content(raw(tooLong, TO, "")).build()));
}
@Test
void bulkSend_isNotSubjectToThePerSendCheck() {
List<BulkEmailEntryResult> results = service.sendBulkEmail(SendBulkEmailRequest.builder()
.source(SENDER)
.defaultContent(new EmailContent.InlineTemplate("Subject", "body", null, null, List.of()))
.entries(List.of(new BulkEmailEntry(List.of(address(321, 'a')), null, null, null, null, null)))
.region(REGION)
.build());
assertEquals(BulkEmailEntryResult.Status.SUCCESS, results.get(0).getStatus());
}
private static void assertRejects(String reported, Executable send) {
AwsException e = assertThrows(AwsException.class, send);
assertEquals("InvalidParameterValue", e.getErrorCode());
assertEquals(expectedMessage(reported), e.getMessage());
}
private static String expectedMessage(String address) {
return "Address length is more than 320 characters long: '" + address + "'.";
}
private static SendEmailRequest.Builder request(String source) {
return SendEmailRequest.builder()
.source(source)
.toAddresses(List.of(TO))
.region(REGION);
}
private static EmailContent.Raw raw(String from, String to, String extraHeaders) {
return new EmailContent.Raw("From: " + from + "\r\nTo: " + to + "\r\n" + extraHeaders
+ "Subject: s\r\n\r\nbody");
}
private static EmailContent.Raw rawUtf8(String from) {
return new EmailContent.Raw(Base64.getEncoder().encodeToString(
("From: " + from + "\r\nTo: " + TO + "\r\nSubject: s\r\n\r\nbody").getBytes(StandardCharsets.UTF_8)));
}
private static String address(int length, char fill) {
return String.valueOf(fill).repeat(length - DOMAIN.length() - 1) + "@" + DOMAIN;
}
/** A {@code "N..." <sender>} mailbox whose unquoted {@code N... <sender>} form is {@code length} long. */
private static String quotedName(int length) {
String suffix = " <" + SENDER + ">";
return "\"" + "N".repeat(length - suffix.length()) + "\"" + suffix;
}
}
@@ -290,16 +290,17 @@ class SesServiceSmtpTest {
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.
// AWS reports a missing sender before a missing stored template, but empty inline content
// before either (probe-confirmed).
@Test
void sendEmail_unknownTemplate_reportedBeforeMissingSource() {
void sendEmail_missingSource_reportedBeforeUnknownTemplate() {
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());
assertEquals("InvalidParameterValue", e.getErrorCode());
assertEquals("Source email is required.", e.getMessage());
}
@Test