From b0fe8311a01a609f73cc0508de512c075d4daaaf Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Mon, 31 Aug 2026 22:35:40 +0900 Subject: [PATCH] feat(ses): support v2 tenant-scoped sending with association gate (#2815) * feat(ses): support v2 tenant-scoped sending with association gate * fix(ses): guard tenantForSending against a null TenantName and pin the raw-test charset * fix(ses): validate an inline bulk template before the tenant gate --- .../java/com/floci/test/SesTenantTest.java | 32 +- docs/services/ses.md | 4 +- .../floci/services/ses/SesController.java | 25 ++ .../floci/services/ses/SesService.java | 113 ++++++- .../floci/services/ses/SesTenantService.java | 37 +++ .../ses/SesTenantSendV2IntegrationTest.java | 277 ++++++++++++++++++ .../services/ses/SesTenantServiceTest.java | 39 +++ 7 files changed, 511 insertions(+), 16 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantTest.java index 9a5098bb8f..98da12823e 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantTest.java @@ -31,6 +31,8 @@ import software.amazon.awssdk.services.sesv2.model.ListTenantResourcesResponse; import software.amazon.awssdk.services.sesv2.model.ListTenantsRequest; import software.amazon.awssdk.services.sesv2.model.ListTenantsResponse; import software.amazon.awssdk.services.sesv2.model.NotFoundException; +import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; +import software.amazon.awssdk.services.sesv2.model.SesV2Exception; import software.amazon.awssdk.services.sesv2.model.SuppressionListReason; import software.amazon.awssdk.services.sesv2.model.Tag; @@ -326,6 +328,34 @@ class SesTenantTest { @Test @Order(22) + void tenantSend_gatesOnAssociations() { + // The domain identity is still associated (order 6); the config set's association was + // removed in order 14, so using it in a tenant send must be refused with the 403. + SendEmailRequest.Builder send = SendEmailRequest.builder() + .fromEmailAddress("probe@" + IDENTITY) + .destination(d -> d.toAddresses("success@simulator.amazonses.com")) + .content(c -> c.simple(s -> s + .subject(sub -> sub.data("s")) + .body(b -> b.text(t -> t.data("t"))))); + + assertThat(sesV2.sendEmail(send.tenantName(TENANT).build()).messageId()).isNotNull(); + + assertThatThrownBy(() -> sesV2.sendEmail(send.tenantName("compat-send-ghost").build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Tenant compat-send-ghost for AwsAccountId") + .hasMessageContaining("not found."); + + assertThatThrownBy(() -> sesV2.sendEmail( + send.tenantName(TENANT).configurationSetName(CONFIG_SET).build())) + .isInstanceOfSatisfying(SesV2Exception.class, e -> { + assertThat(e.statusCode()).isEqualTo(403); + assertThat(e.getMessage()).contains("Tenant not associated with resources ["); + assertThat(e.getMessage()).contains("configuration-set/" + CONFIG_SET); + }); + } + + @Test + @Order(23) void deleteTenant_cascadesAssociationsAndSuppressionEntries_thenGetIsNotFound() { sesV2.putSuppressedDestination(r -> r.emailAddress(TENANT_ADDR) .reason(SuppressionListReason.COMPLAINT).tenantName(TENANT)); @@ -340,7 +370,7 @@ class SesTenantTest { } @Test - @Order(23) + @Order(24) void deleteTenant_missing_throwsNotFound() { assertThatThrownBy(() -> sesV2.deleteTenant(DeleteTenantRequest.builder() .tenantName("compat-tenant-does-not-exist").build())) diff --git a/docs/services/ses.md b/docs/services/ses.md index 53a2314212..4475fe558b 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -291,7 +291,9 @@ Account provisioning details are stored per region. `PutAccountDetails` sets `Ma Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `TenantName` (1–64 chars, `[A-Za-z0-9_-]`) and accepts optional `Tags`; it returns the tenant with a generated `TenantId` (`tn-` + 30 hex), a `TenantArn` (`arn:aws:ses:::tenant//`), a `CreatedTimestamp`, and `SendingStatus` `ENABLED`. The operations use RPC-style POST subpaths (`/tenants/get`, `/tenants/list`, `/tenants/delete`); `ListTenants` returns the `TenantInfo` subset (no `Tags`/`SendingStatus`) and currently returns every tenant in a single page — `PageSize`/`NextToken` pagination is not yet implemented. A duplicate name is `AlreadyExistsException`; an unknown tenant on get/delete is `NotFoundException`. -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. The list operations return a single page (no `PageSize`/`NextToken` pagination yet, like `ListTenants`); tenant-scoped sending is not yet implemented. +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. The list operations return a single page (no `PageSize`/`NextToken` pagination yet, like `ListTenants`). + +A `TenantName` on `SendEmail`/`SendBulkEmail` makes the send tenant-scoped: the resources it uses — 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 — must all be associated with the tenant, or 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. Not emulated: the `SendingStatus` gate (nothing can move the status off `ENABLED`) and 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/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java index 55fceafb2a..a698544dae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -504,6 +504,7 @@ public class SesController { List replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses")); List allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses); String configurationSetName = request.path("ConfigurationSetName").asText(null); + String tenantName = stringMemberOrAbsent(request, "TenantName"); List emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags"); ListManagementOptions listManagement = parseListManagementOptions(request.path("ListManagementOptions")); @@ -521,6 +522,8 @@ public class SesController { throw new AwsException("BadRequestException", "At least one destination address is required.", 400); } + sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData, + configurationSetName, regionResolver.getAccountId(), region); messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData, configurationSetName, emailTags, listManagement, region); } else if (content.has("Simple")) { @@ -534,6 +537,8 @@ public class SesController { String bodyHtml = simple.path("Body").path("Html").path("Data").asText(null); List additionalHeaders = parseHeadersArray(simple.path("Headers"), "content.simple.headers"); + sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, + null, regionResolver.getAccountId(), region); messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses, bccAddresses, replyToAddresses, subject, bodyText, bodyHtml, configurationSetName, emailTags, additionalHeaders, listManagement, region); @@ -564,6 +569,8 @@ public class SesController { String resolvedName = hasName ? templateName : SesService.templateNameFromArn(templateArn); + sesService.checkTenantSendAccess(tenantName, fromEmailAddress, + configurationSetName, resolvedName, regionResolver.getAccountId(), region); messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses, bccAddresses, replyToAddresses, resolvedName, templateData, configurationSetName, emailTags, additionalHeaders, listManagement, region); @@ -572,6 +579,12 @@ public class SesController { String subject = inline.path("Subject").asText(null); String text = inline.path("Text").asText(null); String html = inline.path("Html").asText(null); + // An empty inline template is reported before the tenant lookup on AWS; the + // inline content is not a stored template resource, so only the identity and + // configuration set pass through the gate. + SesService.requireInlineTemplateContent(subject, text, html); + sesService.checkTenantSendAccess(tenantName, fromEmailAddress, + configurationSetName, null, regionResolver.getAccountId(), region); messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses, bccAddresses, replyToAddresses, subject, text, html, templateData, @@ -614,6 +627,7 @@ public class SesController { } List replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses")); String configurationSetName = request.path("ConfigurationSetName").asText(null); + String tenantName = stringMemberOrAbsent(request, "TenantName"); JsonNode template = request.path("DefaultContent").path("Template"); if (template.isMissingNode() || template.isNull()) { @@ -639,15 +653,21 @@ public class SesController { String subject; String text; String html; + // Inline template content is not a stored template resource, so it stays out of the + // tenant gate below. + String gateTemplateName = 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. + SesService.requireInlineTemplateContent(subject, text, html); } else { String resolvedName = hasName ? templateName : SesService.templateNameFromArn(templateArn); + gateTemplateName = resolvedName; EmailTemplate stored = sesService.getTemplate(resolvedName, region); subject = stored.getSubject(); text = stored.getTextPart(); @@ -686,6 +706,11 @@ public class SesController { 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.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, + gateTemplateName, regionResolver.getAccountId(), region); + List results = sesService.sendBulkTemplatedEmail(fromEmailAddress, replyToAddresses, subject, text, html, defaultTemplateData, entries, configurationSetName, 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 94fbaa8460..0b153d845c 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 @@ -1728,6 +1728,88 @@ public class SesService { return tenantService.listResourceTenants(ref, region); } + /** + * The tenant send gate (Phase 4): resolves the tenant with the send-flavored not-found wording, + * then requires every resource the send uses to be associated with it. The tenant's + * SendingStatus is not checked — no API can move it off ENABLED, so the DISABLED gate is not + * emulated. 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. + */ + public void checkTenantSendAccess(String tenantName, String fromEmailAddress, + String configurationSetName, String templateName, + String accountId, String region) { + if (tenantName == null) { + return; + } + Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId); + String arnPrefix = "arn:aws:ses:" + region + ":" + accountId + ":"; + List used = new ArrayList<>(); + if (fromEmailAddress != null && !fromEmailAddress.isBlank()) { + String identityName = sendIdentityName(fromEmailAddress, 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, + arnPrefix + "configuration-set/" + effectiveConfigSet)); + } + if (templateName != null && !templateName.isBlank()) { + used.add(new SesTenantService.AssociationResource( + SesTenantService.RESOURCE_TYPE_TEMPLATE, templateName, + arnPrefix + "template/" + templateName)); + } + 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. + */ + public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress, + String rawMessage, String configurationSetName, + String accountId, String region) { + if (tenantName == null) { + return; + } + String effectiveSource = fromEmailAddress; + if (effectiveSource == null || effectiveSource.isBlank()) { + SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage); + effectiveSource = headers != null && !headers.from().isBlank() ? headers.from() : null; + } + checkTenantSendAccess(tenantName, effectiveSource, configurationSetName, null, + accountId, region); + } + + // The gate names the identity the way AWS did in the probed error: the exact address identity + // when one exists, otherwise the domain identity the address falls under. The sender may carry + // display-name syntax ("Name "), so the bare address is extracted first. + private String sendIdentityName(String fromEmailAddress, String region) { + String email = extractEmailAddress(fromEmailAddress); + if (email.isBlank()) { + return fromEmailAddress.trim(); + } + if (identityStore.get(identityKey(region, email)).isPresent()) { + return email; + } + int at = email.lastIndexOf('@'); + if (at >= 0) { + String domain = email.substring(at + 1); + if (identityStore.get(identityKey(region, domain)).isPresent()) { + return domain; + } + } + return email; + } + // The association APIs 404 with a per-type message when the referenced resource is missing; the // trailing colon on the configuration-set variant is AWS's own. private void requireTenantResourceExists(SesTenantService.AssociationResource ref, String region) { @@ -2812,13 +2894,12 @@ public class SesService { return "===_floci_" + HexFormat.of().formatHex(bytes) + "_==="; } - public String sendInlineTemplatedEmail(String source, List toAddresses, List ccAddresses, - List bccAddresses, List replyToAddresses, - String subject, String textPart, String htmlPart, - JsonNode templateData, - String configurationSetName, List emailTags, - List additionalHeaders, - ListManagementOptions listManagement, String region) { + /** + * Also called by the controller ahead of the tenant send gate: AWS reports an empty inline + * template before it looks the tenant up (probe-confirmed), so the check must not stay behind + * the gate for tenant sends. + */ + static void requireInlineTemplateContent(String subject, String textPart, String htmlPart) { boolean hasSubject = subject != null && !subject.isBlank(); boolean hasText = textPart != null && !textPart.isBlank(); boolean hasHtml = htmlPart != null && !htmlPart.isBlank(); @@ -2826,6 +2907,16 @@ public class SesService { throw new AwsException("InvalidTemplate", "Template must have at least a subject, text, or html part.", 400); } + } + + public String sendInlineTemplatedEmail(String source, List toAddresses, List ccAddresses, + List bccAddresses, List replyToAddresses, + String subject, String textPart, String htmlPart, + JsonNode templateData, + String configurationSetName, List emailTags, + List additionalHeaders, + ListManagementOptions listManagement, String region) { + requireInlineTemplateContent(subject, textPart, htmlPart); return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, applyTemplateData(subject, templateData), applyTemplateData(textPart, templateData), @@ -2845,13 +2936,7 @@ public class SesService { if (source == null || source.isBlank()) { throw new AwsException("InvalidParameterValue", "Source email is required.", 400); } - boolean hasSubject = subject != null && !subject.isBlank(); - boolean hasText = textPart != null && !textPart.isBlank(); - boolean hasHtml = htmlPart != null && !htmlPart.isBlank(); - if (!hasSubject && !hasText && !hasHtml) { - throw new AwsException("InvalidTemplate", - "Template must have at least a subject, text, or html part.", 400); - } + requireInlineTemplateContent(subject, textPart, htmlPart); if (entries == null || entries.isEmpty()) { throw new AwsException("InvalidParameterValue", "At least one destination entry is required.", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java index bc6361c9f9..b0c349bc59 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java @@ -193,6 +193,43 @@ public class SesTenantService { .orElseThrow(() -> tenantNotFound(tenantName)); } + // ──────────────────────── Tenant-scoped sending (Phase 4) ──────────────────────── + // Behavior and messages probe-confirmed against real AWS us-east-1, 2026-08-30. + + /** + * Resolves the tenant for a send. The not-found wording differs from the management operations: + * no angle brackets, and the account id is included. + */ + public Tenant tenantForSending(String tenantName, String region, String accountId) { + // Unreachable through the facade (which treats a null TenantName as a non-tenant send), but + // a public helper should fail the AWS way — same guard as runWithTenant. + if (tenantName == null || tenantName.isBlank()) { + throw new AwsException("BadRequestException", "TenantName cannot be empty", 400); + } + return tenantStore.get(tenantKey(region, tenantName)) + .orElseThrow(() -> new AwsException("NotFoundException", + "Tenant " + tenantName + " for AwsAccountId " + accountId + " not found.", 404)); + } + + /** + * The send gate: every resource a tenant send uses (From identity, configuration set, template) + * must be associated with the tenant, or AWS refuses the send with a 403. The bracket list + * carries every missing ARN (the plural is AWS's own wording even for a single resource; on the + * wire AWS spells the body key "Message" — Floci renders its usual error shape instead). + */ + public void requireResourcesAssociated(Tenant tenant, List resources, + String region) { + List missing = resources.stream() + .filter(ref -> associationStore + .get(associationKey(region, tenant.tenantId(), ref)).isEmpty()) + .map(AssociationResource::arn) + .toList(); + if (!missing.isEmpty()) { + throw new AwsException("AccessDeniedException", + "Tenant not associated with resources [" + String.join(", ", missing) + "].", 403); + } + } + /** * Parses and format-validates a resource ARN for the association operations. Check order matches * the observed AWS precedence: not an ARN at all, then not an SES ARN, then an unsupported SES 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 new file mode 100644 index 0000000000..a50e98d168 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java @@ -0,0 +1,277 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +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 static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +/** + * Integration tests for SES v2 tenant-scoped sending (Phase 4): the {@code TenantName} member on + * {@code SendEmail} and {@code SendBulkEmail}. A send whose resources are not associated with the + * tenant is refused with a 403 {@code AccessDeniedException} listing every missing ARN — probed for + * the From identity (exact-address precedence included) and the configuration set; the + * stored-template gate is inferred from the association model, not observed. The send-path + * tenant-not-found wording differs from the management operations (no angle brackets, account id + * included, probe-confirmed). The tenant's SendingStatus is not checked — nothing can move it off + * ENABLED in the emulator. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesTenantSendV2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String TENANT = "floci-send-tenant"; + private static final String DOMAIN = "floci-send.example.com"; + private static final String FROM = "no-reply@" + DOMAIN; + private static final String CONFIG_SET = "floci-send-cs"; + private static final String TEMPLATE = "floci-send-tpl"; + private static final String ARN_PREFIX = "arn:aws:ses:us-east-1:000000000000:"; + + private static io.restassured.specification.RequestSpecification v2() { + return given().contentType("application/json").header("Authorization", AUTH); + } + + private static String simpleSend(String tenantName, String configSetLine) { + return "{\"FromEmailAddress\":\"" + FROM + "\"," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}," + + (tenantName == null ? "" : "\"TenantName\":\"" + tenantName + "\",") + + configSetLine + + "\"Content\":{\"Simple\":{\"Subject\":{\"Data\":\"s\"}," + + "\"Body\":{\"Text\":{\"Data\":\"t\"}}}}}"; + } + + private static void associate(String arn) { + v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + arn + "\"}") + .when().post("/v2/email/tenants/resources").then().statusCode(200); + } + + @Test + @Order(1) + void setup_tenantAndResources() { + v2().body("{\"TenantName\":\"" + TENANT + "\"}") + .when().post("/v2/email/tenants").then().statusCode(200); + v2().body("{\"EmailIdentity\":\"" + DOMAIN + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + 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 send_ghostTenant_sendFlavoredNotFound() { + v2().body(simpleSend("ghost-tenant", "")) + .when().post("/v2/email/outbound-emails").then().statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo( + "Tenant ghost-tenant for AwsAccountId 000000000000 not found.")); + } + + @Test + @Order(3) + void send_validationOrderMatchesAws() { + // Probe-confirmed split: request-shape errors win over the ghost tenant... + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}}") + .when().post("/v2/email/outbound-emails").then().statusCode(400); + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}," + + "\"Content\":{\"Template\":{\"TemplateContent\":{},\"TemplateData\":\"{}\"}}}") + .when().post("/v2/email/outbound-emails").then().statusCode(400); + + // ...while the recipient check and the raw sender derivation lose to the tenant 404. + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"Destination\":{\"ToAddresses\":[]}," + + "\"Content\":{\"Simple\":{\"Subject\":{\"Data\":\"s\"}," + + "\"Body\":{\"Text\":{\"Data\":\"t\"}}}}}") + .when().post("/v2/email/outbound-emails").then().statusCode(404) + .body("message", equalTo( + "Tenant ghost-tenant for AwsAccountId 000000000000 not found.")); + } + + @Test + @Order(4) + void send_unassociatedIdentity_is403() { + // The domain identity backs the From address, so its ARN is the one in the message. + v2().body(simpleSend(TENANT, "")) + .when().post("/v2/email/outbound-emails").then().statusCode(403) + .body("__type", equalTo("AccessDeniedException")) + .body("message", equalTo("Tenant not associated with resources [" + + ARN_PREFIX + "identity/" + DOMAIN + "].")); + } + + @Test + @Order(5) + void send_associatedIdentity_succeeds_unassociatedConfigSetStill403() { + associate(ARN_PREFIX + "identity/" + DOMAIN); + v2().body(simpleSend(TENANT, "")) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .body("MessageId", notNullValue()); + + v2().body(simpleSend(TENANT, "\"ConfigurationSetName\":\"" + CONFIG_SET + "\",")) + .when().post("/v2/email/outbound-emails").then().statusCode(403) + .body("message", equalTo("Tenant not associated with resources [" + + ARN_PREFIX + "configuration-set/" + CONFIG_SET + "].")); + + associate(ARN_PREFIX + "configuration-set/" + CONFIG_SET); + v2().body(simpleSend(TENANT, "\"ConfigurationSetName\":\"" + CONFIG_SET + "\",")) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(6) + void send_templated_requiresTemplateAssociation() { + String templatedSend = "{\"FromEmailAddress\":\"" + FROM + "\"," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}," + + "\"TenantName\":\"" + TENANT + "\"," + + "\"Content\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\"," + + "\"TemplateData\":\"{}\"}}}"; + v2().body(templatedSend) + .when().post("/v2/email/outbound-emails").then().statusCode(403) + .body("message", equalTo("Tenant not associated with resources [" + + ARN_PREFIX + "template/" + TEMPLATE + "].")); + + associate(ARN_PREFIX + "template/" + TEMPLATE); + v2().body(templatedSend) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(7) + void send_nonStringTenantName_isSerializationError_displayNameFromResolves() { + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":123," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}," + + "\"Content\":{\"Simple\":{\"Subject\":{\"Data\":\"s\"}," + + "\"Body\":{\"Text\":{\"Data\":\"t\"}}}}}") + .when().post("/v2/email/outbound-emails").then().statusCode(400) + .body("__type", equalTo("SerializationException")); + + // Display-name syntax must not break the identity resolution behind the gate. + v2().body("{\"FromEmailAddress\":\"Floci <" + FROM + ">\"," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}," + + "\"TenantName\":\"" + TENANT + "\"," + + "\"Content\":{\"Simple\":{\"Subject\":{\"Data\":\"s\"}," + + "\"Body\":{\"Text\":{\"Data\":\"t\"}}}}}") + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .body("MessageId", notNullValue()); + + // An exact-address identity takes precedence over the (associated) domain identity — the + // probed AWS 403 named the address identity's ARN in exactly this setup. + v2().body("{\"EmailIdentity\":\"" + FROM + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + v2().body(simpleSend(TENANT, "")) + .when().post("/v2/email/outbound-emails").then().statusCode(403) + .body("message", equalTo("Tenant not associated with resources [" + + ARN_PREFIX + "identity/" + FROM + "].")); + associate(ARN_PREFIX + "identity/" + FROM); + v2().body(simpleSend(TENANT, "")) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(8) + void rawSend_gatesTheMimeDerivedSender() { + v2().body("{\"EmailIdentity\":\"floci-raw.example.com\"}") + .when().post("/v2/email/identities").then().statusCode(200); + 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)); + // FromEmailAddress omitted: the sender comes from the MIME From header, and that identity + // is not associated with the tenant. + v2().body("{\"TenantName\":\"" + TENANT + "\"," + + "\"Destination\":{\"ToAddresses\":[\"success@simulator.amazonses.com\"]}," + + "\"Content\":{\"Raw\":{\"Data\":\"" + data + "\"}}}") + .when().post("/v2/email/outbound-emails").then().statusCode(403) + .body("message", equalTo("Tenant not associated with resources [" + + ARN_PREFIX + "identity/floci-raw.example.com].")); + } + + @Test + @Order(9) + void send_gatesTheIdentityDefaultConfigurationSet() { + v2().body("{\"ConfigurationSetName\":\"floci-send-default-cs\"}") + .when().post("/v2/email/configuration-sets").then().statusCode(200); + v2().body("{\"ConfigurationSetName\":\"floci-send-default-cs\"}") + .when().put("/v2/email/identities/" + DOMAIN + "/configuration-set") + .then().statusCode(200); + + // No explicit ConfigurationSetName — the identity's default is the effective one, and it + // needs the association just the same. + v2().body(simpleSend(TENANT, "")) + .when().post("/v2/email/outbound-emails").then().statusCode(403) + .body("message", equalTo("Tenant not associated with resources [" + + ARN_PREFIX + "configuration-set/floci-send-default-cs].")); + + associate(ARN_PREFIX + "configuration-set/floci-send-default-cs"); + v2().body(simpleSend(TENANT, "")) + .when().post("/v2/email/outbound-emails").then().statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(10) + void bulkSend_contentValidationPrecedesTenantExistence() { + // Probe-confirmed: a bulk send without template content fails on the content before the + // ghost tenant is even looked at. The same holds for the rest of the request shape. + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"DefaultContent\":{}," + + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":" + + "[\"success@simulator.amazonses.com\"]}}]}") + .when().post("/v2/email/outbound-bulk-emails").then().statusCode(400); + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\"," + + "\"TemplateData\":\"{}\"}},\"BulkEmailEntries\":[]}") + .when().post("/v2/email/outbound-bulk-emails").then().statusCode(400); + // An all-blank inline template is a shape error too — 400 before the ghost tenant's 404. + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"DefaultContent\":{\"Template\":{\"TemplateContent\":{}," + + "\"TemplateData\":\"{}\"}}," + + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":" + + "[\"success@simulator.amazonses.com\"]}}]}") + .when().post("/v2/email/outbound-bulk-emails").then().statusCode(400); + + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\"," + + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\"," + + "\"TemplateData\":\"{}\"}}," + + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":" + + "[\"success@simulator.amazonses.com\"]}}]}") + .when().post("/v2/email/outbound-bulk-emails").then().statusCode(404) + .body("message", equalTo( + "Tenant ghost-tenant for AwsAccountId 000000000000 not found.")); + } + + @Test + @Order(11) + void bulkSend_withAssociatedResources_succeeds() { + v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"" + TENANT + "\"," + + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\"," + + "\"TemplateData\":\"{}\"}}," + + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":" + + "[\"success@simulator.amazonses.com\"]}}]}") + .when().post("/v2/email/outbound-bulk-emails").then().statusCode(200) + .body("BulkEmailEntryResults[0].Status", equalTo("SUCCESS")); + } + + @Test + @Order(12) + void cleanup_cascadeAndResources() { + 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/configuration-sets/floci-send-default-cs").then().statusCode(200); + v2().when().delete("/v2/email/identities/" + FROM).then().statusCode(200); + v2().when().delete("/v2/email/identities/" + DOMAIN).then().statusCode(200); + v2().when().delete("/v2/email/identities/floci-raw.example.com").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java index 928c3d5d46..f05348b6d9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java @@ -436,6 +436,45 @@ class SesTenantServiceTest { assertTrue(service.find("acme", REGION).isEmpty()); } + // ──────────────────────── Tenant-scoped sending (Phase 4) ──────────────────────── + + @Test + void tenantForSending_hasSendFlavoredNotFoundWording() { + AwsException e = assertThrows(AwsException.class, + () -> service.tenantForSending("ghost", REGION, ACCOUNT)); + assertEquals("NotFoundException", e.getErrorCode()); + // No angle brackets, and the account id is included — unlike the management operations. + assertEquals("Tenant ghost for AwsAccountId " + ACCOUNT + " not found.", e.getMessage()); + assertEquals("TenantName cannot be empty", + assertThrows(AwsException.class, + () -> service.tenantForSending(" ", REGION, ACCOUNT)).getMessage()); + assertEquals("TenantName cannot be empty", + assertThrows(AwsException.class, + () -> service.tenantForSending(null, REGION, ACCOUNT)).getMessage()); + } + + @Test + void requireResourcesAssociated_collectsEveryMissingArn() { + Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION); + SesTenantService.AssociationResource identity = identityRef("example.com"); + SesTenantService.AssociationResource cs = SesTenantService.parseResourceArn( + "arn:aws:ses:" + REGION + ":" + ACCOUNT + ":configuration-set/cs", ACCOUNT, REGION); + service.associate(tenant, identity, REGION, () -> {}); + + service.requireResourcesAssociated(tenant, List.of(identity), REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.requireResourcesAssociated(tenant, List.of(identity, cs), REGION)); + assertEquals("AccessDeniedException", e.getErrorCode()); + assertEquals(403, e.getHttpStatus()); + assertEquals("Tenant not associated with resources [" + cs.arn() + "].", e.getMessage()); + + service.disassociate(tenant, identity, REGION); + AwsException both = assertThrows(AwsException.class, + () -> service.requireResourcesAssociated(tenant, List.of(identity, cs), REGION)); + assertEquals("Tenant not associated with resources [" + identity.arn() + ", " + cs.arn() + "].", + both.getMessage()); + } + @Test void validateFilterAndPaging_matchAwsMessages() { assertEquals("Invalid resource type NOPE specified.",