Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Kenshin Okinaka6d76af083464
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressLength.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressLength.java
index 77b22be0ea..76022b328c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressLength.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressLength.java
@@ -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);
- }
- }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressSyntax.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressSyntax.java
new file mode 100644
index 0000000000..768c3ef72b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressSyntax.java
@@ -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();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java
index cdd59b17f3..c2c933898e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java
@@ -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");
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendAddresses.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendAddresses.java
new file mode 100644
index 0000000000..7fbbcdad28
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendAddresses.java
@@ -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);
+ }
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java
index f294e44c4b..87cd2987b1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java
@@ -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");
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java
index 6bb5c1ec4a..ce61b2a6de 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java
@@ -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) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressLengthTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressLengthTest.java
index ed5cadcf86..552d810ad1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressLengthTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressLengthTest.java
@@ -5,17 +5,17 @@ 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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
- * 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.
+ * The normalization rules of {@link SesAddressLength#require(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 {
@@ -29,6 +29,15 @@ class SesAddressLengthTest {
assertDoesNotThrow(() -> SesAddressLength.require(" "));
}
+ @Test
+ void exceedsLimitUsesTheSameNormalization() {
+ assertFalse(SesAddressLength.exceedsLimit(null));
+ assertFalse(SesAddressLength.exceedsLimit(address(320)));
+ assertTrue(SesAddressLength.exceedsLimit(address(321)));
+ String name = "N".repeat(320 - SUFFIX.length());
+ assertFalse(SesAddressLength.exceedsLimit("\"" + name + "\"" + SUFFIX));
+ }
+
@Test
void bareAddressLimitIsInclusive() {
assertDoesNotThrow(() -> SesAddressLength.require(address(320)));
@@ -136,36 +145,6 @@ class SesAddressLengthTest {
assertRejects(name + SUFFIX, "\"" + name + "\"" + SUFFIX);
}
- @Test
- void splitAddressListSeparatesAddressesAtTopLevelCommas() {
- assertEquals(List.of("[email protected]", " \"Doe, John\" <[email protected]>", " \"x \\\"y, z\\\"\" <[email protected]>"),
- SesAddressLength.splitAddressList("[email protected], \"Doe, John\" <[email protected]>, \"x \\\"y, z\\\"\" <[email protected]>"));
- }
-
- @Test
- void splitAddressListKeepsCommasInsideAngleBrackets() {
- assertEquals(List.of("Name <a,[email protected]>"), SesAddressLength.splitAddressList("Name <a,[email protected]>"));
- }
-
- @Test
- void splitAddressListIgnoresQuotesAndCommasInsideComments() {
- assertEquals(List.of("[email protected] (it\"s, (nested)) ", " [email protected]"),
- SesAddressLength.splitAddressList("[email protected] (it\"s, (nested)) , [email protected]"));
- }
-
- @Test
- void splitAddressListKeepsParenthesesInsideQuotedNames() {
- assertEquals(List.of("\"a (b\" <[email protected]>", " [email protected]"),
- SesAddressLength.splitAddressList("\"a (b\" <[email protected]>, [email protected]"));
- }
-
- @Test
- void splitAddressListDropsGroupSyntax() {
- assertEquals(List.of(" [email protected]", " [email protected]"),
- SesAddressLength.splitAddressList("team: [email protected], [email protected];"));
- 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());
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressSyntaxTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressSyntaxTest.java
new file mode 100644
index 0000000000..b4c25ecf02
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressSyntaxTest.java
@@ -0,0 +1,129 @@
+package io.github.hectorvent.floci.services.ses;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * The address forms of {@link SesAddressSyntax#violation(String)}. The four messages and the
+ * accepted Punycode, dotless, display-name, encoded-word and comment forms are probe-confirmed;
+ * the quoted local part follows the probe-confirmed CVET handling, and the scan order and the
+ * first-{@code @} split follow JavaMail's {@code InternetAddress} check, whose messages AWS returns.
+ */
+class SesAddressSyntaxTest {
+
+ private static final String MISSING_FINAL_DOMAIN = "Missing final '@domain'";
+ private static final String MISSING_DOMAIN = "Missing domain";
+ private static final String LOCAL_CONTROL = "Local address contains control or whitespace";
+ private static final String DOMAIN_CONTROL = "Domain contains control or whitespace";
+
+ @Test
+ void nullAndBlankAreLeftToTheRequiredFieldCheck() {
+ assertNull(SesAddressSyntax.violation(null));
+ assertNull(SesAddressSyntax.violation(" "));
+ }
+
+ @Test
+ void addressWithoutAtIsMissingFinalDomain() {
+ assertEquals(MISSING_FINAL_DOMAIN, SesAddressSyntax.violation("sender.example.com"));
+ assertEquals(MISSING_FINAL_DOMAIN, SesAddressSyntax.violation("Alice <sender.example.com>"));
+ }
+
+ @Test
+ void addressWithEmptyDomainIsMissingDomain() {
+ assertEquals(MISSING_DOMAIN, SesAddressSyntax.violation("sender@"));
+ assertEquals(MISSING_DOMAIN, SesAddressSyntax.violation("Alice <sender@>"));
+ }
+
+ @Test
+ void nonAsciiLocalPartIsRejected() {
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("やまだ@example.com"));
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("Alice <やまだ@example.com>"));
+ }
+
+ @Test
+ void whitespaceInLocalPartIsRejected() {
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("a [email protected]"));
+ }
+
+ @Test
+ void nonAsciiDomainIsRejected() {
+ assertEquals(DOMAIN_CONTROL, SesAddressSyntax.violation("sender@例え.jp"));
+ }
+
+ @Test
+ void localPartIsReportedBeforeDomain() {
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("やまだ@例え.jp"));
+ }
+
+ @Test
+ void punycodeAndDotlessDomainsPass() {
+ assertNull(SesAddressSyntax.violation("[email protected]"));
+ assertNull(SesAddressSyntax.violation("sender@b"));
+ }
+
+ @Test
+ void nonAsciiDisplayNamesPass() {
+ assertNull(SesAddressSyntax.violation("山田 <[email protected]>"));
+ assertNull(SesAddressSyntax.violation("\"山田\" <[email protected]>"));
+ assertNull(SesAddressSyntax.violation("=?UTF-8?B?5bGx55Sw?= <[email protected]>"));
+ }
+
+ @Test
+ void nonAsciiCommentPasses() {
+ assertNull(SesAddressSyntax.violation("[email protected] (山田)"));
+ }
+
+ @Test
+ void localPartIsScannedBeforeTheMissingAtIsReported() {
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("やまだ"));
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("a b"));
+ }
+
+ @Test
+ void firstUnquotedAtSeparatesTheDomain() {
+ assertEquals(DOMAIN_CONTROL, SesAddressSyntax.violation("a@例え@example.com"));
+ assertNull(SesAddressSyntax.violation("a@[email protected]"));
+ }
+
+ @Test
+ void commentAfterTheAngleBracketsIsIgnored() {
+ assertNull(SesAddressSyntax.violation("Alice <[email protected]> (work)"));
+ assertEquals(LOCAL_CONTROL, SesAddressSyntax.violation("Alice <やまだ@example.com> (work)"));
+ }
+
+ @Test
+ void atInsideAQuotedLocalPartIsNotTheSeparator() {
+ assertNull(SesAddressSyntax.violation("\"a@b\"@example.com"));
+ assertNull(SesAddressSyntax.violation("\"a b\"@example.com"));
+ assertEquals(MISSING_FINAL_DOMAIN, SesAddressSyntax.violation("\"a@b\""));
+ }
+
+ @Test
+ void newlineInsideAQuotedLocalPartIsAnInvalidAddress() {
+ for (String local : new String[] {"\"a\nb\"", "\"a\r\nb\"", "\"a\rb\"", "\"a\r\n b\""}) {
+ String address = local + "@example.com";
+ assertEquals("Invalid email address " + address + ".", SesAddressSyntax.violation(address));
+ }
+ }
+
+ @Test
+ void lessThanInsideAQuotedLocalPartIsNotTheAngleBracket() {
+ assertNull(SesAddressSyntax.violation("Display <\"a<b\"@example.com>"));
+ assertEquals(DOMAIN_CONTROL, SesAddressSyntax.violation("Display <\"a<b\"@例え.jp>"));
+ }
+
+ @Test
+ void requireThrowsInvalidParameterValue() {
+ AwsException e = assertThrows(AwsException.class, () -> SesAddressSyntax.require("sender@"));
+
+ assertEquals("InvalidParameterValue", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ assertEquals(MISSING_DOMAIN, e.getMessage());
+ assertDoesNotThrow(() -> SesAddressSyntax.require("[email protected]"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressLengthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressLengthIntegrationTest.java
index 843538f13a..b16a550c91 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressLengthIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressLengthIntegrationTest.java
@@ -117,4 +117,44 @@ class SesSendAddressLengthIntegrationTest {
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(EXPECTED_MESSAGE));
}
+
+ @Test
+ void v2SendBulkEmail_fromOverLimit_returnsInvalidEmailAddress() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "%s",
+ "DefaultContent": {"Template": {
+ "TemplateContent": {"Subject": "s", "Text": "b"},
+ "TemplateData": "{}"}},
+ "BulkEmailEntries": [{"Destination": {"ToAddresses": ["[email protected]"]}}]
+ }
+ """.formatted(TOO_LONG))
+ .when()
+ .post("/v2/email/outbound-bulk-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid email address<" + TOO_LONG + ">."));
+ }
+
+ @Test
+ void v1SendBulkTemplatedEmail_sourceOverLimit_returnsInvalidEmailAddress() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendBulkTemplatedEmail")
+ .formParam("Source", TOO_LONG)
+ .formParam("Template", "address-length-missing")
+ .formParam("DefaultTemplateData", "{}")
+ .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "[email protected]")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
+ .body("ErrorResponse.Error.Message", equalTo("Invalid email address<" + TOO_LONG + ">."));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java
new file mode 100644
index 0000000000..ffa1794500
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java
@@ -0,0 +1,272 @@
+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;
+import static org.hamcrest.Matchers.nullValue;
+
+@QuarkusTest
+class SesSendAddressSyntaxIntegrationTest {
+
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
+ private static final String TO = "[email protected]";
+
+ @Test
+ void v1SendEmail_sourceWithoutAt_returnsInvalidParameterValue() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendEmail")
+ .formParam("Source", "sender.example.com")
+ .formParam("Destination.ToAddresses.member.1", TO)
+ .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("Missing final '@domain'"));
+ }
+
+ @Test
+ void v1SendRawEmail_nonAsciiDomainDestination_returnsInvalidParameterValue() {
+ given()
+ .contentType("application/x-www-form-urlencoded; charset=UTF-8")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendRawEmail")
+ .formParam("Source", "[email protected]")
+ .formParam("Destinations.member.1", "success@例え.jp")
+ .formParam("RawMessage.Data", Base64.getEncoder().encodeToString(
+ "From: [email protected]\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("Domain contains control or whitespace"));
+ }
+
+ @Test
+ void v2SendEmail_nonAsciiLocalRecipient_returnsBadRequestException() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Destination": {"ToAddresses": ["やまだ@simulator.amazonses.com"]},
+ "Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
+ }
+ """)
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Local address contains control or whitespace"));
+ }
+
+ @Test
+ void v2SendBulkEmail_fromWithEmptyDomain_returnsInvalidEmailAddress() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "sender@",
+ "DefaultContent": {"Template": {
+ "TemplateContent": {"Subject": "s", "Text": "b"},
+ "TemplateData": "{}"}},
+ "BulkEmailEntries": [{"Destination": {"ToAddresses": ["%s"]}}]
+ }
+ """.formatted(TO))
+ .when()
+ .post("/v2/email/outbound-bulk-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid email address<sender@>."));
+ }
+
+ @Test
+ void v2SendBulkEmail_malformedEntryRecipient_failsOnlyThatEntry() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "DefaultContent": {"Template": {
+ "TemplateContent": {"Subject": "s", "Text": "b"},
+ "TemplateData": "{}"}},
+ "BulkEmailEntries": [
+ {"Destination": {"ToAddresses": ["%1$s"]}},
+ {"Destination": {"ToAddresses": ["success.simulator.amazonses.com"]}},
+ {"Destination": {"ToAddresses": ["%1$s"], "CcAddresses": ["やまだ@example.com"]}}
+ ]
+ }
+ """.formatted(TO))
+ .when()
+ .post("/v2/email/outbound-bulk-emails")
+ .then()
+ .statusCode(200)
+ .body("BulkEmailEntryResults[0].Status", equalTo("SUCCESS"))
+ .body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER"))
+ .body("BulkEmailEntryResults[1].Error", equalTo("Missing final '@domain'"))
+ .body("BulkEmailEntryResults[1].MessageId", nullValue())
+ .body("BulkEmailEntryResults[2].Status", equalTo("INVALID_PARAMETER"))
+ .body("BulkEmailEntryResults[2].Error", equalTo("Local address contains control or whitespace"));
+ }
+
+ @Test
+ void v1SendBulkTemplatedEmail_malformedEntryRecipient_failsOnlyThatEntry() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "CreateTemplate")
+ .formParam("Template.TemplateName", "address-syntax-bulk")
+ .formParam("Template.SubjectPart", "s")
+ .formParam("Template.TextPart", "b")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendBulkTemplatedEmail")
+ .formParam("Source", "[email protected]")
+ .formParam("Template", "address-syntax-bulk")
+ .formParam("DefaultTemplateData", "{}")
+ .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "success@")
+ .formParam("Destinations.member.2.Destination.ToAddresses.member.1", TO)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[0].Status",
+ equalTo("InvalidParameterValue"))
+ .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[0].Error",
+ equalTo("Missing domain"))
+ .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[1].Status",
+ equalTo("Success"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "DeleteTemplate")
+ .formParam("TemplateName", "address-syntax-bulk")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ void v1SendBulkTemplatedEmail_malformedSourceIsReportedBeforeMissingTemplate() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendBulkTemplatedEmail")
+ .formParam("Source", "Alice <sender@>")
+ .formParam("Template", "address-syntax-missing")
+ .formParam("DefaultTemplateData", "{}")
+ .formParam("Destinations.member.1.Destination.ToAddresses.member.1", TO)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
+ .body("ErrorResponse.Error.Message", equalTo("Invalid email address<Alice <sender@>>."));
+ }
+
+ @Test
+ void v2SendBulkEmail_malformedFromIsReportedBeforeMissingTemplate() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "sender.example.com",
+ "DefaultContent": {"Template": {"TemplateName": "address-syntax-missing", "TemplateData": "{}"}},
+ "BulkEmailEntries": [{"Destination": {"ToAddresses": ["%s"]}}]
+ }
+ """.formatted(TO))
+ .when()
+ .post("/v2/email/outbound-bulk-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid email address<sender.example.com>."));
+ }
+
+ @Test
+ void v2SendEmail_newlineInQuotedLocalPart_returnsInvalidEmailAddress() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "\\"a\\nb\\"@example.com",
+ "Destination": {"ToAddresses": ["%s"]},
+ "Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
+ }
+ """.formatted(TO))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid email address \"a\nb\"@example.com."));
+ }
+
+ @Test
+ void v2SendBulkEmail_malformedFeedbackForwarding_rejectsTheRequest() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "FeedbackForwardingEmailAddress": "bounce.example.com",
+ "DefaultContent": {"Template": {
+ "TemplateContent": {"Subject": "s", "Text": "b"},
+ "TemplateData": "{}"}},
+ "BulkEmailEntries": [{"Destination": {"ToAddresses": ["%s"]}}]
+ }
+ """.formatted(TO))
+ .when()
+ .post("/v2/email/outbound-bulk-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid email address<bounce.example.com>."));
+ }
+
+ @Test
+ void v1SendBulkTemplatedEmail_malformedReturnPath_rejectsTheRequest() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendBulkTemplatedEmail")
+ .formParam("Source", "[email protected]")
+ .formParam("ReturnPath", "bounce@")
+ .formParam("Template", "address-syntax-missing")
+ .formParam("DefaultTemplateData", "{}")
+ .formParam("Destinations.member.1.Destination.ToAddresses.member.1", TO)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
+ .body("ErrorResponse.Error.Message", equalTo("Invalid email address<bounce@>."));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressesTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressesTest.java
new file mode 100644
index 0000000000..d54589c121
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressesTest.java
@@ -0,0 +1,55 @@
+package io.github.hectorvent.floci.services.ses;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class SesSendAddressesTest {
+
+ @Test
+ void splitAddressListSeparatesAddressesAtTopLevelCommas() {
+ assertEquals(List.of("[email protected]", " \"Doe, John\" <[email protected]>", " \"x \\\"y, z\\\"\" <[email protected]>"),
+ SesSendAddresses.splitAddressList("[email protected], \"Doe, John\" <[email protected]>, \"x \\\"y, z\\\"\" <[email protected]>"));
+ }
+
+ @Test
+ void splitAddressListKeepsCommasInsideAngleBrackets() {
+ assertEquals(List.of("Name <a,[email protected]>"), SesSendAddresses.splitAddressList("Name <a,[email protected]>"));
+ }
+
+ @Test
+ void splitAddressListIgnoresQuotesAndCommasInsideComments() {
+ assertEquals(List.of("[email protected] (it\"s, (nested)) ", " [email protected]"),
+ SesSendAddresses.splitAddressList("[email protected] (it\"s, (nested)) , [email protected]"));
+ }
+
+ @Test
+ void splitAddressListKeepsParenthesesInsideQuotedNames() {
+ assertEquals(List.of("\"a (b\" <[email protected]>", " [email protected]"),
+ SesSendAddresses.splitAddressList("\"a (b\" <[email protected]>, [email protected]"));
+ }
+
+ @Test
+ void splitAddressListDropsGroupSyntax() {
+ assertEquals(List.of(" [email protected]", " [email protected]"),
+ SesSendAddresses.splitAddressList("team: [email protected], [email protected];"));
+ assertEquals(List.of(), SesSendAddresses.splitAddressList("undisclosed-recipients:;"));
+ }
+
+ @Test
+ void splitAddressListKeepsColonsAndCommasInsideDomainLiterals() {
+ assertEquals(List.of("user@[IPv6:2001:db8::1]", " a@[x,y]"),
+ SesSendAddresses.splitAddressList("user@[IPv6:2001:db8::1], a@[x,y]"));
+ assertEquals(List.of(" user@[IPv6:2001:db8::1]"),
+ SesSendAddresses.splitAddressList("team: user@[IPv6:2001:db8::1];"));
+ }
+
+ @Test
+ void lastUnquotedAngleSkipsQuotedLessThan() {
+ assertEquals(8, SesSendAddresses.lastUnquotedAngle("Display <\"a<b\"@example.com>"));
+ assertEquals(-1, SesSendAddresses.lastUnquotedAngle("\"a<b\"@example.com"));
+ assertEquals(-1, SesSendAddresses.lastUnquotedAngle("[email protected]"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceAddressSyntaxTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceAddressSyntaxTest.java
new file mode 100644
index 0000000000..ba931bff3c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceAddressSyntaxTest.java
@@ -0,0 +1,224 @@
+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 SesServiceAddressSyntaxTest {
+
+ 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 = "[email protected]";
+ private static final String NON_ASCII_LOCAL = "やまだ@" + DOMAIN;
+ private static final String NO_AT = "sender." + DOMAIN;
+ private static final String MISSING_FINAL_DOMAIN = "Missing final '@domain'";
+ private static final String LOCAL_CONTROL = "Local address contains control or whitespace";
+ private static final EmailContent.Simple SIMPLE =
+ new EmailContent.Simple("Subject", "body", null, List.of());
+
+ private SesService service;
+ private SesSentEmailService sentEmails;
+
+ @BeforeEach
+ void setUp() {
+ SesServiceTestBuilder builder = SesServiceTestBuilder.create();
+ service = builder.build();
+ sentEmails = builder.sentEmailService();
+ }
+
+ @Test
+ void simpleSend_eachEnvelopeFieldIsChecked() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .toAddresses(List.of(TO, NON_ASCII_LOCAL)).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .ccAddresses(List.of(NON_ASCII_LOCAL)).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .bccAddresses(List.of(NON_ASCII_LOCAL)).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .returnPath(NON_ASCII_LOCAL).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .replyToAddresses(List.of(NON_ASCII_LOCAL)).content(SIMPLE).build()));
+ }
+
+ @Test
+ void simpleSend_sourceIsReportedBeforeRecipients() {
+ assertRejects(MISSING_FINAL_DOMAIN, () -> service.sendEmail(request(NO_AT)
+ .toAddresses(List.of(NON_ASCII_LOCAL)).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL)
+ .toAddresses(List.of("success.simulator.amazonses.com")).content(SIMPLE).build()));
+ }
+
+ @Test
+ void simpleSend_ccIsReportedBeforeBcc() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .ccAddresses(List.of(NON_ASCII_LOCAL)).bccAddresses(List.of(NO_AT)).content(SIMPLE).build()));
+ }
+
+ @Test
+ void simpleSend_syntaxIsReportedBeforeUnknownConfigurationSet() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL)
+ .configurationSetName("missing").content(SIMPLE).build()));
+ }
+
+ @Test
+ void simpleSend_syntaxOfAnyFieldIsReportedBeforeLength() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL)
+ .toAddresses(List.of(address(321))).content(SIMPLE).build()));
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(address(321))
+ .toAddresses(List.of(NON_ASCII_LOCAL)).content(SIMPLE).build()));
+ }
+
+ @Test
+ void simpleSend_syntaxIsReportedBeforeMissingDestination() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL)
+ .toAddresses(List.of()).content(SIMPLE).build()));
+ }
+
+ @Test
+ void simpleSend_missingSourceIsStillReportedFirst() {
+ AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(request(null)
+ .toAddresses(List.of(NON_ASCII_LOCAL)).content(SIMPLE).build()));
+
+ assertEquals("Source email is required.", e.getMessage());
+ }
+
+ @Test
+ void simpleSend_nonAsciiDisplayNamesAreAccepted() {
+ assertDoesNotThrow(() -> service.sendEmail(request("山田 <" + SENDER + ">")
+ .toAddresses(List.of("\"山田\" <" + TO + ">")).content(SIMPLE).build()));
+ }
+
+ @Test
+ void templatedSend_syntaxIsReportedBeforeMissingTemplate() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL)
+ .content(new EmailContent.Template("missing", null, List.of())).build()));
+ }
+
+ @Test
+ void rawSend_sourceParameterIsChecked() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(NON_ASCII_LOCAL)
+ .content(raw(SENDER, TO)).build()));
+ }
+
+ @Test
+ void rawSend_fromHeaderIsChecked() {
+ assertRejects(MISSING_FINAL_DOMAIN, () -> service.sendEmail(request(null)
+ .content(raw(NO_AT, TO)).build()));
+ }
+
+ @Test
+ void rawSend_destinationsAreChecked() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .toAddresses(List.of(NON_ASCII_LOCAL)).content(raw(SENDER, TO)).build()));
+ }
+
+ @Test
+ void rawSend_toHeaderIsChecked() {
+ assertRejects(MISSING_FINAL_DOMAIN, () -> service.sendEmail(request(null).toAddresses(List.of())
+ .content(raw(SENDER, TO + ", " + NO_AT)).build()));
+ }
+
+ @Test
+ void rawSend_domainLiteralInToHeaderIsAccepted() {
+ assertDoesNotThrow(() -> service.sendEmail(request(SENDER).content(raw(SENDER,
+ TO + ", user@[IPv6:2001:db8::1]")).build()));
+ }
+
+ @Test
+ void rawSend_unprobedAddressHeadersAreNotChecked() {
+ assertDoesNotThrow(() -> service.sendEmail(request(SENDER).content(raw(SENDER, TO,
+ "Cc: " + NO_AT + "\r\nBcc: " + NON_ASCII_LOCAL + "\r\nReply-To: " + NO_AT
+ + "\r\nReturn-Path: <>\r\n")).build()));
+ }
+
+ @Test
+ void rawSend_nonAsciiFromHeaderNameIsAccepted() {
+ String raw = Base64.getEncoder().encodeToString(("From: 山田 <" + SENDER + ">\r\nTo: " + TO
+ + "\r\nSubject: s\r\n\r\nbody").getBytes(StandardCharsets.UTF_8));
+
+ assertDoesNotThrow(() -> service.sendEmail(request(null).content(new EmailContent.Raw(raw)).build()));
+ }
+
+ @Test
+ void bulkSend_malformedEntryRecipientFailsOnlyThatEntry() {
+ 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(TO), null, null, null, null, null),
+ new BulkEmailEntry(List.of(TO), List.of(NON_ASCII_LOCAL), null, null, null, null),
+ new BulkEmailEntry(List.of(TO), null, List.of(NO_AT), null, null, null)))
+ .region(REGION)
+ .build());
+
+ assertEquals(BulkEmailEntryResult.Status.SUCCESS, results.get(0).getStatus());
+ assertEquals(BulkEmailEntryResult.Status.INVALID_PARAMETER, results.get(1).getStatus());
+ assertEquals(LOCAL_CONTROL, results.get(1).getError());
+ assertEquals(BulkEmailEntryResult.Status.INVALID_PARAMETER, results.get(2).getStatus());
+ assertEquals(MISSING_FINAL_DOMAIN, results.get(2).getError());
+ assertEquals(1, sentEmails.countInRegion(REGION), "only the successful entry is recorded");
+ }
+
+ @Test
+ void bulkSend_malformedReplyToFailsEveryEntry() {
+ List<BulkEmailEntryResult> results = service.sendBulkEmail(SendBulkEmailRequest.builder()
+ .source(SENDER)
+ .replyToAddresses(List.of(NO_AT))
+ .defaultContent(new EmailContent.InlineTemplate("Subject", "body", null, null, List.of()))
+ .entries(List.of(
+ new BulkEmailEntry(List.of(TO), null, null, null, null, null),
+ new BulkEmailEntry(List.of(TO), null, null, null, null, null)))
+ .region(REGION)
+ .build());
+
+ for (BulkEmailEntryResult result : results) {
+ assertEquals(BulkEmailEntryResult.Status.INVALID_PARAMETER, result.getStatus());
+ assertEquals(MISSING_FINAL_DOMAIN, result.getError());
+ }
+ assertEquals(0, sentEmails.countInRegion(REGION), "no entry is recorded");
+ }
+
+ private void assertRejects(String message, Executable send) {
+ long recorded = sentEmails.countInRegion(REGION);
+ AwsException e = assertThrows(AwsException.class, send);
+ assertEquals("InvalidParameterValue", e.getErrorCode());
+ assertEquals(message, e.getMessage());
+ assertEquals(recorded, sentEmails.countInRegion(REGION), "a rejected send must not be recorded");
+ }
+
+ 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) {
+ return raw(from, to, "");
+ }
+
+ 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 String address(int length) {
+ return "a".repeat(length - DOMAIN.length() - 1) + "@" + DOMAIN;
+ }
+}