From e8bfef562c172d2cecc23853103be2629d0b1f00 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Tue, 1 Dec 2026 23:21:59 +0900 Subject: [PATCH] fix(ses): require template data on v2 template sends and answer empty bulk destinations first (#9893) A v2 template send without TemplateData, or with an empty string, read it as {}. SendBulkEmail now answers 400 BadRequestException "The default template data does not exist" and SendEmail "Template data cannot be empty", ahead of the configuration set lookup and the sender check. A SendBulkEmail in which no entry names a recipient answers every entry INVALID_PARAMETER "Destination cannot be empty" even when its configuration set is unknown or paused. With a recipient, a bulk send looks its configuration set up first and refuses a paused one only after the sender check. --- .../floci/test/SesEventPublishingTest.java | 1 + .../java/com/floci/test/SesTemplateTest.java | 1 + docs/services/ses.md | 2 +- .../ses/SesConfigurationSetService.java | 14 ++ .../aws/services/ses/SesQueryHandler.java | 1 + .../aws/services/ses/SesSendController.java | 24 ++- .../io/floci/aws/services/ses/SesService.java | 38 +++-- .../ses/model/SendBulkEmailRequest.java | 12 +- ...AccountSendingPausedV2IntegrationTest.java | 3 +- .../ses/SesBulkV2IntegrationTest.java | 7 +- ...endTemplateLookupOrderIntegrationTest.java | 111 ++++++++++++-- .../SesSendVerifiedSenderIntegrationTest.java | 3 +- .../SesServiceBulkEmptyDestinationTest.java | 144 ++++++++++++++++++ .../SesTenantSendOrderV2IntegrationTest.java | 3 +- 14 files changed, 329 insertions(+), 35 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/ses/SesServiceBulkEmptyDestinationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java index 2557c8cca4..a3e61bd321 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesEventPublishingTest.java @@ -452,6 +452,7 @@ class SesEventPublishingTest { .subject("bulk-subject") .text("bulk body") .build()) + .templateData("{}") .headers(MessageHeader.builder() .name("X-Mailer").value("default").build()) .build()) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplateTest.java index 92a6a9f3b5..539f54d11e 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplateTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplateTest.java @@ -518,6 +518,7 @@ class SesTemplateTest { .defaultContent(BulkEmailContent.builder() .template(Template.builder() .templateName("sdk-v2-bulk-missing-" + System.currentTimeMillis()) + .templateData("{}") .build()) .build()) .bulkEmailEntries(BulkEmailEntry.builder() diff --git a/docs/services/ses.md b/docs/services/ses.md index 40dc3759bf..e63f68cbd0 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -307,7 +307,7 @@ curl $AWS_ENDPOINT_URL/_aws/ses - v2 `SendEmail` refuses a `Content.Simple.Headers` entry named `From`, `To`, `Cc`, `Bcc`, `Subject`, `Date`, `Message-ID`, `Reply-To`, `Return-Path`, `MIME-Version`, `Content-Type` or `Content-Disposition`, in any case, with a 400 `BadRequestException` ("Header is not supported"), ahead of the configuration set lookup and the sender verification (probe-confirmed). The same names are refused in `Content.Template.Headers` and in the `SendBulkEmail` default and replacement headers, where one refused header in any entry fails the whole call. On these sends the refusal comes ahead of every other check of the request after its shape: a missing sender, incomplete inline content, missing template data, the destination count, an all-empty bulk, the template lookup, the configuration set and the sender verification (probe-confirmed). - `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 . Template must be in region "), a value that does not start with `arn:` answers "ARNs must start with 'arn:': ", and an ARN beside a template name must name the same template ("The SES resource '' does not align with the given 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 exceeds maximum allowed length 64", then "Template 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 : 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). +- The v1 and v2 templated sends check the name of the stored template they use just before the sender verification, length first: "Template name exceeds maximum allowed length 64", then "Template 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. v2 `SendBulkEmail` gives that answer even when its configuration set is unknown or has sending paused (probe-confirmed); v1 `SendBulkTemplatedEmail`, not probed there, reports the configuration set first. With a recipient, a bulk send looks its configuration set up first but refuses a paused one only after the sender verification, so an unverified sender is answered for the sender; a single send refuses the pause first (probe-confirmed). A `TemplateArn` naming such a template answers the template operations' wording ("Template name : 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). A v2 template send needs its `TemplateData`: without it, or with an empty string, `SendBulkEmail` answers a 400 `BadRequestException` "The default template data does not exist" ahead of the configuration set lookup, the sender verification and the answer for a request with no recipient (probe-confirmed), and `SendEmail` answers "Template data cannot be empty" (probe-confirmed for an absent value, ahead of the sender verification; Floci treats the empty string and the configuration set lookup as on `SendBulkEmail`). `"{}"` is accepted, and `ReplacementTemplateData` stays optional. - `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. diff --git a/src/main/java/io/floci/aws/services/ses/SesConfigurationSetService.java b/src/main/java/io/floci/aws/services/ses/SesConfigurationSetService.java index ff9957cbff..9ea3836bc7 100644 --- a/src/main/java/io/floci/aws/services/ses/SesConfigurationSetService.java +++ b/src/main/java/io/floci/aws/services/ses/SesConfigurationSetService.java @@ -206,6 +206,20 @@ public class SesConfigurationSetService implements SesTaggable { * storing/relaying the message and skipping event publishing later. */ public void validateForSending(String configurationSetName, String region) { + requireExistsForSending(configurationSetName, region); + requireSendingNotPaused(configurationSetName, region); + } + + /** The existence gate of {@link #validateForSending} alone, for a send that pauses later. */ + public void requireExistsForSending(String configurationSetName, String region) { + if (configurationSetName == null || configurationSetName.isBlank()) { + return; + } + get(configurationSetName, region); + } + + /** The sending-paused gate of {@link #validateForSending} alone. */ + public void requireSendingNotPaused(String configurationSetName, String region) { if (configurationSetName == null || configurationSetName.isBlank()) { return; } diff --git a/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java b/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java index 3177814fe9..fd9d8d26e9 100644 --- a/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java +++ b/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java @@ -854,6 +854,7 @@ public class SesQueryHandler { .defaultEmailTags(defaultEmailTags) .region(region) .recipientLimitPerEntry(true) + .configurationSetBeforeEmptyDestinations(true) .defaultContent(new EmailContent.Template(resolvedName, defaultTemplateData, List.of())) .entries(entries) .build()); diff --git a/src/main/java/io/floci/aws/services/ses/SesSendController.java b/src/main/java/io/floci/aws/services/ses/SesSendController.java index acf3c22c4f..f0152747d2 100644 --- a/src/main/java/io/floci/aws/services/ses/SesSendController.java +++ b/src/main/java/io/floci/aws/services/ses/SesSendController.java @@ -180,13 +180,14 @@ public class SesSendController { "TemplateName and TemplateArn cannot be both empty", 400); } selector.requireNameAlignsWithArn(region); - JsonNode templateData = parseTemplateData(template, "TemplateData"); + String storedTemplateName = selector.namesStoredTemplate() ? selector.storedName(region) : null; + JsonNode templateData = requireTemplateData(template, "Template data cannot be empty"); List additionalHeaders = parseHeadersArray(template.path("Headers"), "content.template.headers"); - if (selector.namesStoredTemplate()) { + if (storedTemplateName != null) { requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses); SendEmailRequest templateRequest = sendRequest - .content(new EmailContent.Template(selector.storedName(region), templateData, + .content(new EmailContent.Template(storedTemplateName, templateData, additionalHeaders)) .build(); messageId = sesService.sendEmail(templateRequest); @@ -288,7 +289,8 @@ public class SesSendController { storedTemplateName = selector.storedName(region); } - JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData"); + JsonNode defaultTemplateData = + requireTemplateData(template, "The default template data does not exist"); List defaultEmailTags = parseEmailTagsArray(request.path("DefaultEmailTags"), "DefaultEmailTags"); List defaultHeaders = parseHeadersArray(template.path("Headers"), "defaultContent.template.headers"); @@ -466,6 +468,20 @@ public class SesSendController { } } + // A template send without its data is refused ahead of the configuration set lookup and the + // sender verification, whether the template is inline, stored or missing, and SendBulkEmail + // also ahead of the answer it gives when no entry names a recipient. SendBulkEmail refuses an + // empty string the same way and accepts "{}" (probe-confirmed). SendEmail was probed for an + // absent value and against the sender verification only: the rest follows SendBulkEmail. Both + // run the TemplateArn checks first, which is a choice. + private JsonNode requireTemplateData(JsonNode template, String missingMessage) { + String raw = template.path("TemplateData").asText(null); + if (raw == null || raw.isEmpty()) { + throw new AwsException("BadRequestException", missingMessage, 400); + } + return parseTemplateData(raw); + } + private JsonNode parseTemplateData(JsonNode parent, String fieldName) { return parseTemplateData(parent.path(fieldName).asText(null)); } diff --git a/src/main/java/io/floci/aws/services/ses/SesService.java b/src/main/java/io/floci/aws/services/ses/SesService.java index 1efab76b33..ad30a8b969 100644 --- a/src/main/java/io/floci/aws/services/ses/SesService.java +++ b/src/main/java/io/floci/aws/services/ses/SesService.java @@ -1780,7 +1780,15 @@ public class SesService { Tenant tenant = anyBulkRecipient(request.entries()) ? requireSendingTenant(request.tenantName(), request.region(), null, () -> null) : null; - configSetService.validateForSending(request.configurationSetName(), request.region()); + // SendBulkEmail answers a request in which no entry names a recipient entry by entry even + // when its configuration set is unknown or paused (probe-confirmed). SendBulkTemplatedEmail + // has not been probed there and keeps looking the configuration set up first. + if (!request.configurationSetBeforeEmptyDestinations() && !anyBulkRecipient(request.entries())) { + return emptyDestinationResults(request); + } + // A bulk send looks the configuration set up here and refuses a paused one only after the + // sender check, unlike a single send (probe-confirmed). + configSetService.requireExistsForSending(request.configurationSetName(), request.region()); if (!request.recipientLimitPerEntry()) { for (BulkEmailEntry entry : request.entries()) { int recipientCount = recipientCount(entry); @@ -1792,15 +1800,11 @@ public class SesService { } } - // When no entry names a recipient, SES answers every entry the same, whatever its lists hold - // (probe-confirmed for null elements, empty lists and an empty Destination). No sender is - // checked then, so a paused account is still refused (unprobed). + // SendBulkTemplatedEmail with no recipient checks no sender, so its paused configuration + // set is still refused (unprobed). if (!anyBulkRecipient(request.entries())) { - accountService.requireAccountSendingEnabled(request.region()); - return request.entries().stream() - .map(entry -> BulkEmailEntryResult.failure(BulkEmailEntryResult.Status.INVALID_PARAMETER, - "Destination cannot be empty")) - .toList(); + configSetService.requireSendingNotPaused(request.configurationSetName(), request.region()); + return emptyDestinationResults(request); } if (request.templateName() != null) { SesTemplateService.requireSendTemplateName(request.templateName()); @@ -1808,10 +1812,13 @@ public class SesService { // 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). A paused // account is refused after the sender check (probe-confirmed); placing it ahead of the - // template lookup is a choice. + // template lookup is a choice. A paused configuration set is refused after the sender check + // too (probe-confirmed); placing it ahead of the paused account, as on a single send, is a + // choice. requireVerifiedSenders(List.of( new SendingAddress(request.source(), request.sourceArn()), new SendingAddress(request.returnPath(), request.returnPathArn())), request.region()); + configSetService.requireSendingNotPaused(request.configurationSetName(), request.region()); accountService.requireAccountSendingEnabled(request.region()); EmailContent.InlineTemplate template = switch (request.defaultContent()) { case EmailContent.Template stored -> templateService.inline(stored, request.region()); @@ -1873,6 +1880,17 @@ public class SesService { return results; } + // When no entry names a recipient, SES answers every entry the same, whatever its lists hold + // (probe-confirmed for null elements, empty lists and an empty Destination). No sender is + // checked then, so a paused account is still refused (unprobed). + private List emptyDestinationResults(SendBulkEmailRequest request) { + accountService.requireAccountSendingEnabled(request.region()); + return request.entries().stream() + .map(entry -> BulkEmailEntryResult.failure(BulkEmailEntryResult.Status.INVALID_PARAMETER, + "Destination cannot be empty")) + .toList(); + } + private static boolean anyBulkRecipient(List entries) { return entries.stream() .flatMap(entry -> Stream.of(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())) diff --git a/src/main/java/io/floci/aws/services/ses/model/SendBulkEmailRequest.java b/src/main/java/io/floci/aws/services/ses/model/SendBulkEmailRequest.java index 836a0f6ce7..51ad48d38f 100644 --- a/src/main/java/io/floci/aws/services/ses/model/SendBulkEmailRequest.java +++ b/src/main/java/io/floci/aws/services/ses/model/SendBulkEmailRequest.java @@ -11,7 +11,10 @@ import java.util.Objects; * each entry's replacements merge over. {@code sourceArn} and {@code returnPathArn} are the * sending-authorization identity ARNs of the sender and the return path. With * {@code recipientLimitPerEntry} an entry over the recipient limit fails on its own, as on v1 - * (probe-confirmed); without it the whole call is rejected. + * (probe-confirmed); without it the whole call is rejected. With + * {@code configurationSetBeforeEmptyDestinations} an unknown or paused configuration set is + * reported even when no entry names a recipient, the order v1 keeps because AWS has not been + * probed there; without it every entry is answered on its own first, as on v2 (probe-confirmed). */ public record SendBulkEmailRequest( String source, @@ -24,6 +27,7 @@ public record SendBulkEmailRequest( String tenantName, String region, boolean recipientLimitPerEntry, + boolean configurationSetBeforeEmptyDestinations, EmailContent.TemplateContent defaultContent, List entries) { @@ -53,6 +57,7 @@ public record SendBulkEmailRequest( private String tenantName; private String region; private boolean recipientLimitPerEntry; + private boolean configurationSetBeforeEmptyDestinations; private EmailContent.TemplateContent defaultContent; private List entries = List.of(); @@ -69,13 +74,14 @@ public record SendBulkEmailRequest( public Builder tenantName(String tenantName) { this.tenantName = tenantName; return this; } public Builder region(String region) { this.region = region; return this; } public Builder recipientLimitPerEntry(boolean recipientLimitPerEntry) { this.recipientLimitPerEntry = recipientLimitPerEntry; return this; } + public Builder configurationSetBeforeEmptyDestinations(boolean configurationSetBeforeEmptyDestinations) { this.configurationSetBeforeEmptyDestinations = configurationSetBeforeEmptyDestinations; return this; } public Builder defaultContent(EmailContent.TemplateContent defaultContent) { this.defaultContent = defaultContent; return this; } public Builder entries(List entries) { this.entries = entries; return this; } public SendBulkEmailRequest build() { return new SendBulkEmailRequest(source, sourceArn, replyToAddresses, returnPath, returnPathArn, - configurationSetName, defaultEmailTags, tenantName, region, recipientLimitPerEntry, defaultContent, - entries); + configurationSetName, defaultEmailTags, tenantName, region, recipientLimitPerEntry, + configurationSetBeforeEmptyDestinations, defaultContent, entries); } } } diff --git a/src/test/java/io/floci/aws/services/ses/SesAccountSendingPausedV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesAccountSendingPausedV2IntegrationTest.java index 029a4c8389..faf927c60b 100644 --- a/src/test/java/io/floci/aws/services/ses/SesAccountSendingPausedV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesAccountSendingPausedV2IntegrationTest.java @@ -107,7 +107,8 @@ class SesAccountSendingPausedV2IntegrationTest { private static String bulkBody(String sender) { return """ {"FromEmailAddress": "%s", - "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "t"}}}, + "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "t"}, + "TemplateData": "{}"}}, "BulkEmailEntries": [{"Destination": {"ToAddresses": ["to@example.com"]}}]} """.formatted(sender); } diff --git a/src/test/java/io/floci/aws/services/ses/SesBulkV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesBulkV2IntegrationTest.java index 6168e61cd1..744f6e2c27 100644 --- a/src/test/java/io/floci/aws/services/ses/SesBulkV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesBulkV2IntegrationTest.java @@ -208,7 +208,7 @@ class SesBulkV2IntegrationTest { { "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { - "Template": {"TemplateName": "ghost"} + "Template": {"TemplateName": "ghost", "TemplateData": "{}"} }, "BulkEmailEntries": [ {"Destination": {"ToAddresses": ["alice@example.com"]}} @@ -468,7 +468,7 @@ class SesBulkV2IntegrationTest { { "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { - "Template": {"TemplateName": "v2-bulk-welcome"} + "Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": "{}"} }, "BulkEmailEntries": [ {"Destination": {"ToAddresses": [%s]}} @@ -614,7 +614,8 @@ class SesBulkV2IntegrationTest { .body(""" { "FromEmailAddress": "bulk-v2-inline@floci.test", - "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "t"}}}, + "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "t"}, + "TemplateData": "{}"}}, "BulkEmailEntries": [ {"Destination": {"ToAddresses": ["alice@example.com"]}}, {"Destination": {"ToAddresses": []}} diff --git a/src/test/java/io/floci/aws/services/ses/SesSendTemplateLookupOrderIntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesSendTemplateLookupOrderIntegrationTest.java index fa4b6e9745..98422e3c50 100644 --- a/src/test/java/io/floci/aws/services/ses/SesSendTemplateLookupOrderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesSendTemplateLookupOrderIntegrationTest.java @@ -5,6 +5,8 @@ import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static io.floci.aws.services.ses.SesV2Requests.ENTRY; import static io.floci.aws.services.ses.SesV2Requests.TO; @@ -19,9 +21,11 @@ import static org.hamcrest.Matchers.nullValue; * Without a tenant, the v2 sends look a stored template up last: an unknown configuration set is * reported first, then an unverified sender or feedback forwarding address, and only then an * unknown template (probe-confirmed). A SendBulkEmail in which no entry names a recipient answers - * every entry before any of them. The v1 SendTemplatedEmail and SendBulkTemplatedEmail follow the - * same order with Source and ReturnPath, and the bulk send counts its destinations first - * (probe-confirmed). + * every entry before any of them, an unknown configuration set included, and a template send + * without its template data is refused ahead of all of these (probe-confirmed; on SendEmail only + * against the sender check, the rest follows SendBulkEmail). The v1 SendTemplatedEmail and + * SendBulkTemplatedEmail follow the same order with Source and ReturnPath, and the bulk send + * counts its destinations first (probe-confirmed). */ @QuarkusTest class SesSendTemplateLookupOrderIntegrationTest { @@ -36,6 +40,9 @@ class SesSendTemplateLookupOrderIntegrationTest { 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 V1_GHOST_TEMPLATE = "template-order-v1-ghost"; + private static final String GHOST_CONFIG_SET_MEMBER = "\"ConfigurationSetName\": \"" + GHOST_CONFIG_SET + "\", "; + private static final String NO_RECIPIENT_ENTRIES = + "{\"Destination\": {}}, {\"Destination\": {\"ToAddresses\": []}}"; // Not @BeforeAll: the Quarkus test port is only bound once the first test starts. @BeforeEach @@ -114,6 +121,24 @@ class SesSendTemplateLookupOrderIntegrationTest { .body("message", equalTo("Configuration set <" + GHOST_CONFIG_SET + "> does not exist.")); } + private static void assertBadRequest(ValidatableResponse response, String message) { + response + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + } + + private static void assertEveryEntryEmpty(ValidatableResponse response) { + response + .statusCode(200) + .body("BulkEmailEntryResults", hasSize(2)) + .body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER")) + .body("BulkEmailEntryResults[0].Error", equalTo("Destination cannot be empty")) + .body("BulkEmailEntryResults[0].MessageId", nullValue()) + .body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER")) + .body("BulkEmailEntryResults[1].Error", equalTo("Destination cannot be empty")); + } + private static void assertTemplateNotFound(ValidatableResponse response) { response .statusCode(404) @@ -166,14 +191,60 @@ class SesSendTemplateLookupOrderIntegrationTest { @Test void sendBulkEmail_noEntryWithARecipient_answersEveryEntryBeforeSenderAndTemplate() { for (String sender : new String[] {UNVERIFIED, VERIFIED}) { - bulk(sender, GHOST_TEMPLATE, "", "{\"Destination\": {}}, {\"Destination\": {\"ToAddresses\": []}}") - .statusCode(200) - .body("BulkEmailEntryResults", hasSize(2)) - .body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER")) - .body("BulkEmailEntryResults[0].Error", equalTo("Destination cannot be empty")) - .body("BulkEmailEntryResults[0].MessageId", nullValue()) - .body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER")) - .body("BulkEmailEntryResults[1].Error", equalTo("Destination cannot be empty")); + assertEveryEntryEmpty(bulk(sender, GHOST_TEMPLATE, "", NO_RECIPIENT_ENTRIES)); + } + } + + @Test + void sendBulkEmail_noEntryWithARecipient_answersEveryEntryBeforeUnknownConfigurationSet() { + assertEveryEntryEmpty(bulk(UNVERIFIED, GHOST_TEMPLATE, GHOST_CONFIG_SET_MEMBER, NO_RECIPIENT_ENTRIES)); + assertEveryEntryEmpty(bulk(UNVERIFIED, INLINE_TEMPLATE, GHOST_CONFIG_SET_MEMBER, NO_RECIPIENT_ENTRIES)); + } + + @Test + void sendBulkEmail_oneEntryWithARecipient_stillReportsUnknownConfigurationSet() { + assertConfigSetNotFound(bulk(UNVERIFIED, GHOST_TEMPLATE, GHOST_CONFIG_SET_MEMBER, + "{\"Destination\": {}}, " + ENTRY)); + } + + @ParameterizedTest + @ValueSource(strings = { + "\"TemplateName\": \"template-order-ghost\"", + "\"TemplateName\": \"template-order-ghost\", \"TemplateData\": \"\"", + "\"TemplateName\": \"template-order-ghost\", \"TemplateData\": null", + "\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}", + "\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}, \"TemplateData\": \"\"" + }) + void sendBulkEmail_missingDefaultTemplateDataPrecedesEveryLookup(String template) { + String content = "{\"Template\": {" + template + "}}"; + + assertBadRequest(bulk(UNVERIFIED, content, "", ENTRY), "The default template data does not exist"); + assertBadRequest(bulk(UNVERIFIED, content, GHOST_CONFIG_SET_MEMBER, ENTRY), + "The default template data does not exist"); + assertBadRequest(bulk(UNVERIFIED, content, GHOST_CONFIG_SET_MEMBER, NO_RECIPIENT_ENTRIES), + "The default template data does not exist"); + } + + @Test + void sendBulkEmail_replacementTemplateDataStaysOptional() { + assertTemplateNotFound(bulk(VERIFIED, GHOST_TEMPLATE, "", + "{\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"ReplacementEmailContent\": " + + "{\"ReplacementTemplate\": {}}}")); + } + + @ParameterizedTest + @ValueSource(strings = { + "\"TemplateName\": \"template-order-ghost\"", + "\"TemplateName\": \"template-order-ghost\", \"TemplateData\": \"\"", + "\"TemplateName\": \"template-order-ghost\", \"TemplateData\": null", + "\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}", + "\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}, \"TemplateData\": \"\"" + }) + void sendEmail_missingTemplateDataPrecedesEveryLookup(String template) { + for (String members : new String[] {"", GHOST_CONFIG_SET_MEMBER}) { + assertBadRequest(post("/v2/email/outbound-emails", "{\"FromEmailAddress\": \"" + UNVERIFIED + "\", " + + members + "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"Content\": {\"Template\": {" + + template + "}}}"), "Template data cannot be empty"); } } @@ -238,6 +309,24 @@ class SesSendTemplateLookupOrderIntegrationTest { "ConfigurationSetDoesNotExist", "Configuration set <" + GHOST_CONFIG_SET + "> does not exist."); } + @Test + void templateArnChecksPrecedeMissingTemplateData() { + String content = "{\"Template\": {\"TemplateArn\": \"not-an-arn\"}}"; + + assertBadRequest(bulk(UNVERIFIED, content, "", ENTRY), "ARNs must start with 'arn:': not-an-arn"); + assertBadRequest(post("/v2/email/outbound-emails", "{\"FromEmailAddress\": \"" + UNVERIFIED + "\", " + + "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"Content\": " + content + "}"), + "ARNs must start with 'arn:': not-an-arn"); + } + + @Test + void sendBulkTemplatedEmail_noEntryWithARecipient_stillReportsUnknownConfigurationSet() { + // Not probed on v1: it keeps the order it had, unlike SendBulkEmail. + assertV1Error(bulkTemplated(UNVERIFIED, 0, "ConfigurationSetName", GHOST_CONFIG_SET, + "Destinations.member.1.Destination.ToAddresses", ""), + "ConfigurationSetDoesNotExist", "Configuration set <" + GHOST_CONFIG_SET + "> does not exist."); + } + @Test void sendBulkTemplatedEmail_verifiedSource_unknownTemplate() { assertV1Error(bulkTemplated(VERIFIED, 1), "TemplateDoesNotExist", diff --git a/src/test/java/io/floci/aws/services/ses/SesSendVerifiedSenderIntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesSendVerifiedSenderIntegrationTest.java index 8bb11c50fb..05071ab072 100644 --- a/src/test/java/io/floci/aws/services/ses/SesSendVerifiedSenderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesSendVerifiedSenderIntegrationTest.java @@ -550,7 +550,8 @@ class SesSendVerifiedSenderIntegrationTest { { "FromEmailAddress": "%s", %s - "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "b"}}}, + "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "b"}, + "TemplateData": "{}"}}, "BulkEmailEntries": %s } """.formatted(from, extraMembers, entries); diff --git a/src/test/java/io/floci/aws/services/ses/SesServiceBulkEmptyDestinationTest.java b/src/test/java/io/floci/aws/services/ses/SesServiceBulkEmptyDestinationTest.java new file mode 100644 index 0000000000..198ff141ed --- /dev/null +++ b/src/test/java/io/floci/aws/services/ses/SesServiceBulkEmptyDestinationTest.java @@ -0,0 +1,144 @@ +package io.floci.aws.services.ses; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.ses.model.BulkEmailEntry; +import io.floci.aws.services.ses.model.BulkEmailEntryResult; +import io.floci.aws.services.ses.model.ConfigurationSet; +import io.floci.aws.services.ses.model.EmailContent; +import io.floci.aws.services.ses.model.SendBulkEmailRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * A v2 SendBulkEmail in which no entry names a recipient answers every entry on its own, ahead of + * the configuration set lookup, the sending-paused gate of the set and the stored template lookup + * (probe-confirmed). With one addressed entry the request-level checks run as usual: the set is + * looked up first and its pause is refused after the sender check (probe-confirmed). The v1 + * SendBulkTemplatedEmail has not been probed with no recipient and keeps the configuration set first. + */ +class SesServiceBulkEmptyDestinationTest { + + private static final String REGION = "us-east-1"; + private static final String SENDER = "from@example.com"; + private static final String GHOST_SET = "ghost-set"; + private static final String PAUSED_SET = "paused-set"; + private static final String ENABLED_SET = "enabled-set"; + private static final EmailContent.InlineTemplate INLINE = + new EmailContent.InlineTemplate("s", "t", null, null, List.of()); + private static final BulkEmailEntry EMPTY = new BulkEmailEntry(List.of(), null, null, null, null, null); + private static final BulkEmailEntry ADDRESSED = + new BulkEmailEntry(List.of("to@example.com"), null, null, null, null, null); + + private SesServiceTestBuilder builder; + private SesService service; + + @BeforeEach + void setUp() { + builder = SesServiceTestBuilder.create(); + service = builder.build(); + service.createConfigurationSet(new ConfigurationSet(ENABLED_SET), REGION); + service.createConfigurationSet(new ConfigurationSet(PAUSED_SET), REGION); + builder.configSetService().setSendingEnabled(PAUSED_SET, false, REGION); + } + + @Test + void noRecipient_unknownConfigurationSet_answersEveryEntry() { + assertEveryEntryEmpty(service.sendBulkEmail(request(GHOST_SET, INLINE, EMPTY, EMPTY).build()), 2); + } + + @Test + void noRecipient_pausedConfigurationSet_answersEveryEntry() { + assertEveryEntryEmpty(service.sendBulkEmail(request(PAUSED_SET, INLINE, EMPTY).build()), 1); + } + + @Test + void noRecipient_unknownConfigurationSetAndMissingTemplate_answersEveryEntry() { + EmailContent.Template missing = new EmailContent.Template("missing", null, List.of()); + + assertEveryEntryEmpty(service.sendBulkEmail(request(GHOST_SET, missing, EMPTY).build()), 1); + } + + @Test + void oneAddressedEntry_unknownConfigurationSet_isRefused() { + AwsException e = assertThrows(AwsException.class, + () -> service.sendBulkEmail(request(GHOST_SET, INLINE, EMPTY, ADDRESSED).build())); + + assertEquals("ConfigurationSetDoesNotExist", e.getErrorCode()); + } + + @Test + void oneAddressedEntry_pausedConfigurationSetAndUnverifiedSender_isRejectedForTheSender() { + AwsException e = assertThrows(AwsException.class, + () -> service.sendBulkEmail(request(PAUSED_SET, INLINE, EMPTY, ADDRESSED).build())); + + assertEquals("MessageRejected", e.getErrorCode()); + } + + @Test + void oneAddressedEntry_pausedConfigurationSetAndVerifiedSender_isRefusedByThePause() { + builder.identityService().verifyEmailIdentity(SENDER, REGION); + + AwsException e = assertThrows(AwsException.class, + () -> service.sendBulkEmail(request(PAUSED_SET, INLINE, EMPTY, ADDRESSED).build())); + + assertEquals("ConfigurationSetSendingPausedException", e.getErrorCode()); + } + + @Test + void oneAddressedEntry_pausedConfigurationSetAndPausedAccount_isRefusedByTheSet() { + builder.identityService().verifyEmailIdentity(SENDER, REGION); + builder.accountService().setAccountSendingEnabled(REGION, false); + + AwsException e = assertThrows(AwsException.class, + () -> service.sendBulkEmail(request(PAUSED_SET, INLINE, EMPTY, ADDRESSED).build())); + + assertEquals("ConfigurationSetSendingPausedException", e.getErrorCode()); + } + + @Test + void v1Order_noRecipient_unknownConfigurationSet_isRefused() { + AwsException e = assertThrows(AwsException.class, () -> service.sendBulkEmail( + request(GHOST_SET, INLINE, EMPTY).configurationSetBeforeEmptyDestinations(true).build())); + + assertEquals("ConfigurationSetDoesNotExist", e.getErrorCode()); + } + + @Test + void v1Order_noRecipient_pausedConfigurationSet_isRefused() { + AwsException e = assertThrows(AwsException.class, () -> service.sendBulkEmail( + request(PAUSED_SET, INLINE, EMPTY).configurationSetBeforeEmptyDestinations(true).build())); + + assertEquals("ConfigurationSetSendingPausedException", e.getErrorCode()); + } + + @Test + void v1Order_noRecipient_knownConfigurationSet_answersEveryEntry() { + assertEveryEntryEmpty(service.sendBulkEmail( + request(ENABLED_SET, INLINE, EMPTY).configurationSetBeforeEmptyDestinations(true).build()), 1); + } + + private static SendBulkEmailRequest.Builder request(String configurationSet, EmailContent.TemplateContent content, + BulkEmailEntry... entries) { + return SendBulkEmailRequest.builder() + .source(SENDER) + .region(REGION) + .configurationSetName(configurationSet) + .defaultContent(content) + .entries(List.of(entries)); + } + + private static void assertEveryEntryEmpty(List results, int expected) { + assertEquals(expected, results.size()); + for (BulkEmailEntryResult result : results) { + assertEquals(BulkEmailEntryResult.Status.INVALID_PARAMETER, result.getStatus()); + assertEquals("Destination cannot be empty", result.getError()); + assertNull(result.getMessageId()); + } + } +} diff --git a/src/test/java/io/floci/aws/services/ses/SesTenantSendOrderV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesTenantSendOrderV2IntegrationTest.java index 99977bc4a6..774dcecb0c 100644 --- a/src/test/java/io/floci/aws/services/ses/SesTenantSendOrderV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesTenantSendOrderV2IntegrationTest.java @@ -49,7 +49,8 @@ class SesTenantSendOrderV2IntegrationTest { private static ValidatableResponse bulk(String members) { return v2().body("{" + member("TenantName", TENANT) + members - + "\"DefaultContent\":{\"Template\":{\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}}}," + + "\"DefaultContent\":{\"Template\":{\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}," + + "\"TemplateData\":\"{}\"}}," + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":" + "[\"success@simulator.amazonses.com\"]}}]}") .when().post("/v2/email/outbound-bulk-emails").then();