mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ses): take v2 Raw send recipients from the MIME headers (#5442)
* fix(ses): take v2 Raw send recipients from the MIME headers A v2 SendEmail with Content.Raw and no Destination was rejected in the controller. AWS reads the recipients from the To/Cc/Bcc headers instead, and when there are none it answers "Missing required header 'To'." (BadRequestException on v2, InvalidParameterValue on v1 SendRawEmail). * fix(ses): report a recipient-less Raw send between the tenant checks AWS checks that the tenant exists, then answers "Missing required header 'To'." for a v2 Raw send with no recipients, ahead of the tenant association gate. The tenant gate now follows that order. Adds tests for an empty Destination and for a malformed To header recipient. * fix(ses): reject a non-array v2 SendEmail destination member A present ToAddresses/CcAddresses/BccAddresses of the wrong JSON type was read as an omitted destination, which a Raw send now fills from the MIME headers. It is rejected with SerializationException instead. * refactor(ses): use SendEmailRequest.hasRecipients for Raw sends The Raw tenant gate and sendRawEmail each spelled out the explicit recipient check; both now ask the request. * fix(ses): syntax-check the Cc and Bcc headers of a Raw send AWS rejects a malformed address in a raw message's Cc or Bcc header with the same messages as the To header, and a Raw send without a Destination now takes its recipients from those headers. * docs(ses): reword the raw header note on SesAddressSyntax
This commit is contained in:
1 parent
af3672ed0c
commit
3ad1a76507
6 files changed
+224
-23
No files matched your search
@@ -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() {
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
+165
@@ -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 = "success@simulator.amazonses.com";
|
||||
|
||||
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": "sender@example.com",
|
||||
"Content": {"Raw": {"Data": "%s"}}
|
||||
}
|
||||
""".formatted(rawData("From: sender@example.com\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": "sender@example.com",
|
||||
"Content": {"Raw": {"Data": "%s"}}
|
||||
}
|
||||
""".formatted(rawData("From: sender@example.com\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": "sender@example.com",
|
||||
"Destination": {"ToAddresses": []},
|
||||
"Content": {"Raw": {"Data": "%s"}}
|
||||
}
|
||||
""".formatted(rawData("From: sender@example.com\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": "sender@example.com",
|
||||
"Destination": {"ToAddresses": "bad-shape"},
|
||||
"Content": {"Raw": {"Data": "%s"}}
|
||||
}
|
||||
""".formatted(rawData("From: sender@example.com\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": "sender@example.com",
|
||||
"Content": {"Raw": {"Data": "%s"}}
|
||||
}
|
||||
""".formatted(rawData("From: sender@example.com\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": "sender@example.com",
|
||||
"Content": {"Raw": {"Data": "%s"}}
|
||||
}
|
||||
""".formatted(rawData("From: sender@example.com\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", "sender@example.com")
|
||||
.formParam("RawMessage.Data", rawData("From: sender@example.com\r\n"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
|
||||
.body("ErrorResponse.Error.Message", equalTo("Missing required header 'To'."));
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -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
|
||||
|
||||
+18
@@ -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: probe@floci-raw.example.com\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
|
||||
|
||||
Reference in new issue
Block a user