fix(ses): reject malformed send addresses with AWS's messages (#5380)

* fix(ses): reject malformed send addresses with AWS's messages

Sends accepted any address string. AWS checks every address of a send
with JavaMail's strict InternetAddress rules and answers with its
messages (probe-confirmed in us-west-2):

- no '@': Missing final '@domain'
- empty domain: Missing domain
- control, whitespace or non-ASCII in the local part:
  Local address contains control or whitespace
- the same in the domain: Domain contains control or whitespace

v1 returns InvalidParameterValue, v2 BadRequestException. Display
names, comments, encoded words, Punycode and dotless domains pass.
The check runs after the missing-sender check and before the
destination, configuration set, length and template checks, over the
sender, To, Cc, Bcc, return path and Reply-To, and on raw sends over
the Source and Destinations parameters and the From and To headers.
A bulk send reports a malformed or over-long sender as "Invalid email
address<addr>." ahead of a missing template, and a malformed bulk entry
recipient fails only that entry.

The field walk shared with the 320-character check moves to
SesSendAddresses so both checks visit the same fields in one order.

* fix(ses): check bulk reply-to and return path, quoted CR/LF and quoted '<'

Review follow-ups, probe-confirmed in us-east-1 with a verified sender:

- A malformed bulk Reply-To fails every entry with the JavaMail
  message, while a malformed bulk return path (v1 ReturnPath, v2
  FeedbackForwardingEmailAddress) rejects the whole request as
  "Invalid email address<addr>.", like the sender.
- A CR or LF inside a quoted local part is rejected, even when followed
  by whitespace, as "Invalid email address <addr>.".

A '<' inside a quoted local part is no longer taken for the start of
the angle-bracketed address, in both the syntax and the length check.
The syntax tests now also assert that a rejected send is not recorded.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-10 08:40:49 -04:00
1 parent 517409a7aa
commit 6d76af0834
12 files changed
+1078 -148

No files matched your search

@@ -2,11 +2,8 @@ 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;
/**
@@ -26,119 +23,46 @@ final class SesAddressLength {
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);
SesSendAddresses.forEachEnvelope(request, SesAddressLength::require);
}
/**
* 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.
* 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);
}
SesSendAddresses.forEachRaw(request, message, RAW_RECIPIENT_HEADERS, SesAddressLength::require);
}
static void require(String address) {
String normalized = normalized(address);
if (normalized != null && normalized.length() > MAX_LENGTH) {
throw new AwsException("InvalidParameterValue",
"Address length is more than " + MAX_LENGTH + " characters long: '" + normalized + "'.", 400);
}
}
static boolean exceedsLimit(String address) {
String normalized = normalized(address);
return normalized != null && normalized.length() > MAX_LENGTH;
}
private static String normalized(String address) {
if (address == null || address.isBlank()) {
return;
return null;
}
String trimmed = address.trim();
int open = trimmed.lastIndexOf('<');
int open = SesSendAddresses.lastUnquotedAngle(trimmed);
if (open < 0 || !trimmed.endsWith(">")) {
requireNormalized(trimmed);
return;
return trimmed;
}
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;
return format(name, trimmed.substring(open + 1, trimmed.length() - 1).trim());
}
private static String format(String name, String address) {
@@ -157,11 +81,4 @@ final class SesAddressLength {
}
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);
}
}
}
@@ -0,0 +1,157 @@
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.SendEmailRequest;
import org.apache.james.mime4j.dom.Message;
import java.util.Arrays;
import java.util.List;
/**
* The address syntax check AWS applies to every address of a send ahead of the destination,
* configuration-set and length checks (probe-confirmed). The messages are those of JavaMail's
* strict {@code InternetAddress} check, which scans the addr-spec once from the left, and only
* the four AWS was seen to return are reproduced: a control, whitespace or non-ASCII character in
* the local part, a missing {@code @}, an empty domain, and such a character in the domain. A
* display name or a comment may hold any character, and a quoted local part is not inspected
* except for a CR or LF, which AWS rejects with its own wording even before whitespace.
* Of the raw headers, only From and To were probed, so only those are checked. The v2 controller
* remaps the code to BadRequestException.
*/
final class SesAddressSyntax {
private static final List<String> RAW_CHECKED_HEADERS = List.of("To");
private SesAddressSyntax() {
}
static void requireEnvelope(SendEmailRequest request) {
SesSendAddresses.forEachEnvelope(request, SesAddressSyntax::require);
}
static void requireRaw(SendEmailRequest request, Message message) {
SesSendAddresses.forEachRaw(request, message, RAW_CHECKED_HEADERS, SesAddressSyntax::require);
}
/**
* Checks a bulk sender or return path (v2 FeedbackForwardingEmailAddress). A bulk send words a
* malformed or over-long one as an invalid address for the whole request, echoing it as given,
* and reports it before a missing stored template (probe-confirmed; an over-long display-name
* address is assumed to be measured as on a single send). The v1 handler and the v2 controller
* call it as soon as the address is read, ahead of the template lookup they perform.
*/
static void requireBulkAddress(String address) {
if (violation(address) != null || SesAddressLength.exceedsLimit(address)) {
throw new AwsException("InvalidParameterValue", "Invalid email address<" + address + ">.", 400);
}
}
/**
* Checks the To, Cc and Bcc of one bulk entry, then the request's Reply-To. AWS reports a
* malformed entry recipient as that entry's status, and a malformed Reply-To as the status of
* every entry, not as a request error (probe-confirmed).
*/
static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses) {
for (List<String> addresses : Arrays.asList(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(),
replyToAddresses)) {
if (addresses != null) {
addresses.forEach(SesAddressSyntax::require);
}
}
}
static void require(String address) {
String violation = violation(address);
if (violation != null) {
throw new AwsException("InvalidParameterValue", violation, 400);
}
}
/**
* Returns the message AWS answers for a malformed address, or null when the address passes or
* is blank (a missing address is reported by the caller's own required-field check).
*/
static String violation(String address) {
if (address == null || address.isBlank()) {
return null;
}
String addrSpec = addrSpec(address);
boolean quoted = false;
int i = 0;
for (; i < addrSpec.length(); i++) {
char c = addrSpec.charAt(i);
if (c == '\\') {
i++;
} else if (c == '"') {
quoted = !quoted;
} else if (quoted) {
if (c == '\r' || c == '\n') {
return "Invalid email address " + address + ".";
}
} else if (c == '@') {
break;
} else if (isControlOrWhitespace(c)) {
return "Local address contains control or whitespace";
}
}
if (i >= addrSpec.length()) {
return "Missing final '@domain'";
}
String domain = addrSpec.substring(i + 1);
if (domain.isEmpty()) {
return "Missing domain";
}
for (int j = 0; j < domain.length(); j++) {
if (isControlOrWhitespace(domain.charAt(j))) {
return "Domain contains control or whitespace";
}
}
return null;
}
private static boolean isControlOrWhitespace(char c) {
return c <= ' ' || c >= 0x7f;
}
private static String addrSpec(String mailbox) {
String withoutComments = withoutComments(mailbox).trim();
int open = SesSendAddresses.lastUnquotedAngle(withoutComments);
if (open >= 0 && withoutComments.endsWith(">")) {
return withoutComments.substring(open + 1, withoutComments.length() - 1).trim();
}
return withoutComments;
}
private static String withoutComments(String mailbox) {
StringBuilder out = new StringBuilder();
boolean quoted = false;
int commentDepth = 0;
for (int i = 0; i < mailbox.length(); i++) {
char c = mailbox.charAt(i);
if ((quoted || commentDepth > 0) && c == '\\' && i + 1 < mailbox.length()) {
if (commentDepth == 0) {
out.append(c).append(mailbox.charAt(i + 1));
}
i++;
continue;
}
if (commentDepth > 0) {
if (c == '(') {
commentDepth++;
} else if (c == ')') {
commentDepth--;
}
continue;
}
if (c == '"') {
quoted = !quoted;
} else if (!quoted && c == '(') {
commentDepth = 1;
continue;
}
out.append(c);
}
return out.toString();
}
}
@@ -756,6 +756,8 @@ public class SesQueryHandler {
"Account sending is disabled.", 400);
}
String source = getParam(params, "Source");
SesAddressSyntax.requireBulkAddress(source);
SesAddressSyntax.requireBulkAddress(getParam(params, "ReturnPath"));
List<String> replyToAddresses = extractMembers(params, "ReplyToAddresses");
String templateName = getParam(params, "Template");
String templateArn = getParam(params, "TemplateArn");
@@ -0,0 +1,144 @@
package io.github.hectorvent.floci.services.ses;
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;
import java.util.function.Consumer;
/**
* Walks the addresses of a send in the order AWS reports them, so every per-address check
* (length, syntax) visits the same fields in the same order.
*/
final class SesSendAddresses {
private SesSendAddresses() {
}
/**
* The envelope fields: the sender, To, Cc, Bcc, the return path (v2
* FeedbackForwardingEmailAddress), then Reply-To.
*/
static void forEachEnvelope(SendEmailRequest request, Consumer<String> check) {
check.accept(request.source());
forEachRecipient(request, check);
}
/**
* A raw send: the sender parameter, the From header, the envelope fields of the request, and
* then the named headers of the MIME message. Each address of a header is visited on its own,
* as written (an encoded-word name stays encoded).
*/
static void forEachRaw(SendEmailRequest request, Message message, List<String> headerNames,
Consumer<String> check) {
check.accept(request.source());
forEachHeaderAddress(message, "From", check);
forEachRecipient(request, check);
for (String name : headerNames) {
forEachHeaderAddress(message, name, check);
}
}
/**
* Splits an RFC 5322 address-list header body at the commas that separate its addresses,
* ignoring commas inside a quoted display name, a comment, an angle-bracketed address or a
* domain literal ({@code [IPv6:2001:db8::1]}). 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;
boolean bracketed = false;
int commentDepth = 0;
for (int i = 0; i < body.length(); i++) {
char c = body.charAt(i);
if ((quoted || commentDepth > 0 || bracketed) && 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 (bracketed) {
if (c == ']') {
bracketed = false;
}
} else if (c == '"') {
quoted = !quoted;
} else if (!quoted && c == '(') {
commentDepth = 1;
} else if (!quoted && c == '[') {
bracketed = true;
} 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;
}
/**
* The index of the last {@code <} outside a quoted string, so a quoted local part holding a
* {@code <} is not mistaken for the start of the angle-bracketed address; -1 when there is none.
*/
static int lastUnquotedAngle(String mailbox) {
int open = -1;
boolean quoted = false;
for (int i = 0; i < mailbox.length(); i++) {
char c = mailbox.charAt(i);
if (quoted && c == '\\') {
i++;
} else if (c == '"') {
quoted = !quoted;
} else if (!quoted && c == '<') {
open = i;
}
}
return open;
}
private static void forEachRecipient(SendEmailRequest request, Consumer<String> check) {
forEach(request.toAddresses(), check);
forEach(request.ccAddresses(), check);
forEach(request.bccAddresses(), check);
check.accept(request.returnPath());
forEach(request.replyToAddresses(), check);
}
private static void forEach(List<String> addresses, Consumer<String> check) {
if (addresses != null) {
addresses.forEach(check);
}
}
private static void forEachHeaderAddress(Message message, String name, Consumer<String> check) {
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(check);
}
}
}
}
@@ -243,9 +243,11 @@ public class SesSendController {
throw new AwsException("BadRequestException",
"FromEmailAddress is required.", 400);
}
SesAddressSyntax.requireBulkAddress(fromEmailAddress);
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
String feedbackForwardingAddress =
request.path("FeedbackForwardingEmailAddress").asText(null);
SesAddressSyntax.requireBulkAddress(feedbackForwardingAddress);
String configurationSetName = request.path("ConfigurationSetName").asText(null);
String tenantName = stringMemberOrAbsent(request, "TenantName");
@@ -249,8 +249,11 @@ public class SesService {
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.
// After a missing sender, AWS reports a malformed address ahead of the destination and
// configuration-set checks, then an over-long address, and only then a missing stored
// template (probe-confirmed), so the content is resolved after these checks.
requireSource(request);
SesAddressSyntax.requireEnvelope(request);
String effectiveConfigSet = validateEnvelope(request);
SesAddressLength.requireEnvelope(request);
EmailContent.Simple content = switch (request.content()) {
@@ -268,11 +271,14 @@ public class SesService {
return SesTemplateService.render(template);
}
private String validateEnvelope(SendEmailRequest request) {
String source = request.source();
if (source == null || source.isBlank()) {
private static void requireSource(SendEmailRequest request) {
if (request.source() == null || request.source().isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
}
private String validateEnvelope(SendEmailRequest request) {
String source = request.source();
if (!request.hasRecipients()) {
throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);
}
@@ -428,6 +434,7 @@ public class SesService {
// resolved before the message has been read.
SmtpRelay.ParsedRawMessage parsed = SmtpRelay.parseRawMessage(raw.data());
SmtpRelay.RawMessageHeaders headers = parsed.headers();
SesAddressSyntax.requireRaw(request, parsed.message());
// AWS accepts the configuration set either as a request field or as the
// X-SES-CONFIGURATION-SET header on the message itself; the request field wins.
String requestedConfigSet = firstNonBlank(request.configurationSetName(), headers.configurationSet());
@@ -1564,6 +1571,7 @@ public class SesService {
List<BulkEmailEntryResult> results = new ArrayList<>(request.entries().size());
for (BulkEmailEntry entry : request.entries()) {
try {
SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses());
JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData());
List<MessageTag> mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags());
List<MessageHeader> mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders());
@@ -1584,9 +1592,10 @@ public class SesService {
.region(request.region())
.content(rendered)
.build();
// 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).
// SesAddressLength is not applied to entries: an over-long bulk destination did not
// fail the length check ahead of sender verification (probe-confirmed; the
// verified-sender case is unprobed). The bulk sender and return path are checked
// by requireBulkAddress.
String messageId = sendSimpleEmail(entryRequest, rendered, validateEnvelope(entryRequest));
results.add(BulkEmailEntryResult.success(messageId));
} catch (AwsException e) {