From bd01c1a70b2c3f99beac29ce2de359bb6464a978 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Tue, 11 Aug 2026 09:34:09 +0900 Subject: [PATCH] feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191) * feat(ses): implement SendCustomVerificationEmail for v1 and v2 Add the SendCustomVerificationEmail action on both the v1 Query API and the v2 REST JSON API (POST /v2/email/outbound-custom-verification-emails). The service renders the stored custom-verification-email template into the inspection mailbox and the SMTP relay, returns a MessageId, and registers the recipient as a pending-verification identity, matching AWS. A missing template is the v1-native CustomVerificationEmailTemplateDoesNotExist (remapped to NotFoundException on v2), with the v1 send message ("Template does not exist") verified against AWS. * test(ses): log custom-verification compat cleanup failures instead of swallowing them The @AfterAll cleanup deleted templates and identities in best-effort try/catch blocks that swallowed every exception, so a real deletion failure would leave state behind with no diagnostic. Log the affected template/identity and the exception message, per AGENTS.md's rule against silently discarding exceptions. --- ...esCustomVerificationEmailTemplateTest.java | 34 ++- docs/services/ses.md | 4 +- .../floci/core/common/AwsQueryController.java | 2 +- .../floci/services/ses/SesController.java | 32 +++ .../floci/services/ses/SesQueryHandler.java | 17 ++ .../floci/services/ses/SesService.java | 98 +++++++++ ...tomVerificationEmailV1IntegrationTest.java | 196 +++++++++++++++++ ...tomVerificationEmailV2IntegrationTest.java | 201 ++++++++++++++++++ 8 files changed, 576 insertions(+), 8 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV1IntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplateTest.java index 8f1ca0b803..697efa1385 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplateTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplateTest.java @@ -31,6 +31,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class SesCustomVerificationEmailTemplateTest { private static final String FROM = "cvet-sdk-sender@floci-cvet.test"; + private static final String RECIPIENT = "cvet-sdk-recipient@floci-cvet.test"; private static final String NAME = "cvet-sdk-a"; private static SesClient sesV1; @@ -49,14 +50,19 @@ class SesCustomVerificationEmailTemplateTest { for (String n : new String[] {NAME, "cvet-sdk-shared"}) { try { sesV2.deleteCustomVerificationEmailTemplate(b -> b.templateName(n)); - } catch (Exception ignored) { - // Best-effort cleanup: the template may already be gone. + } catch (Exception e) { + // Best-effort cleanup (the template may already be gone); log so a real failure + // is diagnosable rather than silently leaving state behind. + System.out.println("Cleanup: failed to delete template " + n + ": " + e.getMessage()); } } - try { - sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(FROM).build()); - } catch (Exception ignored) { - // Best-effort cleanup. + for (String id : new String[] {FROM, RECIPIENT}) { + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(id).build()); + } catch (Exception e) { + // Best-effort cleanup; log so a real deletion failure is diagnosable. + System.out.println("Cleanup: failed to delete identity " + id + ": " + e.getMessage()); + } } sesV2.close(); } @@ -118,4 +124,20 @@ class SesCustomVerificationEmailTemplateTest { assertThat(sesV2.getCustomVerificationEmailTemplate(b -> b.templateName("cvet-sdk-shared")) .templateSubject()).isEqualTo("Shared"); } + + @Test + @Order(4) + void v2_sendCustomVerificationEmail() { + String messageId = sesV2.sendCustomVerificationEmail(b -> b + .emailAddress(RECIPIENT).templateName(NAME)).messageId(); + assertThat(messageId).isNotBlank(); + + // The recipient is registered as a pending-verification identity by the send. + assertThat(sesV2.getEmailIdentity(b -> b.emailIdentity(RECIPIENT)).verifiedForSendingStatus()) + .isFalse(); + + assertThatThrownBy(() -> sesV2.sendCustomVerificationEmail(b -> b + .emailAddress(RECIPIENT).templateName("nope-sdk"))) + .isInstanceOf(NotFoundException.class); + } } diff --git a/docs/services/ses.md b/docs/services/ses.md index aa1a5e6529..271c6f3a03 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -30,6 +30,7 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an | `ListCustomVerificationEmailTemplates` | List custom verification email templates (no content) | | `UpdateCustomVerificationEmailTemplate` | Replace a custom verification email template | | `DeleteCustomVerificationEmailTemplate` | Delete a custom verification email template | +| `SendCustomVerificationEmail` | Send a custom verification email and register the recipient as a pending identity | | `GetSendQuota` | Return local send quota counters | | `GetSendStatistics` | Return aggregate delivery stats for sent messages | | `GetAccountSendingEnabled` | Report whether sending is enabled | @@ -173,7 +174,7 @@ curl $AWS_ENDPOINT_URL/_aws/ses - `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. - Receipt rule sets are stored inertly: Floci has no inbound-mail endpoint, so a rule set never holds any receipt rules and routes no mail. `CreateReceiptRuleSet` / `DescribeReceiptRuleSet` (Rules always empty) / `ListReceiptRuleSets` / `DeleteReceiptRuleSet` (idempotent) and `SetActiveReceiptRuleSet` / `DescribeActiveReceiptRuleSet` round-trip so tools like Terraform (`aws_ses_receipt_rule_set`, `aws_ses_active_receipt_rule_set`) can declare a rule set during bootstrap. Individual receipt rules and receipt filters are not implemented. -- Custom verification email templates are stored and returned; `Create`/`Update` require the `FromEmailAddress` to be a verified identity (or a verified domain) and reject an invalid redirection URL, matching AWS. `SendCustomVerificationEmail` is not yet implemented. +- Custom verification email templates are stored and returned; `Create`/`Update` require the `FromEmailAddress` to be a verified identity (or a verified domain) and reject an invalid redirection URL, matching AWS. `SendCustomVerificationEmail` renders the template into the `/_aws/ses` inspection mailbox (and the SMTP relay, when configured) and registers the recipient as a pending-verification identity, matching AWS. The template body has no placeholder that AWS substitutes, so it is passed through verbatim with the same fixed disclaimer AWS always appends; the unique verification link AWS appends is not reproduced because Floci has no verification-click flow. The `SuccessRedirectionURL` / `FailureRedirectionURL` are stored and returned by Get/List but are the post-click redirect targets, so they are not used at send time. - For the REST JSON API see [SES v2](#v2) below. ## SES v2 (REST JSON) {#v2} @@ -215,6 +216,7 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `GET` | `/v2/email/custom-verification-email-templates/{templateName}` | `GetCustomVerificationEmailTemplate` | | `PUT` | `/v2/email/custom-verification-email-templates/{templateName}` | `UpdateCustomVerificationEmailTemplate` | | `DELETE` | `/v2/email/custom-verification-email-templates/{templateName}` | `DeleteCustomVerificationEmailTemplate` | +| `POST` | `/v2/email/outbound-custom-verification-emails` | `SendCustomVerificationEmail` | | `POST` | `/v2/email/configuration-sets` | `CreateConfigurationSet` | | `GET` | `/v2/email/configuration-sets` | `ListConfigurationSets` | | `GET` | `/v2/email/configuration-sets/{name}` | `GetConfigurationSet` | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 39818cd879..a33e8605f7 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -398,7 +398,7 @@ public class AwsQueryController { "TestRenderTemplate", "CreateCustomVerificationEmailTemplate", "GetCustomVerificationEmailTemplate", "ListCustomVerificationEmailTemplates", "UpdateCustomVerificationEmailTemplate", - "DeleteCustomVerificationEmailTemplate", + "DeleteCustomVerificationEmailTemplate", "SendCustomVerificationEmail", "CreateConfigurationSet", "DescribeConfigurationSet", "ListConfigurationSets", "DeleteConfigurationSet", "CreateConfigurationSetEventDestination", 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 ab9011020f..ea4c5bbfee 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 @@ -702,6 +702,38 @@ public class SesController { } } + @POST + @Path("/outbound-custom-verification-emails") + public Response sendCustomVerificationEmail(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + String templateName = null; + try { + if (!sesService.isAccountSendingEnabled(region)) { + throw new AwsException("SendingPausedException", + "Account sending is disabled.", 400); + } + JsonNode request = objectMapper.readTree(body); + requireJsonObject(request); + templateName = request.path("TemplateName").asText(null); + String messageId = sesService.sendCustomVerificationEmail( + request.path("EmailAddress").asText(null), templateName, + request.path("ConfigurationSetName").asText(null), region); + ObjectNode result = objectMapper.createObjectNode(); + result.put("MessageId", messageId); + return Response.ok(result).build(); + } catch (AwsException e) { + // AWS returns a longer not-found message on v2 than the v1 send message ("Template + // does not exist"); the service throws the v1-native form, so restate it in the v2 wording. + if ("CustomVerificationEmailTemplateDoesNotExist".equals(e.getErrorCode())) { + throw new AwsException("NotFoundException", + "Custom verification email template <" + templateName + "> does not exist", 404); + } + throw remapV1Exception(e); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + private CustomVerificationEmailTemplate parseCvet(JsonNode request) { requireJsonObject(request); CustomVerificationEmailTemplate t = new CustomVerificationEmailTemplate(); 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 f1ec30b82d..5566af60c7 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 @@ -97,6 +97,8 @@ public class SesQueryHandler { handleUpdateCustomVerificationEmailTemplate(params, region); case "DeleteCustomVerificationEmailTemplate" -> handleDeleteCustomVerificationEmailTemplate(params, region); + case "SendCustomVerificationEmail" -> + handleSendCustomVerificationEmail(params, region); case "CreateConfigurationSet" -> handleCreateConfigurationSet(params, region); case "DescribeConfigurationSet" -> handleDescribeConfigurationSet(params, region); case "ListConfigurationSets" -> handleListConfigurationSets(region); @@ -611,6 +613,21 @@ public class SesQueryHandler { "DeleteCustomVerificationEmailTemplate", AwsNamespaces.SES)).build(); } + private Response handleSendCustomVerificationEmail(MultivaluedMap params, String region) { + if (!sesService.isAccountSendingEnabled(region)) { + throw new AwsException("AccountSendingPausedException", + "Account sending is disabled.", 400); + } + // getParam (not requireParam) so the service is the single validation authority and returns + // the AWS-faithful "Email address not specified." / "Invalid email address<...>." shapes. + String messageId = sesService.sendCustomVerificationEmail( + getParam(params, "EmailAddress"), getParam(params, "TemplateName"), + getParam(params, "ConfigurationSetName"), region); + String result = new XmlBuilder().elem("MessageId", messageId).build(); + return Response.ok(AwsQueryResponse.envelope( + "SendCustomVerificationEmail", AwsNamespaces.SES, result)).build(); + } + private CustomVerificationEmailTemplate readCvetParams(MultivaluedMap params) { CustomVerificationEmailTemplate t = new CustomVerificationEmailTemplate(); t.setTemplateName(params.getFirst("TemplateName")); 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 c513a84471..11258b1f50 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 @@ -1146,6 +1146,104 @@ public class SesService { LOG.infov("Deleted custom verification email template {0} in region {1}", templateName, region); } + // AWS appends this exact disclaimer to the end of every custom verification email and it cannot + // be removed (SES docs Q10). + private static final String CUSTOM_VERIFICATION_DISCLAIMER = + "If you did not request to verify this email address, please disregard this message."; + + public String sendCustomVerificationEmail(String emailAddress, String templateName, + String configurationSetName, String region) { + // AWS validates the recipient before the template exists check (probe-confirmed): a blank + // address is "Email address not specified."; anything that isn't a single valid address — + // no local-part/domain separator, more than one separator, whitespace, or longer than 320 + // chars — is "Invalid email address." (both InvalidParameterValue / 400, remapped to + // BadRequestException on v2). The separator count ignores '@' inside a quoted local part, + // since AWS accepts an RFC-5321 quoted local part that contains '@' (e.g. "a@b"@example.com). + if (emailAddress == null || emailAddress.isBlank()) { + throw new AwsException("InvalidParameterValue", "Email address not specified.", 400); + } + // A leading/trailing '@' means an empty local part (@example.com) or empty domain (local@), + // both of which AWS rejects (probe-confirmed). AWS does not require a dot in the domain + // (a@b is accepted), so no stricter domain shape is enforced. + boolean emptyBoundary = emailAddress.charAt(0) == '@' + || emailAddress.charAt(emailAddress.length() - 1) == '@'; + if (emailAddress.length() > 320 || unquotedAtCount(emailAddress) != 1 || emptyBoundary + || emailAddress.chars().anyMatch(Character::isWhitespace)) { + throw new AwsException("InvalidParameterValue", + "Invalid email address<" + emailAddress + ">.", 400); + } + if (templateName == null || templateName.isBlank()) { + throw new AwsException("InvalidParameterValue", "TemplateName is required.", 400); + } + CustomVerificationEmailTemplate template = cvetStore.get(cvetKey(region, templateName)) + .orElseThrow(() -> new AwsException("CustomVerificationEmailTemplateDoesNotExist", + "Template <" + templateName + "> does not exist", 400)); + if (!isVerifiedSender(template.getFromEmailAddress(), region)) { + throw new AwsException("FromEmailAddressNotVerified", + "Email address is not verified. The following identities failed the check in region " + + region.toUpperCase(Locale.ROOT) + ": " + template.getFromEmailAddress(), 400); + } + if (configurationSetName != null && !configurationSetName.isBlank()) { + getConfigurationSet(configurationSetName, region); + } + + // AWS registers the recipient as a pending-verification identity as part of sending the + // verification email, so ListIdentities / GetIdentityVerificationAttributes surface it. + markPendingEmailIdentity(emailAddress, region); + + // AWS sends the template content verbatim and appends a fixed, non-removable disclaimer (SES + // docs Q10). AWS also appends a unique verification link, which Floci does not reproduce + // because it has no verification-click flow. The template body carries no placeholder that + // AWS substitutes, so the content itself is passed through unchanged. + String body = template.getTemplateContent() == null ? "" : template.getTemplateContent(); + String renderedHtml = body + "

" + CUSTOM_VERIFICATION_DISCLAIMER + "

"; + + String messageId = UUID.randomUUID().toString(); + SentEmail email = new SentEmail(messageId, region, template.getFromEmailAddress(), + List.of(emailAddress), List.of(), List.of(), List.of(), + template.getTemplateSubject(), null, renderedHtml); + emailStore.put("email::" + region + "::" + messageId, email); + smtpRelay.relay(template.getFromEmailAddress(), List.of(emailAddress), List.of(), List.of(), + List.of(), template.getTemplateSubject(), null, renderedHtml, List.of()); + LOG.infov("SES custom verification email sent: to={0}, template={1}, messageId={2}", + emailAddress, templateName, messageId); + return messageId; + } + + // Counts '@' characters outside a quoted local part. A valid address has exactly one — the + // local-part/domain separator; '@' inside a quoted local part (honoring backslash escapes) is + // part of the local part and doesn't count, so AWS-accepted forms like "a@b"@example.com pass + // while a@@b.com and "a"@@example.com are rejected. + private static int unquotedAtCount(String address) { + int count = 0; + boolean inQuotes = false; + boolean escaped = false; + for (int i = 0; i < address.length(); i++) { + char c = address.charAt(i); + if (escaped) { + escaped = false; + } else if (c == '\\') { + escaped = true; + } else if (c == '"') { + inQuotes = !inQuotes; + } else if (c == '@' && !inQuotes) { + count++; + } + } + return count; + } + + private void markPendingEmailIdentity(String emailAddress, String region) { + String key = identityKey(region, emailAddress); + if (identityStore.get(key).isEmpty()) { + Identity identity = new Identity(emailAddress, "EmailAddress"); + identity.setVerificationStatus("Pending"); + identityStore.put(key, identity); + LOG.infov("SES custom verification email registered pending identity {0} in region {1}", + emailAddress, region); + } + } + private void validateCustomVerificationTemplate(CustomVerificationEmailTemplate t, String region) { requireCvetField(t.getTemplateName(), "TemplateName"); requireCvetField(t.getFromEmailAddress(), "FromEmailAddress"); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV1IntegrationTest.java new file mode 100644 index 0000000000..8317086523 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV1IntegrationTest.java @@ -0,0 +1,196 @@ +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.containsString; + +/** + * Integration tests for the SES V1 Query-protocol {@code SendCustomVerificationEmail}: a successful + * send returns a MessageId and registers the recipient as a pending-verification identity, and a + * missing template fails with the v1-native {@code CustomVerificationEmailTemplateDoesNotExist} code + * and the v1 send message ("Template does not exist"), both verified against real AWS. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesSendCustomVerificationEmailV1IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request"; + private static final String FROM = "scve-v1-sender@floci.test"; + private static final String RECIPIENT = "scve-v1-recipient@floci.test"; + private static final String NAME = "scve-v1-template"; + + private static io.restassured.specification.RequestSpecification query(String action) { + return given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", action); + } + + @Test + @Order(0) + void setup_verifyFromAndCreateTemplate() { + query("VerifyEmailIdentity").formParam("EmailAddress", FROM).when().post("/").then().statusCode(200); + query("CreateCustomVerificationEmailTemplate") + .formParam("TemplateName", NAME) + .formParam("FromEmailAddress", FROM) + .formParam("TemplateSubject", "Verify your email") + .formParam("TemplateContent", "verify") + .formParam("SuccessRedirectionURL", "https://example.com/ok") + .formParam("FailureRedirectionURL", "https://example.com/fail") + .when().post("/").then().statusCode(200); + } + + @Test + @Order(1) + void send_returnsMessageId() { + query("SendCustomVerificationEmail") + .formParam("EmailAddress", RECIPIENT) + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(200) + .body(containsString("")); + } + + @Test + @Order(2) + void send_registersRecipientAsPendingIdentity() { + // AWS registers the recipient as a pending-verification identity as part of the send. + query("GetIdentityVerificationAttributes") + .formParam("Identities.member.1", RECIPIENT) + .when().post("/").then().statusCode(200) + .body(containsString("Pending")); + } + + @Test + @Order(3) + void send_missingTemplate_returnsDoesNotExistWithV1Message() { + query("SendCustomVerificationEmail") + .formParam("EmailAddress", RECIPIENT) + .formParam("TemplateName", "scve-v1-ghost") + .when().post("/").then().statusCode(400) + .body(containsString("CustomVerificationEmailTemplateDoesNotExist")) + .body(containsString("Template <scve-v1-ghost> does not exist")); + } + + @Test + @Order(4) + void send_templateFromNoLongerVerified_returnsFromEmailAddressNotVerified() { + // The template's From was verified at create time; once that identity is deleted, sending + // through the template fails with the v1-native FromEmailAddressNotVerified / 400. + String from2 = "scve-v1-stale-from@floci.test"; + String template2 = "scve-v1-stale-template"; + query("VerifyEmailIdentity").formParam("EmailAddress", from2).when().post("/").then().statusCode(200); + query("CreateCustomVerificationEmailTemplate") + .formParam("TemplateName", template2) + .formParam("FromEmailAddress", from2) + .formParam("TemplateSubject", "Verify your email") + .formParam("TemplateContent", "verify") + .formParam("SuccessRedirectionURL", "https://example.com/ok") + .formParam("FailureRedirectionURL", "https://example.com/fail") + .when().post("/").then().statusCode(200); + query("DeleteIdentity").formParam("Identity", from2).when().post("/").then().statusCode(200); + + query("SendCustomVerificationEmail") + .formParam("EmailAddress", RECIPIENT) + .formParam("TemplateName", template2) + .when().post("/").then().statusCode(400) + .body(containsString("FromEmailAddressNotVerified")); + } + + @Test + @Order(5) + void send_accountSendingDisabled_returnsAccountSendingPaused() { + // Like every other v1 send action, the send is refused while account sending is paused. + query("UpdateAccountSendingEnabled").formParam("Enabled", "false") + .when().post("/").then().statusCode(200); + try { + query("SendCustomVerificationEmail") + .formParam("EmailAddress", RECIPIENT) + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(400) + .body(containsString("AccountSendingPausedException")); + } finally { + query("UpdateAccountSendingEnabled").formParam("Enabled", "true") + .when().post("/").then().statusCode(200); + } + } + + @Test + @Order(6) + void send_malformedEmailAddress_returnsInvalidParameterValue() { + // AWS validates the recipient address before the template check: a value without a single + // '@' is InvalidParameterValue / 400 "Invalid email address." (verified against AWS). + query("SendCustomVerificationEmail") + .formParam("EmailAddress", "not-an-email") + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Invalid email address<not-an-email>.")); + } + + @Test + @Order(7) + void send_blankEmailAddress_returnsNotSpecified() { + query("SendCustomVerificationEmail") + .formParam("EmailAddress", "") + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Email address not specified.")); + } + + @Test + @Order(8) + void send_multipleUnquotedAt_returnsInvalidParameterValue() { + // AWS rejects an address with more than one unquoted '@' (verified). + query("SendCustomVerificationEmail") + .formParam("EmailAddress", "a@@b.com") + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Invalid email address<a@@b.com>.")); + } + + @Test + @Order(9) + void send_quotedLocalPartWithAt_passesAddressValidation() { + // AWS accepts an RFC-5321 quoted local part that contains '@' (verified), so it must not be + // rejected as invalid. A non-existent template proves the address passed validation and the + // call reached the template-existence check. + query("SendCustomVerificationEmail") + .formParam("EmailAddress", "\"a@b\"@example.com") + .formParam("TemplateName", "scve-v1-ghost2") + .when().post("/").then().statusCode(400) + .body(containsString("CustomVerificationEmailTemplateDoesNotExist")); + } + + @Test + @Order(10) + void send_quoteClosesBeforeMultipleAt_isRejected() { + // The quoted local part closes before the two '@', so both separators are unquoted — invalid. + // Guards against a naive "starts with a quote" exemption that would let this through. + query("SendCustomVerificationEmail") + .formParam("EmailAddress", "\"a\"@@example.com") + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + } + + @Test + @Order(11) + void send_emptyLocalOrDomain_returnsInvalidParameterValue() { + // AWS rejects a boundary '@' — empty local part (@example.com) or empty domain (local@). + for (String bad : new String[] {"@example.com", "local@"}) { + query("SendCustomVerificationEmail") + .formParam("EmailAddress", bad) + .formParam("TemplateName", NAME) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Invalid email address<" + bad + ">.")); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java new file mode 100644 index 0000000000..e28bedef9e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendCustomVerificationEmailV2IntegrationTest.java @@ -0,0 +1,201 @@ +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.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +/** + * Integration tests for the SES V2 REST JSON {@code SendCustomVerificationEmail} + * ({@code POST /v2/email/outbound-custom-verification-emails}): a successful send returns a + * MessageId, stores the rendered email in the inspection mailbox, and registers the recipient as a + * pending identity; a missing template is a {@code NotFoundException}/404 and an unknown + * configuration set is likewise remapped to 404, both verified against real AWS. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesSendCustomVerificationEmailV2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String FROM = "scve-v2-sender@floci.test"; + private static final String RECIPIENT = "scve-v2-recipient@floci.test"; + private static final String NAME = "scve-v2-template"; + private static final String SUBJECT = "Verify your email V2"; + private static final String SEND = "/v2/email/outbound-custom-verification-emails"; + + @Test + @Order(0) + void setup_verifyFromAndCreateTemplate() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\":\"" + FROM + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + + given().contentType("application/json").header("Authorization", AUTH) + .body(""" + { + "TemplateName": "%s", + "FromEmailAddress": "%s", + "TemplateSubject": "%s", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/fail" + } + """.formatted(NAME, FROM, SUBJECT)) + .when().post("/v2/email/custom-verification-email-templates").then().statusCode(200); + } + + @Test + @Order(1) + void send_returnsMessageId() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"" + RECIPIENT + "\",\"TemplateName\":\"" + NAME + "\"}") + .when().post(SEND).then().statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(2) + void send_storesRenderedEmailInInspectionMailbox() { + given().header("Authorization", AUTH).queryParam("email", RECIPIENT) + .when().get("/_aws/ses").then().statusCode(200) + .body(containsString(FROM)) + .body(containsString(SUBJECT)) + // The template body is passed through verbatim (no placeholder substitution)... + .body(containsString("verify")) + // ...followed by the fixed, non-removable disclaimer AWS always appends. + .body(containsString( + "If you did not request to verify this email address, please disregard this message.")); + } + + @Test + @Order(3) + void send_registersRecipientAsIdentity() { + // The recipient is registered (pending) as part of the send, so GetEmailIdentity finds it. + given().header("Authorization", AUTH) + .when().get("/v2/email/identities/" + RECIPIENT).then().statusCode(200); + } + + @Test + @Order(4) + void send_missingTemplate_returnsNotFound() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"" + RECIPIENT + "\",\"TemplateName\":\"scve-v2-ghost\"}") + .when().post(SEND).then().statusCode(404) + .body("__type", equalTo("NotFoundException")) + // v2 uses a longer not-found message than the v1 send ("Template ..."), verified. + .body("message", equalTo( + "Custom verification email template does not exist")); + } + + @Test + @Order(5) + void send_unknownConfigurationSet_returnsNotFound() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"" + RECIPIENT + "\",\"TemplateName\":\"" + NAME + + "\",\"ConfigurationSetName\":\"scve-v2-ghost-cs\"}") + .when().post(SEND).then().statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + @Test + @Order(6) + void send_missingEmailAddress_returnsBadRequest() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"TemplateName\":\"" + NAME + "\"}") + .when().post(SEND).then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(7) + void send_templateFromNoLongerVerified_remapsToNotFound() { + // The template's From was verified at create time; once that identity is deleted, the send + // fails FromEmailAddressNotVerified, which the v2 boundary remaps to NotFoundException / 404 + // (consistent with the CreateCustomVerificationEmailTemplate unverified-From mapping). + String from2 = "scve-v2-stale-from@floci.test"; + String template2 = "scve-v2-stale-template"; + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\":\"" + from2 + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + given().contentType("application/json").header("Authorization", AUTH) + .body(""" + { + "TemplateName": "%s", + "FromEmailAddress": "%s", + "TemplateSubject": "%s", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/fail" + } + """.formatted(template2, from2, SUBJECT)) + .when().post("/v2/email/custom-verification-email-templates").then().statusCode(200); + given().header("Authorization", AUTH) + .when().delete("/v2/email/identities/" + from2).then().statusCode(200); + + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"" + RECIPIENT + "\",\"TemplateName\":\"" + template2 + "\"}") + .when().post(SEND).then().statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + @Test + @Order(8) + void send_accountSendingDisabled_returnsSendingPaused() { + // Like the v2 SendEmail endpoint, the send is refused while account sending is paused. + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"SendingEnabled\":false}") + .when().put("/v2/email/account/sending").then().statusCode(200); + try { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"" + RECIPIENT + "\",\"TemplateName\":\"" + NAME + "\"}") + .when().post(SEND).then().statusCode(400) + .body("__type", equalTo("SendingPausedException")); + } finally { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"SendingEnabled\":true}") + .when().put("/v2/email/account/sending").then().statusCode(200); + } + } + + @Test + @Order(9) + void send_malformedEmailAddress_returnsBadRequestWithAwsMessage() { + // AWS returns the same "Invalid email address." message on v2 as on v1 (verified); + // Floci throws the v1-native InvalidParameterValue which remaps to BadRequestException / 400. + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"not-an-email\",\"TemplateName\":\"" + NAME + "\"}") + .when().post(SEND).then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Invalid email address.")); + } + + @Test + @Order(10) + void send_multipleUnquotedAt_returnsBadRequest() { + // AWS rejects more than one unquoted '@'; a quoted local part that contains '@' is accepted + // (see the v1 test) — the check must only reject the unquoted case. + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"a@@b.com\",\"TemplateName\":\"" + NAME + "\"}") + .when().post(SEND).then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Invalid email address.")); + } + + @Test + @Order(11) + void send_emptyDomain_returnsBadRequest() { + // A trailing '@' is an empty domain, which AWS rejects (verified). + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailAddress\":\"local@\",\"TemplateName\":\"" + NAME + "\"}") + .when().post(SEND).then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Invalid email address.")); + } +}