fix(ses): require a verified sender to send email (#5156)

SendEmail, SendRawEmail and SendTemplatedEmail (v1) and SendEmail (v2)
accepted any Source or FromEmailAddress, so a send from an address that
was never verified succeeded and landed in /_aws/ses. The SendEmail API
Reference says "The message must be sent from a verified email address
or domain", and AWS rejects anything else with MessageRejected.

The send path now checks every address the developer guide names for
this error ("This error could apply to the "From", "Source", "Sender",
or "Return-Path" address"): the Source or FromEmailAddress, the
ReturnPath or FeedbackForwardingEmailAddress and, on a raw message,
every mailbox of its From header, its Sender and its Return-Path
header. A v2 raw send reads the From header only in place of a missing
FromEmailAddress and accepts any From header when one is given
(probe-confirmed), so the header is checked only then. An address
counts as verified when the address itself, its domain or a parent
domain is a verified identity ("if you create and verify an identity
for example.com, you don't need to create separate identities for
a.example.com, a.b.example.com, user@example.com, user@a.example.com").
The error matches AWS: one MessageRejected, "Email address is not
verified. The following identities failed the check in region
US-EAST-1: <address>, <address>", and nothing is captured or relayed.
The check runs after the request's own validation, so the existing
error order is unchanged.

A delegate sender names the owner's identity with SourceArn, FromArn
and ReturnPathArn, their X-SES-SOURCE-ARN, X-SES-FROM-ARN and
X-SES-RETURN-PATH-ARN headers, or v2 FromEmailAddressIdentityArn and
FeedbackForwardingEmailAddressIdentityArn. These are now read (a
parameter wins over its header, and only the first instance of a header
counts), and an address covered by another account's identity ARN is
not checked against the caller's identities. Floci does not evaluate
sending-authorization policies, so it lets such a send through, as it
did before. On a raw send the source ARN also covers the From and
return-path addresses that have no ARN of their own, as SendRawEmail
describes.

Cognito's verification codes and invitations go through SES too, from
Cognito's own no-reply@verificationemail.com or a pool's
EmailConfiguration sender that Cognito has already found verified. They
now use a separate entry point, sendServiceEmail, that skips the check.

Tests and compatibility tests that sent from an unverified address now
verify it first; where a test sent from an address under a domain
identity, the domain is verified by publishing its DKIM records, since
Floci keeps a domain Pending until they exist. SesDomainIdentityTestHelper
does that, and the two copies of the same setup in the configuration-set
tests and the one in SesV2IntegrationTest now use it.

Closes #5141
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-12 23:11:15 -04:00
1 parent bcda5958e0
commit 0edb6993ce
31 files changed
+1030 -259

No files matched your search

@@ -167,7 +167,7 @@ class CognitoLambdaTriggersTest {
private static void assertVerificationEmail(SesService ses, String to, String subject, String body) {
ArgumentCaptor<SendEmailRequest> captor = ArgumentCaptor.forClass(SendEmailRequest.class);
verify(ses).sendEmail(captor.capture());
verify(ses).sendServiceEmail(captor.capture());
SendEmailRequest sent = captor.getValue();
assertEquals(SendEmailRequest.builder()
.source(sent.source())
@@ -561,7 +561,7 @@ class CognitoMessageDispatcherTest {
@Test
void dispatchInvitation_failureOnTheOnlyMedium_isRethrown() {
when(ses.sendEmail(any())).thenThrow(new IllegalStateException("SES down"));
when(ses.sendServiceEmail(any())).thenThrow(new IllegalStateException("SES down"));
assertThrows(IllegalStateException.class, () -> dispatcher.dispatchInvitation(pool(Map.of()),
invitee("alice@example.com", null), "Temp1234!", List.of("EMAIL"), null));
@@ -587,7 +587,7 @@ class CognitoMessageDispatcherTest {
private SendEmailRequest sentEmail() {
ArgumentCaptor<SendEmailRequest> captor = ArgumentCaptor.forClass(SendEmailRequest.class);
verify(ses).sendEmail(captor.capture());
verify(ses).sendServiceEmail(captor.capture());
return captor.getValue();
}
@@ -26,7 +26,23 @@ class SesConfigurationSetSendingOptionsV2IntegrationTest {
private static final String SES_AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String CS = "cs-sending-options";
private static final String SENDER = "sender@example.com";
// A sender of its own, verified below: the identity outlives this class, and other SES classes
// that share the application create sender@example.com themselves.
private static final String SENDER = "cs-sending-options-sender@floci.test";
@Test
@Order(0)
void verifySender() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SES_AUTH)
.formParam("Action", "VerifyEmailIdentity")
.formParam("EmailAddress", SENDER)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(1)
@@ -7,8 +7,6 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@@ -33,75 +31,6 @@ class SesConfigurationSetTrackingOptionsV1IntegrationTest {
private static final String DOMAIN = "track-v1.floci.test";
private static final String CS = "v1-cs-tracking";
private static void verifyDomainIdentityViaRoute53(String domain, String callerReference) {
List<String> tokens = given()
.contentType("application/json")
.header("Authorization", AUTH_V2)
.body("{\"EmailIdentity\": \"" + domain + "\"}")
.when()
.post("/v2/email/identities")
.then()
.statusCode(200)
.extract()
.jsonPath()
.getList("DkimAttributes.Tokens", String.class);
String locationHeader = given()
.contentType("application/xml")
.body("""
<?xml version="1.0" encoding="UTF-8"?>
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>floci.test</Name>
<CallerReference>""" + callerReference + """
</CallerReference>
</CreateHostedZoneRequest>
""")
.when()
.post("/2013-04-01/hostedzone")
.then()
.statusCode(201)
.extract()
.header("Location");
String zoneId = locationHeader.substring(locationHeader.lastIndexOf('/') + 1);
StringBuilder body = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
""");
for (String token : tokens) {
body.append("""
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>""").append(token).append("._domainkey.").append(domain).append(".</Name>\n")
.append("""
<Type>CNAME</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>""").append(token).append(".dkim.amazonses.com.</Value></ResourceRecord>\n")
.append("""
</ResourceRecords>
</ResourceRecordSet>
</Change>
""");
}
body.append("""
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""");
given()
.contentType("application/xml")
.body(body.toString())
.when()
.post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(200);
}
private static RequestSpecification query(String action) {
return given()
.contentType("application/x-www-form-urlencoded")
@@ -112,7 +41,7 @@ class SesConfigurationSetTrackingOptionsV1IntegrationTest {
@Test
@Order(1)
void setup_verifyDomain_andCreateConfigSet() {
verifyDomainIdentityViaRoute53(DOMAIN, "v1-cs-tracking");
SesDomainIdentityTestHelper.createVerified(DOMAIN, AUTH_V2);
query("CreateConfigurationSet").formParam("ConfigurationSet.Name", CS)
.when().post("/").then().statusCode(200);
}
@@ -172,7 +101,7 @@ class SesConfigurationSetTrackingOptionsV1IntegrationTest {
@Test
@Order(6)
void updateTrackingOptions_changesDomain() {
verifyDomainIdentityViaRoute53("other." + DOMAIN, "v1-cs-tracking-other");
SesDomainIdentityTestHelper.createVerified("other." + DOMAIN, AUTH_V2);
query("UpdateConfigurationSetTrackingOptions")
.formParam("ConfigurationSetName", CS)
.formParam("TrackingOptions.CustomRedirectDomain", "other." + DOMAIN)
@@ -6,8 +6,6 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@@ -24,75 +22,6 @@ class SesConfigurationSetV2IntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static void verifyDomainIdentityViaRoute53(String domain, String callerReference) {
List<String> tokens = given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("{\"EmailIdentity\": \"" + domain + "\"}")
.when()
.post("/v2/email/identities")
.then()
.statusCode(200)
.extract()
.jsonPath()
.getList("DkimAttributes.Tokens", String.class);
String locationHeader = given()
.contentType("application/xml")
.body("""
<?xml version="1.0" encoding="UTF-8"?>
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>floci.test</Name>
<CallerReference>""" + callerReference + """
</CallerReference>
</CreateHostedZoneRequest>
""")
.when()
.post("/2013-04-01/hostedzone")
.then()
.statusCode(201)
.extract()
.header("Location");
String zoneId = locationHeader.substring(locationHeader.lastIndexOf('/') + 1);
StringBuilder body = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
""");
for (String token : tokens) {
body.append("""
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>""").append(token).append("._domainkey.").append(domain).append(".</Name>\n")
.append("""
<Type>CNAME</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>""").append(token).append(".dkim.amazonses.com.</Value></ResourceRecord>\n")
.append("""
</ResourceRecords>
</ResourceRecordSet>
</Change>
""");
}
body.append("""
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""");
given()
.contentType("application/xml")
.body(body.toString())
.when()
.post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(200);
}
@Test
@Order(1)
void createConfigurationSet() {
@@ -837,7 +766,7 @@ class SesConfigurationSetV2IntegrationTest {
@Test
@Order(37)
void putTrackingOptions_verifiedDomain_echoed() {
verifyDomainIdentityViaRoute53("track.floci.test", "v2-cs-tracking");
SesDomainIdentityTestHelper.createVerified("track.floci.test", AUTH_HEADER);
putConfigSet("v2-cs-tracking");
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"CustomRedirectDomain\": \"track.floci.test\", \"HttpsPolicy\": \"REQUIRE\"}")
@@ -867,7 +796,7 @@ class SesConfigurationSetV2IntegrationTest {
void putTrackingOptions_invalidHttpsPolicy_returns400() {
// AWS validates the HttpsPolicy enum only after CustomRedirectDomain
// presence and verification, so the domain must be verified to reach it.
verifyDomainIdentityViaRoute53("track-enum.floci.test", "v2-cs-tracking-enum");
SesDomainIdentityTestHelper.createVerified("track-enum.floci.test", AUTH_HEADER);
putConfigSet("v2-cs-tracking-enum");
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"CustomRedirectDomain\": \"track-enum.floci.test\", \"HttpsPolicy\": \"BOGUS\"}")
@@ -1053,7 +982,7 @@ class SesConfigurationSetV2IntegrationTest {
void putTrackingOptions_emptyBody_clears() {
// An empty PUT body clears tracking options rather than persisting an
// empty block that GetConfigurationSet would echo as {}.
verifyDomainIdentityViaRoute53("clear.floci.test", "v2-cs-tracking-clear");
SesDomainIdentityTestHelper.createVerified("clear.floci.test", AUTH_HEADER);
putConfigSet("v2-cs-tracking-clear");
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"CustomRedirectDomain\": \"clear.floci.test\", \"HttpsPolicy\": \"REQUIRE\"}")
@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.ses;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
/**
* Creates a domain identity that is verified for sending. A domain identity stays Pending until
* its DKIM CNAME records exist in a Route 53 hosted zone, so this publishes them in a zone of its
* own. A test that checks the Pending state first creates the identity itself and then calls
* {@link #publishDkimRecords}.
*/
final class SesDomainIdentityTestHelper {
private SesDomainIdentityTestHelper() {
}
static void createVerified(String domain, String sesAuthorization) {
List<String> tokens = given()
.contentType("application/json")
.header("Authorization", sesAuthorization)
.body("{\"EmailIdentity\": \"" + domain + "\"}")
.when()
.post("/v2/email/identities")
.then()
.statusCode(200)
.extract()
.jsonPath()
.getList("DkimAttributes.Tokens", String.class);
publishDkimRecords(domain, tokens);
}
static void publishDkimRecords(String domain, List<String> tokens) {
String location = given()
.contentType("application/xml")
.body("""
<?xml version="1.0" encoding="UTF-8"?>
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>%s</Name>
<CallerReference>%s</CallerReference>
</CreateHostedZoneRequest>
""".formatted(domain, UUID.randomUUID()))
.when()
.post("/2013-04-01/hostedzone")
.then()
.statusCode(201)
.extract()
.header("Location");
StringBuilder changes = new StringBuilder();
for (String token : tokens) {
changes.append("""
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>%s._domainkey.%s.</Name>
<Type>CNAME</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>%s.dkim.amazonses.com.</Value></ResourceRecord>
</ResourceRecords>
</ResourceRecordSet>
</Change>
""".formatted(token, domain, token));
}
given()
.contentType("application/xml")
.body("""
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
%s </Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""".formatted(changes))
.when()
.post("/2013-04-01/hostedzone/" + location.substring(location.lastIndexOf('/') + 1) + "/rrset")
.then()
.statusCode(200);
}
}
@@ -1304,6 +1304,15 @@ class SesEventPublishingV2IntegrationTest {
.then()
.statusCode(200);
given()
.contentType("application/json")
.header("Authorization", sesAuth)
.body("{\"EmailIdentity\":\"" + SENDER + "\"}")
.when()
.post("/v2/email/identities")
.then()
.statusCode(200);
given()
.contentType("application/json")
.header("Authorization", sesAuth)
@@ -119,6 +119,9 @@ class SesIdentityNotificationTopicPublishV1IntegrationTest {
verifyDomainIdentity(FALLBACK_DOMAIN);
setIdentityNotificationTopic(FALLBACK_DOMAIN, "Bounce", topicArn);
// The domain stays Pending without its DKIM records, so the address under it is verified
// on its own to be allowed to send; it has no topic of its own.
verifyEmailIdentity("anyone@" + FALLBACK_DOMAIN);
}
@Test
@@ -16,6 +16,10 @@ import static org.hamcrest.Matchers.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesIntegrationTest {
// sender@example.com is deleted at @Order(20), and the domain test after it expects no
// identity under example.com, so the later sends use a sender of their own.
private static final String INSPECTION_SENDER = "inspection-sender@floci.test";
private static String authorization(String service) {
return authorization(service, "us-east-1");
}
@@ -24,6 +28,18 @@ class SesIntegrationTest {
return "AWS4-HMAC-SHA256 Credential=AKID/20260101/" + region + "/" + service + "/aws4_request";
}
private static void verifySender(String address) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", authorization("email"))
.formParam("Action", "VerifyEmailIdentity")
.formParam("EmailAddress", address)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(1)
void verifyEmailIdentity() {
@@ -222,13 +238,14 @@ class SesIntegrationTest {
// Regression for https://github.com/floci-io/floci/issues/797
// AWS SES SendRawEmail allows omitting the Source parameter when the
// raw MIME message contains a From: header.
verifySender(INSPECTION_SENDER);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
.formParam("Action", "SendRawEmail")
.formParam("Destinations.member.1", "recipient@example.com")
.formParam("RawMessage.Data",
"From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: hello\r\n\r\nbody\r\n")
"From: " + INSPECTION_SENDER + "\r\nTo: recipient@example.com\r\nSubject: hello\r\n\r\nbody\r\n")
.when()
.post("/")
.then()
@@ -421,13 +438,14 @@ class SesIntegrationTest {
@Test
@Order(21)
void sendEmailV1_replyToAddressesStoredInInspection() {
verifySender(INSPECTION_SENDER);
given().delete("/_aws/ses").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
.formParam("Action", "SendEmail")
.formParam("Source", "sender@example.com")
.formParam("Source", INSPECTION_SENDER)
.formParam("Destination.ToAddresses.member.1", "recipient@example.com")
.formParam("ReplyToAddresses.member.1", "reply@example.com")
.formParam("Message.Subject.Data", "V1 ReplyTo")
@@ -449,15 +467,17 @@ class SesIntegrationTest {
@Test
@Order(21)
void sendEmailV1_returnPathStoredInInspection() {
verifySender(INSPECTION_SENDER);
verifySender("inspection-bounces@floci.test");
given().delete("/_aws/ses").then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
.formParam("Action", "SendEmail")
.formParam("Source", "sender@example.com")
.formParam("Source", INSPECTION_SENDER)
.formParam("Destination.ToAddresses.member.1", "recipient@example.com")
.formParam("ReturnPath", "bounces@example.com")
.formParam("ReturnPath", "inspection-bounces@floci.test")
.formParam("Message.Subject.Data", "V1 ReturnPath")
.formParam("Message.Body.Text.Data", "body")
.when()
@@ -470,17 +490,19 @@ class SesIntegrationTest {
.get("/_aws/ses")
.then()
.statusCode(200)
.body("messages[0].ReturnPath", equalTo("bounces@example.com"));
.body("messages[0].ReturnPath", equalTo("inspection-bounces@floci.test"));
}
@Test
@Order(21)
void sendRawEmailV1_returnPathHeaderStoredInInspection() {
verifySender(INSPECTION_SENDER);
verifySender("inspection-mime-bounces@floci.test");
given().delete("/_aws/ses").then().statusCode(200);
String raw = "From: sender@example.com\r\n"
String raw = "From: " + INSPECTION_SENDER + "\r\n"
+ "To: recipient@example.com\r\n"
+ "Return-Path: <mime-bounces@example.com>\r\n"
+ "Return-Path: <inspection-mime-bounces@floci.test>\r\n"
+ "Subject: raw-return-path\r\n\r\nbody";
String rawB64 = java.util.Base64.getEncoder().encodeToString(
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
@@ -489,7 +511,7 @@ class SesIntegrationTest {
.contentType("application/x-www-form-urlencoded")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
.formParam("Action", "SendRawEmail")
.formParam("Source", "sender@example.com")
.formParam("Source", INSPECTION_SENDER)
.formParam("Destinations.member.1", "recipient@example.com")
.formParam("RawMessage.Data", rawB64)
.when()
@@ -502,7 +524,7 @@ class SesIntegrationTest {
.get("/_aws/ses")
.then()
.statusCode(200)
.body("messages[0].ReturnPath", equalTo("mime-bounces@example.com"));
.body("messages[0].ReturnPath", equalTo("inspection-mime-bounces@floci.test"));
}
@Test
@@ -24,6 +24,15 @@ class SesListManagementOptionsV2IntegrationTest {
private static final String LIST = "lmo-newsletter";
private static final String FROM = "lmo-sender@floci.test";
@Test
@Order(0)
void setup_verifySender() {
given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
.formParam("Action", "VerifyEmailIdentity")
.formParam("EmailAddress", FROM)
.when().post("/").then().statusCode(200);
}
@Test
@Order(0)
void setup_contactList() {
@@ -20,6 +20,21 @@ class SesSendAddressSyntaxIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String TO = "success@simulator.amazonses.com";
// A sender of its own: an identity under example.com would outlive this class and reach the
// other SES classes that share the application.
private static final String VERIFIED_SENDER = "syntax-sender@floci.test";
private static void verifySender() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH)
.formParam("Action", "VerifyEmailIdentity")
.formParam("EmailAddress", VERIFIED_SENDER)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void v1SendEmail_sourceWithoutAt_returnsInvalidParameterValue() {
@@ -302,16 +317,17 @@ class SesSendAddressSyntaxIntegrationTest {
@ParameterizedTest
@ValueSource(strings = {"sender.example.com", "sender@", "やまだ@example.com", "sender@例え.jp"})
void v2SendEmailRaw_malformedFromHeaderIsNotCheckedWithFromEmailAddress(String from) {
verifySender();
given()
.contentType("application/json; charset=UTF-8")
.header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "sender@example.com",
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["%s"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(TO, rawMessage(from)))
""".formatted(VERIFIED_SENDER, TO, rawMessage(from)))
.when()
.post("/v2/email/outbound-emails")
.then()
@@ -322,17 +338,18 @@ class SesSendAddressSyntaxIntegrationTest {
@Test
void v2SendEmailRaw_overLimitFromHeaderIsNotMeasuredWithFromEmailAddress() {
String from = "A".repeat(321 - " <sender@example.com>".length()) + " <sender@example.com>";
verifySender();
given()
.contentType("application/json; charset=UTF-8")
.header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "sender@example.com",
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["%s"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(TO, rawMessage(from)))
""".formatted(VERIFIED_SENDER, TO, rawMessage(from)))
.when()
.post("/v2/email/outbound-emails")
.then()
@@ -17,6 +17,7 @@ class SesSendRawNoDestinationIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String TO = "success@simulator.amazonses.com";
private static final String VERIFIED_SENDER = "no-destination-sender@floci.test";
private static String rawData(String headers) {
return Base64.getEncoder().encodeToString(
@@ -25,15 +26,25 @@ class SesSendRawNoDestinationIntegrationTest {
@Test
void v2SendEmail_rawWithoutDestination_takesRecipientsFromHeaders() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH)
.formParam("Action", "VerifyEmailIdentity")
.formParam("EmailAddress", VERIFIED_SENDER)
.when()
.post("/")
.then()
.statusCode(200);
String messageId = given()
.contentType("application/json")
.header("Authorization", AUTH)
.body("""
{
"FromEmailAddress": "sender@example.com",
"FromEmailAddress": "%s",
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(rawData("From: sender@example.com\r\nTo: " + TO + "\r\n")))
""".formatted(VERIFIED_SENDER, rawData("From: " + VERIFIED_SENDER + "\r\nTo: " + TO + "\r\n")))
.when()
.post("/v2/email/outbound-emails")
.then()
@@ -0,0 +1,560 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
/**
* The send operations require a verified sender, as on AWS: "The message must be sent from a
* verified email address or domain. If you attempt to send email using a non-verified address or
* domain, the operation results in an "Email address not verified" error."
* (<a href="https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html">SendEmail</a>).
* An address counts as verified when the address itself, its domain or a parent domain is a verified
* identity. The check covers every "From", "Source", "Sender" and "Return-Path" address
* (<a href="https://docs.aws.amazon.com/ses/latest/dg/troubleshoot-error-messages.html">Email
* sending errors</a>) the send uses, except the ones a sending-authorization ARN puts under another
* account's identity.
*/
@QuarkusTest
class SesSendVerifiedSenderIntegrationTest {
private static final String AUTH_V1 =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String AUTH_V2 =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String UNVERIFIED = "never-verified@unverified-sender.floci.test";
private static final String VERIFIED = "verified@verified-sender.floci.test";
private static final String NOT_VERIFIED_MESSAGE =
"Email address is not verified. The following identities failed the check in region US-EAST-1: ";
private static final String TEMPLATE = "verified-sender-check";
// Sending authorization: the owner account verifies OWNER_ADDRESS, and the delegate account
// sends from it.
private static final String OWNER_ACCOUNT = "111111111111";
private static final String DELEGATE_ACCOUNT = "222222222222";
private static final String OWNER_ADDRESS = "user@owner.floci.test";
private static final String OWNER_IDENTITY_ARN =
"arn:aws:ses:us-east-1:" + OWNER_ACCOUNT + ":identity/" + OWNER_ADDRESS;
private static final String DELEGATE_IDENTITY_ARN =
"arn:aws:ses:us-east-1:" + DELEGATE_ACCOUNT + ":identity/" + OWNER_ADDRESS;
private static final String DELEGATE_AUTH_V1 =
"AWS4-HMAC-SHA256 Credential=" + DELEGATE_ACCOUNT + "/20260101/us-east-1/email/aws4_request";
private static final String DELEGATE_AUTH_V2 =
"AWS4-HMAC-SHA256 Credential=" + DELEGATE_ACCOUNT + "/20260101/us-east-1/ses/aws4_request";
private static RequestSpecification query(String action) {
return query(AUTH_V1, action);
}
private static RequestSpecification query(String authorization, String action) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", authorization)
.formParam("Action", action);
}
private static RequestSpecification sendEmail(String authorization, String source) {
return query(authorization, "SendEmail")
.formParam("Source", source)
.formParam("Destination.ToAddresses.member.1", "to@example.com")
.formParam("Message.Subject.Data", "s")
.formParam("Message.Body.Text.Data", "b");
}
private static RequestSpecification sendRawEmail(String authorization, String rawMessage) {
return query(authorization, "SendRawEmail")
.formParam("Destinations.member.1", "to@example.com")
.formParam("RawMessage.Data", rawMessage);
}
private static RequestSpecification sendTemplatedEmail(String authorization, String source) {
return query(authorization, "SendTemplatedEmail")
.formParam("Source", source)
.formParam("Destination.ToAddresses.member.1", "to@example.com")
.formParam("Template", TEMPLATE)
.formParam("TemplateData", "{}");
}
private static String simpleBody(String from) {
return """
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
}
""".formatted(from);
}
private static RequestSpecification v2Request(String authorization, String body) {
return given()
.contentType("application/json")
.header("Authorization", authorization)
.body(body);
}
private static void verifyEmailIdentity(String address) {
query("VerifyEmailIdentity").formParam("EmailAddress", address)
.when().post("/").then().statusCode(200);
}
private static void verifyOwnerAddress() {
query("AWS4-HMAC-SHA256 Credential=" + OWNER_ACCOUNT + "/20260101/us-east-1/email/aws4_request",
"VerifyEmailIdentity")
.formParam("EmailAddress", OWNER_ADDRESS)
.when().post("/").then().statusCode(200);
}
private static void createTemplate(String authorization) {
query(authorization, "CreateTemplate")
.formParam("Template.TemplateName", TEMPLATE)
.formParam("Template.SubjectPart", "s")
.formParam("Template.TextPart", "b")
.when()
.post("/");
}
/** A base64 raw message from {@code from}, with each of {@code headers} ("Name: value") above it. */
private static String rawMessage(String from, String... headers) {
StringBuilder raw = new StringBuilder();
for (String header : headers) {
raw.append(header).append("\r\n");
}
raw.append("From: ").append(from).append("\r\nTo: to@example.com\r\nSubject: s\r\n\r\nbody");
return Base64.getEncoder().encodeToString(raw.toString().getBytes(StandardCharsets.UTF_8));
}
private static void assertSent(RequestSpecification request, String action) {
request
.when()
.post("/")
.then()
.statusCode(200)
.body(action + "Response." + action + "Result.MessageId", notNullValue());
}
private static void assertSentV2(RequestSpecification request) {
request
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(200)
.body("MessageId", notNullValue());
}
private static void assertMessageRejectedV2(RequestSpecification request, String unverified) {
request
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(400)
.body("__type", equalTo("MessageRejected"))
.body("message", equalTo(NOT_VERIFIED_MESSAGE + unverified));
}
private static void assertMessageRejected(RequestSpecification request, String unverified) {
request
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MessageRejected"))
.body("ErrorResponse.Error.Message", equalTo(NOT_VERIFIED_MESSAGE + unverified));
}
private static void assertNothingCapturedFrom(String source) {
given()
.when()
.get("/_aws/ses")
.then()
.statusCode(200)
.body("messages.Source", everyItem(not(equalTo(source))));
}
@Test
void v1SendEmail_unverifiedSource_returnsMessageRejected() {
assertMessageRejected(sendEmail(AUTH_V1, UNVERIFIED), UNVERIFIED);
assertNothingCapturedFrom(UNVERIFIED);
}
@Test
void v1SendEmail_displayNameSourceWithVerifiedAddress_succeeds() {
verifyEmailIdentity(VERIFIED);
assertSent(sendEmail(AUTH_V1, "Verified Sender <" + VERIFIED + ">"), "SendEmail");
}
@Test
void v1SendRawEmail_unverifiedSource_returnsMessageRejected() {
assertMessageRejected(sendRawEmail(AUTH_V1, rawMessage(UNVERIFIED)).formParam("Source", UNVERIFIED),
UNVERIFIED);
assertNothingCapturedFrom(UNVERIFIED);
}
@Test
void v1SendRawEmail_withoutSource_unverifiedMimeFrom_returnsMessageRejected() {
assertMessageRejected(sendRawEmail(AUTH_V1, rawMessage(UNVERIFIED)), UNVERIFIED);
}
@Test
void v1SendTemplatedEmail_unverifiedSource_returnsMessageRejected() {
createTemplate(AUTH_V1);
assertMessageRejected(sendTemplatedEmail(AUTH_V1, UNVERIFIED), UNVERIFIED);
}
@Test
void v2SendEmail_simple_unverifiedFrom_returnsMessageRejected() {
assertMessageRejectedV2(v2Request(AUTH_V2, simpleBody(UNVERIFIED)), UNVERIFIED);
assertNothingCapturedFrom(UNVERIFIED);
}
@Test
void v2SendEmail_raw_unverifiedMimeFrom_returnsMessageRejected() {
assertMessageRejectedV2(v2Request(AUTH_V2, """
{
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(rawMessage(UNVERIFIED))), UNVERIFIED);
}
@Test
void v2SendEmail_verifiedEmailIdentity_succeeds() {
v2Request(AUTH_V2, "{\"EmailIdentity\": \"v2-" + VERIFIED + "\"}")
.when()
.post("/v2/email/identities");
assertSentV2(v2Request(AUTH_V2, simpleBody("v2-" + VERIFIED)));
}
@Test
void v2SendEmail_addressUnderVerifiedDomain_succeeds() {
String domain = "verified-domain.floci.test";
SesDomainIdentityTestHelper.createVerified(domain, AUTH_V2);
assertSentV2(v2Request(AUTH_V2, simpleBody("anyone@" + domain)));
}
@Test
void v2SendEmail_addressUnderASubdomainOfAVerifiedDomain_succeeds() {
// "if you create and verify an identity for example.com, you don't need to create separate
// identities for a.example.com, a.b.example.com, user@example.com, user@a.example.com".
String domain = "verified-parent.floci.test";
SesDomainIdentityTestHelper.createVerified(domain, AUTH_V2);
assertSentV2(v2Request(AUTH_V2, simpleBody("anyone@a.b." + domain)));
}
@Test
void v1SendEmail_addressUnderADomainThatOnlyEndsLikeAVerifiedOne_returnsMessageRejected() {
String domain = "verified-suffix.floci.test";
SesDomainIdentityTestHelper.createVerified(domain, AUTH_V2);
String lookalike = "anyone@not-" + domain;
assertMessageRejected(sendEmail(AUTH_V1, lookalike), lookalike);
}
@Test
void v1SendRawEmail_withoutSource_unverifiedSecondMimeFrom_returnsMessageRejected() {
String first = "first-" + VERIFIED;
String second = "second@unverified-sender.floci.test";
verifyEmailIdentity(first);
assertMessageRejected(sendRawEmail(AUTH_V1, rawMessage(first + ", " + second)), second);
assertNothingCapturedFrom(first);
}
@Test
void v1SendRawEmail_withoutSource_everyMimeFromVerified_succeeds() {
String first = "both-first-" + VERIFIED;
String second = "both-second-" + VERIFIED;
verifyEmailIdentity(first);
verifyEmailIdentity(second);
assertSent(sendRawEmail(AUTH_V1, rawMessage(first + ", " + second)), "SendRawEmail");
}
@Test
void v1SendEmail_addressUnderPendingDomain_returnsMessageRejected() {
// A domain identity stays Pending until its DKIM records are published, and a pending
// domain does not verify the addresses under it.
String domain = "pending-domain.floci.test";
query("VerifyDomainIdentity").formParam("Domain", domain)
.when().post("/").then().statusCode(200);
assertMessageRejected(sendEmail(AUTH_V1, "anyone@" + domain), "anyone@" + domain);
}
@Test
void v1SendEmail_unverifiedReturnPath_returnsMessageRejected() {
String source = "rp-source-" + VERIFIED;
String returnPath = "bounces@unverified-sender.floci.test";
verifyEmailIdentity(source);
assertMessageRejected(sendEmail(AUTH_V1, source).formParam("ReturnPath", returnPath), returnPath);
assertNothingCapturedFrom(source);
}
@Test
void v1SendTemplatedEmail_unverifiedReturnPath_returnsMessageRejected() {
String source = "rp-templated-" + VERIFIED;
String returnPath = "templated-bounces@unverified-sender.floci.test";
verifyEmailIdentity(source);
createTemplate(AUTH_V1);
assertMessageRejected(sendTemplatedEmail(AUTH_V1, source).formParam("ReturnPath", returnPath), returnPath);
assertNothingCapturedFrom(source);
}
@Test
void v2SendEmail_simple_unverifiedFeedbackForwardingAddress_returnsMessageRejected() {
String source = "rp-v2-" + VERIFIED;
String feedback = "v2-bounces@unverified-sender.floci.test";
verifyEmailIdentity(source);
assertMessageRejectedV2(v2Request(AUTH_V2, """
{
"FromEmailAddress": "%s",
"FeedbackForwardingEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
}
""".formatted(source, feedback)), feedback);
assertNothingCapturedFrom(source);
}
@Test
void v2SendEmail_raw_unverifiedFeedbackForwardingAddress_returnsMessageRejected() {
String source = "rp-v2-raw-" + VERIFIED;
String feedback = "v2-raw-bounces@unverified-sender.floci.test";
verifyEmailIdentity(source);
assertMessageRejectedV2(v2Request(AUTH_V2, """
{
"FeedbackForwardingEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(feedback, rawMessage(source))), feedback);
assertNothingCapturedFrom(source);
}
@Test
void v1SendRawEmail_verifiedSourceWithUnverifiedMimeFrom_returnsMessageRejected() {
String source = "raw-source-" + VERIFIED;
verifyEmailIdentity(source);
assertMessageRejected(sendRawEmail(AUTH_V1, rawMessage(UNVERIFIED)).formParam("Source", source), UNVERIFIED);
assertNothingCapturedFrom(source);
}
@Test
void v2SendEmail_raw_verifiedFromEmailAddress_mimeFromIsNotChecked() {
// A v2 raw send reads the From header only in place of a missing FromEmailAddress.
String source = "raw-v2-source-" + VERIFIED;
verifyEmailIdentity(source);
assertSentV2(v2Request(AUTH_V2, """
{
"FromEmailAddress": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(source, rawMessage(UNVERIFIED))));
}
@Test
void v1SendRawEmail_unverifiedSenderHeader_returnsMessageRejected() {
String from = "raw-sender-from-" + VERIFIED;
String sender = "assistant@unverified-sender.floci.test";
verifyEmailIdentity(from);
assertMessageRejected(sendRawEmail(AUTH_V1, rawMessage(from, "Sender: " + sender)), sender);
assertNothingCapturedFrom(from);
}
@Test
void v1SendRawEmail_unverifiedReturnPathHeader_returnsMessageRejected() {
String from = "raw-return-path-from-" + VERIFIED;
String returnPath = "raw-bounces@unverified-sender.floci.test";
verifyEmailIdentity(from);
assertMessageRejected(sendRawEmail(AUTH_V1, rawMessage(from, "Return-Path: <" + returnPath + ">")),
returnPath);
assertNothingCapturedFrom(from);
}
@Test
void v1SendRawEmail_sourceFromSenderAndReturnPathAllVerified_succeeds() {
String source = "all-source-" + VERIFIED;
String from = "all-from-" + VERIFIED;
String sender = "all-sender-" + VERIFIED;
String returnPath = "all-return-path-" + VERIFIED;
for (String address : List.of(source, from, sender, returnPath)) {
verifyEmailIdentity(address);
}
assertSent(sendRawEmail(AUTH_V1, rawMessage(from, "Sender: " + sender, "Return-Path: <" + returnPath + ">"))
.formParam("Source", source), "SendRawEmail");
}
@Test
void v1SendEmail_twoUnverifiedAddresses_oneErrorNamesBoth() {
String returnPath = "both-bounces@unverified-sender.floci.test";
assertMessageRejected(sendEmail(AUTH_V1, UNVERIFIED).formParam("ReturnPath", returnPath),
UNVERIFIED + ", " + returnPath);
}
@Test
void v1SendEmail_sourceArnOfAnotherAccount_succeeds() {
verifyOwnerAddress();
assertSent(sendEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS).formParam("SourceArn", OWNER_IDENTITY_ARN),
"SendEmail");
}
@Test
void v1SendEmail_addressVerifiedOnlyInAnotherAccount_withoutSourceArn_returnsMessageRejected() {
verifyOwnerAddress();
assertMessageRejected(sendEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS), OWNER_ADDRESS);
}
@Test
void v1SendEmail_sourceArnOfTheCallersOwnAccount_returnsMessageRejected() {
verifyOwnerAddress();
assertMessageRejected(sendEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS)
.formParam("SourceArn", DELEGATE_IDENTITY_ARN), OWNER_ADDRESS);
}
@Test
void v1SendEmail_sourceArnThatNamesNoSesIdentity_returnsMessageRejected() {
verifyOwnerAddress();
assertMessageRejected(sendEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS)
.formParam("SourceArn", "arn:aws:ses:us-east-1:" + OWNER_ACCOUNT + ":configuration-set/owner"),
OWNER_ADDRESS);
assertMessageRejected(sendEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS)
.formParam("SourceArn", "arn:aws:sns:us-east-1:" + OWNER_ACCOUNT + ":identity/" + OWNER_ADDRESS),
OWNER_ADDRESS);
}
@Test
void v1SendEmail_returnPathArnOfAnotherAccount_coversOnlyTheReturnPath() {
verifyOwnerAddress();
assertMessageRejected(sendEmail(DELEGATE_AUTH_V1, UNVERIFIED)
.formParam("ReturnPath", OWNER_ADDRESS)
.formParam("ReturnPathArn", OWNER_IDENTITY_ARN), UNVERIFIED);
}
@Test
void v1SendTemplatedEmail_sourceAndReturnPathArnsOfAnotherAccount_succeeds() {
verifyOwnerAddress();
createTemplate(DELEGATE_AUTH_V1);
assertSent(sendTemplatedEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS)
.formParam("SourceArn", OWNER_IDENTITY_ARN)
.formParam("ReturnPath", OWNER_ADDRESS)
.formParam("ReturnPathArn", OWNER_IDENTITY_ARN), "SendTemplatedEmail");
}
@Test
void v1SendRawEmail_sourceArnHeaderOfAnotherAccount_coversTheFromAndReturnPath() {
verifyOwnerAddress();
assertSent(sendRawEmail(DELEGATE_AUTH_V1, rawMessage(OWNER_ADDRESS,
"X-SES-SOURCE-ARN: " + OWNER_IDENTITY_ARN, "Return-Path: <" + OWNER_ADDRESS + ">")), "SendRawEmail");
}
@Test
void v1SendRawEmail_fromAndReturnPathArnHeadersOfAnotherAccount_coverTheirAddresses() {
verifyOwnerAddress();
assertSent(sendRawEmail(DELEGATE_AUTH_V1, rawMessage(OWNER_ADDRESS,
"X-SES-FROM-ARN: " + OWNER_IDENTITY_ARN, "X-SES-RETURN-PATH-ARN: " + OWNER_IDENTITY_ARN,
"Return-Path: <" + OWNER_ADDRESS + ">")), "SendRawEmail");
}
@Test
void v1SendRawEmail_sourceArnParameterWinsOverItsHeader() {
verifyOwnerAddress();
assertSent(sendRawEmail(DELEGATE_AUTH_V1,
rawMessage(OWNER_ADDRESS, "X-SES-SOURCE-ARN: " + DELEGATE_IDENTITY_ARN))
.formParam("Source", OWNER_ADDRESS)
.formParam("SourceArn", OWNER_IDENTITY_ARN), "SendRawEmail");
}
@Test
void v1SendRawEmail_fromArnParameterWinsOverItsHeader() {
verifyOwnerAddress();
assertSent(sendRawEmail(DELEGATE_AUTH_V1, rawMessage(OWNER_ADDRESS, "X-SES-FROM-ARN: " + DELEGATE_IDENTITY_ARN))
.formParam("FromArn", OWNER_IDENTITY_ARN), "SendRawEmail");
}
@Test
void v1SendRawEmail_returnPathArnParameterCoversTheReturnPathHeader() {
verifyOwnerAddress();
assertSent(sendRawEmail(DELEGATE_AUTH_V1, rawMessage(OWNER_ADDRESS, "Return-Path: <" + OWNER_ADDRESS + ">"))
.formParam("FromArn", OWNER_IDENTITY_ARN)
.formParam("ReturnPathArn", OWNER_IDENTITY_ARN), "SendRawEmail");
}
@Test
void v2SendEmail_fromAndFeedbackForwardingIdentityArnsOfAnotherAccount_succeeds() {
verifyOwnerAddress();
assertSentV2(v2Request(DELEGATE_AUTH_V2, """
{
"FromEmailAddress": "%s",
"FromEmailAddressIdentityArn": "%s",
"FeedbackForwardingEmailAddress": "%s",
"FeedbackForwardingEmailAddressIdentityArn": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
}
""".formatted(OWNER_ADDRESS, OWNER_IDENTITY_ARN, OWNER_ADDRESS, OWNER_IDENTITY_ARN)));
}
@Test
void v2SendEmail_raw_fromEmailAddressIdentityArnOverridesTheArnHeaders() {
// "For Raw emails, the FromEmailAddressIdentityArn value overrides the X-SES-SOURCE-ARN and
// X-SES-FROM-ARN headers specified in raw email message content."
verifyOwnerAddress();
assertSentV2(v2Request(DELEGATE_AUTH_V2, """
{
"FromEmailAddressIdentityArn": "%s",
"Destination": {"ToAddresses": ["to@example.com"]},
"Content": {"Raw": {"Data": "%s"}}
}
""".formatted(OWNER_IDENTITY_ARN, rawMessage(OWNER_ADDRESS,
"X-SES-SOURCE-ARN: " + DELEGATE_IDENTITY_ARN, "X-SES-FROM-ARN: " + DELEGATE_IDENTITY_ARN))));
}
}
@@ -28,10 +28,14 @@ class SesServiceAddressLengthTest {
new EmailContent.Simple("Subject", "body", null, List.of());
private SesService service;
private SesIdentityService identityService;
@BeforeEach
void setUp() {
service = SesServiceTestBuilder.create().build();
SesServiceTestBuilder builder = SesServiceTestBuilder.create();
service = builder.build();
identityService = builder.identityService();
identityService.verifyEmailIdentity(SENDER, REGION);
}
@Test
@@ -218,6 +222,8 @@ class SesServiceAddressLengthTest {
@Test
void rawSend_otherAddressHeadersAreNotChecked() {
String tooLong = address(330, 'a');
// Sender is a sending address, so it must be verified to reach the send.
identityService.verifyEmailIdentity(tooLong, REGION);
assertDoesNotThrow(() -> service.sendEmail(request(SENDER).content(raw(SENDER, TO,
"Sender: " + tooLong + "\r\nResent-To: " + tooLong + "\r\n")).build()));
@@ -46,6 +46,7 @@ class SesServiceAddressSyntaxTest {
service = builder.build();
sentEmails = builder.sentEmailService();
identityService = builder.identityService();
identityService.verifyEmailIdentity(SENDER, REGION);
}
@Test
@@ -52,6 +52,7 @@ class SesServiceListManagementTest {
contactStore = builder.contactStore();
service = builder.build();
contacts = builder.contactService();
builder.identityService().verifyEmailIdentity(FROM, REGION);
// Sports defaults OPT_IN, Promos defaults OPT_OUT.
contacts.createContactList(LIST, "desc", List.of(
@@ -48,6 +48,7 @@ class SesServiceSmtpTest {
suppression = builder.suppressionService();
cvetTemplates = builder.cvetService();
identities = builder.identityService();
identities.verifyEmailIdentity("from@example.com", "us-east-1");
}
private void cvetTemplate(String name, String subject, String content) {
@@ -239,6 +240,7 @@ class SesServiceSmtpTest {
@Test
void sendEmail_explicitReturnPath_isRelayedAndStored() {
identities.verifyEmailIdentity("bounces@example.com", "us-east-1");
String messageId = service.sendEmail(SendEmailRequest.builder()
.source("from@example.com")
.toAddresses(List.of("to@example.com"))
@@ -254,7 +256,10 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_rejectedMessage_keepsNoReturnPathFromItsHeaders() {
// The scan trips on the subject; the Return-Path header, read off the same message, must
// not survive on the record either, so the request's return path is used.
// not survive on the record either, so the request's return path is used. Both return paths
// are verified, so the send gets past the sender check to the scan.
identities.verifyEmailIdentity("bounces@example.com", "us-east-1");
identities.verifyEmailIdentity("bounces@evil.example", "us-east-1");
String raw = "From: from@example.com\r\nTo: to@example.com\r\nReturn-Path: <bounces@evil.example>\r\n"
+ "Subject: " + SesContentScan.signature() + "\r\n\r\nbody\r\n";
@@ -307,6 +312,8 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_returnPathHeader_winsOverRequestField() {
identities.verifyEmailIdentity("request-bounces@example.com", "us-east-1");
identities.verifyEmailIdentity("mime-bounces@example.com", "us-east-1");
String raw = "From: from@example.com\r\n"
+ "To: to@example.com\r\n"
+ "Return-Path: <mime-bounces@example.com>\r\n"
@@ -326,6 +333,7 @@ class SesServiceSmtpTest {
@Test
void sendRawEmail_noReturnPathHeader_usesRequestField() {
identities.verifyEmailIdentity("request-bounces@example.com", "us-east-1");
String raw = "From: from@example.com\r\nTo: to@example.com\r\nSubject: x\r\n\r\nbody";
service.sendEmail(SendEmailRequest.builder()
@@ -59,8 +59,8 @@ class SesTenantSendV2IntegrationTest {
void setup_tenantAndResources() {
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants").then().statusCode(200);
v2().body("{\"EmailIdentity\":\"" + DOMAIN + "\"}")
.when().post("/v2/email/identities").then().statusCode(200);
// Verified, so the addresses under it may send once the tenant gate lets them through.
SesDomainIdentityTestHelper.createVerified(DOMAIN, AUTH);
v2().body("{\"ConfigurationSetName\":\"" + CONFIG_SET + "\"}")
.when().post("/v2/email/configuration-sets").then().statusCode(200);
v2().body("{\"TemplateName\":\"" + TEMPLATE + "\",\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}}")
@@ -145,59 +145,7 @@ class SesV2IntegrationTest {
.jsonPath()
.getList("DkimAttributes.Tokens", String.class);
String locationHeader = given()
.contentType("application/xml")
.body("""
<?xml version="1.0" encoding="UTF-8"?>
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>floci.test</Name>
<CallerReference>ses-v2-dkim-success</CallerReference>
</CreateHostedZoneRequest>
""")
.when()
.post("/2013-04-01/hostedzone")
.then()
.statusCode(201)
.extract()
.header("Location");
String zoneId = locationHeader.substring(locationHeader.lastIndexOf('/') + 1);
StringBuilder body = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
""");
for (String token : tokens) {
body.append("""
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>""").append(token).append("._domainkey.v2dkim-success.floci.test.</Name>\n")
.append("""
<Type>CNAME</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>""").append(token).append(".dkim.amazonses.com.</Value></ResourceRecord>\n")
.append("""
</ResourceRecords>
</ResourceRecordSet>
</Change>
""");
}
body.append("""
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""");
given()
.contentType("application/xml")
.body(body.toString())
.when()
.post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(200);
SesDomainIdentityTestHelper.publishDkimRecords("v2dkim-success.floci.test", tokens);
given()
.contentType("application/json")
@@ -998,6 +946,17 @@ class SesV2IntegrationTest {
@Test
@Order(67)
void sendEmail_raw_noFromAddress_usesMimeFrom() {
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"EmailIdentity": "raw-from@floci.test"}
""")
.when()
.post("/v2/email/identities")
.then()
.statusCode(200);
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
@@ -1304,17 +1263,19 @@ class SesV2IntegrationTest {
void inspectionEndpoint_returnsEmailsFromAllRegions() {
given().delete("/_aws/ses").then().statusCode(200);
// Create identity usable in both regions (domain covers all addresses)
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"EmailIdentity": "example.com"}
""")
.when()
.post("/v2/email/identities")
.then()
.statusCode(200);
// Identities are regional, so the sender is verified in each region it sends from.
for (String region : List.of("us-east-1", "ap-northeast-1")) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=AKID/20260101/" + region + "/email/aws4_request")
.formParam("Action", "VerifyEmailIdentity")
.formParam("EmailAddress", "multi@example.com")
.when()
.post("/")
.then()
.statusCode(200);
}
// Send from us-east-1
given()
@@ -440,6 +440,37 @@ class SmtpRelayTest {
assertTrue(h.messageTags().isEmpty());
}
@Test
void parseRawHeaders_extractsSenderAndTheFirstSendingAuthorizationHeaders() {
String raw = "From: sender@example.com\r\n"
+ "Sender: Assistant <assistant@example.com>\r\n"
+ "To: to@example.com\r\n"
+ "X-SES-SOURCE-ARN: arn:aws:ses:us-east-1:111111111111:identity/example.com\r\n"
+ "X-SES-SOURCE-ARN: arn:aws:ses:us-east-1:222222222222:identity/example.com\r\n"
+ "X-SES-FROM-ARN: arn:aws:ses:us-east-1:333333333333:identity/example.com\r\n"
+ "X-SES-RETURN-PATH-ARN: arn:aws:ses:us-east-1:444444444444:identity/example.com\r\n"
+ "Subject: x\r\n\r\nbody";
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(raw);
assertEquals("assistant@example.com", h.sender());
assertEquals("arn:aws:ses:us-east-1:111111111111:identity/example.com", h.sourceArn());
assertEquals("arn:aws:ses:us-east-1:333333333333:identity/example.com", h.fromArn());
assertEquals("arn:aws:ses:us-east-1:444444444444:identity/example.com", h.returnPathArn());
}
@Test
void parseRawHeaders_withoutSenderOrSendingAuthorizationHeaders_returnsBlanks() {
String raw = "From: sender@example.com\r\nTo: to@example.com\r\nSubject: x\r\n\r\nbody";
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(raw);
assertEquals("", h.sender());
assertEquals("", h.sourceArn());
assertEquals("", h.fromArn());
assertEquals("", h.returnPathArn());
}
@Test
void parseMessageTagsHeader_skipsEntriesWithoutAName() {
assertEquals(List.of(new MessageTag("ok", "1")),