From 898fee8bb13d4c0c3e2325a72b379f95627cf8f6 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Sat, 14 Nov 2026 04:58:23 +0900 Subject: [PATCH] fix(ses): validate the topic in SetIdentityNotificationTopic (#8202) * fix(ses): validate the topic in SetIdentityNotificationTopic * test(ses): share the SNS topic helpers in the notification topic test * refactor(ses): build the notificationType enum violation with the shared helper --- .../sdk-test-awscli/test/ses.bats | 7 +- docs/services/ses.md | 2 +- .../aws/services/ses/SesEventPublisher.java | 11 ++ .../aws/services/ses/SesIdentityService.java | 50 ++++- .../aws/services/ses/SesQueryHandler.java | 3 +- .../io/floci/aws/services/ses/SesService.java | 9 + ...ficationTopicPublishV1IntegrationTest.java | 180 +++++++++++++++--- .../services/ses/SesIdentityServiceTest.java | 110 ++++++++++- .../aws/services/ses/SesIntegrationTest.java | 12 ++ ...nsPublishAuthorizationIntegrationTest.java | 17 +- 10 files changed, 350 insertions(+), 51 deletions(-) diff --git a/compatibility-tests/sdk-test-awscli/test/ses.bats b/compatibility-tests/sdk-test-awscli/test/ses.bats index a8a16b66c5..a0fe411100 100644 --- a/compatibility-tests/sdk-test-awscli/test/ses.bats +++ b/compatibility-tests/sdk-test-awscli/test/ses.bats @@ -6,12 +6,17 @@ load 'test_helper/common-setup' setup_file() { export TEST_EMAIL="$(unique_name test)@example.com" export TEST_DOMAIN="$(unique_name test).example.com" + # SES refuses a notification topic that does not exist. + local topic_out + topic_out=$(aws_cmd sns create-topic --name "$(unique_name bounce-topic)") + export BOUNCE_TOPIC_ARN=$(json_get "$topic_out" '.TopicArn') } teardown_file() { # Cleanup identities aws_cmd ses delete-identity --identity "$TEST_EMAIL" >/dev/null 2>&1 || true aws_cmd ses delete-identity --identity "$TEST_DOMAIN" >/dev/null 2>&1 || true + aws_cmd sns delete-topic --topic-arn "$BOUNCE_TOPIC_ARN" >/dev/null 2>&1 || true } @test "SES: verify email identity" { @@ -112,7 +117,7 @@ teardown_file() { run aws_cmd ses set-identity-notification-topic \ --identity "$TEST_EMAIL" \ --notification-type Bounce \ - --sns-topic arn:aws:sns:us-east-1:000000000000:bounce-topic + --sns-topic "$BOUNCE_TOPIC_ARN" # Accept success or known parser bug output [[ $status -eq 0 ]] || [[ "$output" == *"SetIdentityNotificationTopicResult"* ]] } diff --git a/docs/services/ses.md b/docs/services/ses.md index c8732e5b42..4833012227 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -306,7 +306,7 @@ curl $AWS_ENDPOINT_URL/_aws/ses - `SendEmail`, `SendRawEmail`, `SendTemplatedEmail` and `SendBulkTemplatedEmail`, and v2 `SendEmail` and `SendBulkEmail`, require verified senders, as on AWS ([SendEmail](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html), [Email sending errors](https://docs.aws.amazon.com/ses/latest/dg/troubleshoot-error-messages.html)): each address used as a "From", "Source", "Sender" or "Return-Path" address must be a verified email address identity or an address in a verified domain identity or one of its subdomains. That is the `Source` or `FromEmailAddress` and the `ReturnPath` or `FeedbackForwardingEmailAddress`, plus, on a raw message, every mailbox of its `From` header, its `Sender` and its `Return-Path` header. A v2 raw send reads the `From` header only in place of a missing `FromEmailAddress` and accepts any `From` header when one is given (probe-confirmed), so the header is checked only then. Every other address present is checked; whether AWS still checks a `Return-Path` header that the request's return path overrides has not been probed. One `MessageRejected` lists every unverified address ("Email address is not verified. The following identities failed the check in region US-EAST-1: a@example.com, b@example.com") and nothing is captured or relayed. An address covered by a sending-authorization ARN of another account (`SourceArn`, `FromArn`, `ReturnPathArn`, their `X-SES-*-ARN` headers, or v2 `FromEmailAddressIdentityArn` and `FeedbackForwardingEmailAddressIdentityArn`) is not checked, since it is the owner's identity; on a raw send the source ARN also covers the `From` and return-path addresses that have no ARN of their own. A bulk send checks its sender and return path once and rejects the whole call; when no entry has a recipient it checks neither and every entry fails on its own (probe-confirmed on v2 `SendBulkEmail` and v1 `SendBulkTemplatedEmail`). On v2 `SendEmail` and `SendBulkEmail`, and v1 `SendTemplatedEmail` and `SendBulkTemplatedEmail`, an unknown configuration set is reported before the check and an unknown stored template only after it (probe-confirmed). The verification codes and invitations Cognito sends are not affected. - `SendBulkTemplatedEmail` reads every `Destinations.member.N` up to the highest N. A missing `Template` (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). A `DefaultTags` or `ReplacementTags` tag without a `Name` or a `Value` is a model violation too, a skipped tag index listing both, and the top-level members are listed ahead of the nested ones ('template' before 'defaultTags.1.member.name'). A missing or empty `DefaultTemplateData` is a 400 `InvalidParameterValue` ("The default template data does not exist"), answered after the `Source` syntax and the destination count and before the template lookup and the sender verification (probe-confirmed). On `SendBulkTemplatedEmail` an entry with more than 50 recipients ("Recipient count exceeds 50."), template data that is not a JSON object ("The template data is invalid") or a tag with an empty name ("The tag name must be specified.") fails on its own with `InvalidParameterValue`. Invalid `DefaultTemplateData` or an empty `DefaultTags` name fails every entry, and within one entry an address syntax error wins over an empty tag name, which wins over invalid template data, which wins over the recipient count (probe-confirmed). v2 `SendBulkEmail` still rejects the whole call for more than 50 recipients in a destination (not probed). - `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). +- `SetIdentityNotificationTopic` publishes to the configured topic on a Bounce/Complaint/Delivery event (triggered via the mailbox simulator addresses or the suppression list), independent of any configuration set. The payload uses the legacy format (`notificationType`, no `mail.tags`, headers only when `SetIdentityHeadersInNotificationsEnabled` is on). The topic is checked when it is set: one that does not exist in the identity's region, or whose policy does not let SES publish under IAM enforcement, is refused with `InvalidParameterValue`. A topic of another account that exists in Floci and grants SES is accepted. - Identity (sending authorization) policies are stored and returned as metadata: the policy document, the per-identity limit of 20, and the create/update/delete error shapes match AWS, but Floci does not evaluate policy authorization (Principal-account existence, Resource-ARN match) or gate sending on it. A send naming another account's identity ARN skips the verified-sender check for the addresses it covers, without looking that identity up or reading its policy. - Receipt rule sets and receipt rules are stored inertly: Floci has no inbound-mail endpoint, so stored rules route no mail and their actions never execute, but the management API round-trips with AWS ordering, validation, and error semantics (probe-verified). Action targets are validated against the local emulator with the AWS error codes: an SNS `TopicArn`, S3 `BucketName`, or Lambda `FunctionArn` must reference an existing local resource, and a `BounceAction` `Sender` must be a verified identity. Deviations: S3 bucket write permissions, KMS keys, and `ConnectAction` role assumability are not verified (AWS checks these); `WorkmailAction` gets no resource validation (neither does AWS). Receipt IP filters are stored the same way, with the probed AWS validation and the 100-filter limit, but no inbound connection is ever filtered. `ReorderReceiptRuleSet` requires an exact permutation of the set's rules; `CloneReceiptRuleSet` copies them under a new creation timestamp, leaving the active flag behind. - 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. diff --git a/src/main/java/io/floci/aws/services/ses/SesEventPublisher.java b/src/main/java/io/floci/aws/services/ses/SesEventPublisher.java index 2afd57a97f..97de96791a 100644 --- a/src/main/java/io/floci/aws/services/ses/SesEventPublisher.java +++ b/src/main/java/io/floci/aws/services/ses/SesEventPublisher.java @@ -201,6 +201,17 @@ public class SesEventPublisher { ed.getName(), eventType); } + /** + * Whether an identity may name {@code topicArn} for its notifications: the topic exists in + * {@code region}, the identity's own, and lets SES publish for {@code identityArn}. Probed: + * {@code SetIdentityNotificationTopic} refuses a topic of another region and one whose policy + * denies SES, not only a missing one. + */ + public boolean mayNotifyIdentityTopic(String topicArn, String identityArn, String identityAccountId, + String region) { + return snsService.topicExists(topicArn, region) && sesMayPublish(topicArn, identityArn, identityAccountId); + } + /** Whether the topic's policy lets SES publish to it for {@code sourceArn}, owned by {@code sourceAccount}. */ private boolean sesMayPublish(String topicArn, String sourceArn, String sourceAccount) { return serviceCallAuthorizer.authorize("ses", "sns:Publish", topicArn, sourceArn, sourceAccount) diff --git a/src/main/java/io/floci/aws/services/ses/SesIdentityService.java b/src/main/java/io/floci/aws/services/ses/SesIdentityService.java index c4b62f426c..2fc1391a7b 100644 --- a/src/main/java/io/floci/aws/services/ses/SesIdentityService.java +++ b/src/main/java/io/floci/aws/services/ses/SesIdentityService.java @@ -30,6 +30,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -401,13 +402,51 @@ public class SesIdentityService implements SesTaggable { static final List NOTIFICATION_TYPES = List.of("Bounce", "Complaint", "Delivery"); + /** + * Probed: SES answers in this order. The members the model requires come first, reported + * together; then the shape of the identity, where an empty value and one with whitespace around + * it are refused; then the topic; and only then whether the identity exists, so a bad topic on + * an unknown identity reports the topic. Every topic SES cannot use (malformed, missing, in + * another region, or one whose policy refuses SES) gets the same message, an empty value is + * refused instead of clearing, and only an absent {@code SnsTopic} clears the setting. A + * refused call leaves the stored topic as it was. + * + * @param publishableTopic whether SES may publish to the topic for this identity + */ public void setIdentityNotificationTopic(String identityValue, String notificationType, - String snsTopic, String region) { + String snsTopic, String region, + Predicate publishableTopic) { + List violations = new ArrayList<>(); + if (identityValue == null) { + violations.add(SmithyValidationErrors.notNullWithoutValue("identity")); + } + if (notificationType == null) { + violations.add(SmithyValidationErrors.notNullWithoutValue("notificationType")); + } else if (!NOTIFICATION_TYPES.contains(notificationType)) { + violations.add(SmithyValidationErrors.Violations.WITHOUT_VALUES.notInEnum( + notificationType, "notificationType", NOTIFICATION_TYPES)); + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationError(violations); + } + if (identityValue.isBlank() || !identityValue.equals(identityValue.strip())) { + throw new AwsException("InvalidParameterValue", "Identity " + identityValue + + " is invalid. Must be a valid email address or domain or identity ARN.", 400); + } + if (snsTopic != null) { + if (snsTopic.isBlank()) { + throw new AwsException("InvalidParameterValue", "SNS topic cannot be empty.", 400); + } + if (!publishableTopic.test(snsTopic)) { + throw new AwsException("InvalidParameterValue", "SNS topic " + snsTopic + " is invalid.", 400); + } + } synchronized (identityCreationLock) { Identity identity = identityStore.get(identityKey(region, identityValue)) .orElseThrow(() -> new AwsException("InvalidParameterValue", - "Identity does not exist: " + identityValue, 400)); - if (snsTopic != null && !snsTopic.isBlank()) { + "Identity " + identityValue + + " is invalid. Must be a verified email address or domain.", 400)); + if (snsTopic != null) { identity.getNotificationAttributes().put(notificationType + "Topic", snsTopic); } else { identity.getNotificationAttributes().remove(notificationType + "Topic"); @@ -472,9 +511,8 @@ public class SesIdentityService implements SesTaggable { } if (!NOTIFICATION_TYPES.contains(notificationType)) { throw SmithyValidationErrors.validationError( - "Value at 'notificationType' failed to satisfy " - + "constraint: Member must satisfy enum value set: " - + NOTIFICATION_TYPES); + SmithyValidationErrors.Violations.WITHOUT_VALUES.notInEnum( + notificationType, "notificationType", NOTIFICATION_TYPES)); } synchronized (identityCreationLock) { Identity identity = identityStore.get(identityKey(region, identityValue)) diff --git a/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java b/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java index bda936c1bf..621fc77eb8 100644 --- a/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java +++ b/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java @@ -376,8 +376,7 @@ public class SesQueryHandler { String identityValue = getParam(params, "Identity"); String notificationType = getParam(params, "NotificationType"); String snsTopic = getParam(params, "SnsTopic"); - identityService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, - region); + sesService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityNotificationTopic", AwsNamespaces.SES)).build(); } diff --git a/src/main/java/io/floci/aws/services/ses/SesService.java b/src/main/java/io/floci/aws/services/ses/SesService.java index e56adcbc47..fa828218ae 100644 --- a/src/main/java/io/floci/aws/services/ses/SesService.java +++ b/src/main/java/io/floci/aws/services/ses/SesService.java @@ -769,6 +769,15 @@ public class SesService { return targets; } + public void setIdentityNotificationTopic(String identityValue, String notificationType, + String snsTopic, String region) { + String accountId = callerAccountId(); + identityService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, region, + topicArn -> eventPublisher == null || eventPublisher.mayNotifyIdentityTopic(topicArn, + AwsArnUtils.Arn.of("ses", region, accountId, "identity/" + identityValue).toString(), + accountId, region)); + } + private static String notificationTopicFor(Identity identity, String type) { if (identity == null) { return null; diff --git a/src/test/java/io/floci/aws/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java index f79c5170e5..64dd75dc8e 100644 --- a/src/test/java/io/floci/aws/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -18,6 +19,7 @@ import java.util.Base64; import java.util.List; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -85,16 +87,7 @@ class SesIdentityNotificationTopicPublishV1IntegrationTest { .extract().jsonPath().getString("Attributes.QueueArn"); assertNotNull(queueArn); - topicArn = given() - .contentType(JSON_10) - .header("Authorization", SNS_AUTH) - .header("X-Amz-Target", "SNS_20100331.CreateTopic") - .body("{\"Name\":\"ses-id-notif-topic\"}") - .when() - .post("/") - .then() - .statusCode(200) - .extract().jsonPath().getString("TopicArn"); + topicArn = createSnsTopic(SNS_AUTH, "ses-id-notif-topic"); assertNotNull(topicArn); given() @@ -256,16 +249,7 @@ class SesIdentityNotificationTopicPublishV1IntegrationTest { void aDeletedBounceTopicIsTakenOutOfTheIdentityAndForwardingTurnsBackOn() { String gone = "id-notif-gone@floci.test"; verifyEmailIdentity(gone); - String goneTopic = given() - .contentType(JSON_10) - .header("Authorization", SNS_AUTH) - .header("X-Amz-Target", "SNS_20100331.CreateTopic") - .body("{\"Name\":\"ses-id-notif-gone-topic\"}") - .when() - .post("/") - .then() - .statusCode(200) - .extract().jsonPath().getString("TopicArn"); + String goneTopic = createSnsTopic(SNS_AUTH, "ses-id-notif-gone-topic"); setIdentityNotificationTopic(gone, "Bounce", goneTopic); setIdentityNotificationTopic(gone, "Complaint", goneTopic); given() @@ -278,15 +262,7 @@ class SesIdentityNotificationTopicPublishV1IntegrationTest { .post("/") .then() .statusCode(200); - given() - .contentType(JSON_10) - .header("Authorization", SNS_AUTH) - .header("X-Amz-Target", "SNS_20100331.DeleteTopic") - .body("{\"TopicArn\":\"" + goneTopic + "\"}") - .when() - .post("/") - .then() - .statusCode(200); + deleteSnsTopic(SNS_AUTH, goneTopic); sendEmail(gone, "bounce@simulator.amazonses.com", "id-notif-gone"); @@ -305,6 +281,152 @@ class SesIdentityNotificationTopicPublishV1IntegrationTest { assertTrue(attributes.contains("true"), attributes); } + @Test + @Order(11) + void aTopicThatDoesNotExistIsRefusedAndTheStoredTopicStays() { + String missing = topicArn + "-missing"; + + setIdentityNotificationTopicRaw(SENDER, "Bounce", + "&SnsTopic=" + URLEncoder.encode(missing, StandardCharsets.UTF_8)) + .statusCode(400) + .body(containsString("Sender")) + .body(containsString("InvalidParameterValue")) + .body(containsString("SNS topic " + missing + " is invalid.")); + + notificationAttributes(SENDER).body(containsString("" + topicArn + "")); + } + + @Test + @Order(12) + void aTopicOfAnotherRegionIsRefused() { + String elsewhereAuth = SNS_AUTH.replace("us-east-1", "us-west-2"); + String elsewhere = createSnsTopic(elsewhereAuth, "ses-id-notif-elsewhere-topic"); + + try { + setIdentityNotificationTopicRaw(SENDER, "Delivery", + "&SnsTopic=" + URLEncoder.encode(elsewhere, StandardCharsets.UTF_8)) + .statusCode(400) + .body(containsString("SNS topic " + elsewhere + " is invalid.")); + } finally { + deleteSnsTopic(elsewhereAuth, elsewhere); + } + } + + @Test + @Order(13) + void aValueThatIsNotATopicArnGetsTheSameMessage() { + setIdentityNotificationTopicRaw(SENDER, "Delivery", "&SnsTopic=not-an-arn") + .statusCode(400) + .body(containsString("SNS topic not-an-arn is invalid.")); + } + + @Test + @Order(14) + void anEmptyTopicIsRefusedAndOnlyAnAbsentOneClears() { + setIdentityNotificationTopicRaw(SENDER, "Complaint", "&SnsTopic=") + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("SNS topic cannot be empty.")); + notificationAttributes(SENDER).body(containsString("" + topicArn + "")); + + setIdentityNotificationTopicRaw(SENDER, "Complaint", "").statusCode(200); + notificationAttributes(SENDER).body(containsString("")); + } + + @Test + @Order(15) + void theTopicIsCheckedBeforeTheIdentity() { + String unknown = "id-notif-unknown@floci.test"; + + setIdentityNotificationTopicRaw(unknown, "Bounce", "&SnsTopic=not-an-arn") + .statusCode(400) + .body(containsString("SNS topic not-an-arn is invalid.")); + setIdentityNotificationTopicRaw(unknown, "Bounce", + "&SnsTopic=" + URLEncoder.encode(topicArn, StandardCharsets.UTF_8)) + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Identity " + unknown + + " is invalid. Must be a verified email address or domain.")); + setIdentityNotificationTopicRaw(SENDER, "Bogus", "&SnsTopic=not-an-arn") + .statusCode(400) + .body(containsString("ValidationError")); + setIdentityNotificationTopicRaw(" " + SENDER, "Bounce", "&SnsTopic=not-an-arn") + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Identity " + SENDER + + " is invalid. Must be a valid email address or domain or identity ARN.")); + } + + @Test + @Order(16) + void theMissingMembersAreReportedTogether() { + given() + .contentType(FORM) + .header("Authorization", SES_AUTH) + .body("Action=SetIdentityNotificationTopic&SnsTopic=not-an-arn&Version=2010-12-01") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("2 validation errors detected: Value at 'identity' " + + "failed to satisfy constraint: Member must not be null; " + + "Value at 'notificationType' failed to satisfy constraint: " + + "Member must not be null")); + } + + private static String createSnsTopic(String auth, String name) { + return given() + .contentType(JSON_10) + .header("Authorization", auth) + .header("X-Amz-Target", "SNS_20100331.CreateTopic") + .body("{\"Name\":\"" + name + "\"}") + .when() + .post("/") + .then() + .statusCode(200) + .extract().jsonPath().getString("TopicArn"); + } + + private static void deleteSnsTopic(String auth, String topicArn) { + given() + .contentType(JSON_10) + .header("Authorization", auth) + .header("X-Amz-Target", "SNS_20100331.DeleteTopic") + .body("{\"TopicArn\":\"" + topicArn + "\"}") + .when() + .post("/") + .then() + .statusCode(200); + } + + private ValidatableResponse setIdentityNotificationTopicRaw(String identity, String notificationType, + String topicParam) { + return given() + .contentType(FORM) + .header("Authorization", SES_AUTH) + .body("Action=SetIdentityNotificationTopic" + + "&Identity=" + URLEncoder.encode(identity, StandardCharsets.UTF_8) + + "&NotificationType=" + notificationType + + topicParam + + "&Version=2010-12-01") + .when() + .post("/") + .then(); + } + + private ValidatableResponse notificationAttributes(String identity) { + return given() + .contentType(FORM) + .header("Authorization", SES_AUTH) + .body("Action=GetIdentityNotificationAttributes&Identities.member.1=" + + URLEncoder.encode(identity, StandardCharsets.UTF_8) + "&Version=2010-12-01") + .when() + .post("/") + .then() + .statusCode(200); + } + private void verifyEmailIdentity(String email) { given() .contentType(FORM) diff --git a/src/test/java/io/floci/aws/services/ses/SesIdentityServiceTest.java b/src/test/java/io/floci/aws/services/ses/SesIdentityServiceTest.java index 6380d0548f..c904de969f 100644 --- a/src/test/java/io/floci/aws/services/ses/SesIdentityServiceTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesIdentityServiceTest.java @@ -49,6 +49,8 @@ class SesIdentityServiceTest { private static final String REGION = "us-east-1"; private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:feedback"; private static final String OTHER_TOPIC = "arn:aws:sns:us-east-1:000000000000:other-feedback"; + private static final Predicate ANY_TOPIC = topic -> true; + private static final Predicate NO_TOPIC = topic -> false; private SesIdentityService service; @BeforeEach @@ -343,11 +345,105 @@ class SesIdentityServiceTest { service.createEmailIdentity(identity, null, null, REGION, null); } + @Test + void setIdentityNotificationTopic_refusesATopicSesCannotPublishToAndKeepsTheStoredOne() { + service.verifyEmailIdentity("alice@example.com", REGION); + service.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION, ANY_TOPIC); + + AwsException e = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + "alice@example.com", "Bounce", OTHER_TOPIC, REGION, NO_TOPIC)); + + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("SNS topic " + OTHER_TOPIC + " is invalid.", e.getMessage()); + assertEquals(400, e.getHttpStatus()); + Identity identity = service.find("alice@example.com", REGION).orElseThrow(); + assertEquals(TOPIC, identity.getNotificationAttributes().get("BounceTopic")); + } + + @ParameterizedTest + @MethodSource("emptyTopics") + void setIdentityNotificationTopic_refusesAnEmptyTopicInsteadOfClearing(String empty) { + service.verifyEmailIdentity("alice@example.com", REGION); + service.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION, ANY_TOPIC); + + AwsException e = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + "alice@example.com", "Bounce", empty, REGION, ANY_TOPIC)); + + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("SNS topic cannot be empty.", e.getMessage()); + Identity identity = service.find("alice@example.com", REGION).orElseThrow(); + assertEquals(TOPIC, identity.getNotificationAttributes().get("BounceTopic")); + } + + static Stream emptyTopics() { + return Stream.of("", " "); + } + + @Test + void setIdentityNotificationTopic_clearsWhenTheTopicIsAbsent() { + service.verifyEmailIdentity("alice@example.com", REGION); + service.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION, ANY_TOPIC); + + service.setIdentityNotificationTopic("alice@example.com", "Bounce", null, REGION, NO_TOPIC); + + Identity identity = service.find("alice@example.com", REGION).orElseThrow(); + assertFalse(identity.getNotificationAttributes().containsKey("BounceTopic")); + } + + @Test + void setIdentityNotificationTopic_reportsTheMissingMembersTogether() { + AwsException both = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + null, null, TOPIC, REGION, NO_TOPIC)); + assertEquals("ValidationError", both.getErrorCode()); + assertEquals("2 validation errors detected: Value at 'identity' failed to satisfy constraint: " + + "Member must not be null; Value at 'notificationType' failed to satisfy constraint: " + + "Member must not be null", both.getMessage()); + + AwsException emptyType = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + "alice@example.com", "", TOPIC, REGION, NO_TOPIC)); + assertEquals("1 validation error detected: Value at 'notificationType' failed to satisfy constraint: " + + "Member must satisfy enum value set: [Bounce, Complaint, Delivery]", emptyType.getMessage()); + } + + @ParameterizedTest + @MethodSource("malformedIdentities") + void setIdentityNotificationTopic_refusesAMalformedIdentityBeforeTheTopic(String malformed) { + AwsException e = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + malformed, "Bounce", TOPIC, REGION, NO_TOPIC)); + + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("Identity " + malformed + + " is invalid. Must be a valid email address or domain or identity ARN.", e.getMessage()); + } + + static Stream malformedIdentities() { + return Stream.of("", " alice@example.com", "alice@example.com "); + } + + @Test + void setIdentityNotificationTopic_checksTheTypeThenTheTopicThenTheIdentity() { + AwsException type = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + "nobody@example.com", "Bogus", TOPIC, REGION, NO_TOPIC)); + assertEquals("ValidationError", type.getErrorCode()); + assertEquals("1 validation error detected: Value at 'notificationType' failed to satisfy constraint: " + + "Member must satisfy enum value set: [Bounce, Complaint, Delivery]", type.getMessage()); + + AwsException topic = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + "nobody@example.com", "Bounce", TOPIC, REGION, NO_TOPIC)); + assertEquals("SNS topic " + TOPIC + " is invalid.", topic.getMessage()); + + AwsException identity = assertThrows(AwsException.class, () -> service.setIdentityNotificationTopic( + "nobody@example.com", "Bounce", TOPIC, REGION, ANY_TOPIC)); + assertEquals("InvalidParameterValue", identity.getErrorCode()); + assertEquals("Identity nobody@example.com is invalid. Must be a verified email address or domain.", + identity.getMessage()); + } + @Test void aRefusedTopicIsTakenOutOfEveryBounceAndComplaintSettingThatNamesIt() { service.verifyEmailIdentity("alice@example.com", REGION); for (String type : List.of("Bounce", "Complaint", "Delivery")) { - service.setIdentityNotificationTopic("alice@example.com", type, TOPIC, REGION); + service.setIdentityNotificationTopic("alice@example.com", type, TOPIC, REGION, ANY_TOPIC); } service.setFeedbackForwardingEnabled("alice@example.com", false, REGION); @@ -363,8 +459,8 @@ class SesIdentityServiceTest { @Test void aSettingNamingAnotherTopicIsKept() { service.verifyEmailIdentity("alice@example.com", REGION); - service.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION); - service.setIdentityNotificationTopic("alice@example.com", "Complaint", OTHER_TOPIC, REGION); + service.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION, ANY_TOPIC); + service.setIdentityNotificationTopic("alice@example.com", "Complaint", OTHER_TOPIC, REGION, ANY_TOPIC); service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION); @@ -376,7 +472,7 @@ class SesIdentityServiceTest { @Test void aTopicNamedOnlyForDeliveriesStaysConfigured() { service.verifyEmailIdentity("alice@example.com", REGION); - service.setIdentityNotificationTopic("alice@example.com", "Delivery", TOPIC, REGION); + service.setIdentityNotificationTopic("alice@example.com", "Delivery", TOPIC, REGION, ANY_TOPIC); service.setFeedbackForwardingEnabled("alice@example.com", false, REGION); service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION); @@ -389,7 +485,7 @@ class SesIdentityServiceTest { @Test void aTopicSetAgainSinceTheRefusalIsKept() { service.verifyEmailIdentity("alice@example.com", REGION); - service.setIdentityNotificationTopic("alice@example.com", "Bounce", OTHER_TOPIC, REGION); + service.setIdentityNotificationTopic("alice@example.com", "Bounce", OTHER_TOPIC, REGION, ANY_TOPIC); service.setFeedbackForwardingEnabled("alice@example.com", false, REGION); service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION); @@ -403,7 +499,7 @@ class SesIdentityServiceTest { return Stream.of( Arguments.of("a topic", (Consumer) identities -> identities.setIdentityNotificationTopic( - "alice@example.com", "Bounce", OTHER_TOPIC, REGION), + "alice@example.com", "Bounce", OTHER_TOPIC, REGION, ANY_TOPIC), (Predicate) identity -> OTHER_TOPIC.equals(identity.getNotificationAttributes().get("BounceTopic"))), Arguments.of("feedback forwarding", @@ -424,7 +520,7 @@ class SesIdentityServiceTest { InMemoryStorage store = Mockito.spy(new InMemoryStorage()); SesIdentityService parked = new SesIdentityService(store, null, Clock.systemUTC()); parked.verifyEmailIdentity("alice@example.com", REGION); - parked.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION); + parked.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION, ANY_TOPIC); CountDownLatch read = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); // The removal parks right after reading the identity, before writing it back. diff --git a/src/test/java/io/floci/aws/services/ses/SesIntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesIntegrationTest.java index c3d6f1ce08..0e8114431b 100644 --- a/src/test/java/io/floci/aws/services/ses/SesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesIntegrationTest.java @@ -357,6 +357,18 @@ class SesIntegrationTest { @Test @Order(17) void setIdentityNotificationTopic() { + // SES refuses a topic that does not exist. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/sns/aws4_request") + .formParam("Action", "CreateTopic") + .formParam("Name", "bounce-topic") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("arn:aws:sns:us-east-1:000000000000:bounce-topic")); + given() .contentType("application/x-www-form-urlencoded") .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") diff --git a/src/test/java/io/floci/aws/services/ses/SesSnsPublishAuthorizationIntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesSnsPublishAuthorizationIntegrationTest.java index 6e40cc8904..e92eb655b3 100644 --- a/src/test/java/io/floci/aws/services/ses/SesSnsPublishAuthorizationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesSnsPublishAuthorizationIntegrationTest.java @@ -186,14 +186,21 @@ class SesSnsPublishAuthorizationIntegrationTest { .body(containsString("" + topicArn + "")); } + /** Probed: SetIdentityNotificationTopic refuses a topic whose policy does not let SES publish. */ @Test - void anotherAccountsTopicWithoutAnSesGrantRefusesTheNotification() { - String topicArn = createTopic(OTHER, "foreign-" + suffix()); + void anIdentityCannotNameATopicThatRefusesSes() { String sender = createSender(); - setIdentityNotificationTopic(sender, "Bounce", topicArn); - - sendEmail(sender, BOUNCE, null); + String closed = createTopic(OWNER, "closed-" + suffix()); + setTopicPolicy(OWNER, closed, rootOnly(closed)); + String foreign = createTopic(OTHER, "foreign-" + suffix()); + for (String topicArn : List.of(closed, foreign)) { + ses(OWNER, "SetIdentityNotificationTopic", + Map.of("Identity", sender, "NotificationType", "Bounce", "SnsTopic", topicArn)) + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("SNS topic " + topicArn + " is invalid.")); + } notificationAttributes(sender).body(containsString("")); }