Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(ses): take v2 Raw send recipients from the MIME headers (#5442)

Kenshin Okinaka3ad1a76507d4
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 768c3ef72b..c6fbe1c269 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
@@ -16,12 +16,13 @@ import java.util.List;
* 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
+ * In a raw message AWS checks the From, To, Cc and Bcc headers (probe-confirmed);
+ * the Reply-To and Return-Path headers were not probed and are left unchecked. The v2 controller
* remaps the code to BadRequestException.
*/
final class SesAddressSyntax {
- private static final List<String> RAW_CHECKED_HEADERS = List.of("To");
+ private static final List<String> RAW_CHECKED_HEADERS = List.of("To", "Cc", "Bcc");
private SesAddressSyntax() {
}
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 87cd2987b1..3708680c23 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
@@ -39,10 +39,12 @@ import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception;
import static io.github.hectorvent.floci.services.ses.SesV2Json.requireJsonObject;
import static io.github.hectorvent.floci.services.ses.SesV2Json.requireObjectOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.stringArrayOrAbsent;
import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
/**
@@ -101,9 +103,9 @@ public class SesSendController {
String fromEmailAddress = request.path("FromEmailAddress").asText(null);
JsonNode destination = requireObjectOrAbsent(request, "Destination");
- List<String> toAddresses = jsonArrayToList(destination.path("ToAddresses"));
- List<String> ccAddresses = jsonArrayToList(destination.path("CcAddresses"));
- List<String> bccAddresses = jsonArrayToList(destination.path("BccAddresses"));
+ List<String> toAddresses = destinationAddresses(destination, "ToAddresses");
+ List<String> ccAddresses = destinationAddresses(destination, "CcAddresses");
+ List<String> bccAddresses = destinationAddresses(destination, "BccAddresses");
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
String feedbackForwardingAddress =
request.path("FeedbackForwardingEmailAddress").asText(null);
@@ -134,13 +136,10 @@ public class SesSendController {
throw new AwsException("BadRequestException",
"Content.Raw.Data is required.", 400);
}
- if (toAddresses.isEmpty() && ccAddresses.isEmpty() && bccAddresses.isEmpty()) {
- throw new AwsException("BadRequestException",
- "At least one destination address is required.", 400);
- }
+ SendEmailRequest rawRequest = sendRequest.content(new EmailContent.Raw(rawData)).build();
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
- configurationSetName, regionResolver.getAccountId(), region);
- messageId = sesService.sendEmail(sendRequest.content(new EmailContent.Raw(rawData)).build());
+ rawRequest.hasRecipients(), configurationSetName, regionResolver.getAccountId(), region);
+ messageId = sesService.sendEmail(rawRequest);
} else if (content.has("Simple")) {
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
// AWS returns BadRequestException with a null message body here.
@@ -406,6 +405,12 @@ public class SesSendController {
// ──────────────────────────── Helpers ────────────────────────────
+ // A Raw send falls back to the MIME recipients when no destination is given, so a present member
+ // of the wrong JSON type must be rejected rather than read as an omitted one.
+ private static List<String> destinationAddresses(JsonNode destination, String field) {
+ return Objects.requireNonNullElse(stringArrayOrAbsent(destination, field), List.of());
+ }
+
private List<String> jsonArrayToList(JsonNode arrayNode) {
if (arrayNode == null || arrayNode.isMissingNode() || !arrayNode.isArray()) {
return Collections.emptyList();
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 ce61b2a6de..a14c5c971d 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
@@ -423,11 +423,9 @@ public class SesService {
private String sendRawEmail(SendEmailRequest request, EmailContent.Raw raw) {
String source = request.source();
String region = request.region();
- List<String> destinations = request.recipients();
if (raw.data() == null || raw.data().isBlank()) {
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
}
- boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty();
boolean sourceOmitted = source == null || source.isBlank();
// The MIME headers are always parsed: X-SES-CONFIGURATION-SET can name the configuration
// set that decides whether events are published at all, so the configuration set cannot be
@@ -465,12 +463,11 @@ public class SesService {
effectiveConfigSet = resolveDefaultConfigurationSet(requestedConfigSet, effectiveSource, region);
configSetService.validateForSending(effectiveConfigSet, region);
}
- List<String> effectiveDestinations = hasExplicitDestinations
- ? destinations
+ List<String> effectiveDestinations = request.hasRecipients()
+ ? request.recipients()
: SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc());
if (effectiveDestinations.isEmpty()) {
- throw new AwsException("InvalidParameterValue",
- "At least one destination address is required.", 400);
+ throw new AwsException("InvalidParameterValue", "Missing required header 'To'.", 400);
}
// Resolve suppression before recording the message so a bad ListManagementOptions (e.g. an
// unknown contact list) fails the whole send without leaving an orphaned SentEmail record.
@@ -1066,16 +1063,24 @@ public class SesService {
/**
* The raw-content variant of the tenant send gate: when {@code FromEmailAddress} is omitted,
- * the effective sender comes from the MIME {@code From} header — the same derivation
- * {@code sendRawEmail} applies — so the gate must resolve it the same way before checking.
+ * the effective sender comes from the MIME {@code From} header, the same derivation
+ * {@code sendRawEmail} applies, so the gate must resolve it the same way before checking.
+ * {@code hasDestination} says whether the request named any recipient; when it did not and the
+ * MIME To, Cc and Bcc headers are empty too, only the tenant's existence is checked.
*/
public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress,
- String rawMessage, String configurationSetName,
- String accountId, String region) {
+ String rawMessage, boolean hasDestination,
+ String configurationSetName, String accountId, String region) {
if (tenantName == null) {
return;
}
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
+ // AWS checks that the tenant exists, then reports a message with no recipients anywhere
+ // ahead of the association gate (probe-confirmed), so that error is left to sendRawEmail.
+ if (!hasDestination && SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc()).isEmpty()) {
+ tenantService.tenantForSending(tenantName, region, accountId);
+ return;
+ }
String effectiveSource = fromEmailAddress;
if (effectiveSource == null || effectiveSource.isBlank()) {
effectiveSource = headers.from().isBlank() ? null : headers.from();
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java
new file mode 100644
index 0000000000..a6ea35d507
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendRawNoDestinationIntegrationTest.java
@@ -0,0 +1,165 @@
+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.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+
+@QuarkusTest
+class SesSendRawNoDestinationIntegrationTest {
+
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
+ private static final String TO = "[email protected]";
+
+ private static String rawData(String headers) {
+ return Base64.getEncoder().encodeToString(
+ (headers + "Subject: s\r\n\r\nb").getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Test
+ void v2SendEmail_rawWithoutDestination_takesRecipientsFromHeaders() {
+ String messageId = given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Content": {"Raw": {"Data": "%s"}}
+ }
+ """.formatted(rawData("From: [email protected]\r\nTo: " + TO + "\r\n")))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(200)
+ .body("MessageId", notNullValue())
+ .extract().path("MessageId");
+
+ given()
+ .queryParam("id", messageId)
+ .queryParam("email", TO)
+ .when()
+ .get("/_aws/ses")
+ .then()
+ .statusCode(200)
+ .body("messages.Id", contains(messageId));
+ }
+
+ @Test
+ void v2SendEmail_rawWithoutAnyRecipient_returnsMissingToHeader() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Content": {"Raw": {"Data": "%s"}}
+ }
+ """.formatted(rawData("From: [email protected]\r\n")))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Missing required header 'To'."));
+ }
+
+ @Test
+ void v2SendEmail_rawWithEmptyDestination_returnsMissingToHeader() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Destination": {"ToAddresses": []},
+ "Content": {"Raw": {"Data": "%s"}}
+ }
+ """.formatted(rawData("From: [email protected]\r\n")))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Missing required header 'To'."));
+ }
+
+ @Test
+ void v2SendEmail_rawWithNonArrayDestinationMember_returnsSerializationException() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Destination": {"ToAddresses": "bad-shape"},
+ "Content": {"Raw": {"Data": "%s"}}
+ }
+ """.formatted(rawData("From: [email protected]\r\nTo: " + TO + "\r\n")))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"));
+ }
+
+ @Test
+ void v2SendEmail_rawWithoutDestination_checksHeaderRecipientSyntax() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Content": {"Raw": {"Data": "%s"}}
+ }
+ """.formatted(rawData("From: [email protected]\r\nTo: やまだ@simulator.amazonses.com\r\n")))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Local address contains control or whitespace"));
+ }
+
+ @Test
+ void v2SendEmail_rawWithoutDestination_checksCcHeaderRecipientSyntax() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH)
+ .body("""
+ {
+ "FromEmailAddress": "[email protected]",
+ "Content": {"Raw": {"Data": "%s"}}
+ }
+ """.formatted(rawData("From: [email protected]\r\nCc: やまだ@simulator.amazonses.com\r\n")))
+ .when()
+ .post("/v2/email/outbound-emails")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Local address contains control or whitespace"));
+ }
+
+ @Test
+ void v1SendRawEmail_withoutAnyRecipient_returnsMissingToHeader() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH)
+ .formParam("Action", "SendRawEmail")
+ .formParam("Source", "[email protected]")
+ .formParam("RawMessage.Data", rawData("From: [email protected]\r\n"))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
+ .body("ErrorResponse.Error.Message", equalTo("Missing required header 'To'."));
+ }
+}
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 ba931bff3c..748129a6b8 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
@@ -140,11 +140,18 @@ class SesServiceAddressSyntaxTest {
TO + ", user@[IPv6:2001:db8::1]")).build()));
}
+ @Test
+ void rawSend_ccAndBccHeadersAreChecked() {
+ assertRejects(LOCAL_CONTROL, () -> service.sendEmail(request(SENDER)
+ .content(raw(SENDER, TO, "Cc: " + NON_ASCII_LOCAL + "\r\n")).build()));
+ assertRejects(MISSING_FINAL_DOMAIN, () -> service.sendEmail(request(SENDER)
+ .content(raw(SENDER, TO, "Bcc: " + NO_AT + "\r\n")).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()));
+ "Reply-To: " + NO_AT + "\r\nReturn-Path: <>\r\n")).build()));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java
index a50e98d168..ca2cd58086 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java
@@ -6,6 +6,9 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+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.notNullValue;
@@ -194,6 +197,21 @@ class SesTenantSendV2IntegrationTest {
.when().post("/v2/email/outbound-emails").then().statusCode(403)
.body("message", equalTo("Tenant not associated with resources ["
+ ARN_PREFIX + "identity/floci-raw.example.com]."));
+
+ // A message with no recipients anywhere is reported after the tenant lookup but ahead of
+ // the association gate (probe-confirmed).
+ String noRecipients = Base64.getEncoder().encodeToString(
+ "From: [email protected]\r\nSubject: s\r\n\r\nbody".getBytes(StandardCharsets.UTF_8));
+ v2().body("{\"TenantName\":\"" + TENANT + "\","
+ + "\"Content\":{\"Raw\":{\"Data\":\"" + noRecipients + "\"}}}")
+ .when().post("/v2/email/outbound-emails").then().statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Missing required header 'To'."));
+ v2().body("{\"TenantName\":\"ghost-tenant\","
+ + "\"Content\":{\"Raw\":{\"Data\":\"" + noRecipients + "\"}}}")
+ .when().post("/v2/email/outbound-emails").then().statusCode(404)
+ .body("message", equalTo(
+ "Tenant ghost-tenant for AwsAccountId 000000000000 not found."));
}
@Test