fix(ses): check the template name of a send as SES does (#9271)

This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-11-23 10:36:52 -04:00
1 parent 64f74c6bc4
commit 7b2e60cfe0
6 files changed
+239 -1

No files matched your search

+1
View File
@@ -306,6 +306,7 @@ curl $AWS_ENDPOINT_URL/_aws/ses
- `SendEmail`, `SendRawEmail`, `SendTemplatedEmail` and `SendBulkTemplatedEmail`, and v2 `SendEmail` and `SendBulkEmail`, require verified senders, as on AWS ([SendEmail](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html), [Email sending errors](https://docs.aws.amazon.com/ses/latest/dg/troubleshoot-error-messages.html)): each address used as a "From", "Source", "Sender" or "Return-Path" address must be a verified email address identity or an address in a verified domain identity or one of its subdomains. That is the `Source` or `FromEmailAddress` and the `ReturnPath` or `FeedbackForwardingEmailAddress`, plus, 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. Every other address present is checked; whether AWS still checks a `Return-Path` header that the request's return path overrides has not been probed. One `MessageRejected` lists every unverified address ("Email address is not verified. The following identities failed the check in region US-EAST-1: a@example.com, b@example.com") and nothing is captured or relayed. An address covered by a sending-authorization ARN of another account (`SourceArn`, `FromArn`, `ReturnPathArn`, their `X-SES-*-ARN` headers, or v2 `FromEmailAddressIdentityArn` and `FeedbackForwardingEmailAddressIdentityArn`) is not checked, since it is the owner's identity; on a raw send the source ARN also covers the `From` and return-path addresses that have no ARN of their own. A bulk send checks its sender and return path once and rejects the whole call; when no entry has a recipient it checks neither and every entry fails on its own (probe-confirmed on v2 `SendBulkEmail` and v1 `SendBulkTemplatedEmail`). On v2 `SendEmail` and `SendBulkEmail`, and v1 `SendTemplatedEmail` and `SendBulkTemplatedEmail`, an unknown configuration set is reported before the check and an unknown stored template only after it (probe-confirmed). The verification codes and invitations Cognito sends are not affected.
- `SendBulkTemplatedEmail` reads every `Destinations.member.N` up to the highest N. A missing `Template` (whatever `TemplateArn` holds), missing `Destinations`, and an entry without a `Destination` or a skipped N are model violations, answered together as one 400 `ValidationError` ("2 validation errors detected: Value at 'template' failed to satisfy constraint: Member must not be null; Value at 'destinations.2.member.destination' failed to satisfy constraint: Member must not be null") ahead of every other check of the request, the address syntax and the destination count included (probe-confirmed). Floci lists the skipped entries of the first 1000 indexes only; a higher index fails the destination count. On both bulk sends an entry whose address lists are empty answers "Missing required header 'To'." on its own when another entry has a recipient, and when none has one every entry answers "Destination cannot be empty" (probe-confirmed). A `DefaultTags` or `ReplacementTags` tag without a `Name` or a `Value` is a model violation too, a skipped tag index listing both, and the top-level members are listed ahead of the nested ones ('template' before 'defaultTags.1.member.name'). A missing or empty `DefaultTemplateData` is a 400 `InvalidParameterValue` ("The default template data does not exist"), answered after the `Source` syntax and the destination count and before the template lookup and the sender verification (probe-confirmed). On `SendBulkTemplatedEmail` an entry with more than 50 recipients ("Recipient count exceeds 50."), template data that is not a JSON object ("The template data is invalid") or a tag with an empty name ("The tag name must be specified.") fails on its own with `InvalidParameterValue`. Invalid `DefaultTemplateData` or an empty `DefaultTags` name fails every entry, and within one entry an address syntax error wins over an empty tag name, which wins over invalid template data, which wins over the recipient count (probe-confirmed). v2 `SendBulkEmail` still rejects the whole call for more than 50 recipients in a destination (not probed).
- A `TemplateArn` on v1 `SendTemplatedEmail` and `SendBulkTemplatedEmail` and v2 `SendEmail` and `SendBulkEmail` must be in the request's partition and region, name the `ses` service and start its resource with `template/`; its account is not checked. Each mismatch has its own message ("Invalid template ARN <arn>. Template must be in region <us-east-1>"), a value that does not start with `arn:` answers "ARNs must start with 'arn:': <value>", and an ARN beside a template name must name the same template ("The SES resource '<name>' does not align with the given ARN '<arn>'."). The checks run before the sender verification; v1 answers `InvalidParameterValue` and v2 `BadRequestException` (probe-confirmed). The v1 sends require `Template` even beside a `TemplateArn`, and an empty one answers "Template cannot be empty" ahead of the ARN checks; `SendBulkTemplatedEmail` answers the same for a whitespace-only `Template` (probe-confirmed).
- The v1 and v2 templated sends check the name of the stored template they use just before the sender verification, length first: "Template name <name> exceeds maximum allowed length 64", then "Template name <name> is only allowed to contain alphanumeric characters, underscore, and dash". A bulk send in which no entry names a recipient answers every entry "Destination cannot be empty" instead. A `TemplateArn` naming such a template answers the template operations' wording ("Template name <a.b>: only alphanumeric ASCII characters, '_', and '-' are allowed.") with the other ARN checks. v2 `SendBulkEmail` answers a template with no name, ARN or content, or a whitespace-only name, "TemplateName and TemplateArn both can not be empty", and an empty `TemplateName` is a model violation (probe-confirmed).
- `SendEmail` stores the text body or the HTML body as the captured message body.
- `SetIdentityNotificationTopic` publishes to the configured topic on a Bounce/Complaint/Delivery event (triggered via the mailbox simulator addresses or the suppression list), independent of any configuration set. The payload uses the legacy format (`notificationType`, no `mail.tags`, headers only when `SetIdentityHeadersInNotificationsEnabled` is on). The topic is checked when it is set: one that does not exist in the identity's region, or whose policy does not let SES publish under IAM enforcement, is refused with `InvalidParameterValue`. A topic of another account that exists in Floci and grants SES is accepted.
- Identity (sending authorization) policies are stored and returned as metadata: the policy document, the per-identity limit of 20, and the create/update/delete error shapes match AWS, but Floci does not evaluate policy authorization (Principal-account existence, Resource-ARN match) or gate sending on it. A send naming another account's identity ARN skips the verified-sender check for the addresses it covers, without looking that identity up or reading its policy.
@@ -229,6 +229,11 @@ public class SesSendController {
JsonNode request = readOptionBody(objectMapper, body);
SesV2RequestShapes.check("SendBulkEmail", request);
validateTrackingOverrides(request);
JsonNode defaultTemplateName = request.path("DefaultContent").path("Template").path("TemplateName");
if (defaultTemplateName.isTextual() && defaultTemplateName.textValue().isEmpty()) {
throw SmithyValidationErrors.badRequest("Value at 'defaultContent.template.templateName' failed to "
+ "satisfy constraint: Member must have length greater than or equal to 1");
}
JsonNode bulkEntries = request.path("BulkEmailEntries");
if (bulkEntries.isMissingNode() || bulkEntries.isNull()) {
throw SmithyValidationErrors.badRequest(SmithyValidationErrors.notNullWithoutValue("bulkEmailEntries"));
@@ -254,7 +259,7 @@ public class SesSendController {
TemplateSelector selector = TemplateSelector.of(template);
if (selector.isEmpty()) {
throw new AwsException("BadRequestException",
"DefaultContent.Template requires TemplateName, TemplateArn, or TemplateContent.", 400);
"TemplateName and TemplateArn both can not be empty", 400);
}
// AWS counts the entries after the inline content check and the sender checks, and
// before it rejects a stored template named beside the content or looks one up
@@ -292,6 +292,9 @@ public class SesService {
SesAddressSyntax.requireEnvelope(request);
String effectiveConfigSet = validateEnvelope(request);
SesAddressLength.requireEnvelope(request);
if (request.content() instanceof EmailContent.Template template) {
SesTemplateService.requireSendTemplateName(template.templateName());
}
if (requireVerifiedSender) {
requireVerifiedSenders(List.of(
new SendingAddress(request.source(), request.sourceArn()),
@@ -1727,6 +1730,9 @@ public class SesService {
"Destination cannot be empty"))
.toList();
}
if (request.templateName() != null) {
SesTemplateService.requireSendTemplateName(request.templateName());
}
// The sender and return path are checked once for the whole call, then a stored template is
// looked up, then the tenant associations, as on a single send (probe-confirmed).
requireVerifiedSenders(List.of(
@@ -269,9 +269,26 @@ public class SesTemplateService implements SesTaggable {
if (name.isEmpty()) {
throw new AwsException("InvalidParameterValue", "The template name must be specified.", 400);
}
SesNames.requireAllowedCharacters(name, "InvalidParameterValue", "Template name");
return name;
}
/**
* The name rule a send applies to the stored template it names, worded unlike the template
* operations' rule and checked just before the sender verification (probe-confirmed on the v1
* and v2 sends).
*/
public static void requireSendTemplateName(String name) {
if (name.length() > SesNames.MAX_LENGTH) {
throw new AwsException("InvalidParameterValue",
"Template name " + name + " exceeds maximum allowed length " + SesNames.MAX_LENGTH, 400);
}
if (!SesNames.hasOnlyAllowedCharacters(name)) {
throw new AwsException("InvalidParameterValue", "Template name " + name
+ " is only allowed to contain alphanumeric characters, underscore, and dash", 400);
}
}
/**
* A send may name its template beside a {@code TemplateArn} only when both name the same
* template; a malformed ARN is reported first (probe-confirmed on both protocols).
@@ -0,0 +1,207 @@
package io.floci.aws.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.LinkedHashMap;
import java.util.Map;
import static io.floci.aws.services.ses.SesV2Requests.DESTINATION;
import static io.floci.aws.services.ses.SesV2Requests.ENTRY;
import static io.floci.aws.services.ses.SesV2Requests.TO;
import static io.floci.aws.services.ses.SesV2Requests.post;
import static org.hamcrest.Matchers.equalTo;
/**
* The name rule the v1 and v2 sends apply to the stored template they name. It is worded unlike
* the template operations' rule, checks the length before the characters, and answers just before
* the sender verification (probe-confirmed). The sender is never verified, so a name that passes
* reaches the sender check.
*/
@QuarkusTest
class SesSendTemplateNameIntegrationTest {
private static final String UNVERIFIED = "sender@unverified-send-template-name.floci.test";
private static final String DOTTED = "a.b";
private static final String TOO_LONG = "a.b" + "a".repeat(62);
private static final String LONGEST = "a".repeat(64);
private static final String DOTTED_ARN = "arn:aws:ses:us-east-1:000000000000:template/" + DOTTED;
private static String charactersMessage(String name) {
return "Template name " + name + " is only allowed to contain alphanumeric characters, underscore, and dash";
}
private static String lengthMessage(String name) {
return "Template name " + name + " exceeds maximum allowed length 64";
}
// A member in extra replaces the default one rather than being sent twice.
private static RequestSpecification v1(String operation, String template, Map<String, String> extra) {
Map<String, String> params = new LinkedHashMap<>();
params.put("Source", UNVERIFIED);
params.put("Template", template);
if ("SendTemplatedEmail".equals(operation)) {
params.put("Destination.ToAddresses.member.1", TO);
params.put("TemplateData", "{}");
} else {
params.put("Destinations.member.1.Destination.ToAddresses.member.1", TO);
params.put("DefaultTemplateData", "{}");
}
params.putAll(extra);
return SesV1Requests.query(operation).formParams(params);
}
private static ValidatableResponse sendV1(String operation, String template, Map<String, String> extra) {
return v1(operation, template, extra).when().post("/").then();
}
private static ValidatableResponse sendV1(String operation, String template) {
return sendV1(operation, template, Map.of());
}
private static void assertV1(ValidatableResponse response, String code, String message) {
response
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo(code))
.body("ErrorResponse.Error.Message", equalTo(message));
}
private static ValidatableResponse sendV2(String template) {
return post("/v2/email/outbound-emails", "{\"FromEmailAddress\": \"" + UNVERIFIED + "\","
+ " " + DESTINATION + ","
+ " \"Content\": {\"Template\": {" + template + ", \"TemplateData\": \"{}\"}}}");
}
private static ValidatableResponse sendBulkV2(String template, String entry) {
return post("/v2/email/outbound-bulk-emails", "{\"FromEmailAddress\": \"" + UNVERIFIED + "\","
+ " \"DefaultContent\": {\"Template\": {" + template + ", \"TemplateData\": \"{}\"}},"
+ " \"BulkEmailEntries\": [" + entry + "]}");
}
private static void assertV2(ValidatableResponse response, String message) {
response
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(message));
}
@ParameterizedTest
@ValueSource(strings = {"SendTemplatedEmail", "SendBulkTemplatedEmail"})
void v1_nameWithAnotherCharacter_isRejected(String operation) {
assertV1(sendV1(operation, DOTTED), "InvalidParameterValue", charactersMessage(DOTTED));
}
@ParameterizedTest
@ValueSource(strings = {"SendTemplatedEmail", "SendBulkTemplatedEmail"})
void v1_nameOverSixtyFourCharacters_reportsTheLengthFirst(String operation) {
assertV1(sendV1(operation, TOO_LONG), "InvalidParameterValue", lengthMessage(TOO_LONG));
}
@ParameterizedTest
@ValueSource(strings = {"SendTemplatedEmail", "SendBulkTemplatedEmail"})
void v1_sixtyFourCharacterName_reachesTheSenderCheck(String operation) {
sendV1(operation, LONGEST)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MessageRejected"));
}
@Test
void sendTemplatedEmail_whitespaceName_isRejectedByTheCharacterRule() {
assertV1(sendV1("SendTemplatedEmail", " "), "InvalidParameterValue", charactersMessage(" "));
}
@Test
void sendTemplatedEmail_sourceSyntax_isReportedFirst() {
assertV1(sendV1("SendTemplatedEmail", DOTTED, Map.of("Source", "not-an-address")),
"InvalidParameterValue", "Missing final '@domain'");
}
@Test
void sendTemplatedEmail_unknownConfigurationSet_isReportedFirst() {
sendV1("SendTemplatedEmail", DOTTED, Map.of("ConfigurationSetName", "send-template-name-no-such-set"))
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ConfigurationSetDoesNotExist"));
}
@Test
void sendBulkTemplatedEmail_missingDefaultTemplateData_isReportedFirst() {
SesV1Requests.query("SendBulkTemplatedEmail")
.formParam("Source", UNVERIFIED)
.formParam("Template", DOTTED)
.formParam("Destinations.member.1.Destination.ToAddresses.member.1", TO)
.when().post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue"))
.body("ErrorResponse.Error.Message", equalTo("The default template data does not exist"));
}
@Test
void sendBulkTemplatedEmail_noRecipient_answersEveryEntryInstead() {
SesV1Requests.query("SendBulkTemplatedEmail")
.formParam("Source", UNVERIFIED)
.formParam("Template", DOTTED)
.formParam("DefaultTemplateData", "{}")
.formParam("Destinations.member.1.Destination.ToAddresses", "")
.when().post("/")
.then()
.statusCode(200)
.body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member.Error",
equalTo("Destination cannot be empty"));
}
// An ARN naming such a template answers the template operations' wording instead.
@ParameterizedTest
@ValueSource(strings = {"SendTemplatedEmail", "SendBulkTemplatedEmail"})
void v1_templateArnNamingSuchATemplate_answersTheTemplateOperationsWording(String operation) {
assertV1(sendV1(operation, DOTTED, Map.of("TemplateArn", DOTTED_ARN)), "InvalidParameterValue",
"Template name <a.b>: only alphanumeric ASCII characters, '_', and '-' are allowed.");
}
@Test
void v2_sendEmail_appliesTheSameRule() {
assertV2(sendV2("\"TemplateName\": \"" + DOTTED + "\""), charactersMessage(DOTTED));
assertV2(sendV2("\"TemplateName\": \"" + TOO_LONG + "\""), lengthMessage(TOO_LONG));
}
@Test
void v2_sendBulkEmail_appliesTheSameRule() {
assertV2(sendBulkV2("\"TemplateName\": \"" + DOTTED + "\"", ENTRY), charactersMessage(DOTTED));
assertV2(sendBulkV2("\"TemplateName\": \"" + TOO_LONG + "\"", ENTRY), lengthMessage(TOO_LONG));
}
@Test
void v2_templateArnNamingSuchATemplate_answersTheTemplateOperationsWording() {
assertV2(sendV2("\"TemplateName\": \"" + DOTTED + "\", \"TemplateArn\": \"" + DOTTED_ARN + "\""),
"Template name <a.b>: only alphanumeric ASCII characters, '_', and '-' are allowed.");
}
@Test
void v2_sendBulkEmail_noRecipient_answersEveryEntryInstead() {
post("/v2/email/outbound-bulk-emails", "{\"FromEmailAddress\": \"" + UNVERIFIED + "\","
+ " \"DefaultContent\": {\"Template\": {\"TemplateName\": \"" + DOTTED + "\", \"TemplateData\": \"{}\"}},"
+ " \"BulkEmailEntries\": [{\"Destination\": {\"ToAddresses\": []}}]}")
.statusCode(200)
.body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[0].Error", equalTo("Destination cannot be empty"));
}
@ParameterizedTest
@ValueSource(strings = {"\"TemplateData\": \"{}\"", "\"TemplateName\": \" \""})
void v2_sendBulkEmail_withoutATemplateSelector_isRejected(String template) {
assertV2(post("/v2/email/outbound-bulk-emails", "{\"FromEmailAddress\": \"" + UNVERIFIED + "\","
+ " \"DefaultContent\": {\"Template\": {" + template + "}}, \"BulkEmailEntries\": [" + ENTRY + "]}"),
"TemplateName and TemplateArn both can not be empty");
}
@Test
void v2_sendBulkEmail_emptyTemplateName_isModelViolation() {
assertV2(sendBulkV2("\"TemplateName\": \"\"", ENTRY), "1 validation error detected: Value at "
+ "'defaultContent.template.templateName' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1");
}
}
@@ -55,6 +55,8 @@ class SesTemplateArnTest {
"Invalid template ARN <arn:aws:ses:us-west-2:000000000000:configuration-set/welcome>. "
+ "Relative ID should start with <template/>"),
Arguments.of("arn:aws:ses:us-west-2:000000000000:template/", "The template name must be specified."),
Arguments.of("arn:aws:ses:us-west-2:000000000000:template/a.b",
"Template name <a.b>: only alphanumeric ASCII characters, '_', and '-' are allowed."),
Arguments.of("not-an-arn", "ARNs must start with 'arn:': not-an-arn"));
}