diff --git a/docs/services/ses.md b/docs/services/ses.md index e84a88b638..00a96fbdcc 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -303,7 +303,8 @@ curl $AWS_ENDPOINT_URL/_aws/ses ## Current Behavior - An email address identity is verified as soon as it is created; no inbox verification flow is required. A domain identity stays `Pending` until its DKIM CNAME records exist in a Route 53 hosted zone in Floci, then becomes `Success`. -- `SendEmail`, `SendRawEmail` and `SendTemplatedEmail`, and v2 `SendEmail`, 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. The bulk sends do not check the sender. The verification codes and invitations Cognito sends are not affected. +- `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` (with no `TemplateArn`), 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). - `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). - 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. @@ -457,7 +458,7 @@ Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `Tenant Tenant resource associations link a tenant to email identities, configuration sets, and email templates. Matching real AWS, the wire values for `ResourceType` (in responses and as the `Filter` `RESOURCE_TYPE` value) are the ARN segments `identity` / `configuration-set` / `template`; the SDK's `EMAIL_IDENTITY`-style enum constants are rejected, as AWS itself does. The resource must exist in the same account and region; a duplicate association is `AlreadyExistsException`, and deleting a missing one succeeds silently. Deleting a resource that still has associations is rejected, while `DeleteTenant` cascades its associations away. -A `TenantName` on `SendEmail`/`SendBulkEmail` makes the send tenant-scoped. Every resource it uses must be associated with the tenant: the From identity (the exact address identity, else its domain identity), the effective configuration set (an omitted name resolves to the identity's default), and a stored template. Otherwise the send is refused with a 403 `AccessDeniedException` listing the missing ARNs. The send path has its own tenant-not-found wording ("Tenant \ for AwsAccountId \ not found."), reached only after the request shape validates. A tenant whose sending status is `DISABLED` is refused with a 400 `MessageRejected` before identity verification, the association check and a raw message's missing recipients. As on SES, a malformed address, a Simple or Template send with no recipient, and an unknown configuration set named by a `SendEmail` request are reported first; `SendBulkEmail` refuses the tenant before it looks up the configuration set. `SendBulkEmail` looks the tenant up before an unknown stored template, and skips the tenant checks altogether when no entry names a recipient: every entry then answers `Destination cannot be empty`, as it does without a tenant. Not emulated: tenant-scoped suppression filtering of sends (the account-level semantics apply). +A `TenantName` on `SendEmail`/`SendBulkEmail` makes the send tenant-scoped. Every resource it uses must be associated with the tenant: the From identity (the exact address identity, else its domain identity), the effective configuration set (an omitted name resolves to the identity's default), and a stored template. Otherwise the send is refused with a 403 `AccessDeniedException` listing the missing ARNs. That 403 is the last check of the send: an unverified sender or return path, a missing configuration set and a missing stored template are reported first (probe-confirmed). The send path has its own tenant-not-found wording ("Tenant \ for AwsAccountId \ not found."), reached only after the request shape validates. A tenant whose sending status is `DISABLED` is refused with a 400 `MessageRejected` before identity verification, the association check and a raw message's missing recipients. As on SES, a malformed address, a Simple or Template send with no recipient, and an unknown configuration set named by a `SendEmail` request are reported first; `SendBulkEmail` refuses the tenant before it looks up the configuration set. `SendBulkEmail` looks the tenant up before an unknown stored template, and skips the tenant checks altogether when no entry names a recipient: every entry then answers `Destination cannot be empty`, as it does without a tenant. Not emulated: tenant-scoped suppression filtering of sends (the account-level semantics apply). `PutTenantSuppressionAttributes` sets a tenant's `SuppressedReasons`/`SuppressionScope` pair on AWS's own singular `/v2/email/tenant/suppression` route. The pair is all-or-nothing: both members set the block (an empty reason list is valid), half a pair is rejected, and a bare `TenantName` clears it. A `TenantName` on the suppression-list operations (body member on put, query parameter on get/delete/list) routes them to the tenant's own list — separate from the account list, independent of `SuppressionScope`, cascaded away by `DeleteTenant`, and with a non-idempotent delete. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java b/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java index 37c08d28f7..1426744bc1 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/SmithyValidationErrors.java @@ -31,6 +31,11 @@ public final class SmithyValidationErrors { return "Value null at '" + path + "' failed to satisfy constraint: Member must not be null"; } + /** The same violation in the form some operations answer, without {@code null} after "Value". */ + public static String notNullWithoutValue(String path) { + return "Value at '" + path + "' failed to satisfy constraint: Member must not be null"; + } + /** The 400 error carrying {@link #message} under the protocol's validation error code. */ public static AwsException exception(String errorCode, List violations) { return new AwsException(errorCode, message(violations), 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java index f3a0f10089..9e08b9392c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java @@ -137,11 +137,12 @@ public class SesExportJobService implements Resettable { throw new AwsException("BadRequestException", "One data source must be provided", 400); } if (!exportDestination.isObject()) { - throw notNull("exportDestination"); + throw SmithyValidationErrors.badRequest(SmithyValidationErrors.notNullWithoutValue("exportDestination")); } String dataFormat = exportDestination.path("DataFormat").textValue(); if (dataFormat == null) { - throw notNull("exportDestination.dataFormat"); + throw SmithyValidationErrors.badRequest( + SmithyValidationErrors.notNullWithoutValue("exportDestination.dataFormat")); } if (!DATA_FORMATS.contains(dataFormat)) { throw SmithyValidationErrors.badRequest( @@ -540,11 +541,6 @@ public class SesExportJobService implements Resettable { return ExportJob.FORMAT_CSV.equals(dataFormat) ? "text/csv" : "application/json"; } - private static AwsException notNull(String member) { - return SmithyValidationErrors.badRequest( - "Value at '" + member + "' failed to satisfy constraint: Member must not be null"); - } - /** * The model bounds {@code MaxResults} at 1 to 10000. An unchecked negative value reached * {@code subList} inside the filter and surfaced as a 500. The value is stored as the int it @@ -572,10 +568,8 @@ public class SesExportJobService implements Resettable { private static Instant requireDate(JsonNode source, String field) { Instant value = date(source, field); if (value == null) { - throw SmithyValidationErrors.badRequest( - "Value at '" + field.substring(0, 1).toLowerCase(Locale.ROOT) - + field.substring(1) + "' failed to satisfy constraint: " - + "Member must not be null"); + throw SmithyValidationErrors.badRequest(SmithyValidationErrors.notNullWithoutValue( + field.substring(0, 1).toLowerCase(Locale.ROOT) + field.substring(1))); } return value; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java index 79cee27fac..07518fbe05 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java @@ -38,9 +38,11 @@ import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; /** * Query-protocol handler for SES actions. @@ -764,12 +766,33 @@ public class SesQueryHandler { throw new AwsException("AccountSendingPausedException", "Account sending is disabled.", 400); } + String templateName = getParam(params, "Template"); + String templateArn = getParam(params, "TemplateArn"); + BulkDestinationIndexes destinations = bulkDestinationIndexes(params); + // The model validation answers ahead of every other check of the request, listing its + // violations in the model's member order (probe-confirmed). + List violations = new ArrayList<>(); + if (templateName == null && templateArn == null) { + violations.add(SmithyValidationErrors.notNullWithoutValue("template")); + } + if (!params.containsKey("Destinations") && !hasParamWithPrefix(params, "Destinations.")) { + violations.add(SmithyValidationErrors.notNullWithoutValue("destinations")); + } + // A skipped index, like an entry without a Destination, is a null destination + // (probe-confirmed). An empty address list still sends its bare key. + for (int i = 1; i <= Math.min(destinations.last(), MAX_VALIDATED_DESTINATION_INDEX); i++) { + if (!destinations.withDestination().contains(i)) { + violations.add(SmithyValidationErrors.notNullWithoutValue("destinations." + i + ".member.destination")); + } + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationError(violations); + } + String source = getParam(params, "Source"); SesAddressSyntax.requireBulkAddress(source); SesAddressSyntax.requireBulkAddress(getParam(params, "ReturnPath")); List replyToAddresses = extractMembers(params, "ReplyToAddresses"); - String templateName = getParam(params, "Template"); - String templateArn = getParam(params, "TemplateArn"); String defaultDataRaw = getParam(params, "DefaultTemplateData"); boolean hasName = templateName != null && !templateName.isBlank(); @@ -780,28 +803,25 @@ public class SesQueryHandler { } String resolvedName = hasName ? templateName : SesTemplateService.templateNameFromArn(templateArn); + int lastIndex = destinations.last(); + if (lastIndex == 0) { + throw new AwsException("InvalidParameterValue", + "At least one destination is required.", 400); + } + // AWS counts the destinations before it looks the template up (probe-confirmed). The list + // runs to its highest index, so counting that index first also bounds the scan below. + SesService.requireBulkDestinationCount(lastIndex); List entries = new ArrayList<>(); - for (int i = 1; ; i++) { + for (int i = 1; i <= lastIndex; i++) { String destPrefix = "Destinations.member." + i; List to = extractMembers(params, destPrefix + ".Destination.ToAddresses"); List cc = extractMembers(params, destPrefix + ".Destination.CcAddresses"); List bcc = extractMembers(params, destPrefix + ".Destination.BccAddresses"); String replacementRaw = getParam(params, destPrefix + ".ReplacementTemplateData"); List replacementTags = extractMessageTags(params, destPrefix + ".ReplacementTags"); - if (to.isEmpty() && cc.isEmpty() && bcc.isEmpty() - && replacementRaw == null && replacementTags.isEmpty()) { - break; - } entries.add(new BulkEmailEntry(to, cc, bcc, parseTemplateData(replacementRaw), replacementTags, List.of())); } - if (entries.isEmpty()) { - throw new AwsException("InvalidParameterValue", - "At least one destination is required.", 400); - } - // AWS counts the destinations before it looks the template up (probe-confirmed). - SesService.requireBulkDestinationCount(entries.size()); - EmailTemplate template = templateService.getTemplate(resolvedName, region); JsonNode defaultTemplateData = parseTemplateData(defaultDataRaw); String configurationSetName = getParam(params, "ConfigurationSetName"); @@ -809,13 +829,14 @@ public class SesQueryHandler { List defaultEmailTags = extractMessageTags(params, "DefaultTags"); List results = sesService.sendBulkEmail(SendBulkEmailRequest.builder() .source(source) + .sourceArn(getParam(params, "SourceArn")) .replyToAddresses(replyToAddresses) .returnPath(returnPath) + .returnPathArn(getParam(params, "ReturnPathArn")) .configurationSetName(configurationSetName) .defaultEmailTags(defaultEmailTags) .region(region) - .defaultContent(new EmailContent.InlineTemplate(template.getSubject(), template.getTextPart(), - template.getHtmlPart(), defaultTemplateData, List.of())) + .defaultContent(new EmailContent.Template(resolvedName, defaultTemplateData, List.of())) .entries(entries) .build()); @@ -1558,6 +1579,46 @@ public class SesQueryHandler { // --- Helpers --- + private static boolean hasParamWithPrefix(MultivaluedMap params, String prefix) { + return params.keySet().stream().anyMatch(key -> key.startsWith(prefix)); + } + + // Bounds the violation list a hostile index could inflate; an index above it still fails the + // destination count. Where AWS stops listing null destinations has not been probed. + private static final int MAX_VALIDATED_DESTINATION_INDEX = 1000; + + /** The highest {@code Destinations.member.N}, and the Ns that carry a {@code Destination}. */ + private record BulkDestinationIndexes(int last, Set withDestination) {} + + private static BulkDestinationIndexes bulkDestinationIndexes(MultivaluedMap params) { + String prefix = "Destinations.member."; + int last = 0; + Set withDestination = new HashSet<>(); + for (String key : params.keySet()) { + if (!key.startsWith(prefix)) { + continue; + } + int dot = key.indexOf('.', prefix.length()); + int index = memberIndex(dot < 0 ? key.substring(prefix.length()) : key.substring(prefix.length(), dot)); + if (index == 0) { + continue; + } + last = Math.max(last, index); + if (dot >= 0 && key.startsWith(".Destination.", dot)) { + withDestination.add(index); + } + } + return new BulkDestinationIndexes(last, withDestination); + } + + // 0 for a token that is not a member index; one too long for an int is past any limit. + private static int memberIndex(String token) { + if (token.isEmpty() || token.charAt(0) == '0' || !token.chars().allMatch(c -> c >= '0' && c <= '9')) { + return 0; + } + return token.length() > 9 ? Integer.MAX_VALUE : Integer.parseInt(token); + } + private List extractMembers(MultivaluedMap params, String prefix) { List members = new ArrayList<>(); for (int i = 1; ; i++) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java index 87769f34c0..e8bf7960bf 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java @@ -751,25 +751,24 @@ public class SesReceiptRuleService { */ private static void validateFilterShape(ReceiptFilter filter) { if (filter == null) { - throw SmithyValidationErrors.validationError( - notNullViolation("filter")); + throw SmithyValidationErrors.validationError(SmithyValidationErrors.notNullWithoutValue("filter")); } List violations = new ArrayList<>(); if (filter.getName() == null) { - violations.add(notNullViolation("filter.name")); + violations.add(SmithyValidationErrors.notNullWithoutValue("filter.name")); } boolean hasIpFilter = filter.getPolicy() != null || filter.getCidr() != null; if (!hasIpFilter) { - violations.add(notNullViolation("filter.ipFilter")); + violations.add(SmithyValidationErrors.notNullWithoutValue("filter.ipFilter")); } else { if (filter.getPolicy() == null) { - violations.add(notNullViolation("filter.ipFilter.policy")); + violations.add(SmithyValidationErrors.notNullWithoutValue("filter.ipFilter.policy")); } else if (!"Allow".equals(filter.getPolicy()) && !"Block".equals(filter.getPolicy())) { violations.add("Value at 'filter.ipFilter.policy' failed to satisfy constraint: " + "Member must satisfy enum value set: [Allow, Block]"); } if (filter.getCidr() == null) { - violations.add(notNullViolation("filter.ipFilter.cidr")); + violations.add(SmithyValidationErrors.notNullWithoutValue("filter.ipFilter.cidr")); } } if (!violations.isEmpty()) { @@ -777,10 +776,6 @@ public class SesReceiptRuleService { } } - private static String notNullViolation(String path) { - return "Value at '" + path + "' failed to satisfy constraint: Member must not be null"; - } - /** * Service-level filter name checks, probed: empty gets its own message, and every other * malformed shape (bad character, longer than 64, non-alphanumeric start or end) shares 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 b886cb7f2b..db5184557a 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 @@ -11,7 +11,6 @@ import io.github.hectorvent.floci.services.ses.address.SesAddressSyntax; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; import io.github.hectorvent.floci.services.ses.model.EmailContent; -import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; import io.github.hectorvent.floci.services.ses.model.MessageAttachment; import io.github.hectorvent.floci.services.ses.model.MessageHeader; @@ -49,8 +48,7 @@ import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception * {@code /v2/email/outbound-custom-verification-emails}. Every other v2 URL group has its own * controller in this package; the send path stays here because it is the one group that reads * across several domains. It goes through the {@link SesService} facade for that reason, and - * through {@link SesTemplateService} and {@link SesAccountService} for the stored template and - * the account-level sending switch. + * through {@link SesAccountService} for the account-level sending switch. */ @Path("/v2/email") @Produces(MediaType.APPLICATION_JSON) @@ -62,19 +60,15 @@ public class SesSendController { private static final List TRACKING_VALUES = List.of("ENABLED", "DISABLED"); private final SesService sesService; - // The bulk send resolves a stored template's content before handing the entries to the facade. - private final SesTemplateService templateService; // The send endpoints read the account-level sending switch before building the message. private final SesAccountService accountService; private final RegionResolver regionResolver; private final ObjectMapper objectMapper; @Inject - public SesSendController(SesService sesService, SesTemplateService templateService, - SesAccountService accountService, RegionResolver regionResolver, - ObjectMapper objectMapper) { + public SesSendController(SesService sesService, SesAccountService accountService, + RegionResolver regionResolver, ObjectMapper objectMapper) { this.sesService = sesService; - this.templateService = templateService; this.accountService = accountService; this.regionResolver = regionResolver; this.objectMapper = objectMapper; @@ -143,8 +137,6 @@ public class SesSendController { } requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses); SendEmailRequest rawRequest = sendRequest.content(new EmailContent.Raw(rawData, true)).build(); - sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData, - rawRequest.hasRecipients(), configurationSetName, regionResolver.getAccountId(), region); messageId = sesService.sendEmail(rawRequest); } else if (content.has("Simple")) { if (fromEmailAddress == null || fromEmailAddress.isBlank()) { @@ -164,7 +156,6 @@ public class SesSendController { .content(new EmailContent.Simple(subject, bodyText, bodyHtml, additionalHeaders, attachments)) .build(); - sesService.checkTenantSendAccess(simpleRequest, null, regionResolver.getAccountId()); messageId = sesService.sendEmail(simpleRequest); } else if (content.has("Template")) { if (fromEmailAddress == null || fromEmailAddress.isBlank()) { @@ -197,7 +188,6 @@ public class SesSendController { SendEmailRequest templateRequest = sendRequest .content(new EmailContent.Template(resolvedName, templateData, additionalHeaders)) .build(); - sesService.checkTenantSendAccess(templateRequest, resolvedName, regionResolver.getAccountId()); messageId = sesService.sendEmail(templateRequest); } else { JsonNode inline = template.path("TemplateContent"); @@ -213,7 +203,6 @@ public class SesSendController { .content(new EmailContent.InlineTemplate(subject, text, html, templateData, additionalHeaders)) .build(); - sesService.checkTenantSendAccess(inlineRequest, null, regionResolver.getAccountId()); messageId = sesService.sendEmail(inlineRequest); } } else { @@ -288,28 +277,23 @@ public class SesSendController { String subject = null; String text = null; String html = null; - // Inline template content is not a stored template resource, so it stays out of the - // tenant gate below. - String gateTemplateName = null; + // The send looks the stored template up only after its sender checks (probe-confirmed). + String storedTemplateName = null; if (hasInline) { JsonNode inline = template.path("TemplateContent"); subject = inline.path("Subject").asText(null); text = inline.path("Text").asText(null); html = inline.path("Html").asText(null); - // Shape validation belongs before the tenant gate below, as on SendEmail. + // Shape validation belongs before the send's tenant lookup, as on SendEmail. SesService.requireInlineTemplateContent(subject, text, html); } // AWS counts the entries after the inline content check and before it looks the stored // template up (probe-confirmed). SesService.requireBulkDestinationCount(bulkEntries.size()); if (!hasInline) { - String resolvedName = hasName + storedTemplateName = hasName ? templateName : SesTemplateService.templateNameFromArn(templateArn); - gateTemplateName = resolvedName; - subject = null; - text = null; - html = null; } JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData"); @@ -337,28 +321,23 @@ public class SesSendController { entryIndex++; } - // The tenant gate runs only after every part of the request has been parsed and - // validated — AWS reports malformed content before a missing tenant (probe-confirmed). - sesService.checkTenantBulkSendAccess(tenantName, fromEmailAddress, configurationSetName, - gateTemplateName, entries, regionResolver.getAccountId(), region); - // SES reports an unknown or DISABLED tenant before an unknown stored template (probe-confirmed). - if (gateTemplateName != null) { - EmailTemplate stored = templateService.getTemplate(gateTemplateName, region); - subject = stored.getSubject(); - text = stored.getTextPart(); - html = stored.getHtmlPart(); - } + // The send looks the tenant up, so only after every part of the request has been parsed + // and validated: AWS reports malformed content before a missing tenant (probe-confirmed). + EmailContent.TemplateContent defaultContent = storedTemplateName == null + ? new EmailContent.InlineTemplate(subject, text, html, defaultTemplateData, defaultHeaders) + : new EmailContent.Template(storedTemplateName, defaultTemplateData, defaultHeaders); List results = sesService.sendBulkEmail(SendBulkEmailRequest.builder() .source(fromEmailAddress) + .sourceArn(request.path("FromEmailAddressIdentityArn").asText(null)) .replyToAddresses(replyToAddresses) .returnPath(feedbackForwardingAddress) + .returnPathArn(request.path("FeedbackForwardingEmailAddressIdentityArn").asText(null)) .configurationSetName(configurationSetName) .defaultEmailTags(defaultEmailTags) .tenantName(tenantName) .region(region) - .defaultContent(new EmailContent.InlineTemplate(subject, text, html, defaultTemplateData, - defaultHeaders)) + .defaultContent(defaultContent) .entries(entries) .build()); 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 a1fe8cdd96..7030421547 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 @@ -52,6 +52,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Supplier; import java.util.stream.Stream; /** @@ -275,16 +276,23 @@ public class SesService { if (request.content() instanceof EmailContent.Raw raw) { return sendRawEmail(request, raw, requireVerifiedSender); } + Tenant tenant = requireSendingTenant(request.tenantName(), request.region(), request, + request::configurationSetName); if (request.content() instanceof EmailContent.InlineTemplate inline) { requireInlineTemplateContent(inline.subject(), inline.textPart(), inline.htmlPart()); } // After a missing sender, AWS reports a malformed address ahead of the destination and - // configuration-set checks, then an over-long address, and only then a missing stored - // template (probe-confirmed), so the content is resolved after these checks. + // configuration-set checks, then an over-long address, then an unverified sender, and only + // then a missing stored template (probe-confirmed), so the content is resolved last. requireSource(request); SesAddressSyntax.requireEnvelope(request); String effectiveConfigSet = validateEnvelope(request); SesAddressLength.requireEnvelope(request); + if (requireVerifiedSender) { + requireVerifiedSenders(List.of( + new SendingAddress(request.source(), request.sourceArn()), + new SendingAddress(request.returnPath(), request.returnPathArn())), request.region()); + } EmailContent.Simple content = switch (request.content()) { case EmailContent.Simple simple -> simple; case EmailContent.Template template -> @@ -292,11 +300,10 @@ public class SesService { case EmailContent.InlineTemplate inline -> SesTemplateService.render(inline); case EmailContent.Raw raw -> throw new IllegalStateException("Raw content is sent above"); }; - if (requireVerifiedSender) { - requireVerifiedSenders(List.of( - new SendingAddress(request.source(), request.sourceArn()), - new SendingAddress(request.returnPath(), request.returnPathArn())), request.region()); - } + String templateName = request.content() instanceof EmailContent.Template template + ? template.templateName() + : null; + requireTenantAssociations(tenant, request.source(), effectiveConfigSet, templateName, request.region()); return sendSimpleEmail(request.toBuilder().content(content).build(), content, effectiveConfigSet); } @@ -309,9 +316,10 @@ public class SesService { // "The message must be sent from a verified email address or domain" (API_SendEmail), and the // error "could apply to the "From", "Source", "Sender", or "Return-Path" address" (developer - // guide, Email sending errors). It runs after the request's own validation so that - // probe-confirmed order is unchanged; where AWS places this check among those errors has not - // been probed. + // guide, Email sending errors). It runs after the request's own validation: a missing + // configuration set is reported ahead of an unverified sender, and an unverified sender or + // return path ahead of a missing stored template and a tenant association 403 (probe-confirmed + // on v2). Where AWS places it among the other validation errors has not been probed. private void requireVerifiedSenders(List senders, String region) { String accountId = callerAccountId(); // A blank address is not used, and neither is the null reverse-path "<>". @@ -527,6 +535,11 @@ public class SesService { private String sendRawEmail(SendEmailRequest request, EmailContent.Raw raw, boolean requireVerifiedSender) { String source = request.source(); String region = request.region(); + // The configuration set checked before a DISABLED refusal may be named by the + // X-SES-CONFIGURATION-SET header alone, so the message is read for it only on that path. + Tenant tenant = requireSendingTenant(request.tenantName(), region, null, + () -> firstNonBlank(request.configurationSetName(), + SmtpRelay.parseRawHeaders(raw.data()).configurationSet())); if (raw.data() == null || raw.data().isBlank()) { throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400); } @@ -576,6 +589,7 @@ public class SesService { if (requireVerifiedSender) { requireVerifiedSenders(rawSendingAddresses(request, raw, headers), region); } + requireTenantAssociations(tenant, effectiveSource, effectiveConfigSet, null, region); // 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. Map suppressedReasons = new LinkedHashMap<>( @@ -1134,71 +1148,47 @@ public class SesService { } /** - * The tenant send gate (Phase 4): resolves the tenant with the send-flavored not-found wording, - * refuses a tenant whose sending is DISABLED, then requires every resource the send uses to be - * associated with it. Placement is probe-confirmed: request-shape validation (a missing Content, - * an empty inline template, a missing FromEmailAddress on Simple, the bulk template-content - * checks) runs before the tenant lookup, while the recipient checks, the raw MIME-From - * derivation, and identity verification all lose to the tenant 404. The DISABLED refusal also - * beats identity verification, the association check and a raw message's missing recipients, - * but an unknown configuration set named by the request is reported before it, and so are the - * address and recipient checks of a Simple or Template send, which goes through the overload - * that takes its envelope. + * The first half of the tenant send gate, run where each send starts: resolves the + * tenant with the send-flavored not-found wording and refuses a tenant whose sending is DISABLED, + * or returns null for a send with no tenant. Placement is probe-confirmed: request-shape + * validation (a missing Content, an empty inline template, a missing FromEmailAddress on Simple, + * the bulk template-content checks) runs before the tenant lookup, while the recipient checks, + * the raw MIME-From derivation, and identity verification all lose to the tenant 404. The + * DISABLED refusal also beats identity verification, the association check and a raw message's + * missing recipients, but the configuration set the request names is looked up before it, and + * a Simple or Template send's {@code envelope} has its address and recipient checks run first. + * The association half runs at the end of the send, see {@code requireTenantAssociations}. */ - public void checkTenantSendAccess(String tenantName, String fromEmailAddress, - String configurationSetName, String templateName, - String accountId, String region) { - checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId, - region, null, configurationSetName); - } - - /** - * The send gate for SendBulkEmail, which refuses a DISABLED tenant before it looks up the - * configuration set, unlike SendEmail. A request in which no entry names a recipient skips the - * gate altogether, even for an unknown tenant: each entry is answered on its own instead - * (probe-confirmed). - */ - public void checkTenantBulkSendAccess(String tenantName, String fromEmailAddress, - String configurationSetName, String templateName, - List entries, String accountId, String region) { - if (!anyBulkRecipient(entries)) { - return; - } - checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId, - region, null, null); - } - - /** - * The send gate for a Simple or Template send, whose envelope SES validates before it refuses a - * DISABLED tenant: a malformed address and a request with no recipient are reported first - * (probe-confirmed), while a tenant that may send still meets the gate before them. - */ - public void checkTenantSendAccess(SendEmailRequest envelope, String templateName, String accountId) { - checkTenantSendAccess(envelope.tenantName(), envelope.source(), envelope.configurationSetName(), - templateName, accountId, envelope.region(), envelope, envelope.configurationSetName()); - } - - private void checkTenantSendAccess(String tenantName, String fromEmailAddress, - String configurationSetName, String templateName, - String accountId, String region, SendEmailRequest envelope, - String configurationSetBeforeRefusal) { + private Tenant requireSendingTenant(String tenantName, String region, SendEmailRequest envelope, + Supplier configurationSetBeforeRefusal) { if (tenantName == null) { + return null; + } + Tenant tenant = tenantService.tenantForSending(tenantName, region, callerAccountId()); + requireSendingEnabled(tenant, configurationSetBeforeRefusal, region, envelope); + return tenant; + } + + // The second half of the tenant send gate, and the last check of a send: AWS reports a missing + // configuration set or stored template and an unverified sender or return path ahead of the 403 + // (probe-confirmed). Every resource the send uses must be associated with the tenant: the + // sender's identity, the effective configuration set (an omitted name resolves to the sender + // identity's default, which needs the association just as an explicit one does) and the stored + // template. + private void requireTenantAssociations(Tenant tenant, String source, String effectiveConfigSet, + String templateName, String region) { + if (tenant == null) { return; } - Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId); - requireSendingEnabled(tenant, configurationSetBeforeRefusal, region, envelope); - String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + accountId + ":"; + String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + callerAccountId() + + ":"; List used = new ArrayList<>(); - if (fromEmailAddress != null && !fromEmailAddress.isBlank()) { - String identityName = sendIdentityName(fromEmailAddress, region); + if (source != null && !source.isBlank()) { + String identityName = sendIdentityName(source, region); used.add(new SesTenantService.AssociationResource( SesTenantService.RESOURCE_TYPE_IDENTITY, identityName, arnPrefix + "identity/" + identityName)); } - // The gate covers the EFFECTIVE configuration set: an omitted name resolves to the sender - // identity's default, and that one needs the association just as an explicit one does. - String effectiveConfigSet = - resolveDefaultConfigurationSet(configurationSetName, fromEmailAddress, region); if (effectiveConfigSet != null && !effectiveConfigSet.isBlank()) { used.add(new SesTenantService.AssociationResource( SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET, effectiveConfigSet, @@ -1212,41 +1202,7 @@ public class SesService { tenantService.requireResourcesAssociated(tenant, used, region); } - /** - * 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. - * {@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 and sending status - * are checked. - */ - public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress, - 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 and may send, 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()) { - requireSendingEnabled(tenantService.tenantForSending(tenantName, region, accountId), - firstNonBlank(configurationSetName, headers.configurationSet()), region, null); - return; - } - String effectiveSource = fromEmailAddress; - if (effectiveSource == null || effectiveSource.isBlank()) { - effectiveSource = headers.from().isBlank() ? null : headers.from(); - } - // The gate sees the same configuration set the send will use, so one named only by the - // X-SES-CONFIGURATION-SET header cannot slip past the tenant association check. - checkTenantSendAccess(tenantName, effectiveSource, - firstNonBlank(configurationSetName, headers.configurationSet()), null, - accountId, region); - } - - private void requireSendingEnabled(Tenant tenant, String configurationSetName, String region, + private void requireSendingEnabled(Tenant tenant, Supplier configurationSetName, String region, SendEmailRequest envelope) { if (!"DISABLED".equals(tenant.sendingStatus())) { return; @@ -1255,8 +1211,9 @@ public class SesService { SesAddressSyntax.requireEnvelope(envelope); requireRecipients(envelope); } - if (configurationSetName != null && !configurationSetName.isBlank()) { - configSetService.get(configurationSetName, region); + String configurationSet = configurationSetName.get(); + if (configurationSet != null && !configurationSet.isBlank()) { + configSetService.get(configurationSet, region); } throw new AwsException("MessageRejected", "Sending disabled for <" + tenant.tenantArn() + ">. For more information, please check the resource configuration and status.", 400); @@ -1728,12 +1685,19 @@ public class SesService { } public List sendBulkEmail(SendBulkEmailRequest request) { - EmailContent.InlineTemplate template = request.defaultContent(); if (request.source() == null || request.source().isBlank()) { throw new AwsException("InvalidParameterValue", "Source email is required.", 400); } - requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart()); + if (request.defaultContent() instanceof EmailContent.InlineTemplate inline) { + requireInlineTemplateContent(inline.subject(), inline.textPart(), inline.htmlPart()); + } requireBulkDestinationCount(sizeOf(request.entries())); + // SendBulkEmail refuses a DISABLED tenant before it looks up the configuration set, unlike + // SendEmail, and a request in which no entry names a recipient skips the gate altogether, + // even for an unknown tenant: each entry is answered on its own instead (probe-confirmed). + Tenant tenant = anyBulkRecipient(request.entries()) + ? requireSendingTenant(request.tenantName(), request.region(), null, () -> null) + : null; configSetService.validateForSending(request.configurationSetName(), request.region()); for (BulkEmailEntry entry : request.entries()) { int recipientCount = sizeOf(entry.toAddresses()) @@ -1754,10 +1718,27 @@ public class SesService { "Destination cannot be empty")) .toList(); } + // 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( + new SendingAddress(request.source(), request.sourceArn()), + new SendingAddress(request.returnPath(), request.returnPathArn())), request.region()); + EmailContent.InlineTemplate template = switch (request.defaultContent()) { + case EmailContent.Template stored -> templateService.inline(stored, request.region()); + case EmailContent.InlineTemplate inline -> inline; + }; + requireTenantAssociations(tenant, request.source(), + resolveDefaultConfigurationSet(request.configurationSetName(), request.source(), request.region()), + request.templateName(), request.region()); List results = new ArrayList<>(request.entries().size()); for (BulkEmailEntry entry : request.entries()) { try { SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses()); + // An entry with no recipient beside entries with one fails on its own (probe-confirmed + // on v1 and v2). + if (!anyBulkRecipient(List.of(entry))) { + throw new AwsException("InvalidParameterValue", "Missing required header 'To'.", 400); + } JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData()); List mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags()); List mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders()); @@ -1780,8 +1761,8 @@ public class SesService { .build(); // SesAddressLength is not applied to entries: an over-long bulk destination did not // fail the length check ahead of sender verification (probe-confirmed; the - // verified-sender case is unprobed). The bulk sender and return path are checked - // by requireBulkAddress. + // verified-sender case is unprobed). The bulk sender and return path were checked + // above, their syntax by requireBulkAddress and their verification once for the call. String messageId = sendSimpleEmail(entryRequest, rendered, validateEnvelope(entryRequest)); results.add(BulkEmailEntryResult.success(messageId)); } catch (AwsException e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java index 6d13c252e7..0a6646fc03 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java @@ -36,12 +36,18 @@ public sealed interface EmailContent { } } + /** + * The two template variants, the only content a bulk send's default content can be. + */ + sealed interface TemplateContent extends EmailContent { + } + record Template(String templateName, JsonNode templateData, List headers) - implements EmailContent { + implements TemplateContent { } record InlineTemplate(String subject, String textPart, String htmlPart, JsonNode templateData, - List headers) implements EmailContent { + List headers) implements TemplateContent { } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java index 9b1aa68146..15065a22a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java @@ -6,56 +6,70 @@ import java.util.Objects; /** * The service-level input of a bulk send, shaped like the v2 {@code SendBulkEmailRequest}: an * envelope, the default template every entry renders, and the per-destination entries. The - * controllers resolve a stored template before building it, so the default content is always - * {@link EmailContent.InlineTemplate}; its data and headers are the defaults each entry's - * replacements merge over. + * default content is a stored {@link EmailContent.Template}, which the send resolves only after its + * sender checks, or an {@link EmailContent.InlineTemplate}; its data and headers are the defaults + * each entry's replacements merge over. {@code sourceArn} and {@code returnPathArn} are the + * sending-authorization identity ARNs of the sender and the return path. */ public record SendBulkEmailRequest( String source, + String sourceArn, List replyToAddresses, String returnPath, + String returnPathArn, String configurationSetName, List defaultEmailTags, String tenantName, String region, - EmailContent.InlineTemplate defaultContent, + EmailContent.TemplateContent defaultContent, List entries) { public SendBulkEmailRequest { Objects.requireNonNull(defaultContent, "defaultContent"); } + /** + * The name of the stored template the default content names, or {@code null} for inline content. + */ + public String templateName() { + return defaultContent instanceof EmailContent.Template stored ? stored.templateName() : null; + } + public static Builder builder() { return new Builder(); } public static final class Builder { private String source; + private String sourceArn; private List replyToAddresses = List.of(); private String returnPath; + private String returnPathArn; private String configurationSetName; private List defaultEmailTags = List.of(); private String tenantName; private String region; - private EmailContent.InlineTemplate defaultContent; + private EmailContent.TemplateContent defaultContent; private List entries = List.of(); private Builder() { } public Builder source(String source) { this.source = source; return this; } + public Builder sourceArn(String sourceArn) { this.sourceArn = sourceArn; return this; } public Builder replyToAddresses(List replyToAddresses) { this.replyToAddresses = replyToAddresses; return this; } public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; } + public Builder returnPathArn(String returnPathArn) { this.returnPathArn = returnPathArn; return this; } public Builder configurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; return this; } public Builder defaultEmailTags(List defaultEmailTags) { this.defaultEmailTags = defaultEmailTags; return this; } public Builder tenantName(String tenantName) { this.tenantName = tenantName; return this; } public Builder region(String region) { this.region = region; return this; } - public Builder defaultContent(EmailContent.InlineTemplate defaultContent) { this.defaultContent = defaultContent; 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, replyToAddresses, returnPath, configurationSetName, - defaultEmailTags, tenantName, region, defaultContent, entries); + return new SendBulkEmailRequest(source, sourceArn, replyToAddresses, returnPath, returnPathArn, + configurationSetName, defaultEmailTags, tenantName, region, defaultContent, entries); } } } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SmithyValidationErrorsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SmithyValidationErrorsTest.java index 92854195a2..7cf3660f09 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/SmithyValidationErrorsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/SmithyValidationErrorsTest.java @@ -50,6 +50,15 @@ class SmithyValidationErrorsTest { void noViolations_isAProgrammingError() { assertThrows(IllegalArgumentException.class, () -> SmithyValidationErrors.message(List.of())); } + + @Test + void notNull_hasTwoForms() { + assertEquals("Value null at 'a.b' failed to satisfy constraint: Member must not be null", + SmithyValidationErrors.notNull("a.b")); + assertEquals("Value at 'a.b' failed to satisfy constraint: Member must not be null", + SmithyValidationErrors.notNullWithoutValue("a.b")); + } + @Test void lengthBoundsPreserveValuesAndIncludeEndpoints() { assertEquals("Value '' at 'name' failed to satisfy constraint: " diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java index c6ace85829..1810c8e9f1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java @@ -11,7 +11,9 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -19,6 +21,7 @@ import java.util.stream.Stream; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -32,12 +35,29 @@ class SesBulkV1IntegrationTest { private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; + // A sender of its own: an identity under example.com would outlive this class and reach the + // other SES classes that share the application. + private static final String SENDER = "bulk-v1@floci.test"; + + private static final String MISSING_DESTINATION_2 = "1 validation error detected: Value at " + + "'destinations.2.member.destination' failed to satisfy constraint: Member must not be null"; + private static final Pattern MESSAGE_ID_PATTERN = Pattern.compile("([^<]+)"); @Test @Order(1) void createTemplate() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", SENDER) + .when() + .post("/") + .then() + .statusCode(200); + given() .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) @@ -59,7 +79,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .formParam("DefaultTemplateData", "{\"team\":\"floci\"}") .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") @@ -111,7 +131,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "ghost") .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") .when() @@ -128,13 +148,15 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .when() .post("/") .then() .statusCode(400) - .body(containsString("InvalidParameterValue")); + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at 'destinations' " + + "failed to satisfy constraint: Member must not be null")); } @Test @@ -144,38 +166,37 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") .when() .post("/") .then() .statusCode(400) - .body(containsString("InvalidParameterValue")); + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value at 'template' " + + "failed to satisfy constraint: Member must not be null")); } @Test @Order(6) - void sendBulkTemplatedEmail_perEntryMissingDestination_mapsToInvalidParameterValue() { - // An entry with only ReplacementTemplateData (no recipient) reaches the per-entry send, - // which throws AwsException("InvalidParameterValue", ...). Expected per-entry - // Status string in v1 is "InvalidParameterValue", not "Failed" or "InvalidParameter". - // DefaultTemplateData supplies team so rendering succeeds before the recipient check. - String body = given() + void sendBulkTemplatedEmail_entryWithoutDestination_isAValidationError() { + // An entry with only ReplacementTemplateData has a null Destination, which the model + // validation refuses for the whole request (probe-confirmed). + given() .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .formParam("DefaultTemplateData", "{\"team\":\"floci\"}") - .formParam("Destinations.member.1.ReplacementTemplateData", "{\"name\":\"Ghost\"}") + .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") + .formParam("Destinations.member.2.ReplacementTemplateData", "{\"name\":\"Ghost\"}") .when() .post("/") .then() - .statusCode(200) - .extract().body().asString(); - - assertEquals(1L, body.split("InvalidParameterValue", -1).length - 1L, - "expected per-entry Status=InvalidParameterValue"); + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo(MISSING_DESTINATION_2)); } @Test @@ -196,7 +217,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") .when() @@ -223,7 +244,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "ghost"), 51) .when() .post("/") @@ -244,7 +265,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .formParam("DefaultTemplateData", "{\"team\":\"floci\"}") .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") @@ -268,7 +289,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .formParam("DefaultTemplateData", defaultTemplateData) .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com"); @@ -297,7 +318,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome"); for (int i = 1; i <= 51; i++) { spec = spec.formParam( @@ -319,7 +340,7 @@ class SesBulkV1IntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "bulk@example.com") + .formParam("Source", SENDER) .formParam("Template", "v1-bulk-welcome") .formParam("DefaultTemplateData", "{\"name\":\"X\",\"team\":\"floci\"}"), 50) .when() @@ -331,6 +352,133 @@ class SesBulkV1IntegrationTest { assertEquals(50L, body.split("Success", -1).length - 1L); } + @Test + @Order(14) + void sendBulkTemplatedEmail_emptyToAddresses_answersTheEntryBeforeSenderAndTemplate() { + // boto3 serializes ToAddresses=[] as a bare empty-valued key. AWS answers the entry even + // for an unverified Source and a missing template (probe-confirmed). + String body = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "SendBulkTemplatedEmail") + .formParam("Source", "bulk-v1-unverified@floci.test") + .formParam("Template", "ghost") + .formParam("DefaultTemplateData", "{}") + .formParam("Destinations.member.1.Destination.ToAddresses", "") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("InvalidParameterValue")) + .body(containsString("Destination cannot be empty")) + .body(not(containsString(""))) + .extract().body().asString(); + + assertEquals(1L, body.split("", -1).length - 1L); + } + + @Test + @Order(15) + void sendBulkTemplatedEmail_skippedIndex_isAValidationError() { + // boto3 sends nothing for Destination={}, which leaves a gap in the member indexes. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "SendBulkTemplatedEmail") + .formParam("Source", SENDER) + .formParam("Template", "v1-bulk-welcome") + .formParam("DefaultTemplateData", "{\"name\":\"X\",\"team\":\"floci\"}") + .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") + .formParam("Destinations.member.3.Destination.ToAddresses.member.1", "bob@example.com") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo(MISSING_DESTINATION_2)); + } + + @Test + @Order(16) + void sendBulkTemplatedEmail_emptyEntryBesideRecipients_failsOnlyThatEntry() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "SendBulkTemplatedEmail") + .formParam("Source", SENDER) + .formParam("Template", "v1-bulk-welcome") + .formParam("DefaultTemplateData", "{\"name\":\"X\",\"team\":\"floci\"}") + .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com") + .formParam("Destinations.member.2.Destination.ToAddresses", "") + .formParam("Destinations.member.3.Destination.ToAddresses.member.1", "bob@example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member.size()", equalTo(3)) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[0].Status", + equalTo("Success")) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[1].Status", + equalTo("InvalidParameterValue")) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[1].Error", + equalTo("Missing required header 'To'.")) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[1].MessageId.size()", + equalTo(0)) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[2].Status", + equalTo("Success")); + } + + // The model validation answers ahead of the address syntax, the template selector and the + // destination count (probed 2026-10-25). + @ParameterizedTest(name = "{0}") + @MethodSource("modelViolationParams") + @Order(17) + void sendBulkTemplatedEmail_modelValidationPrecedesOtherChecks(String label, Map params, + String message) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "SendBulkTemplatedEmail") + .formParams(params) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo(message)); + } + + static Stream modelViolationParams() { + Map withoutDestination2 = Map.of( + "Destinations.member.1.Destination.ToAddresses.member.1", "alice@example.com", + "Destinations.member.2.ReplacementTemplateData", "{}"); + Map gapAt2 = new HashMap<>(); + for (int i = 1; i <= 51; i++) { + if (i != 2) { + gapAt2.put("Destinations.member." + i + ".Destination.ToAddresses.member.1", + "user" + i + "@example.com"); + } + } + return Stream.of( + Arguments.of("malformed Source", + with(withoutDestination2, "Source", "not-an-address", "Template", "v1-bulk-welcome"), + MISSING_DESTINATION_2), + Arguments.of("no Template", with(withoutDestination2, "Source", SENDER), + "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"), + Arguments.of("51 indexes with a gap", with(gapAt2, "Source", SENDER, "Template", "v1-bulk-welcome"), + MISSING_DESTINATION_2)); + } + + private static Map with(Map params, String... namesAndValues) { + Map merged = new HashMap<>(params); + for (int i = 0; i < namesAndValues.length; i += 2) { + merged.put(namesAndValues[i], namesAndValues[i + 1]); + } + return merged; + } + private static RequestSpecification destinations(RequestSpecification spec, int count) { for (int i = 1; i <= count; i++) { spec = spec.formParam("Destinations.member." + i + ".Destination.ToAddresses.member.1", diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV2IntegrationTest.java index 2b24de7d70..beaa9d5ca0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV2IntegrationTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import java.util.List; import java.util.stream.Stream; import static io.restassured.RestAssured.given; @@ -26,6 +27,10 @@ class SesBulkV2IntegrationTest { private static final String AUTH_HEADER = "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + // Senders of their own: an identity under example.com would outlive this class and reach the + // other SES classes that share the application. + private static final List SENDERS = + List.of("bulk-v2@floci.test", "bulk-v2-second@floci.test", "bulk-v2-inline@floci.test"); private static final String DESTINATION_COUNT_MESSAGE = "You must specify at least 1 destination, and no more than 50 destinations"; @@ -33,6 +38,16 @@ class SesBulkV2IntegrationTest { @Test @Order(1) void createTemplate() { + for (String sender : SENDERS) { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{\"EmailIdentity\": \"" + sender + "\"}") + .when() + .post("/v2/email/identities") + .then() + .statusCode(200); + } given() .contentType("application/json") .header("Authorization", AUTH_HEADER) @@ -60,7 +75,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": { "TemplateName": "v2-bulk-welcome", @@ -103,7 +118,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk2@example.com", + "FromEmailAddress": "bulk-v2-second@floci.test", "DefaultContent": { "Template": { "TemplateName": "v2-bulk-welcome", @@ -156,7 +171,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "inline@example.com", + "FromEmailAddress": "bulk-v2-inline@floci.test", "DefaultContent": { "Template": { "TemplateContent": { @@ -203,7 +218,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "ghost"} }, @@ -227,7 +242,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome"} }, @@ -250,7 +265,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": {}, "BulkEmailEntries": [ {"Destination": {"ToAddresses": ["alice@example.com"]}} @@ -272,7 +287,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome"} }, @@ -295,7 +310,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": "{\\"team\\":\\"floci\\"}"} }, @@ -368,14 +383,14 @@ class SesBulkV2IntegrationTest { return Stream.of( Arguments.of("BulkEmailEntries element is null", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", %s, "BulkEmailEntries": [null] } """.formatted(validDefaultTemplate)), Arguments.of("DefaultTemplateData as invalid JSON string", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": "{not json"} }, @@ -390,21 +405,21 @@ class SesBulkV2IntegrationTest { return Stream.of( Arguments.of("BulkEmailEntries element is string", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", %s, "BulkEmailEntries": ["bad"] } """.formatted(validDefaultTemplate)), Arguments.of("Destination as string", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", %s, "BulkEmailEntries": [{"Destination": "bad"}] } """.formatted(validDefaultTemplate)), Arguments.of("DefaultTemplateData as object", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": {"team": "floci"}} }, @@ -413,7 +428,7 @@ class SesBulkV2IntegrationTest { """), Arguments.of("per-entry ReplacementTemplateData as object", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", %s, "BulkEmailEntries": [ { @@ -427,7 +442,7 @@ class SesBulkV2IntegrationTest { """.formatted(validDefaultTemplate)), Arguments.of("ReplacementEmailContent as string", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", %s, "BulkEmailEntries": [ { @@ -439,7 +454,7 @@ class SesBulkV2IntegrationTest { """.formatted(validDefaultTemplate)), Arguments.of("ReplacementEmailContent as array", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", %s, "BulkEmailEntries": [ { @@ -451,7 +466,7 @@ class SesBulkV2IntegrationTest { """.formatted(validDefaultTemplate)), Arguments.of("ReplacementTemplate as array", """ { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": "{\\"team\\":\\"floci\\"}"} }, @@ -479,7 +494,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": {"TemplateName": "v2-bulk-welcome"} }, @@ -503,7 +518,7 @@ class SesBulkV2IntegrationTest { .header("Authorization", AUTH_HEADER) .body(""" { - "FromEmailAddress": "bulk@example.com", + "FromEmailAddress": "bulk-v2@floci.test", "DefaultContent": { "Template": { "TemplateName": "v2-bulk-welcome", @@ -627,6 +642,33 @@ class SesBulkV2IntegrationTest { """.formatted(entries(51)), "Template must have at least a subject, text, or html part.")); } + // An entry with no recipient beside one with a recipient fails on its own (probed 2026-10-25). + @Test + @Order(18) + void sendBulkEmail_emptyEntryBesideRecipients_failsOnlyThatEntry() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "bulk-v2-inline@floci.test", + "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "t"}}}, + "BulkEmailEntries": [ + {"Destination": {"ToAddresses": ["alice@example.com"]}}, + {"Destination": {"ToAddresses": []}} + ] + } + """) + .when() + .post("/v2/email/outbound-bulk-emails") + .then() + .statusCode(200) + .body("BulkEmailEntryResults", hasSize(2)) + .body("BulkEmailEntryResults[0].Status", equalTo("SUCCESS")) + .body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER")) + .body("BulkEmailEntryResults[1].Error", equalTo("Missing required header 'To'.")); + } + private static String entries(int count) { StringBuilder entries = new StringBuilder(); for (int i = 1; i <= count; i++) { diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java index ef87f1cb8b..a494b40cb0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendAddressSyntaxIntegrationTest.java @@ -116,12 +116,13 @@ class SesSendAddressSyntaxIntegrationTest { @Test void v2SendBulkEmail_malformedEntryRecipient_failsOnlyThatEntry() { + verifySender(); given() .contentType("application/json") .header("Authorization", AUTH) .body(""" { - "FromEmailAddress": "sender@example.com", + "FromEmailAddress": "%2$s", "DefaultContent": {"Template": { "TemplateContent": {"Subject": "s", "Text": "b"}, "TemplateData": "{}"}}, @@ -131,7 +132,7 @@ class SesSendAddressSyntaxIntegrationTest { {"Destination": {"ToAddresses": ["%1$s"], "CcAddresses": ["やまだ@example.com"]}} ] } - """.formatted(TO)) + """.formatted(TO, VERIFIED_SENDER)) .when() .post("/v2/email/outbound-bulk-emails") .then() @@ -146,6 +147,7 @@ class SesSendAddressSyntaxIntegrationTest { @Test void v1SendBulkTemplatedEmail_malformedEntryRecipient_failsOnlyThatEntry() { + verifySender(); given() .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) @@ -162,7 +164,7 @@ class SesSendAddressSyntaxIntegrationTest { .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH) .formParam("Action", "SendBulkTemplatedEmail") - .formParam("Source", "sender@example.com") + .formParam("Source", VERIFIED_SENDER) .formParam("Template", "address-syntax-bulk") .formParam("DefaultTemplateData", "{}") .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "success@") diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java index fd20c688af..8619ff3c20 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ses; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; @@ -18,7 +19,9 @@ class SesSendNullAddressIntegrationTest { private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; - private static final String SENDER = "sender@example.com"; + // A verified sender of its own: an identity under example.com would outlive this class and + // reach the other SES classes that share the application. + private static final String SENDER = "null-address-sender@floci.test"; private static final String TO = "success@simulator.amazonses.com"; private static final String SIMPLE = "{\"Simple\": {\"Subject\": {\"Data\": \"s\"}, \"Body\": {\"Text\": {\"Data\": \"b\"}}}}"; @@ -50,6 +53,19 @@ class SesSendNullAddressIntegrationTest { return "{\"Destination\": " + destination + "}"; } + @BeforeEach + void verifySender() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", SENDER) + .when() + .post("/") + .then() + .statusCode(200); + } + @Test void sendEmail_nullToAddress_isAnInvalidAddress() { send("{\"FromEmailAddress\": \"" + SENDER + "\", \"Destination\": {\"ToAddresses\": [null]}, " diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendTemplateLookupOrderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendTemplateLookupOrderIntegrationTest.java new file mode 100644 index 0000000000..e7f820a40b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendTemplateLookupOrderIntegrationTest.java @@ -0,0 +1,265 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +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). + */ +@QuarkusTest +class SesSendTemplateLookupOrderIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String AUTH_V1 = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; + private static final String UNVERIFIED = "sender@unverified-template-order.floci.test"; + private static final String VERIFIED = "sender@template-order.floci.test"; + private static final String TO = "success@simulator.amazonses.com"; + private static final String GHOST_CONFIG_SET = "template-order-ghost-config-set"; + private static final String GHOST_TEMPLATE = + "{\"Template\": {\"TemplateName\": \"template-order-ghost\", \"TemplateData\": \"{}\"}}"; + private static final String INLINE_TEMPLATE = + "{\"Template\": {\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}, \"TemplateData\": \"{}\"}}"; + private static final String VALID_ENTRY = "{\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}}"; + 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"; + + // Not @BeforeAll: the Quarkus test port is only bound once the first test starts. + @BeforeEach + void verifySender() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_V1) + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", VERIFIED) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static ValidatableResponse post(String path, String body) { + return given() + .contentType("application/json") + .header("Authorization", AUTH) + .body(body) + .when() + .post(path) + .then(); + } + + private static ValidatableResponse bulk(String sender, String content, String members, String entries) { + return post("/v2/email/outbound-bulk-emails", "{\"FromEmailAddress\": \"" + sender + "\", " + members + + "\"DefaultContent\": " + content + ", \"BulkEmailEntries\": [" + entries + "]}"); + } + + private static ValidatableResponse send(String sender, String members) { + return post("/v2/email/outbound-emails", "{\"FromEmailAddress\": \"" + sender + "\", " + members + + "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"Content\": " + GHOST_TEMPLATE + "}"); + } + + private static ValidatableResponse templated(String source, String... params) { + return v1(given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_V1) + .formParam("Action", "SendTemplatedEmail") + .formParam("Source", source) + .formParam("Destination.ToAddresses.member.1", TO) + .formParam("Template", V1_GHOST_TEMPLATE) + .formParam("TemplateData", "{}"), params); + } + + private static ValidatableResponse bulkTemplated(String source, int destinations, String... params) { + RequestSpecification spec = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_V1) + .formParam("Action", "SendBulkTemplatedEmail") + .formParam("Source", source) + .formParam("Template", V1_GHOST_TEMPLATE) + .formParam("DefaultTemplateData", "{}"); + for (int i = 1; i <= destinations; i++) { + spec = spec.formParam("Destinations.member." + i + ".Destination.ToAddresses.member.1", TO); + } + return v1(spec, params); + } + + private static ValidatableResponse v1(RequestSpecification spec, String... params) { + for (int i = 0; i < params.length; i += 2) { + spec = spec.formParam(params[i], params[i + 1]); + } + return spec.when().post("/").then(); + } + + private static void assertV1Error(ValidatableResponse response, String code, String message) { + response + .statusCode(400) + .body(containsString("" + code + "")) + .body(containsString("" + message + "")); + } + + private static void assertNotVerified(ValidatableResponse response, String unverified) { + response + .statusCode(400) + .body("__type", equalTo("MessageRejected")) + .body("message", equalTo(NOT_VERIFIED_MESSAGE + unverified)); + } + + private static void assertConfigSetNotFound(ValidatableResponse response) { + response + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("Configuration set <" + GHOST_CONFIG_SET + "> does not exist.")); + } + + private static void assertTemplateNotFound(ValidatableResponse response) { + response + .statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("Template template-order-ghost does not exist.")); + } + + @Test + void sendBulkEmail_unverifiedSenderPrecedesUnknownTemplate() { + assertNotVerified(bulk(UNVERIFIED, GHOST_TEMPLATE, "", VALID_ENTRY), UNVERIFIED); + } + + @Test + void sendBulkEmail_unverifiedSenderPrecedesUnknownTemplateArn() { + assertNotVerified(bulk(UNVERIFIED, "{\"Template\": {\"TemplateArn\": " + + "\"arn:aws:ses:us-east-1:000000000000:template/template-order-ghost\", \"TemplateData\": \"{}\"}}", + "", VALID_ENTRY), UNVERIFIED); + } + + @Test + void sendBulkEmail_unknownConfigurationSetPrecedesUnverifiedSender() { + assertConfigSetNotFound(bulk(UNVERIFIED, INLINE_TEMPLATE, + "\"ConfigurationSetName\": \"" + GHOST_CONFIG_SET + "\", ", VALID_ENTRY)); + } + + @Test + void sendBulkEmail_verifiedSender_unknownTemplate() { + assertTemplateNotFound(bulk(VERIFIED, GHOST_TEMPLATE, "", VALID_ENTRY)); + } + + @Test + void sendBulkEmail_unknownConfigurationSetPrecedesUnknownTemplate() { + assertConfigSetNotFound(bulk(VERIFIED, GHOST_TEMPLATE, + "\"ConfigurationSetName\": \"" + GHOST_CONFIG_SET + "\", ", VALID_ENTRY)); + } + + @Test + void sendBulkEmail_unverifiedFeedbackForwardingAddressPrecedesUnknownTemplate() { + assertNotVerified(bulk(VERIFIED, GHOST_TEMPLATE, + "\"FeedbackForwardingEmailAddress\": \"" + UNVERIFIED + "\", ", VALID_ENTRY), UNVERIFIED); + } + + @Test + void sendBulkEmail_unknownTemplatePrecedesMalformedEntryAndReplyTo() { + assertTemplateNotFound(bulk(VERIFIED, GHOST_TEMPLATE, "", + "{\"Destination\": {\"ToAddresses\": [\"bad\"]}}")); + assertTemplateNotFound(bulk(VERIFIED, GHOST_TEMPLATE, "\"ReplyToAddresses\": [\"bad\"], ", VALID_ENTRY)); + } + + @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")); + } + } + + @Test + void sendEmail_unverifiedSenderPrecedesUnknownTemplate() { + assertNotVerified(send(UNVERIFIED, ""), UNVERIFIED); + } + + @Test + void sendEmail_unknownConfigurationSetPrecedesUnverifiedSender() { + assertConfigSetNotFound(send(UNVERIFIED, "\"ConfigurationSetName\": \"" + GHOST_CONFIG_SET + "\", ")); + } + + @Test + void sendEmail_unverifiedFeedbackForwardingAddressPrecedesUnknownTemplate() { + assertNotVerified(send(VERIFIED, "\"FeedbackForwardingEmailAddress\": \"" + UNVERIFIED + "\", "), + UNVERIFIED); + } + + @Test + void sendEmail_verifiedSender_unknownTemplate() { + assertTemplateNotFound(send(VERIFIED, "")); + } + + @Test + void sendTemplatedEmail_unverifiedSourcePrecedesUnknownTemplate() { + assertV1Error(templated(UNVERIFIED), "MessageRejected", NOT_VERIFIED_MESSAGE + UNVERIFIED); + } + + @Test + void sendTemplatedEmail_unverifiedReturnPathPrecedesUnknownTemplate() { + assertV1Error(templated(VERIFIED, "ReturnPath", UNVERIFIED), "MessageRejected", + NOT_VERIFIED_MESSAGE + UNVERIFIED); + } + + @Test + void sendTemplatedEmail_unknownConfigurationSetPrecedesUnverifiedSource() { + assertV1Error(templated(UNVERIFIED, "ConfigurationSetName", GHOST_CONFIG_SET), + "ConfigurationSetDoesNotExist", "Configuration set <" + GHOST_CONFIG_SET + "> does not exist."); + } + + @Test + void sendTemplatedEmail_verifiedSource_unknownTemplate() { + assertV1Error(templated(VERIFIED), "TemplateDoesNotExist", + "Template " + V1_GHOST_TEMPLATE + " does not exist."); + } + + @Test + void sendBulkTemplatedEmail_unverifiedSourcePrecedesUnknownTemplate() { + assertV1Error(bulkTemplated(UNVERIFIED, 1), "MessageRejected", NOT_VERIFIED_MESSAGE + UNVERIFIED); + } + + @Test + void sendBulkTemplatedEmail_unverifiedReturnPathPrecedesUnknownTemplate() { + assertV1Error(bulkTemplated(VERIFIED, 1, "ReturnPath", UNVERIFIED), "MessageRejected", + NOT_VERIFIED_MESSAGE + UNVERIFIED); + } + + @Test + void sendBulkTemplatedEmail_unknownConfigurationSetPrecedesUnverifiedSource() { + assertV1Error(bulkTemplated(UNVERIFIED, 1, "ConfigurationSetName", GHOST_CONFIG_SET), + "ConfigurationSetDoesNotExist", "Configuration set <" + GHOST_CONFIG_SET + "> does not exist."); + } + + @Test + void sendBulkTemplatedEmail_verifiedSource_unknownTemplate() { + assertV1Error(bulkTemplated(VERIFIED, 1), "TemplateDoesNotExist", + "Template " + V1_GHOST_TEMPLATE + " does not exist."); + } + + @Test + void sendBulkTemplatedEmail_destinationCountPrecedesUnverifiedSource() { + assertV1Error(bulkTemplated(UNVERIFIED, 51), "InvalidParameterValue", + "You must specify at least 1 destination, and no more than 50 destinations"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendVerifiedSenderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendVerifiedSenderIntegrationTest.java index e2480339e9..eebe88fb68 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendVerifiedSenderIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendVerifiedSenderIntegrationTest.java @@ -557,4 +557,123 @@ class SesSendVerifiedSenderIntegrationTest { """.formatted(OWNER_IDENTITY_ARN, rawMessage(OWNER_ADDRESS, "X-SES-SOURCE-ARN: " + DELEGATE_IDENTITY_ARN, "X-SES-FROM-ARN: " + DELEGATE_IDENTITY_ARN)))); } + + private static RequestSpecification sendBulkTemplatedEmail(String authorization, String source) { + return query(authorization, "SendBulkTemplatedEmail") + .formParam("Source", source) + .formParam("Template", TEMPLATE) + .formParam("DefaultTemplateData", "{}") + .formParam("Destinations.member.1.Destination.ToAddresses.member.1", "to@example.com"); + } + + private static String bulkBody(String from, String extraMembers, String entries) { + return """ + { + "FromEmailAddress": "%s", + %s + "DefaultContent": {"Template": {"TemplateContent": {"Subject": "s", "Text": "b"}}}, + "BulkEmailEntries": %s + } + """.formatted(from, extraMembers, entries); + } + + private static String bulkBody(String from) { + return bulkBody(from, "", "[{\"Destination\": {\"ToAddresses\": [\"to@example.com\"]}}]"); + } + + private static void assertBulkMessageRejectedV2(RequestSpecification request, String unverified) { + request + .when() + .post("/v2/email/outbound-bulk-emails") + .then() + .statusCode(400) + .body("__type", equalTo("MessageRejected")) + .body("message", equalTo(NOT_VERIFIED_MESSAGE + unverified)); + } + + @Test + void v2SendBulkEmail_unverifiedFrom_rejectsTheWholeCall() { + assertBulkMessageRejectedV2(v2Request(AUTH_V2, bulkBody(UNVERIFIED)), UNVERIFIED); + + assertNothingCapturedFrom(UNVERIFIED); + } + + @Test + void v2SendBulkEmail_unverifiedFeedbackForwardingAddress_rejectsTheWholeCall() { + String source = "bulk-rp-" + VERIFIED; + String feedback = "bulk-bounces@unverified-sender.floci.test"; + verifyEmailIdentity(source); + + assertBulkMessageRejectedV2(v2Request(AUTH_V2, bulkBody(source, + "\"FeedbackForwardingEmailAddress\": \"" + feedback + "\",", + "[{\"Destination\": {\"ToAddresses\": [\"to@example.com\"]}}]")), feedback); + + assertNothingCapturedFrom(source); + } + + @Test + void v2SendBulkEmail_noEntryHasARecipient_senderIsNotChecked() { + // AWS fails each entry on its missing destination and never reaches the sender check. + v2Request(AUTH_V2, bulkBody(UNVERIFIED, "", "[{\"Destination\": {}}]")) + .when() + .post("/v2/email/outbound-bulk-emails") + .then() + .statusCode(200) + .body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER")); + } + + @Test + void v2SendBulkEmail_verifiedFrom_succeeds() { + String source = "bulk-" + VERIFIED; + verifyEmailIdentity(source); + + v2Request(AUTH_V2, bulkBody(source)) + .when() + .post("/v2/email/outbound-bulk-emails") + .then() + .statusCode(200) + .body("BulkEmailEntryResults[0].Status", equalTo("SUCCESS")); + } + + @Test + void v2SendBulkEmail_fromAndFeedbackForwardingIdentityArnsOfAnotherAccount_succeeds() { + verifyOwnerAddress(); + + v2Request(DELEGATE_AUTH_V2, bulkBody(OWNER_ADDRESS, + "\"FromEmailAddressIdentityArn\": \"" + OWNER_IDENTITY_ARN + "\"," + + "\"FeedbackForwardingEmailAddress\": \"" + OWNER_ADDRESS + "\"," + + "\"FeedbackForwardingEmailAddressIdentityArn\": \"" + OWNER_IDENTITY_ARN + "\",", + "[{\"Destination\": {\"ToAddresses\": [\"to@example.com\"]}}]")) + .when() + .post("/v2/email/outbound-bulk-emails") + .then() + .statusCode(200) + .body("BulkEmailEntryResults[0].Status", equalTo("SUCCESS")); + } + + @Test + void v1SendBulkTemplatedEmail_unverifiedSource_returnsMessageRejected() { + createTemplate(AUTH_V1); + + assertMessageRejected(sendBulkTemplatedEmail(AUTH_V1, UNVERIFIED), UNVERIFIED); + + assertNothingCapturedFrom(UNVERIFIED); + } + + @Test + void v1SendBulkTemplatedEmail_sourceAndReturnPathArnsOfAnotherAccount_succeeds() { + verifyOwnerAddress(); + createTemplate(DELEGATE_AUTH_V1); + + sendBulkTemplatedEmail(DELEGATE_AUTH_V1, OWNER_ADDRESS) + .formParam("SourceArn", OWNER_IDENTITY_ARN) + .formParam("ReturnPath", OWNER_ADDRESS) + .formParam("ReturnPathArn", OWNER_IDENTITY_ARN) + .when() + .post("/") + .then() + .statusCode(200) + .body("SendBulkTemplatedEmailResponse.SendBulkTemplatedEmailResult.Status.member[0].Status", + equalTo("Success")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendOrderV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendOrderV2IntegrationTest.java new file mode 100644 index 0000000000..e435a7eff7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendOrderV2IntegrationTest.java @@ -0,0 +1,184 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.MethodOrderer; +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; + +/** + * Where the tenant association 403 sits among the other errors of a tenant send. It is the last + * check: AWS reports an unverified sender or return path, a missing configuration set and a missing + * stored template first (probe-confirmed with an ENABLED tenant, on SendEmail Simple, Template and + * Raw, and on SendBulkEmail). + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesTenantSendOrderV2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String TENANT = "floci-order-tenant"; + private static final String DOMAIN = "floci-order.example.com"; + private static final String FROM = "sender@" + DOMAIN; + private static final String UNVERIFIED = "sender@floci-order-unverified.example.com"; + private static final String CONFIG_SET = "floci-order-cs"; + private static final String TEMPLATE = "floci-order-tpl"; + private static final String ARN_PREFIX = "arn:aws:ses:us-east-1:000000000000:"; + private static final String NOT_VERIFIED = + "Email address is not verified. The following identities failed the check in region US-EAST-1: "; + private static final String DESTINATION = + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]},"; + private static final String SIMPLE = + "\"Content\":{\"Simple\":{\"Subject\":{\"Data\":\"s\"},\"Body\":{\"Text\":{\"Data\":\"t\"}}}}"; + + private static RequestSpecification v2() { + return given().contentType("application/json").header("Authorization", AUTH); + } + + private static String member(String name, String value) { + return "\"" + name + "\":\"" + value + "\","; + } + + private static ValidatableResponse send(String members, String content) { + return v2().body("{" + member("TenantName", TENANT) + DESTINATION + members + content + "}") + .when().post("/v2/email/outbound-emails").then(); + } + + private static ValidatableResponse bulk(String members) { + return v2().body("{" + member("TenantName", TENANT) + members + + "\"DefaultContent\":{\"Template\":{\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}}}," + + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":" + + "[\"success@simulator.amazonses.com\"]}}]}") + .when().post("/v2/email/outbound-bulk-emails").then(); + } + + private static String raw(String from) { + return raw(from, ""); + } + + private static String raw(String from, String extraHeaders) { + String mime = "From: " + from + "\r\nTo: success@simulator.amazonses.com\r\n" + extraHeaders + + "Subject: s\r\n\r\nt"; + return "\"Content\":{\"Raw\":{\"Data\":\"" + + Base64.getEncoder().encodeToString(mime.getBytes(StandardCharsets.UTF_8)) + "\"}}"; + } + + private static String storedTemplate(String name) { + return "\"Content\":{\"Template\":{\"TemplateName\":\"" + name + "\",\"TemplateData\":\"{}\"}}"; + } + + private static void assertNotVerified(ValidatableResponse response, String address) { + response.statusCode(400) + .body("__type", equalTo("MessageRejected")) + .body("message", equalTo(NOT_VERIFIED + address)); + } + + private static void assertNotAssociated(ValidatableResponse response, String resource) { + response.statusCode(403) + .body("__type", equalTo("AccessDeniedException")) + .body("message", equalTo("Tenant not associated with resources [" + ARN_PREFIX + resource + "].")); + } + + @Test + @Order(1) + void setup_tenantAndResources() { + v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants").then().statusCode(200); + SesDomainIdentityTestHelper.createVerified(DOMAIN, AUTH); + v2().body("{\"ConfigurationSetName\":\"" + CONFIG_SET + "\"}") + .when().post("/v2/email/configuration-sets").then().statusCode(200); + v2().body("{\"TemplateName\":\"" + TEMPLATE + "\",\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}}") + .when().post("/v2/email/templates").then().statusCode(200); + } + + @Test + @Order(2) + void unverifiedSender_isReportedBeforeTheUnassociatedIdentity() { + assertNotVerified(send(member("FromEmailAddress", UNVERIFIED), SIMPLE), UNVERIFIED); + assertNotVerified(send(member("FromEmailAddress", UNVERIFIED), raw(UNVERIFIED)), UNVERIFIED); + assertNotVerified(send("", raw(UNVERIFIED)), UNVERIFIED); + assertNotVerified(bulk(member("FromEmailAddress", UNVERIFIED)), UNVERIFIED); + } + + @Test + @Order(3) + void unverifiedReturnPath_isReportedBeforeTheUnassociatedIdentity() { + String members = member("FromEmailAddress", FROM) + member("FeedbackForwardingEmailAddress", UNVERIFIED); + + assertNotVerified(send(members, SIMPLE), UNVERIFIED); + assertNotVerified(bulk(members), UNVERIFIED); + } + + @Test + @Order(4) + void missingConfigurationSet_isReportedBeforeTheAssociationAndTheSender() { + String ghost = member("ConfigurationSetName", "floci-order-ghost-cs"); + + send(member("FromEmailAddress", FROM) + ghost, SIMPLE).statusCode(404) + .body("message", equalTo("Configuration set does not exist.")); + send(member("FromEmailAddress", UNVERIFIED) + ghost, SIMPLE).statusCode(404) + .body("message", equalTo("Configuration set does not exist.")); + bulk(member("FromEmailAddress", FROM) + ghost).statusCode(404) + .body("message", equalTo("Configuration set does not exist.")); + } + + @Test + @Order(5) + void missingStoredTemplate_isReportedBeforeTheAssociation() { + send(member("FromEmailAddress", FROM), storedTemplate("floci-order-ghost-tpl")).statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + @Test + @Order(6) + void verifiedSender_unassociatedIdentity_is403() { + assertNotAssociated(send(member("FromEmailAddress", FROM), SIMPLE), "identity/" + DOMAIN); + assertNotAssociated(send(member("FromEmailAddress", FROM), raw(FROM)), "identity/" + DOMAIN); + assertNotAssociated(bulk(member("FromEmailAddress", FROM)), "identity/" + DOMAIN); + } + + @Test + @Order(7) + void associatedIdentity_unassociatedConfigurationSetOrTemplate_is403UnlessTheReturnPathIsUnverified() { + v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + ARN_PREFIX + "identity/" + DOMAIN + "\"}") + .when().post("/v2/email/tenants/resources").then().statusCode(200); + String withConfigSet = member("FromEmailAddress", FROM) + member("ConfigurationSetName", CONFIG_SET); + + assertNotAssociated(send(withConfigSet, SIMPLE), "configuration-set/" + CONFIG_SET); + assertNotAssociated(bulk(withConfigSet), "configuration-set/" + CONFIG_SET); + assertNotAssociated(send(member("FromEmailAddress", FROM), storedTemplate(TEMPLATE)), "template/" + TEMPLATE); + send(member("FromEmailAddress", FROM), storedTemplate("floci-order-ghost-tpl")).statusCode(404); + + String unverifiedReturnPath = withConfigSet + member("FeedbackForwardingEmailAddress", UNVERIFIED); + assertNotVerified(send(unverifiedReturnPath, SIMPLE), UNVERIFIED); + assertNotVerified(bulk(unverifiedReturnPath), UNVERIFIED); + } + + // The configuration set a raw message names only in its X-SES-CONFIGURATION-SET header is the one + // the send uses, so it must be associated too. + @Test + @Order(8) + void associatedIdentity_rawHeaderConfigurationSet_is403() { + assertNotAssociated(send(member("FromEmailAddress", FROM), + raw(FROM, "X-SES-CONFIGURATION-SET: " + CONFIG_SET + "\r\n")), "configuration-set/" + CONFIG_SET); + } + + @Test + @Order(9) + void cleanup() { + v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants/delete").then().statusCode(200); + v2().when().delete("/v2/email/templates/" + TEMPLATE).then().statusCode(200); + v2().when().delete("/v2/email/configuration-sets/" + CONFIG_SET).then().statusCode(200); + v2().when().delete("/v2/email/identities/" + DOMAIN).then().statusCode(200); + } +} 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 8bde0e569b..54311defcd 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 @@ -185,8 +185,8 @@ class SesTenantSendV2IntegrationTest { @Test @Order(8) void rawSend_gatesTheMimeDerivedSender() { - v2().body("{\"EmailIdentity\":\"floci-raw.example.com\"}") - .when().post("/v2/email/identities").then().statusCode(200); + // Verified, so the 403 is what stops the send: an unverified sender is reported first. + SesDomainIdentityTestHelper.createVerified("floci-raw.example.com", AUTH); String mime = "From: probe@floci-raw.example.com\r\nTo: success@simulator.amazonses.com\r\n" + "Subject: s\r\n\r\nbody"; String data = java.util.Base64.getEncoder().encodeToString(mime.getBytes(java.nio.charset.StandardCharsets.UTF_8));