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 index c09ea9da46..8a4e93098f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressSyntax.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesAddressSyntax.java @@ -23,12 +23,16 @@ import java.util.function.Consumer; * remaps the code to BadRequestException. A v2 raw send checks its From header only without a * sender parameter, and then answers an invalid From address for every violation but a missing * {@code @}, which it reports later (probe-confirmed for the four JavaMail messages; a quoted CR - * or LF is assumed to follow). + * or LF is assumed to follow). A v1 raw send with a sender parameter checks every From header + * address but lets a missing {@code @} pass, as JavaMail's non-strict header parse does, and + * reports one only on the first address, later and in its own wording (probe-confirmed). */ final class SesAddressSyntax { private static final List RAW_CHECKED_HEADERS = List.of("To", "Cc", "Bcc"); private static final String MISSING_FINAL_DOMAIN = "Missing final '@domain'"; + private static final String PHRASE_SPECIALS = "()<>@,;:\\\".[]"; + private static final String ADDRESS_SPECIALS = "()<>,;:\\\"[]"; private SesAddressSyntax() { } @@ -43,27 +47,58 @@ final class SesAddressSyntax { } private static Consumer fromHeaderCheck(SendEmailRequest request, EmailContent.Raw raw) { - if (!raw.checksFromHeader(request.hasSource())) { - return SesSendAddresses.UNCHECKED; + if (readsFromHeaderAsSender(request, raw)) { + return SesAddressSyntax::requireFallbackFrom; } - return raw.fromHeaderAsFallback() ? SesAddressSyntax::requireFallbackFrom : SesAddressSyntax::require; + if (checksFromHeaderBesideSender(request, raw)) { + return SesAddressSyntax::requireExceptAt; + } + return raw.checksFromHeader(request.hasSource()) ? SesAddressSyntax::require : SesSendAddresses.UNCHECKED; + } + + private static boolean readsFromHeaderAsSender(SendEmailRequest request, EmailContent.Raw raw) { + return raw.fromHeaderAsFallback() && !request.hasSource(); + } + + private static boolean checksFromHeaderBesideSender(SendEmailRequest request, EmailContent.Raw raw) { + return !raw.fromHeaderAsFallback() && request.hasSource(); } private static void requireFallbackFrom(String address) { - String violation = violation(address); - if (violation != null && !MISSING_FINAL_DOMAIN.equals(violation)) { + if (violationExceptAt(address) != null) { throw new AwsException("InvalidParameterValue", "Invalid From address provided.", 400); } } + private static void requireExceptAt(String address) { + String violation = violationExceptAt(address); + if (violation != null) { + throw new AwsException("InvalidParameterValue", violation, 400); + } + } + + private static String violationExceptAt(String address) { + String violation = violation(address); + return MISSING_FINAL_DOMAIN.equals(violation) ? null : violation; + } + /** - * The missing {@code @} of a v2 raw From header read in place of the sender, which AWS reports - * only after the configuration set and the missing-destination checks, and before the length - * check (probe-confirmed). + * The missing {@code @} the From header check let pass, which AWS reports only after the + * configuration set and the missing-destination checks (probe-confirmed). A v2 send reports it + * on any From header address read in place of the sender, before the length check + * (probe-confirmed). A v1 send with a sender parameter reports it on the first address only, + * as JavaMail's "User name is missing" around that address's {@code toString()} form + * (probe-confirmed; the same place relative to the length check is assumed). */ - static void requireFallbackFromAt(SendEmailRequest request, EmailContent.Raw raw, Message message) { - if (raw.fromHeaderAsFallback() && !request.hasSource()) { + static void requireFromHeaderAt(SendEmailRequest request, EmailContent.Raw raw, Message message) { + if (readsFromHeaderAsSender(request, raw)) { SesSendAddresses.forEachHeaderAddress(message, "From", SesAddressSyntax::requireAt); + } else if (checksFromHeaderBesideSender(request, raw)) { + String first = SesSendAddresses.firstHeaderAddress(message, "From"); + if (MISSING_FINAL_DOMAIN.equals(violation(first))) { + throw new AwsException("InvalidParameterValue", + "User name is missing: '" + javaMailString(first) + "'.", 400); + } } } @@ -73,6 +108,75 @@ final class SesAddressSyntax { } } + /** + * A mailbox as JavaMail's {@code InternetAddress.toString()} writes it once parsed: the display + * name as written from its first character outside a comment to the angle bracket, later + * comments included, and dropped when it is blank once unquoted, or the first comment only when + * only comments precede the angle bracket (probe-confirmed each way). The name is quoted again only when it holds a special character, then the addr-spec + * follows in angle brackets; a bare addr-spec keeps no brackets unless it holds a special + * character. A raw non-ASCII name comes out as + * {@link SesEncodedWord} writes it and an encoded-word stays as written (probe-confirmed for a + * short all non-ASCII name, which is one B encoded-word; longer and mixed names follow JavaMail + * and are assumed). + */ + static String javaMailString(String mailbox) { + String addrSpec = addrSpec(mailbox); + String personal = personal(mailbox); + if (personal != null) { + return encodePhrase(personal) + " <" + addrSpec + ">"; + } + return containsAny(addrSpec, ADDRESS_SPECIALS) ? "<" + addrSpec + ">" : addrSpec; + } + + private static String personal(String mailbox) { + Stripped stripped = stripComments(mailbox); + if (stripped.lastAngle() >= 0 && stripped.text().trim().endsWith(">") + && stripped.phraseStart() < stripped.lastAngle()) { + String phrase = unquote(mailbox.substring(stripped.phraseStart(), stripped.lastAngle()).trim()); + return phrase.isBlank() ? null : phrase; + } + String comment = stripped.firstComment(); + return comment == null || comment.isBlank() ? null : comment.trim(); + } + + private static String unquote(String phrase) { + if (phrase.length() < 2 || !phrase.startsWith("\"") || !phrase.endsWith("\"")) { + return phrase; + } + StringBuilder out = new StringBuilder(); + for (int i = 1; i < phrase.length() - 1; i++) { + char c = phrase.charAt(i); + if (c == '\\' && i + 1 < phrase.length() - 1) { + c = phrase.charAt(++i); + } + out.append(c); + } + return out.toString(); + } + + private static String encodePhrase(String personal) { + if (SesEncodedWord.needsEncoding(personal)) { + return SesEncodedWord.encode(personal); + } + boolean needsQuotes = false; + StringBuilder quoted = new StringBuilder("\""); + for (int i = 0; i < personal.length(); i++) { + char c = personal.charAt(i); + if (c == '"' || c == '\\') { + quoted.append('\\'); + needsQuotes = true; + } else if (PHRASE_SPECIALS.indexOf(c) >= 0) { + needsQuotes = true; + } + quoted.append(c); + } + return needsQuotes ? quoted.append('"').toString() : personal; + } + + private static boolean containsAny(String value, String characters) { + return value.chars().anyMatch(c -> characters.indexOf(c) >= 0); + } + /** * 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, @@ -155,7 +259,7 @@ final class SesAddressSyntax { } private static String addrSpec(String mailbox) { - String withoutComments = withoutComments(mailbox).trim(); + String withoutComments = stripComments(mailbox).text().trim(); int open = SesSendAddresses.lastUnquotedAngle(withoutComments); if (open >= 0 && withoutComments.endsWith(">")) { return withoutComments.substring(open + 1, withoutComments.length() - 1).trim(); @@ -163,8 +267,15 @@ final class SesAddressSyntax { return withoutComments; } - private static String withoutComments(String mailbox) { + private record Stripped(String text, String firstComment, int phraseStart, int lastAngle) { + } + + private static Stripped stripComments(String mailbox) { StringBuilder out = new StringBuilder(); + String firstComment = null; + int commentStart = -1; + int phraseStart = -1; + int lastAngle = -1; boolean quoted = false; int commentDepth = 0; for (int i = 0; i < mailbox.length(); i++) { @@ -179,8 +290,8 @@ final class SesAddressSyntax { if (commentDepth > 0) { if (c == '(') { commentDepth++; - } else if (c == ')') { - commentDepth--; + } else if (c == ')' && --commentDepth == 0 && firstComment == null) { + firstComment = mailbox.substring(commentStart, i); } continue; } @@ -188,10 +299,16 @@ final class SesAddressSyntax { quoted = !quoted; } else if (!quoted && c == '(') { commentDepth = 1; + commentStart = i + 1; continue; + } else if (!quoted && c == '<') { + lastAngle = i; + } + if (phraseStart < 0 && !Character.isWhitespace(c)) { + phraseStart = i; } out.append(c); } - return out.toString(); + return new Stripped(out.toString(), firstComment, phraseStart, lastAngle); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesEncodedWord.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesEncodedWord.java new file mode 100644 index 0000000000..d69a85d537 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEncodedWord.java @@ -0,0 +1,87 @@ +package io.github.hectorvent.floci.services.ses; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +/** + * A display name as JavaMail's {@code MimeUtility.encodeWord} writes it in UTF-8: B when at least + * half its characters are non-ASCII and Q otherwise, halved recursively at the middle until each + * encoded-word fits JavaMail's limit, and the words joined by a space. AWS echoes a name in this + * form in the "User name is missing" message of a v1 raw send. + */ +final class SesEncodedWord { + + private static final String CHARSET = "UTF-8"; + private static final int AVAILABLE = 68 - CHARSET.length(); + private static final String WORD_SPECIALS = "=_?\"#$%&'(),.:;<>@[\\]^`{|}~"; + private static final char[] HEX = "0123456789ABCDEF".toCharArray(); + + private SesEncodedWord() { + } + + static boolean needsEncoding(String text) { + return text.chars().anyMatch(SesEncodedWord::isNonAscii); + } + + static String encode(String text) { + long nonAscii = text.chars().filter(SesEncodedWord::isNonAscii).count(); + StringBuilder out = new StringBuilder(); + encode(text, nonAscii >= text.length() - nonAscii, true, out); + return out.toString(); + } + + private static void encode(String text, boolean base64, boolean first, StringBuilder out) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + int length = base64 ? (bytes.length + 2) / 3 * 4 : qLength(bytes); + if (length > AVAILABLE && text.length() > 1) { + int split = text.length() / 2; + if (Character.isHighSurrogate(text.charAt(split - 1))) { + split--; + } + if (split > 0) { + encode(text.substring(0, split), base64, first, out); + } + encode(text.substring(split), base64, false, out); + return; + } + if (!first) { + out.append(' '); + } + out.append("=?").append(CHARSET).append(base64 ? "?B?" : "?Q?"); + if (base64) { + out.append(Base64.getEncoder().encodeToString(bytes)); + } else { + appendQ(bytes, out); + } + out.append("?="); + } + + private static int qLength(byte[] bytes) { + int length = 0; + for (byte b : bytes) { + length += isQEscaped(b & 0xff) ? 3 : 1; + } + return length; + } + + private static void appendQ(byte[] bytes, StringBuilder out) { + for (byte b : bytes) { + int c = b & 0xff; + if (c == ' ') { + out.append('_'); + } else if (isQEscaped(c)) { + out.append('=').append(HEX[c >> 4]).append(HEX[c & 0x0f]); + } else { + out.append((char) c); + } + } + } + + private static boolean isQEscaped(int c) { + return c < ' ' || c >= 0x7f || WORD_SPECIALS.indexOf(c) >= 0; + } + + private static boolean isNonAscii(int c) { + return c >= 0x7f || (c < ' ' && c != '\r' && c != '\n' && c != '\t'); + } +} 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 index 79e5dfa362..701ce9a993 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendAddresses.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendAddresses.java @@ -133,6 +133,23 @@ final class SesSendAddresses { } } + /** The first address the named headers hold, or null when the message has none. */ + static String firstHeaderAddress(Message message, String name) { + Header header = message == null ? null : message.getHeader(); + if (header == null) { + return null; + } + for (Field field : header.getFields(name)) { + if (field.getBody() != null) { + List addresses = splitAddressList(field.getBody()); + if (!addresses.isEmpty()) { + return addresses.get(0); + } + } + } + return null; + } + static void forEachHeaderAddress(Message message, String name, Consumer check) { Header header = message == null ? null : message.getHeader(); if (header == null) { 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 2ceba294da..5eda026286 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 @@ -563,7 +563,7 @@ public class SesService { if (effectiveDestinations.isEmpty()) { throw new AwsException("InvalidParameterValue", "Missing required header 'To'.", 400); } - SesAddressSyntax.requireFallbackFromAt(request, raw, parsed.message()); + SesAddressSyntax.requireFromHeaderAt(request, raw, parsed.message()); SesAddressLength.requireRaw(request, raw, parsed.message()); if (requireVerifiedSender) { requireVerifiedSenders(rawSendingAddresses(request, raw, headers), region); 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 index b4c25ecf02..f1a3481782 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressSyntaxTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesAddressSyntaxTest.java @@ -126,4 +126,62 @@ class SesAddressSyntaxTest { assertEquals(MISSING_DOMAIN, e.getMessage()); assertDoesNotThrow(() -> SesAddressSyntax.require("sender@example.com")); } + + @Test + void javaMailStringRendersTheProbedForms() { + assertEquals("probe.example.invalid", SesAddressSyntax.javaMailString("probe.example.invalid")); + assertEquals("Alice ", SesAddressSyntax.javaMailString("Alice ")); + assertEquals("Alice ", SesAddressSyntax.javaMailString("probe.example.invalid (Alice)")); + assertEquals("<\"probe example\">", SesAddressSyntax.javaMailString("\"probe example\"")); + assertEquals("=?UTF-8?B?5bGx55Sw?= ", + SesAddressSyntax.javaMailString("山田 ")); + assertEquals("\"Alice, B\" ", + SesAddressSyntax.javaMailString("\"Alice, B\" ")); + } + + @Test + void javaMailStringQuotesTheNameOnlyWhenItHoldsASpecial() { + assertEquals("Alice B ", + SesAddressSyntax.javaMailString("\"Alice B\" ")); + assertEquals("\"Alice B.\" ", + SesAddressSyntax.javaMailString("Alice B. ")); + assertEquals("\"Alice \\\"B\\\"\" ", + SesAddressSyntax.javaMailString("\"Alice \\\"B\\\"\" ")); + } + + @Test + void javaMailStringKeepsAnEncodedWordAndPrefersTheDisplayNameToAComment() { + assertEquals("=?UTF-8?B?5bGx55Sw?= ", + SesAddressSyntax.javaMailString("=?UTF-8?B?5bGx55Sw?= ")); + assertEquals("Alice ", + SesAddressSyntax.javaMailString("Alice (Bob)")); + assertEquals("\"Alice (Bob)\" ", + SesAddressSyntax.javaMailString("Alice (Bob) ")); + assertEquals("Bob ", SesAddressSyntax.javaMailString("(Bob) ")); + assertEquals("Alice ", + SesAddressSyntax.javaMailString("(Bob) Alice ")); + assertEquals("probe.example.invalid", SesAddressSyntax.javaMailString("")); + } + + @Test + void javaMailStringEncodesAMostlyAsciiNameAsQAndHalvesALongName() { + assertEquals("=?UTF-8?Q?Alice_=E5=B1=B1=E7=94=B0?= ", + SesAddressSyntax.javaMailString("Alice 山田 ")); + String word = "=?UTF-8?B?5bGx55Sw5bGx55Sw5bGx55Sw5bGx55Sw5bGx55Sw?="; + assertEquals(String.join(" ", word, word, word, word) + " ", + SesAddressSyntax.javaMailString("山田".repeat(20) + " ")); + } + + @Test + void javaMailStringDropsABlankDisplayName() { + assertEquals("probe.example.invalid", SesAddressSyntax.javaMailString("\"\" ")); + assertEquals("probe.example.invalid", SesAddressSyntax.javaMailString("\" \" (Alice)")); + assertEquals("Alice ", SesAddressSyntax.javaMailString(" (Alice)")); + } + + @Test + void javaMailStringUnquotesAPhraseOnlyAtItsOuterQuotesLikeJavaMail() { + assertEquals("\"Alice\\\" \\\"Bob\" ", + SesAddressSyntax.javaMailString("\"Alice\" \"Bob\" ")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesEncodedWordTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesEncodedWordTest.java new file mode 100644 index 0000000000..d65c9a9c11 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEncodedWordTest.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.ses; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The JavaMail {@code MimeUtility.encodeWord} rules {@link SesEncodedWord} follows: which names are + * encoded, the B or Q choice by character count, Q's word specials, and the recursive halving. + */ +class SesEncodedWordTest { + + @Test + void onlyNonAsciiOrControlCharactersNeedEncoding() { + assertFalse(SesEncodedWord.needsEncoding("Alice B. (x)")); + assertFalse(SesEncodedWord.needsEncoding("Alice\tB")); + assertTrue(SesEncodedWord.needsEncoding("山田")); + assertTrue(SesEncodedWord.needsEncoding("Alice\u007f")); + assertTrue(SesEncodedWord.needsEncoding("Alice\u0001")); + } + + @Test + void anEvenSplitOfAsciiAndNonAsciiIsB() { + assertEquals("=?UTF-8?B?YeWxsQ==?=", SesEncodedWord.encode("a山")); + } + + @Test + void qEscapesWordSpecialsAndWritesASpaceAsUnderscore() { + assertEquals("=?UTF-8?Q?Al_B=2E=E5=B1=B1?=", SesEncodedWord.encode("Al B.山")); + } + + @Test + void halvingNeverSplitsASurrogatePair() { + String encoded = SesEncodedWord.encode("a" + "😀".repeat(16)); + + assertEquals("=?UTF-8?B?YfCfmIDwn5iA8J+YgPCfmIDwn5iA8J+YgPCfmIA=?=" + + " =?UTF-8?B?8J+YgPCfmIDwn5iA8J+YgPCfmIDwn5iA8J+YgPCfmIDwn5iA?=", encoded); + } +} 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 index 03347d41a6..ef87f1cb8b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java @@ -402,6 +402,55 @@ class SesSendAddressSyntaxIntegrationTest { .body("ErrorResponse.Error.Message", equalTo(message)); } + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "sender.example.com | User name is missing: 'sender.example.com'.", + "Alice | User name is missing: 'Alice '.", + "sender.example.com (Alice) | User name is missing: 'Alice '.", + "\"sender example\" | User name is missing: '<\"sender example\">'.", + "山田 | User name is missing: '=?UTF-8?B?5bGx55Sw?= '.", + "\"Alice, B\" | User name is missing: '\"Alice, B\" '.", + "sender@example.com | User name is missing: '\"sender@example.com\" '.", + "Alice (Bob) | User name is missing: '\"Alice (Bob)\" '.", + "Alice (Bob) | User name is missing: 'Alice '.", + "\" \" (Alice) | User name is missing: 'sender.example.com'.", + " (Alice) | User name is missing: 'Alice '.", + "(Bob) | User name is missing: 'Bob '.", + "(Bob) Alice | User name is missing: 'Alice '." + }) + void v1SendRawEmail_fromHeaderWithoutAtAndSource_isAMissingUserName(String from, String message) { + given() + .contentType("application/x-www-form-urlencoded; charset=UTF-8") + .header("Authorization", AUTH) + .formParam("Action", "SendRawEmail") + .formParam("Source", "sender@example.com") + .formParam("Destinations.member.1", TO) + .formParam("RawMessage.Data", rawMessage(from)) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")) + .body("ErrorResponse.Error.Message", equalTo(message)); + } + + @Test + void v1SendRawEmail_otherFromHeaderViolationIsReportedBeforeMissingUserName() { + given() + .contentType("application/x-www-form-urlencoded; charset=UTF-8") + .header("Authorization", AUTH) + .formParam("Action", "SendRawEmail") + .formParam("Source", "sender@example.com") + .formParam("Destinations.member.1", TO) + .formParam("RawMessage.Data", rawMessage("sender.example.com, sender@")) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")) + .body("ErrorResponse.Error.Message", equalTo("Missing domain")); + } + private static String rawMessage(String from) { return Base64.getEncoder().encodeToString(("From: " + from + "\r\nTo: " + TO + "\r\nSubject: s\r\n\r\nb") .getBytes(StandardCharsets.UTF_8)); 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 index c34b7717d6..e4d7f6d302 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceAddressSyntaxTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceAddressSyntaxTest.java @@ -142,6 +142,61 @@ class SesServiceAddressSyntaxTest { } } + @Test + void v1RawSendWithSender_fromHeaderWithoutAtIsAMissingUserName() { + assertRejects("User name is missing: 'sender.example.com'.", () -> service.sendEmail(request(SENDER) + .content(fromHeaderRaw(NO_AT, false)).build())); + assertRejects("User name is missing: '=?UTF-8?B?5bGx55Sw?= '.", + () -> service.sendEmail(request(SENDER).content(fromHeaderRaw("山田 <" + NO_AT + ">", false)).build())); + } + + @Test + void v1RawSendWithSender_addressInTheDisplayNameIsNotSwappedIn() { + assertRejects("User name is missing: '\"sender@example.com\" '.", + () -> service.sendEmail(request(SENDER).content(fromHeaderRaw(SENDER + " <" + NO_AT + ">", false)).build())); + } + + @Test + void v1RawSendWithSender_onlyTheFirstFromHeaderAddressNeedsAnAt() { + assertRejects("User name is missing: 'sender.example.com'.", () -> service.sendEmail(request(SENDER) + .content(fromHeaderRaw(NO_AT + ", " + SENDER, false)).build())); + AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(request(SENDER) + .content(fromHeaderRaw(SENDER + ", " + NO_AT, false)).build())); + assertEquals("MessageRejected", e.getErrorCode(), "a later address without @ reaches sender verification"); + } + + @Test + void v1RawSendWithSender_otherFromHeaderViolationsAreReportedFirst() { + assertRejects("Missing domain", () -> service.sendEmail(request(SENDER) + .content(fromHeaderRaw(NO_AT + ", " + EMPTY_DOMAIN, false)).build())); + } + + @Test + void v1RawSendWithSender_missingUserNameIsReportedAfterRecipientSyntax() { + assertRejects(MISSING_FINAL_DOMAIN, () -> service.sendEmail(request(SENDER).toAddresses(List.of()) + .content(fromHeaderRaw(NO_AT, false, "success.simulator.amazonses.com")).build())); + } + + @Test + void v1RawSendWithSender_missingUserNameIsReportedAfterUnknownConfigurationSet() { + AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(request(SENDER) + .configurationSetName("missing").content(fromHeaderRaw(NO_AT, false)).build())); + + assertEquals("ConfigurationSetDoesNotExist", e.getErrorCode()); + } + + @Test + void v1RawSendWithSender_missingUserNameIsReportedAfterMissingDestination() { + assertRejects("Missing required header 'To'.", () -> service.sendEmail(request(SENDER).toAddresses(List.of()) + .content(rawWithoutTo(NO_AT, false)).build())); + } + + @Test + void v1RawSendWithSender_missingUserNameIsReportedBeforeLength() { + assertRejects("User name is missing: 'sender.example.com'.", () -> service.sendEmail(request(SENDER) + .toAddresses(List.of(address(321))).content(fromHeaderRaw(NO_AT, false)).build())); + } + @Test void v2RawSend_fromHeaderWithoutAtKeepsJavaMailMessage() { assertRejects(MISSING_FINAL_DOMAIN, () -> service.sendEmail(request(null) @@ -324,8 +379,12 @@ class SesServiceAddressSyntaxTest { } private static EmailContent.Raw v2RawWithoutTo(String from) { + return rawWithoutTo(from, true); + } + + private static EmailContent.Raw rawWithoutTo(String from, boolean fromHeaderAsFallback) { return new EmailContent.Raw(Base64.getEncoder().encodeToString(("From: " + from - + "\r\nSubject: s\r\n\r\nbody").getBytes(StandardCharsets.UTF_8)), true); + + "\r\nSubject: s\r\n\r\nbody").getBytes(StandardCharsets.UTF_8)), fromHeaderAsFallback); } private static EmailContent.Raw raw(String from, String to, String extraHeaders) {