diff --git a/compatibility-tests/compat-opentofu/main.tf b/compatibility-tests/compat-opentofu/main.tf index c221d350d1..f06446bf13 100644 --- a/compatibility-tests/compat-opentofu/main.tf +++ b/compatibility-tests/compat-opentofu/main.tf @@ -575,10 +575,39 @@ resource "aws_ses_active_receipt_rule_set" "compat" { rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name } +resource "aws_ses_receipt_rule" "compat" { + rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name + name = "floci-compat-rule" + enabled = true + scan_enabled = true + tls_policy = "Optional" + recipients = ["compat@example.com"] + + add_header_action { + header_name = "X-Floci-Compat" + header_value = "true" + position = 1 + } + + sns_action { + topic_arn = aws_sns_topic.events.arn + position = 2 + } + + stop_action { + scope = "RuleSet" + position = 3 + } +} + output "ses_rule_set_name" { value = aws_ses_receipt_rule_set.compat.rule_set_name } +output "ses_receipt_rule_name" { + value = aws_ses_receipt_rule.compat.name +} + # -- GuardDuty ----------------------------------------------------------------- # Detector, per-feature configuration, and organization configuration mirror the # resource set an org security-baseline stack manages. additional_configuration diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.bats index 42eb6e8eb7..41dc28c302 100644 --- a/compatibility-tests/compat-opentofu/test/opentofu.bats +++ b/compatibility-tests/compat-opentofu/test/opentofu.bats @@ -156,6 +156,15 @@ sha256_composite_by_sizes() { run aws_cmd ses describe-active-receipt-rule-set assert_success assert_output --partial "floci-compat-rule-set" + assert_output --partial "X-Floci-Compat" +} + +@test "OpenTofu: SES receipt rule round-trips its actions" { + run aws_cmd ses describe-receipt-rule --rule-set-name floci-compat-rule-set --rule-name floci-compat-rule + assert_success + assert_output --partial "X-Floci-Compat" + assert_output --partial "floci-compat-events" + assert_output --partial "RuleSet" } @test "OpenTofu: DynamoDB table created" { diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tf index 3784a7fb42..68963001e3 100644 --- a/compatibility-tests/compat-terraform/main.tf +++ b/compatibility-tests/compat-terraform/main.tf @@ -665,10 +665,39 @@ resource "aws_ses_active_receipt_rule_set" "compat" { rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name } +resource "aws_ses_receipt_rule" "compat" { + rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name + name = "floci-compat-rule" + enabled = true + scan_enabled = true + tls_policy = "Optional" + recipients = ["compat@example.com"] + + add_header_action { + header_name = "X-Floci-Compat" + header_value = "true" + position = 1 + } + + sns_action { + topic_arn = aws_sns_topic.events.arn + position = 2 + } + + stop_action { + scope = "RuleSet" + position = 3 + } +} + output "ses_rule_set_name" { value = aws_ses_receipt_rule_set.compat.rule_set_name } +output "ses_receipt_rule_name" { + value = aws_ses_receipt_rule.compat.name +} + # -- IAM managed-policy attachment --------------------------------------------- # These policies sit outside the small curated set Floci used to ship, so the # attachments below only succeed once the full AWS managed-policy catalog is seeded. diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.bats index 1c5c64f566..4b038edf6d 100644 --- a/compatibility-tests/compat-terraform/test/terraform.bats +++ b/compatibility-tests/compat-terraform/test/terraform.bats @@ -156,6 +156,15 @@ sha256_composite_by_sizes() { run aws_cmd ses describe-active-receipt-rule-set assert_success assert_output --partial "floci-compat-rule-set" + assert_output --partial "X-Floci-Compat" +} + +@test "Terraform: SES receipt rule round-trips its actions" { + run aws_cmd ses describe-receipt-rule --rule-set-name floci-compat-rule-set --rule-name floci-compat-rule + assert_success + assert_output --partial "X-Floci-Compat" + assert_output --partial "floci-compat-events" + assert_output --partial "RuleSet" } @test "Terraform: DynamoDB table created" { diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReceiptRuleSetTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReceiptRuleSetTest.java index 2bff2075ee..2b3e4945ed 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReceiptRuleSetTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReceiptRuleSetTest.java @@ -12,30 +12,42 @@ import software.amazon.awssdk.services.ses.SesClient; import software.amazon.awssdk.services.ses.model.AlreadyExistsException; import software.amazon.awssdk.services.ses.model.CannotDeleteException; import software.amazon.awssdk.services.ses.model.DescribeActiveReceiptRuleSetResponse; +import software.amazon.awssdk.services.ses.model.DescribeReceiptRuleResponse; import software.amazon.awssdk.services.ses.model.DescribeReceiptRuleSetResponse; +import software.amazon.awssdk.services.ses.model.InvalidSnsTopicException; import software.amazon.awssdk.services.ses.model.ListReceiptRuleSetsResponse; +import software.amazon.awssdk.services.ses.model.ReceiptRule; +import software.amazon.awssdk.services.ses.model.RuleDoesNotExistException; import software.amazon.awssdk.services.ses.model.RuleSetDoesNotExistException; +import software.amazon.awssdk.services.ses.model.TlsPolicy; +import software.amazon.awssdk.services.sns.SnsClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** - * SDK compatibility test for the SES V1 receipt-rule-set actions. Floci stores rule sets inertly - * (no rules, no mail routing), but the management API must still round-trip through the real AWS SDK - * client — the same surface Terraform's {@code aws_ses_receipt_rule_set} / - * {@code aws_ses_active_receipt_rule_set} drive — including AWS error mapping and idempotent delete. + * SDK compatibility test for the SES V1 receipt-rule-set and receipt-rule actions, the surface + * Terraform's {@code aws_ses_receipt_rule_set} / {@code aws_ses_active_receipt_rule_set} / + * {@code aws_ses_receipt_rule} drive. Rule sets and rules are stored without routing any mail, + * but AWS error mapping, ordering semantics (front insert, After placement, + * SetReceiptRulePosition), full-replace update, idempotent deletes, and local validation of + * action targets all follow behavior probed against real AWS. */ -@DisplayName("SES V1 ReceiptRuleSet") +@DisplayName("SES V1 ReceiptRuleSet and ReceiptRule") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class SesReceiptRuleSetTest { private static SesClient ses; + private static SnsClient sns; private static String ruleSet; + private static String topicArn; @BeforeAll static void setup() { ses = TestFixtures.sesClient(); + sns = TestFixtures.snsClient(); ruleSet = "sdk-v1-rule-set-" + TestFixtures.uniqueName(); + topicArn = sns.createTopic(b -> b.name("sdk-v1-receipt-rule-topic")).topicArn(); } @AfterAll @@ -43,16 +55,26 @@ class SesReceiptRuleSetTest { if (ses != null) { try { ses.setActiveReceiptRuleSet(b -> { }); - } catch (RuntimeException ignored) { - // best-effort: clearing the active rule set + } catch (RuntimeException e) { + System.err.println("Best-effort clearing of the active rule set failed: " + e.getMessage()); } try { ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); - } catch (RuntimeException ignored) { - // best-effort: removing the throwaway rule set + } catch (RuntimeException e) { + System.err.println("Best-effort cleanup of rule set " + ruleSet + + " failed (its rules cascade with it): " + e.getMessage()); } ses.close(); } + if (sns != null) { + try { + sns.deleteTopic(b -> b.topicArn(topicArn)); + } catch (RuntimeException e) { + System.err.println("Best-effort cleanup of topic " + topicArn + + " failed: " + e.getMessage()); + } + sns.close(); + } } @Test @@ -62,7 +84,7 @@ class SesReceiptRuleSetTest { DescribeReceiptRuleSetResponse d = ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet)); assertThat(d.metadata().name()).isEqualTo(ruleSet); assertThat(d.metadata().createdTimestamp()).isNotNull(); - assertThat(d.rules()).isEmpty(); // stored-but-inert: never holds rules + assertThat(d.rules()).isEmpty(); // no rules yet } @Test @@ -81,11 +103,111 @@ class SesReceiptRuleSetTest { @Test @Order(4) + void createRuleAndDescribe_roundTripsActions() { + ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r + .name("rich") + .enabled(true) + .tlsPolicy(TlsPolicy.REQUIRE) + .scanEnabled(true) + .recipients("probe@example.com", "other@example.org") + .actions( + a -> a.addHeaderAction(h -> h.headerName("X-Floci").headerValue("v1")), + a -> a.snsAction(s -> s.topicArn(topicArn)), + a -> a.stopAction(s -> s.scope("RuleSet"))))); + + DescribeReceiptRuleResponse described = ses.describeReceiptRule( + b -> b.ruleSetName(ruleSet).ruleName("rich")); + ReceiptRule rule = described.rule(); + assertThat(rule.enabled()).isTrue(); + assertThat(rule.tlsPolicy()).isEqualTo(TlsPolicy.REQUIRE); + assertThat(rule.scanEnabled()).isTrue(); + // Recipients come back sorted; actions keep their submitted order and the SNS action + // picks up the UTF-8 encoding default (probed against real AWS). + assertThat(rule.recipients()).containsExactly("other@example.org", "probe@example.com"); + assertThat(rule.actions()).hasSize(3); + assertThat(rule.actions().get(0).addHeaderAction().headerName()).isEqualTo("X-Floci"); + assertThat(rule.actions().get(1).snsAction().encodingAsString()).isEqualTo("UTF-8"); + assertThat(rule.actions().get(2).stopAction().scopeAsString()).isEqualTo("RuleSet"); + } + + @Test + @Order(5) + void createRuleOrdering_frontInsertAndAfter() { + ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r.name("first"))); + ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r.name("middle")).after("first")); + + DescribeReceiptRuleSetResponse described = ses.describeReceiptRuleSet( + b -> b.ruleSetName(ruleSet)); + assertThat(described.rules()).extracting(ReceiptRule::name) + .containsExactly("first", "middle", "rich"); + } + + @Test + @Order(6) + void duplicateRuleCreate_andUnknownRules_mapToTypedExceptions() { + assertThatThrownBy(() -> ses.createReceiptRule( + b -> b.ruleSetName(ruleSet).rule(r -> r.name("rich")))) + .isInstanceOf(AlreadyExistsException.class) + .hasMessageContaining("Rule already exists: rich"); + + assertThatThrownBy(() -> ses.describeReceiptRule( + b -> b.ruleSetName(ruleSet).ruleName("ghost"))) + .isInstanceOf(RuleDoesNotExistException.class) + .hasMessageContaining("Rule does not exist: ghost"); + + assertThatThrownBy(() -> ses.createReceiptRule( + b -> b.ruleSetName("sdk-v1-nope").rule(r -> r.name("r")))) + .isInstanceOf(RuleSetDoesNotExistException.class); + } + + @Test + @Order(7) + void ruleWithMissingTopic_failsWithInvalidSnsTopic() { + assertThatThrownBy(() -> ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r + .name("snsneg") + .actions(a -> a.snsAction(s -> s.topicArn( + "arn:aws:sns:us-east-1:000000000000:sdk-v1-no-such-topic")))))) + .isInstanceOf(InvalidSnsTopicException.class) + .hasMessageContaining("Could not publish to SNS topic"); + } + + @Test + @Order(8) + void updateRule_isFullReplace_andSetPositionMovesToFront() { + ses.updateReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r.name("rich"))); + + ReceiptRule updated = ses.describeReceiptRule( + b -> b.ruleSetName(ruleSet).ruleName("rich")).rule(); + assertThat(updated.enabled()).isFalse(); + assertThat(updated.tlsPolicy()).isEqualTo(TlsPolicy.OPTIONAL); + assertThat(updated.actions()).isEmpty(); + assertThat(updated.recipients()).isEmpty(); + + ses.setReceiptRulePosition(b -> b.ruleSetName(ruleSet).ruleName("rich")); + assertThat(ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet)).rules()) + .extracting(ReceiptRule::name) + .containsExactly("rich", "first", "middle"); + } + + @Test + @Order(9) + void deleteRule_isIdempotent() { + ses.deleteReceiptRule(b -> b.ruleSetName(ruleSet).ruleName("middle")); + ses.deleteReceiptRule(b -> b.ruleSetName(ruleSet).ruleName("middle")); + assertThat(ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet)).rules()) + .extracting(ReceiptRule::name) + .containsExactly("rich", "first"); + } + + @Test + @Order(10) void setActive_thenDescribeActive() { ses.setActiveReceiptRuleSet(b -> b.ruleSetName(ruleSet)); DescribeActiveReceiptRuleSetResponse a = ses.describeActiveReceiptRuleSet(b -> { }); assertThat(a.metadata()).isNotNull(); assertThat(a.metadata().name()).isEqualTo(ruleSet); + // The active describe renders the set's remaining rules too. + assertThat(a.rules()).extracting(ReceiptRule::name).containsExactly("rich", "first"); // The active rule set can't be deleted (matches AWS) — a caller must unset it first. assertThatThrownBy(() -> ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet))) @@ -93,14 +215,14 @@ class SesReceiptRuleSetTest { } @Test - @Order(5) + @Order(11) void describeNonExistent_throwsRuleSetDoesNotExist() { assertThatThrownBy(() -> ses.describeReceiptRuleSet(b -> b.ruleSetName("sdk-v1-nope"))) .isInstanceOf(RuleSetDoesNotExistException.class); } @Test - @Order(6) + @Order(12) void unsetActive_leavesNoActiveRuleSet() { ses.setActiveReceiptRuleSet(b -> { }); // no name clears the active rule set DescribeActiveReceiptRuleSetResponse a = ses.describeActiveReceiptRuleSet(b -> { }); @@ -108,8 +230,8 @@ class SesReceiptRuleSetTest { } @Test - @Order(7) - void delete_isIdempotent() { + @Order(13) + void delete_isIdempotent_andCascadesRemainingRules() { ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); // Deleting an already-absent rule set still succeeds (matches AWS). ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); diff --git a/docs/services/ses.md b/docs/services/ses.md index 9665a0ca45..012051a1eb 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -64,11 +64,16 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an | `UpdateConfigurationSetReputationMetricsEnabled` | Enable or disable reputation metrics for a configuration set | | `PutConfigurationSetDeliveryOptions` | Set the TLS policy (delivery options) for a configuration set | | `CreateReceiptRuleSet` | Create a receipt rule set (stored inertly) | -| `DescribeReceiptRuleSet` | Read a receipt rule set (Rules always empty) | +| `DescribeReceiptRuleSet` | Read a receipt rule set and its rules | | `ListReceiptRuleSets` | List receipt rule sets | -| `DeleteReceiptRuleSet` | Delete a receipt rule set (idempotent) | +| `DeleteReceiptRuleSet` | Delete a receipt rule set (idempotent, cascades rules) | | `SetActiveReceiptRuleSet` | Mark a rule set active, or clear the active one | | `DescribeActiveReceiptRuleSet` | Read the active receipt rule set | +| `CreateReceiptRule` | Add a receipt rule (stored inertly, action targets validated) | +| `DescribeReceiptRule` | Read a receipt rule | +| `UpdateReceiptRule` | Replace a receipt rule in place | +| `DeleteReceiptRule` | Delete a receipt rule (idempotent) | +| `SetReceiptRulePosition` | Reorder a receipt rule within its set | ## Configuration @@ -175,7 +180,7 @@ curl $AWS_ENDPOINT_URL/_aws/ses - `SendEmail` stores the text body or the HTML body as the captured message body. - `SetIdentityNotificationTopic` publishes to the configured topic on a Bounce/Complaint/Delivery event (triggered via the mailbox simulator addresses or the suppression list), independent of any configuration set. The payload uses the legacy format (`notificationType`, no `mail.tags`, headers only when `SetIdentityHeadersInNotificationsEnabled` is on). - Identity (sending authorization) policies are stored and returned as metadata: the policy document, the per-identity limit of 20, and the create/update/delete error shapes match AWS, but Floci does not evaluate policy authorization (Principal-account existence, Resource-ARN match) or gate sending on it. -- 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. +- 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 filters, `CloneReceiptRuleSet`, and `ReorderReceiptRuleSet` 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` 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. 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 b8ab737cda..231977f3db 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 @@ -576,7 +576,9 @@ public class AwsQueryController { "UpdateConfigurationSetReputationMetricsEnabled", "PutConfigurationSetDeliveryOptions", "CreateReceiptRuleSet", "DescribeReceiptRuleSet", "ListReceiptRuleSets", - "DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet" + "DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet", + "CreateReceiptRule", "DescribeReceiptRule", "UpdateReceiptRule", + "DeleteReceiptRule", "SetReceiptRulePosition" ); private static final Set COGNITO_ACTIONS = Set.of( diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 55a5f27125..08eb61e83a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -482,6 +482,22 @@ public class LambdaService implements ResourceProvider { "Function not found: " + functionName, 404)); } + public boolean functionExists(String region, String functionName) { + try { + // The qualifier-aware read resolves an embedded alias/version and enforces the ARN's + // region, so a qualified reference to a nonexistent version does not pass just + // because the base function exists. + getFunction(region, functionName, null); + return true; + } catch (AwsException e) { + // Covers both a plain miss and a name/ARN the resolver rejects: the exception is + // this predicate's negative answer, logged at debug so a surprising false stays + // diagnosable without turning ordinary existence misses into log noise. + LOG.debugv("functionExists({0}, {1}) is false: {2}", region, functionName, e.getMessage()); + return false; + } + } + /** * Reads a function, honouring a {@code Qualifier} that selects a published version or an alias. * diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 490e919417..b62c1a444a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -3552,6 +3552,10 @@ public class S3Service implements Resettable, ResourceProvider { } } + public boolean bucketExists(String bucketName) { + return resolveBucket(bucketName).isPresent(); + } + /** * Resolves a bucket for existence/access. With {@code globalBucketNamespace} enabled, the * lookup spans every account's partition (AWS bucket names are globally unique and reachable 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 bd486cb536..1d3e90ab7a 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 @@ -16,6 +16,8 @@ import io.github.hectorvent.floci.services.ses.model.EventDestination; import io.github.hectorvent.floci.services.ses.model.Identity; import io.github.hectorvent.floci.services.ses.model.KinesisFirehoseDestination; import io.github.hectorvent.floci.services.ses.model.MessageTag; +import io.github.hectorvent.floci.services.ses.model.ReceiptAction; +import io.github.hectorvent.floci.services.ses.model.ReceiptRule; import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.SnsDestination; import com.fasterxml.jackson.databind.JsonNode; @@ -27,6 +29,7 @@ import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -129,6 +132,11 @@ public class SesQueryHandler { case "DeleteReceiptRuleSet" -> handleDeleteReceiptRuleSet(params, region); case "SetActiveReceiptRuleSet" -> handleSetActiveReceiptRuleSet(params, region); case "DescribeActiveReceiptRuleSet" -> handleDescribeActiveReceiptRuleSet(region); + case "CreateReceiptRule" -> handleCreateReceiptRule(params, region); + case "DescribeReceiptRule" -> handleDescribeReceiptRule(params, region); + case "UpdateReceiptRule" -> handleUpdateReceiptRule(params, region); + case "DeleteReceiptRule" -> handleDeleteReceiptRule(params, region); + case "SetReceiptRulePosition" -> handleSetReceiptRulePosition(params, region); default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported by SES.", AwsNamespaces.SES, 400); }; @@ -978,7 +986,7 @@ public class SesQueryHandler { ReceiptRuleSet ruleSet = sesService.describeReceiptRuleSet(getParam(params, "RuleSetName"), region); XmlBuilder xml = new XmlBuilder(); writeReceiptRuleSetMetadata(xml, ruleSet); - xml.start("Rules").end("Rules"); + writeReceiptRules(xml, ruleSet.getRules()); return Response.ok(AwsQueryResponse.envelope( "DescribeReceiptRuleSet", AwsNamespaces.SES, xml.build())).build(); } @@ -1014,12 +1022,188 @@ public class SesQueryHandler { // When no rule set is active AWS returns an empty result (no Metadata element). if (active != null) { writeReceiptRuleSetMetadata(xml, active); - xml.start("Rules").end("Rules"); + writeReceiptRules(xml, active.getRules()); } return Response.ok(AwsQueryResponse.envelope( "DescribeActiveReceiptRuleSet", AwsNamespaces.SES, xml.build())).build(); } + private Response handleCreateReceiptRule(MultivaluedMap params, String region) { + sesService.createReceiptRule(getParam(params, "RuleSetName"), parseReceiptRule(params), + getParam(params, "After"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "CreateReceiptRule", AwsNamespaces.SES)).build(); + } + + private Response handleDescribeReceiptRule(MultivaluedMap params, String region) { + ReceiptRule rule = sesService.describeReceiptRule(getParam(params, "RuleSetName"), + getParam(params, "RuleName"), region); + XmlBuilder xml = new XmlBuilder(); + writeReceiptRule(xml, rule, "Rule"); + return Response.ok(AwsQueryResponse.envelope( + "DescribeReceiptRule", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleUpdateReceiptRule(MultivaluedMap params, String region) { + sesService.updateReceiptRule(getParam(params, "RuleSetName"), parseReceiptRule(params), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "UpdateReceiptRule", AwsNamespaces.SES)).build(); + } + + private Response handleDeleteReceiptRule(MultivaluedMap params, String region) { + sesService.deleteReceiptRule(getParam(params, "RuleSetName"), + getParam(params, "RuleName"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "DeleteReceiptRule", AwsNamespaces.SES)).build(); + } + + private Response handleSetReceiptRulePosition(MultivaluedMap params, String region) { + sesService.setReceiptRulePosition(getParam(params, "RuleSetName"), + getParam(params, "RuleName"), getParam(params, "After"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "SetReceiptRulePosition", AwsNamespaces.SES)).build(); + } + + private ReceiptRule parseReceiptRule(MultivaluedMap params) { + ReceiptRule rule = new ReceiptRule(); + rule.setName(getParam(params, "Rule.Name")); + // Absent booleans stay false, matching the AWS defaults a minimal create gets. + rule.setEnabled(parseXsdBoolean(params, "Rule.Enabled")); + rule.setScanEnabled(parseXsdBoolean(params, "Rule.ScanEnabled")); + rule.setTlsPolicy(getParam(params, "Rule.TlsPolicy")); + rule.setRecipients(extractMembers(params, "Rule.Recipients")); + // Index tokens are collected from the submitted keys rather than counted up sequentially: + // an action serialized as an empty structure contributes no keys at all, so the list can + // arrive with gaps (e.g. member.2 only). Probing pinned AWS's exact semantics: tokens are + // grouped by numeric value, ordered by (length, then lexicographically), and the i-th + // token must parse to i, or the padded empty slot is rejected because it carries no + // action type. A leading-zero token such as member.01 is therefore VALID on its own, and + // must be parsed under its original spelling rather than a rebuilt canonical one. + List actions = new ArrayList<>(); + int position = 1; + for (String token : receiptActionIndexTokens(params)) { + if (Integer.parseInt(token) != position) { + throw new AwsException("InvalidParameterValue", + "Exactly one action type must be specified for each ReceiptAction", 400); + } + ReceiptAction action = parseReceiptAction(params, "Rule.Actions.member." + token + "."); + if (action != null) { + actions.add(action); + position++; + } + } + rule.setActions(actions); + return rule; + } + + private List receiptActionIndexTokens(MultivaluedMap params) { + String prefix = "Rule.Actions.member."; + Map byValue = new java.util.HashMap<>(); + for (String key : params.keySet()) { + if (!key.startsWith(prefix)) { + continue; + } + int dot = key.indexOf('.', prefix.length()); + if (dot < 0) { + continue; + } + String token = key.substring(prefix.length(), dot); + // ASCII digits only: Character.isDigit also accepts non-ASCII Unicode digits, which + // no AWS Query index grammar does; such a key is skipped like any unmodeled param. + if (token.isEmpty() || !token.chars().allMatch(c -> c >= '0' && c <= '9')) { + continue; + } + // A digit run that overflows int implies an index far beyond any contiguous list, + // which AWS's gap padding turns into the empty-slot rejection. + if (token.length() > 9) { + throw new AwsException("InvalidParameterValue", + "Exactly one action type must be specified for each ReceiptAction", 400); + } + int value = Integer.parseInt(token); + if (value == 0) { + // Probed: AWS rejects member.0 outright. + throw new AwsException("MalformedInput", "0 is not a valid index", 400); + } + // Two spellings of the same numeric index keep one struct on AWS too; the probe + // showed the padded spelling winning, so prefer the longer token deterministically. + String existing = byValue.get(value); + if (existing == null || token.length() > existing.length() + || (token.length() == existing.length() && token.compareTo(existing) > 0)) { + byValue.put(value, token); + } + } + List tokens = new ArrayList<>(byValue.values()); + tokens.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())); + return tokens; + } + + private ReceiptAction parseReceiptAction(MultivaluedMap params, String prefix) { + ReceiptAction parsed = null; + for (Map.Entry> type : ReceiptAction.ACTION_FIELDS.entrySet()) { + ReceiptAction action = null; + for (String field : type.getValue()) { + String value = getParam(params, prefix + type.getKey() + "." + field); + if (value != null) { + if (action == null) { + action = new ReceiptAction(type.getKey()); + } + action.getProperties().put(field, value); + } + } + if (action != null) { + if (parsed != null) { + // Probed: a member carrying two action types is rejected, not truncated. + throw new AwsException("InvalidParameterValue", + "Exactly one action type must be specified for each ReceiptAction", 400); + } + parsed = action; + } + } + return parsed; + } + + private void writeReceiptRules(XmlBuilder xml, List rules) { + xml.start("Rules"); + for (ReceiptRule rule : rules) { + writeReceiptRule(xml, rule, "member"); + } + xml.end("Rules"); + } + + private void writeReceiptRule(XmlBuilder xml, ReceiptRule rule, String tag) { + xml.start(tag); + xml.elem("Name", rule.getName()); + xml.elem("Enabled", String.valueOf(rule.isEnabled())); + xml.elem("TlsPolicy", rule.getTlsPolicy()); + // AWS omits Recipients entirely when empty but always renders Actions, even as an empty + // list; recipients come back sorted regardless of the order they were sent in (probed). + if (!rule.getRecipients().isEmpty()) { + xml.start("Recipients"); + rule.getRecipients().stream().sorted().forEach(r -> xml.elem("member", r)); + xml.end("Recipients"); + } + xml.start("Actions"); + for (ReceiptAction action : rule.getActions()) { + xml.start("member"); + List fields = action.getType() == null + ? null : ReceiptAction.ACTION_FIELDS.get(action.getType()); + if (fields != null) { + xml.start(action.getType()); + for (String field : fields) { + String value = action.property(field); + if (value != null) { + xml.elem(field, value); + } + } + xml.end(action.getType()); + } + xml.end("member"); + } + xml.end("Actions"); + xml.elem("ScanEnabled", String.valueOf(rule.isScanEnabled())); + xml.end(tag); + } + private void writeReceiptRuleSetMetadata(XmlBuilder xml, ReceiptRuleSet ruleSet) { xml.start("Metadata"); writeReceiptRuleSetMetadataFields(xml, ruleSet); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java index 23cd91d3e2..2c6de6e2bd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java @@ -4,7 +4,12 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.ses.model.ReceiptAction; +import io.github.hectorvent.floci.services.ses.model.ReceiptRule; import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; +import io.github.hectorvent.floci.services.sns.SnsService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -15,17 +20,20 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; +import java.util.function.Predicate; import java.util.regex.Pattern; /** - * Owns the SES receipt-rule-set domain (the {@code receiptRuleSetStore}). Extracted from - * {@link SesService} as the first step of the store-based domain split: a leaf - * domain with no cross-service coupling, reached only through the {@code SesService} facade, which - * now delegates its {@code *ReceiptRuleSet*} methods here. + * Owns the SES receipt-rule domain (the {@code receiptRuleSetStore}: rule sets and the rules they + * hold). Extracted from {@link SesService} in the store-based domain split and reached only through + * that facade. Action-target validation couples this domain to {@link S3Service}, + * {@link SnsService}, and {@link LambdaService}, reproducing the checks real SES runs against the + * account; the bounce-sender check arrives as a predicate the facade binds to + * {@code SesIdentityService}, keeping identity resolution out of this class's dependencies. * - *

Floci has no inbound-mail endpoint, so receipt rule sets are stored inertly: a set never holds - * any rules and routes no mail. They exist only so the management API round-trips (enough to unblock - * tools such as Terraform that declare a rule set during bootstrap). + *

Floci has no inbound-mail endpoint, so rule sets and rules are stored inertly: stored rules + * route no mail and their actions never execute. The management API round-trips (enough to unblock + * tools such as Terraform that declare inbound configuration during bootstrap). */ @ApplicationScoped public class SesReceiptRuleService { @@ -39,22 +47,47 @@ public class SesReceiptRuleService { // start/end with an alphanumeric is a service-level "Not a valid ruleSetName" InvalidParameterValue. // Re-verify against live SES (not the model, which can't confirm it) if these ever need to change. private static final Pattern RULE_SET_NAME_CHARS = Pattern.compile("^[a-zA-Z0-9_.-]+$"); + private static final int MAX_RULES_PER_SET = 200; + private static final int MAX_ACTIONS_PER_RULE = 10; + // Probed: a value that is not a well-formed topic/function ARN (a bare name, or an ARN with + // missing segments) gets the "Invalid ..." message before any existence lookup. There is no + // recipient-count limit (101 recipients are accepted). + private static final Pattern SNS_TOPIC_ARN = Pattern.compile("^arn:aws[a-zA-Z-]*:sns:[a-z0-9-]+:\\d{12}:.+$"); + private static final Pattern LAMBDA_FUNCTION_ARN = + Pattern.compile("^arn:aws[a-zA-Z-]*:lambda:[a-z0-9-]+:\\d{12}:function:.+$"); + // RFC 5322 ftext: printable US-ASCII excluding the colon. Real SES rejects anything else with + // "Invalid header name: " (probed 2026-09). + private static final Pattern HEADER_NAME_CHARS = Pattern.compile("^[\\x21-\\x39\\x3B-\\x7E]+$"); private final StorageBackend receiptRuleSetStore; // Serializes receipt-rule-set create (check-then-put) and set-active (clear-then-set) so the - // one-active-per-region invariant and duplicate-name rejection hold under concurrency. + // one-active-per-region invariant and duplicate-name rejection hold under concurrency. Rule + // mutations (create/update/delete/set-position, all read-modify-write on the set record) take + // the same lock. private final Object receiptRuleSetLock = new Object(); + private final S3Service s3Service; + private final SnsService snsService; + private final LambdaService lambdaService; private final Clock clock; @Inject - public SesReceiptRuleService(StorageFactory storageFactory, Clock clock) { + public SesReceiptRuleService(StorageFactory storageFactory, S3Service s3Service, + SnsService snsService, LambdaService lambdaService, Clock clock) { this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json", new TypeReference>() {}); + this.s3Service = s3Service; + this.snsService = snsService; + this.lambdaService = lambdaService; this.clock = clock; } - SesReceiptRuleService(StorageBackend receiptRuleSetStore, Clock clock) { + SesReceiptRuleService(StorageBackend receiptRuleSetStore, + S3Service s3Service, SnsService snsService, LambdaService lambdaService, + Clock clock) { this.receiptRuleSetStore = receiptRuleSetStore; + this.s3Service = s3Service; + this.snsService = snsService; + this.lambdaService = lambdaService; this.clock = clock; } @@ -139,6 +172,384 @@ public class SesReceiptRuleService { } } + public void createReceiptRule(String ruleSetName, ReceiptRule rule, String after, String region, + Predicate verifiedSender) { + requireRuleSetName(ruleSetName); + List violations = new ArrayList<>(); + collectRuleNameParamViolations(after, "after", violations); + collectRuleShapeViolations(rule, violations); + throwViolations(violations); + requireValidRuleName(rule.getName()); + synchronized (receiptRuleSetLock) { + ReceiptRuleSet ruleSet = requireRuleSet(ruleSetName, region); + List rules = new ArrayList<>(ruleSet.getRules()); + if (rules.stream().anyMatch(r -> rule.getName().equals(r.getName()))) { + throw new AwsException("AlreadyExists", "Rule already exists: " + rule.getName(), 400); + } + if (rules.size() >= MAX_RULES_PER_SET) { + // Probed: the 201st rule in a set is rejected. + throw new AwsException("LimitExceeded", "Too many rules", 400); + } + // AWS inserts at the FRONT when After is absent (probed); After places the rule + // immediately behind the named one. + int index = after == null ? 0 : indexOfRule(rules, after) + 1; + validateActionTargets(rule, region, verifiedSender); + applyRuleDefaults(rule); + rules.add(index, rule); + replaceRules(ruleSet, rules, ruleSetName, region); + } + LOG.infov("Created SES receipt rule {0} in rule set {1} ({2})", rule.getName(), ruleSetName, region); + } + + public ReceiptRule describeReceiptRule(String ruleSetName, String ruleName, String region) { + requireRuleSetName(ruleSetName); + requireRuleNameParam(ruleName, "ruleName"); + ReceiptRuleSet ruleSet = requireRuleSet(ruleSetName, region); + List rules = ruleSet.getRules(); + return rules.get(indexOfRule(rules, ruleName)); + } + + public void updateReceiptRule(String ruleSetName, ReceiptRule rule, String region, + Predicate verifiedSender) { + requireRuleSetName(ruleSetName); + List violations = new ArrayList<>(); + collectRuleShapeViolations(rule, violations); + throwViolations(violations); + requireValidRuleName(rule.getName()); + synchronized (receiptRuleSetLock) { + ReceiptRuleSet ruleSet = requireRuleSet(ruleSetName, region); + List rules = new ArrayList<>(ruleSet.getRules()); + // AWS replaces the whole rule in place (omitted members reset to their defaults) and + // keeps its position; an unknown name is an error, so update cannot rename. + int index = indexOfRule(rules, rule.getName()); + validateActionTargets(rule, region, verifiedSender); + applyRuleDefaults(rule); + rules.set(index, rule); + replaceRules(ruleSet, rules, ruleSetName, region); + } + LOG.infov("Updated SES receipt rule {0} in rule set {1} ({2})", rule.getName(), ruleSetName, region); + } + + public void deleteReceiptRule(String ruleSetName, String ruleName, String region) { + requireRuleSetName(ruleSetName); + requireRuleNameParam(ruleName, "ruleName"); + synchronized (receiptRuleSetLock) { + // The rule set must exist, but deleting an absent rule is idempotent (probed). + ReceiptRuleSet ruleSet = requireRuleSet(ruleSetName, region); + List rules = new ArrayList<>(ruleSet.getRules()); + if (rules.removeIf(r -> ruleName.equals(r.getName()))) { + replaceRules(ruleSet, rules, ruleSetName, region); + } + } + LOG.infov("Deleted SES receipt rule {0} from rule set {1} ({2})", ruleName, ruleSetName, region); + } + + public void setReceiptRulePosition(String ruleSetName, String ruleName, String after, String region) { + requireRuleSetName(ruleSetName); + requireRuleNamePresent(ruleName); + List violations = new ArrayList<>(); + collectRuleNameParamViolations(ruleName, "ruleName", violations); + collectRuleNameParamViolations(after, "after", violations); + throwViolations(violations); + requireValidRuleName(ruleName); + synchronized (receiptRuleSetLock) { + ReceiptRuleSet ruleSet = requireRuleSet(ruleSetName, region); + List rules = new ArrayList<>(ruleSet.getRules()); + int index = indexOfRule(rules, ruleName); + if (ruleName.equals(after)) { + // AWS answers 200 for a rule positioned after itself (probed); nothing moves. + return; + } + if (after != null) { + indexOfRule(rules, after); + } + ReceiptRule moved = rules.remove(index); + int target = after == null ? 0 : indexOfRule(rules, after) + 1; + rules.add(target, moved); + replaceRules(ruleSet, rules, ruleSetName, region); + } + LOG.infov("Positioned SES receipt rule {0} in rule set {1} ({2})", ruleName, ruleSetName, region); + } + + /** + * Swaps in a freshly built rules list and persists the set. Mutations never touch the list a + * previously returned rule set holds: the storage backends hand out live object references, so + * a describe caller may still be iterating the old list after the lock is released. + */ + private void replaceRules(ReceiptRuleSet ruleSet, List rules, + String ruleSetName, String region) { + ruleSet.setRules(rules); + receiptRuleSetStore.put(receiptRuleSetKey(region, ruleSetName), ruleSet); + } + + private ReceiptRuleSet requireRuleSet(String name, String region) { + return receiptRuleSetStore.get(receiptRuleSetKey(region, name)) + .orElseThrow(() -> ruleSetDoesNotExist(name)); + } + + private static int indexOfRule(List rules, String name) { + for (int i = 0; i < rules.size(); i++) { + if (name.equals(rules.get(i).getName())) { + return i; + } + } + throw new AwsException("RuleDoesNotExist", "Rule does not exist: " + name, 400); + } + + /** + * The Smithy-model layer of rule validation, reproduced from probing real SES: violations + * across the rule name, TlsPolicy, and every action member collect into one + * {@code ValidationError} ("N validation errors detected: ...; ..."). A type's required + * members are enforced whenever the action carries any member at all; an action struct with + * no members never reaches this layer, because it serializes to no Query keys and AWS then + * rejects the padded empty slot in the parser (probed). + */ + private static void collectRuleShapeViolations(ReceiptRule rule, List violations) { + String name = rule.getName(); + if (name == null || name.isEmpty()) { + violations.add(lengthViolation("rule.name")); + violations.add(patternViolation("rule.name")); + } else if (!RULE_SET_NAME_CHARS.matcher(name).matches()) { + violations.add(patternViolation("rule.name")); + } + if (rule.getTlsPolicy() != null && !"Optional".equals(rule.getTlsPolicy()) + && !"Require".equals(rule.getTlsPolicy())) { + violations.add(enumViolation("rule.tlsPolicy", "[Optional, Require]")); + } + int i = 1; + for (ReceiptAction action : rule.getActions()) { + String prefix = "rule.actions." + i + ".member."; + if (action.is("AddHeaderAction")) { + requireMember(violations, action, "HeaderName", prefix + "addHeaderAction.headerName"); + requireMember(violations, action, "HeaderValue", prefix + "addHeaderAction.headerValue"); + } else if (action.is("BounceAction")) { + // Probed order: smtpReplyCode, then sender, then message. + requireMember(violations, action, "SmtpReplyCode", prefix + "bounceAction.smtpReplyCode"); + requireMember(violations, action, "Sender", prefix + "bounceAction.sender"); + requireMember(violations, action, "Message", prefix + "bounceAction.message"); + } else if (action.is("ConnectAction")) { + requireMember(violations, action, "InstanceARN", prefix + "connectAction.instanceARN"); + requireMember(violations, action, "IAMRoleARN", prefix + "connectAction.iAMRoleARN"); + } else if (action.is("WorkmailAction")) { + requireMember(violations, action, "OrganizationArn", prefix + "workmailAction.organizationArn"); + } else if (action.is("LambdaAction")) { + requireMember(violations, action, "FunctionArn", prefix + "lambdaAction.functionArn"); + if (invalidEnum(action, "InvocationType", "RequestResponse", "Event")) { + violations.add(enumViolation(prefix + "lambdaAction.invocationType", + "[RequestResponse, Event]")); + } + } else if (action.is("SNSAction")) { + // Probed order: the encoding enum violation is reported before the missing topic. + if (invalidEnum(action, "Encoding", "Base64", "UTF-8")) { + violations.add(enumViolation(prefix + "sNSAction.encoding", "[Base64, UTF-8]")); + } + requireMember(violations, action, "TopicArn", prefix + "sNSAction.topicArn"); + } else if (action.is("S3Action")) { + requireMember(violations, action, "BucketName", prefix + "s3Action.bucketName"); + } else if (action.is("StopAction")) { + requireMember(violations, action, "Scope", prefix + "stopAction.scope"); + if (invalidEnum(action, "Scope", "RuleSet")) { + violations.add(enumViolation(prefix + "stopAction.scope", "[RuleSet]")); + } + } + i++; + } + } + + private static void throwViolations(List violations) { + if (violations.isEmpty()) { + return; + } + String label = violations.size() == 1 ? "1 validation error detected: " + : violations.size() + " validation errors detected: "; + throw new AwsException("ValidationError", label + String.join("; ", violations), 400); + } + + /** + * Smithy-layer checks for the top-level RuleName and After parameters, which real SES + * validates with the same length and pattern constraints as Rule.Name but under their own + * wire member paths ('ruleName' / 'after', probed on describe, delete, set-position, and + * the create After parameter). An absent parameter is left to the caller. + */ + private static void collectRuleNameParamViolations(String value, String path, List violations) { + if (value == null) { + return; + } + if (value.isEmpty()) { + violations.add(lengthViolation(path)); + violations.add(patternViolation(path)); + } else if (!RULE_SET_NAME_CHARS.matcher(value).matches()) { + violations.add(patternViolation(path)); + } + } + + /** + * Full validation of a required top-level RuleName parameter: presence, then the Smithy + * layers, then the service-level "Not a valid ruleName" boundary check (probed on + * describe and delete). + */ + private static void requireRuleNameParam(String ruleName, String path) { + requireRuleNamePresent(ruleName); + List violations = new ArrayList<>(); + collectRuleNameParamViolations(ruleName, path, violations); + throwViolations(violations); + requireValidRuleName(ruleName); + } + + private static void requireMember(List violations, ReceiptAction action, + String member, String path) { + if (action.property(member) == null) { + violations.add("Value at '" + path + "' failed to satisfy constraint: " + + "Member must not be null"); + } + } + + private static boolean invalidEnum(ReceiptAction action, String member, String... allowed) { + String value = action.property(member); + if (value == null) { + return false; + } + for (String candidate : allowed) { + if (candidate.equals(value)) { + return false; + } + } + return true; + } + + private static String patternViolation(String path) { + return "Value at '" + path + "' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$"; + } + + private static String lengthViolation(String path) { + return "Value at '" + path + "' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1"; + } + + private static String enumViolation(String path, String valueSet) { + return "Value at '" + path + "' failed to satisfy constraint: " + + "Member must satisfy enum value set: " + valueSet; + } + + /** + * Validates every resource an action points at against the local emulator, reproducing the + * checks real SES runs on create/update: any TopicArn must be a publishable SNS topic, an + * S3 bucket must exist, a Lambda function must be invokable, and a bounce sender must be a + * verified identity. Each check fires only when its member is present, matching AWS. + */ + private void validateActionTargets(ReceiptRule rule, String region, Predicate verifiedSender) { + if (rule.getActions().size() > MAX_ACTIONS_PER_RULE) { + // Probed: the 11th action is rejected at the service layer, like the rules-per-set cap. + throw new AwsException("LimitExceeded", "Too many actions", 400); + } + for (int i = 0; i < rule.getActions().size() - 1; i++) { + // Probed: a stop action anywhere but the last position is rejected. + if (rule.getActions().get(i).is("StopAction")) { + throw new AwsException("InvalidParameterValue", + "Stop action, if any, must be placed at the end of the actions list", 400); + } + } + for (ReceiptAction action : rule.getActions()) { + String headerName = action.property("HeaderName"); + if (action.is("AddHeaderAction") && headerName != null + && !HEADER_NAME_CHARS.matcher(headerName).matches()) { + throw new AwsException("InvalidParameterValue", "Invalid header name: " + headerName, 400); + } + // Empty members get their own service-level messages before the existence checks + // (probed: they never reach the "no such resource" family). + String topicArn = action.property("TopicArn"); + if (topicArn != null) { + // The shape check covers the probed empty-string case too (same message). + if (!SNS_TOPIC_ARN.matcher(topicArn).matches()) { + throw new AwsException("InvalidSnsTopic", "Invalid SNS topic: " + topicArn, 400); + } + if (!snsService.topicExists(topicArn, region)) { + throw new AwsException("InvalidSnsTopic", + "Could not publish to SNS topic: " + topicArn, 400); + } + } + String bucketName = action.property("BucketName"); + if (action.is("S3Action") && bucketName != null) { + if (bucketName.isEmpty()) { + throw new AwsException("InvalidParameterValue", "Bucket name must not be empty", 400); + } + if (!s3Service.bucketExists(bucketName)) { + throw new AwsException("InvalidS3Configuration", "No such bucket: " + bucketName, 400); + } + } + String functionArn = action.property("FunctionArn"); + if (action.is("LambdaAction") && functionArn != null) { + if (functionArn.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "Lambda function ARN must not be empty", 400); + } + // A bare function name or malformed ARN gets its own message before the + // existence lookup (probed), so a same-named local function cannot make a + // non-ARN value pass. + if (!LAMBDA_FUNCTION_ARN.matcher(functionArn).matches()) { + throw new AwsException("InvalidLambdaFunction", + "Invalid Lambda function: " + functionArn, 400); + } + if (!lambdaService.functionExists(region, functionArn)) { + throw new AwsException("InvalidLambdaFunction", + "Could not invoke Lambda function: " + functionArn, 400); + } + } + if (action.is("BounceAction")) { + String smtpReplyCode = action.property("SmtpReplyCode"); + if (smtpReplyCode != null && smtpReplyCode.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "Invalid SMTP reply code: " + smtpReplyCode, 400); + } + String message = action.property("Message"); + if (message != null && message.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "Invalid SMTP response message: " + message, 400); + } + String sender = action.property("Sender"); + if (sender != null && !verifiedSender.test(sender)) { + throw new AwsException("InvalidParameterValue", + "Identity is not verified: " + sender, 400); + } + } + } + } + + private static void applyRuleDefaults(ReceiptRule rule) { + if (rule.getTlsPolicy() == null) { + rule.setTlsPolicy("Optional"); + } + for (ReceiptAction action : rule.getActions()) { + // AWS fills in the SNS encoding default on the stored rule (probed: UTF-8 comes back + // from Describe without ever being sent). + if (action.is("SNSAction") && action.property("TopicArn") != null + && action.property("Encoding") == null) { + action.getProperties().put("Encoding", "UTF-8"); + } + } + } + + private static void requireRuleNamePresent(String ruleName) { + // Only an ABSENT parameter takes this error; a supplied empty or whitespace-only value + // falls through to the Smithy length/pattern violations probed under the 'ruleName' path. + if (ruleName == null) { + throw new AwsException("InvalidParameterValue", "RuleName is required.", 400); + } + } + + /** + * The service-level rule name check that runs after the Smithy pattern passes, mirroring + * {@link #requireRuleSetName}: too long or not alphanumeric at both ends. + */ + private static void requireValidRuleName(String name) { + if (name.length() > 64 + || !Character.isLetterOrDigit(name.charAt(0)) + || !Character.isLetterOrDigit(name.charAt(name.length() - 1))) { + throw new AwsException("InvalidParameterValue", "Not a valid ruleName: " + name, 400); + } + } + private void clearActiveReceiptRuleSet(String region) { String prefix = "receiptRuleSet::" + region + "::"; for (ReceiptRuleSet rs : receiptRuleSetStore.scan(k -> k.startsWith(prefix))) { 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 30802b7880..76e106b49b 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 @@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ses.model.Identity; import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; import io.github.hectorvent.floci.services.ses.model.MessageHeader; import io.github.hectorvent.floci.services.ses.model.MessageTag; +import io.github.hectorvent.floci.services.ses.model.ReceiptRule; import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.Topic; import io.github.hectorvent.floci.services.ses.model.TopicPreference; @@ -1282,6 +1283,31 @@ public class SesService { return receiptRuleService.describeActiveReceiptRuleSet(region); } + // The bounce-sender check needs identity state; the rule domain receives it as a predicate + // bound here, keeping SesIdentityService out of its constructor surface. + + public void createReceiptRule(String ruleSetName, ReceiptRule rule, String after, String region) { + receiptRuleService.createReceiptRule(ruleSetName, rule, after, region, + sender -> identityService.isVerifiedSender(sender, region)); + } + + public ReceiptRule describeReceiptRule(String ruleSetName, String ruleName, String region) { + return receiptRuleService.describeReceiptRule(ruleSetName, ruleName, region); + } + + public void updateReceiptRule(String ruleSetName, ReceiptRule rule, String region) { + receiptRuleService.updateReceiptRule(ruleSetName, rule, region, + sender -> identityService.isVerifiedSender(sender, region)); + } + + public void deleteReceiptRule(String ruleSetName, String ruleName, String region) { + receiptRuleService.deleteReceiptRule(ruleSetName, ruleName, region); + } + + public void setReceiptRulePosition(String ruleSetName, String ruleName, String after, String region) { + receiptRuleService.setReceiptRulePosition(ruleSetName, ruleName, after, region); + } + // ──────────────────────── Dedicated IP Pools ──────────────────────── // Storage lives in SesDedicatedIpService; the facade forwards. diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptAction.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptAction.java new file mode 100644 index 0000000000..2b4dc8bd7c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptAction.java @@ -0,0 +1,81 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * One action inside a receipt rule, stored as its wire type name plus the members that were + * actually provided. SES renders only the members a caller set (verified against real AWS: + * an S3Action created with just BucketName and ObjectKeyPrefix describes back exactly those + * two members), so a typed class per action would have to model absent-vs-set anyway; a + * single ordered property map keeps parse, storage, and render symmetric. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReceiptAction { + + /** + * Wire member order per action type, used both to parse the Query request and to render + * the Describe XML. A rule may also carry a completely empty action member with no type + * at all; real SES accepts and stores it, so {@link #type} may be null. + * + *

WorkmailAction is kept for wire compatibility only: Amazon WorkMail reaches end of + * support on 2027-03-31, so the action gets storage and round-trip (matching real SES, which + * accepts even a fabricated organization ARN) but will never get resource validation or + * execution behavior. + */ + public static final Map> ACTION_FIELDS = Map.of( + "AddHeaderAction", List.of("HeaderName", "HeaderValue"), + "BounceAction", List.of("TopicArn", "SmtpReplyCode", "StatusCode", "Message", "Sender"), + "ConnectAction", List.of("InstanceARN", "IAMRoleARN"), + "LambdaAction", List.of("TopicArn", "FunctionArn", "InvocationType"), + "S3Action", List.of("TopicArn", "BucketName", "ObjectKeyPrefix", "KmsKeyArn", "IamRoleArn"), + "SNSAction", List.of("TopicArn", "Encoding"), + "StopAction", List.of("Scope", "TopicArn"), + "WorkmailAction", List.of("TopicArn", "OrganizationArn")); + + @JsonProperty("Type") + private String type; + + @JsonProperty("Properties") + private Map properties = new LinkedHashMap<>(); + + public ReceiptAction() { + } + + public ReceiptAction(String type) { + this.type = type; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Map getProperties() { + if (properties == null) { + properties = new LinkedHashMap<>(); + } + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public String property(String name) { + return getProperties().get(name); + } + + public boolean is(String actionType) { + return actionType.equals(type); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRule.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRule.java new file mode 100644 index 0000000000..d04dcdae18 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRule.java @@ -0,0 +1,85 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReceiptRule { + + @JsonProperty("Name") + private String name; + + @JsonProperty("Enabled") + private boolean enabled; + + @JsonProperty("TlsPolicy") + private String tlsPolicy; + + @JsonProperty("Recipients") + private List recipients = new ArrayList<>(); + + @JsonProperty("ScanEnabled") + private boolean scanEnabled; + + @JsonProperty("Actions") + private List actions = new ArrayList<>(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getTlsPolicy() { + return tlsPolicy; + } + + public void setTlsPolicy(String tlsPolicy) { + this.tlsPolicy = tlsPolicy; + } + + public List getRecipients() { + if (recipients == null) { + recipients = new ArrayList<>(); + } + return recipients; + } + + public void setRecipients(List recipients) { + this.recipients = recipients; + } + + public boolean isScanEnabled() { + return scanEnabled; + } + + public void setScanEnabled(boolean scanEnabled) { + this.scanEnabled = scanEnabled; + } + + public List getActions() { + if (actions == null) { + actions = new ArrayList<>(); + } + return actions; + } + + public void setActions(List actions) { + this.actions = actions; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRuleSet.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRuleSet.java index 988fe5b907..dc661f640b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRuleSet.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRuleSet.java @@ -5,12 +5,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; /** - * A SES v1 receipt rule set. Floci stores it inertly: there is no inbound-mail endpoint, so a rule - * set never holds any receipt rules and performs no mail routing. It exists only so the management - * API (create / describe / list / delete and set/describe active) round-trips, which is enough to - * unblock tools like Terraform that declare a rule set during bootstrap. + * A SES v1 receipt rule set. Floci stores it inertly: there is no inbound-mail endpoint, so the + * receipt rules a set holds route no mail. The management API (rule set and rule CRUD, rule + * positioning, set/describe active) round-trips, which is enough to unblock tools like Terraform + * that declare receipt rules during bootstrap. */ @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @@ -27,6 +29,9 @@ public class ReceiptRuleSet { @JsonProperty("Active") private boolean active; + @JsonProperty("Rules") + private List rules = new ArrayList<>(); + public ReceiptRuleSet() { } @@ -58,4 +63,15 @@ public class ReceiptRuleSet { public void setActive(boolean active) { this.active = active; } + + public List getRules() { + if (rules == null) { + rules = new ArrayList<>(); + } + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index eb1f62d56f..575b9665a6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -223,6 +223,10 @@ public class SnsService implements Resettable, ResourceProvider { return topicStore.scan(k -> k.startsWith(prefix)); } + public boolean topicExists(String topicArn, String region) { + return topicStore.get(topicKey(region, topicArn)).isPresent(); + } + public Map getTopicAttributes(String topicArn, String region) { String key = topicKey(region, topicArn); Topic topic = topicStore.get(key) diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java index 93a11884f3..b756fec58d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java @@ -1470,6 +1470,27 @@ class LambdaServiceTest { ))); } + @Test + void functionExists_resolvesQualifiersAndRegions() { + service.createFunction(REGION, baseRequest("exists-fn")); + service.publishVersion(REGION, "exists-fn", null); + + assertTrue(service.functionExists(REGION, "exists-fn")); + assertTrue(service.functionExists(REGION, + "arn:aws:lambda:us-east-1:000000000000:function:exists-fn")); + assertTrue(service.functionExists(REGION, + "arn:aws:lambda:us-east-1:000000000000:function:exists-fn:1")); + + assertFalse(service.functionExists(REGION, "ghost-fn")); + // A qualified reference to a version that was never published must not pass just + // because the base function exists. + assertFalse(service.functionExists(REGION, + "arn:aws:lambda:us-east-1:000000000000:function:exists-fn:5")); + // An ARN whose region disagrees with the request region does not resolve. + assertFalse(service.functionExists(REGION, + "arn:aws:lambda:eu-west-1:000000000000:function:exists-fn")); + } + /** * Issue #2958: a published version stored a reference to {@code $LATEST}'s code directory * rather than a copy of the code, and extraction replaces that directory wholesale on every diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java index 7d6d554b38..993c1e7a69 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java @@ -1150,6 +1150,13 @@ class S3ServiceTest { } } + @Test + void bucketExists_reportsPresenceWithoutThrowing() { + s3Service.createBucket("exists-bucket", "us-east-1"); + assertTrue(s3Service.bucketExists("exists-bucket")); + assertFalse(s3Service.bucketExists("ghost-bucket")); + } + @Test void authorizeAnonymousPutObjectIsANoOpWhenEnforceAuthIsOff() { // Default test config has FLOCI_SERVICES_S3_ENFORCE_AUTH unset/false. diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java index 2b196e4466..8074fa2a3f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java @@ -2,28 +2,75 @@ package io.github.hectorvent.floci.services.ses; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.ses.model.ReceiptAction; +import io.github.hectorvent.floci.services.ses.model.ReceiptRule; import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; +import io.github.hectorvent.floci.services.sns.SnsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Unit test for the extracted receipt-rule domain. The payoff of the split: the - * service is constructed with just its own store and a clock — no 14-argument SesService needed. + * service is constructed with just its own store, mocked resource services, and a clock (no + * 14-argument SesService needed). */ class SesReceiptRuleServiceTest { private static final String REGION = "us-east-1"; + private static final Predicate ANY_SENDER_VERIFIED = sender -> true; + private SesReceiptRuleService service; + private S3Service s3Service; + private SnsService snsService; + private LambdaService lambdaService; @BeforeEach void setUp() { - service = new SesReceiptRuleService(new InMemoryStorage<>(), Clock.systemUTC()); + s3Service = mock(S3Service.class); + snsService = mock(SnsService.class); + lambdaService = mock(LambdaService.class); + when(s3Service.bucketExists(anyString())).thenReturn(true); + when(snsService.topicExists(anyString(), anyString())).thenReturn(true); + when(lambdaService.functionExists(anyString(), anyString())).thenReturn(true); + service = new SesReceiptRuleService(new InMemoryStorage<>(), s3Service, snsService, + lambdaService, Clock.systemUTC()); + } + + private static ReceiptRule rule(String name, ReceiptAction... actions) { + ReceiptRule rule = new ReceiptRule(); + rule.setName(name); + rule.setActions(new ArrayList<>(List.of(actions))); + return rule; + } + + private static ReceiptAction action(String type, String... props) { + ReceiptAction action = new ReceiptAction(type); + for (int i = 0; i < props.length; i += 2) { + action.getProperties().put(props[i], props[i + 1]); + } + return action; + } + + private List ruleNames(String ruleSetName) { + return service.describeReceiptRuleSet(ruleSetName, REGION).getRules().stream() + .map(ReceiptRule::getName) + .toList(); } @Test @@ -67,4 +114,469 @@ class SesReceiptRuleServiceTest { () -> service.createReceiptRuleSet("bad name!", REGION)); assertEquals("ValidationError", e.getErrorCode()); } + + // ---- receipt rules ---- + + @Test + void createRule_withoutAfter_insertsAtFront() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule("rules-a", rule("r2"), null, REGION, ANY_SENDER_VERIFIED); + assertEquals(List.of("r2", "r1"), ruleNames("rules-a")); + } + + @Test + void createRule_withAfter_insertsBehindNamedRule() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule("rules-a", rule("r2"), null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule("rules-a", rule("r3"), "r1", REGION, ANY_SENDER_VERIFIED); + assertEquals(List.of("r2", "r1", "r3"), ruleNames("rules-a")); + } + + @Test + void createRule_afterMissing_throwsRuleDoesNotExist() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule("r1"), "ghost", REGION, ANY_SENDER_VERIFIED)); + assertEquals("RuleDoesNotExist", e.getErrorCode()); + assertEquals("Rule does not exist: ghost", e.getMessage()); + } + + @Test + void createRule_duplicate_throwsAlreadyExists() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("AlreadyExists", e.getErrorCode()); + assertEquals("Rule already exists: r1", e.getMessage()); + } + + @Test + void createRule_inMissingSet_throwsRuleSetDoesNotExist() { + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("ghost", rule("r1"), null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("RuleSetDoesNotExist", e.getErrorCode()); + } + + @Test + void createRule_defaults_tlsPolicyOptionalAndDisabled() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + ReceiptRule stored = service.describeReceiptRule("rules-a", "r1", REGION); + assertEquals("Optional", stored.getTlsPolicy()); + assertFalse(stored.isEnabled()); + assertFalse(stored.isScanEnabled()); + assertTrue(stored.getActions().isEmpty()); + } + + @Test + void createRule_emptyName_reportsBothSmithyViolations() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule(""), null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().startsWith("2 validation errors detected: ")); + assertTrue(e.getMessage().contains("Member must have length greater than or equal to 1")); + assertTrue(e.getMessage().contains("^[a-zA-Z0-9_.-]+$")); + } + + @Test + void createRule_badBoundaryName_throwsServiceLevelInvalidParameterValue() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule("-abc"), null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("Not a valid ruleName: -abc", e.getMessage()); + } + + @Test + void createRule_badTlsPolicy_throwsEnumViolation() { + service.createReceiptRuleSet("rules-a", REGION); + ReceiptRule rule = rule("r1"); + rule.setTlsPolicy("Bogus"); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule, null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().contains("'rule.tlsPolicy'")); + assertTrue(e.getMessage().contains("[Optional, Require]")); + } + + @Test + void createRule_missingRequiredActionMembers_collectsViolationsInOrder() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("BounceAction", "SmtpReplyCode", "550")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().startsWith("2 validation errors detected: ")); + assertTrue(e.getMessage().indexOf("bounceAction.sender") + < e.getMessage().indexOf("bounceAction.message")); + } + + @Test + void connectAndWorkmailActions_requireTheirWireRequiredMembers() { + service.createReceiptRuleSet("rules-a", REGION); + + AwsException connect = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("ConnectAction", "InstanceARN", + "arn:aws:connect:us-east-1:000000000000:instance/i-1")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("ValidationError", connect.getErrorCode()); + assertTrue(connect.getMessage().contains("'rule.actions.1.member.connectAction.iAMRoleARN'")); + + AwsException workmail = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("WorkmailAction", "TopicArn", + "arn:aws:sns:us-east-1:000000000000:topic")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("ValidationError", workmail.getErrorCode()); + assertTrue(workmail.getMessage().contains("'rule.actions.1.member.workmailAction.organizationArn'")); + + // A well-formed OrganizationArn is stored without an existence check (probed: real AWS + // accepts a fabricated organization ARN). + service.createReceiptRule("rules-a", + rule("r1", action("WorkmailAction", "OrganizationArn", + "arn:aws:workmail:us-east-1:000000000000:organization/m-1")), + null, REGION, ANY_SENDER_VERIFIED); + assertEquals(1, service.describeReceiptRule("rules-a", "r1", REGION).getActions().size()); + } + + @Test + void presentActionStructs_enforceTheirRequiredMembers() { + // Probed: once an action carries any member, the type's required members are Smithy + // violations (an all-empty struct never reaches this layer; it has no wire keys). + service.createReceiptRuleSet("rules-a", REGION); + + AwsException s3 = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("S3Action", "ObjectKeyPrefix", "inbox/")), + null, REGION, ANY_SENDER_VERIFIED)); + assertTrue(s3.getMessage().contains("'rule.actions.1.member.s3Action.bucketName'")); + + AwsException stop = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("StopAction", "TopicArn", + "arn:aws:sns:us-east-1:000000000000:topic")), + null, REGION, ANY_SENDER_VERIFIED)); + assertTrue(stop.getMessage().contains("'rule.actions.1.member.stopAction.scope'")); + + AwsException sns = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("SNSAction", "Encoding", "UTF-8")), + null, REGION, ANY_SENDER_VERIFIED)); + assertTrue(sns.getMessage().contains("'rule.actions.1.member.sNSAction.topicArn'")); + + // Probed order for a bounce action with only TopicArn: smtpReplyCode, sender, message. + AwsException bounce = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("BounceAction", "TopicArn", + "arn:aws:sns:us-east-1:000000000000:topic")), + null, REGION, ANY_SENDER_VERIFIED)); + assertTrue(bounce.getMessage().startsWith("3 validation errors detected: ")); + assertTrue(bounce.getMessage().indexOf("bounceAction.smtpReplyCode") + < bounce.getMessage().indexOf("bounceAction.sender")); + assertTrue(bounce.getMessage().indexOf("bounceAction.sender") + < bounce.getMessage().indexOf("bounceAction.message")); + } + + @Test + void createRule_lambdaEnumAndSnsEncodingPaths_matchWireCasing() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("SNSAction", "Encoding", "Bogus")), + null, REGION, ANY_SENDER_VERIFIED)); + assertTrue(e.getMessage().contains("'rule.actions.1.member.sNSAction.encoding'")); + assertTrue(e.getMessage().contains("[Base64, UTF-8]")); + } + + @Test + void createRule_missingBucket_throwsInvalidS3Configuration() { + when(s3Service.bucketExists("ghost-bucket")).thenReturn(false); + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("S3Action", "BucketName", "ghost-bucket")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidS3Configuration", e.getErrorCode()); + assertEquals("No such bucket: ghost-bucket", e.getMessage()); + } + + @Test + void createRule_missingTopicOnAnyAction_throwsInvalidSnsTopic() { + String arn = "arn:aws:sns:us-east-1:000000000000:ghost"; + when(snsService.topicExists(arn, REGION)).thenReturn(false); + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("StopAction", "Scope", "RuleSet", "TopicArn", arn)), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidSnsTopic", e.getErrorCode()); + assertEquals("Could not publish to SNS topic: " + arn, e.getMessage()); + } + + @Test + void createRule_missingLambda_throwsInvalidLambdaFunction() { + String arn = "arn:aws:lambda:us-east-1:000000000000:function:ghost"; + when(lambdaService.functionExists(REGION, arn)).thenReturn(false); + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("LambdaAction", "FunctionArn", arn)), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidLambdaFunction", e.getErrorCode()); + assertEquals("Could not invoke Lambda function: " + arn, e.getMessage()); + } + + @Test + void createRule_unverifiedBounceSender_throwsInvalidParameterValue() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("BounceAction", "SmtpReplyCode", "550", + "Message", "m", "Sender", "no-reply@example.com")), + null, REGION, sender -> false)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("Identity is not verified: no-reply@example.com", e.getMessage()); + } + + @Test + void createRule_invalidHeaderName_throwsInvalidParameterValue() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", + rule("r1", action("AddHeaderAction", "HeaderName", "bad header", + "HeaderValue", "v")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("Invalid header name: bad header", e.getMessage()); + } + + @Test + void createRule_snsActionWithTopic_getsUtf8EncodingDefault() { + service.createReceiptRuleSet("rules-a", REGION); + String arn = "arn:aws:sns:us-east-1:000000000000:topic"; + service.createReceiptRule("rules-a", + rule("r1", action("SNSAction", "TopicArn", arn)), null, REGION, ANY_SENDER_VERIFIED); + assertEquals("UTF-8", + service.describeReceiptRule("rules-a", "r1", REGION).getActions().get(0).property("Encoding")); + } + + @Test + void updateRule_replacesWholeRuleAndKeepsPosition() { + service.createReceiptRuleSet("rules-a", REGION); + ReceiptRule original = rule("r1", action("StopAction", "Scope", "RuleSet")); + original.setEnabled(true); + original.setRecipients(new ArrayList<>(List.of("probe@example.com"))); + service.createReceiptRule("rules-a", original, null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule("rules-a", rule("r0"), null, REGION, ANY_SENDER_VERIFIED); + + service.updateReceiptRule("rules-a", rule("r1"), REGION, ANY_SENDER_VERIFIED); + + ReceiptRule updated = service.describeReceiptRule("rules-a", "r1", REGION); + assertFalse(updated.isEnabled()); + assertTrue(updated.getActions().isEmpty()); + assertTrue(updated.getRecipients().isEmpty()); + assertEquals(List.of("r0", "r1"), ruleNames("rules-a")); + } + + @Test + void updateRule_unknownName_throwsRuleDoesNotExist() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.updateReceiptRule("rules-a", rule("ghost"), REGION, ANY_SENDER_VERIFIED)); + assertEquals("RuleDoesNotExist", e.getErrorCode()); + } + + @Test + void deleteRule_isIdempotentButRequiresRuleSet() { + service.createReceiptRuleSet("rules-a", REGION); + service.deleteReceiptRule("rules-a", "ghost", REGION); + + AwsException e = assertThrows(AwsException.class, + () -> service.deleteReceiptRule("ghost-set", "ghost", REGION)); + assertEquals("RuleSetDoesNotExist", e.getErrorCode()); + } + + @Test + void setRulePosition_movesToFrontWithoutAfter_andAfterSelfIsNoOp() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule("rules-a", rule("r2"), null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule("rules-a", rule("r3"), null, REGION, ANY_SENDER_VERIFIED); + assertEquals(List.of("r3", "r2", "r1"), ruleNames("rules-a")); + + service.setReceiptRulePosition("rules-a", "r1", null, REGION); + assertEquals(List.of("r1", "r3", "r2"), ruleNames("rules-a")); + + service.setReceiptRulePosition("rules-a", "r3", "r2", REGION); + assertEquals(List.of("r1", "r2", "r3"), ruleNames("rules-a")); + + service.setReceiptRulePosition("rules-a", "r2", "r2", REGION); + assertEquals(List.of("r1", "r2", "r3"), ruleNames("rules-a")); + } + + @Test + void setRulePosition_missingAfter_throwsRuleDoesNotExist() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + AwsException e = assertThrows(AwsException.class, + () -> service.setReceiptRulePosition("rules-a", "r1", "ghost", REGION)); + assertEquals("RuleDoesNotExist", e.getErrorCode()); + } + + @Test + void emptyActionMembers_getServiceLevelMessages() { + service.createReceiptRuleSet("rules-a", REGION); + + AwsException topic = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("SNSAction", "TopicArn", "")), null, REGION, + ANY_SENDER_VERIFIED)); + assertEquals("InvalidSnsTopic", topic.getErrorCode()); + assertEquals("Invalid SNS topic: ", topic.getMessage()); + + AwsException bucket = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("S3Action", "BucketName", "")), null, REGION, + ANY_SENDER_VERIFIED)); + assertEquals("InvalidParameterValue", bucket.getErrorCode()); + assertEquals("Bucket name must not be empty", bucket.getMessage()); + + AwsException lambda = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("LambdaAction", "FunctionArn", "")), null, REGION, + ANY_SENDER_VERIFIED)); + assertEquals("InvalidParameterValue", lambda.getErrorCode()); + assertEquals("Lambda function ARN must not be empty", lambda.getMessage()); + + // The empty-message check runs before sender verification (probed: an unverified + // sender with an empty Message still reports the message error). + AwsException bounce = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("BounceAction", "SmtpReplyCode", "550", + "Message", "", "Sender", "x@example.com")), null, REGION, s -> false)); + assertEquals("Invalid SMTP response message: ", bounce.getMessage()); + + AwsException replyCode = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("BounceAction", "SmtpReplyCode", "", + "Message", "m", "Sender", "x@example.com")), null, REGION, s -> false)); + assertEquals("Invalid SMTP reply code: ", replyCode.getMessage()); + } + + @Test + void emptyHeaderValue_isAcceptedAndStored() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", + rule("r1", action("AddHeaderAction", "HeaderName", "X-A", "HeaderValue", "")), + null, REGION, ANY_SENDER_VERIFIED); + assertEquals("", service.describeReceiptRule("rules-a", "r1", REGION) + .getActions().get(0).property("HeaderValue")); + } + + @Test + void ruleNameParams_getTwoLayerValidation() { + service.createReceiptRuleSet("rules-a", REGION); + + AwsException pattern = assertThrows(AwsException.class, + () -> service.describeReceiptRule("rules-a", "bad name", REGION)); + assertEquals("ValidationError", pattern.getErrorCode()); + assertTrue(pattern.getMessage().contains("'ruleName'")); + + AwsException boundary = assertThrows(AwsException.class, + () -> service.deleteReceiptRule("rules-a", "a".repeat(65), REGION)); + assertEquals("InvalidParameterValue", boundary.getErrorCode()); + assertEquals("Not a valid ruleName: " + "a".repeat(65), boundary.getMessage()); + + // A SUPPLIED empty value takes the probed Smithy violations, not "RuleName is required.". + AwsException empty = assertThrows(AwsException.class, + () -> service.describeReceiptRule("rules-a", "", REGION)); + assertEquals("ValidationError", empty.getErrorCode()); + assertTrue(empty.getMessage().startsWith("2 validation errors detected: ")); + assertTrue(empty.getMessage().contains("'ruleName'")); + } + + @Test + void afterParam_getsSmithyValidation() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + + AwsException setPos = assertThrows(AwsException.class, + () -> service.setReceiptRulePosition("rules-a", "r1", "bad name", REGION)); + assertEquals("ValidationError", setPos.getErrorCode()); + assertTrue(setPos.getMessage().contains("'after'")); + + AwsException emptyAfter = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule("r2"), "", REGION, ANY_SENDER_VERIFIED)); + assertEquals("ValidationError", emptyAfter.getErrorCode()); + assertTrue(emptyAfter.getMessage().startsWith("2 validation errors detected: ")); + assertTrue(emptyAfter.getMessage().contains("'after'")); + } + + @Test + void describedRulesList_isNotMutatedByLaterWrites() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + + List snapshot = service.describeReceiptRuleSet("rules-a", REGION).getRules(); + service.createReceiptRule("rules-a", rule("r2"), null, REGION, ANY_SENDER_VERIFIED); + service.deleteReceiptRule("rules-a", "r1", REGION); + + assertEquals(List.of("r1"), snapshot.stream().map(ReceiptRule::getName).toList()); + assertEquals(List.of("r2"), ruleNames("rules-a")); + } + + @Test + void nonArnTargets_getInvalidShapeMessages_andRecipientsHaveNoLimit() { + service.createReceiptRuleSet("rules-a", REGION); + + AwsException lambda = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("LambdaAction", "FunctionArn", "bare-name")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidLambdaFunction", lambda.getErrorCode()); + assertEquals("Invalid Lambda function: bare-name", lambda.getMessage()); + + AwsException topic = assertThrows(AwsException.class, () -> service.createReceiptRule( + "rules-a", rule("r1", action("SNSAction", "TopicArn", "bare-name")), + null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("InvalidSnsTopic", topic.getErrorCode()); + assertEquals("Invalid SNS topic: bare-name", topic.getMessage()); + + // No recipient-count limit exists (101 recipients are accepted by real AWS). + ReceiptRule wide = rule("r1"); + for (int i = 0; i < 101; i++) { + wide.getRecipients().add("r" + i + "@example.com"); + } + service.createReceiptRule("rules-a", wide, null, REGION, ANY_SENDER_VERIFIED); + assertEquals(101, service.describeReceiptRule("rules-a", "r1", REGION).getRecipients().size()); + } + + @Test + void createRule_with11Actions_throwsLimitExceeded() { + service.createReceiptRuleSet("rules-a", REGION); + ReceiptRule rule = rule("r1"); + for (int i = 0; i < 11; i++) { + rule.getActions().add(action("AddHeaderAction", "HeaderName", "X-H" + i, "HeaderValue", "v")); + } + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule, null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("LimitExceeded", e.getErrorCode()); + assertEquals("Too many actions", e.getMessage()); + } + + @Test + void createRule_beyond200_throwsLimitExceeded() { + service.createReceiptRuleSet("rules-a", REGION); + for (int i = 1; i <= 200; i++) { + service.createReceiptRule("rules-a", rule("r" + i), null, REGION, ANY_SENDER_VERIFIED); + } + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRule("rules-a", rule("r201"), null, REGION, ANY_SENDER_VERIFIED)); + assertEquals("LimitExceeded", e.getErrorCode()); + assertEquals("Too many rules", e.getMessage()); + } + + @Test + void deleteRuleSet_cascadesRules() { + service.createReceiptRuleSet("rules-a", REGION); + service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + service.deleteReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.describeReceiptRuleSet("rules-a", REGION)); + assertEquals("RuleSetDoesNotExist", e.getErrorCode()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleV1IntegrationTest.java new file mode 100644 index 0000000000..aa68350a3f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleV1IntegrationTest.java @@ -0,0 +1,417 @@ +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.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration tests for the SES V1 Query-protocol receipt-rule actions. Rules are stored inertly + * (no mail routing), but action targets are validated against the local emulator the way real SES + * validates them against the account: SNS topics, S3 buckets, and Lambda functions must exist, and + * a bounce sender must be a verified identity. Error codes, messages, ordering semantics, and the + * SNS encoding default are all probe-confirmed against real AWS (2026-09). + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesReceiptRuleV1IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/email/aws4_request"; + private static final String RS = "floci-v1-rules"; + private static final String BOUNCE_SENDER = "receipt-bounce@floci-rules.example.com"; + + private static String snsTopicArn; + + private static io.restassured.specification.RequestSpecification req(String action) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH) + .formParam("Action", action); + } + + @Test + @Order(1) + void createRuleSet_andRichRule() { + req("CreateReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "rich") + .formParam("Rule.Enabled", "true") + .formParam("Rule.TlsPolicy", "Require") + .formParam("Rule.ScanEnabled", "true") + .formParam("Rule.Recipients.member.1", "probe@example.com") + .formParam("Rule.Recipients.member.2", "other@example.org") + .formParam("Rule.Actions.member.1.AddHeaderAction.HeaderName", "X-Floci") + .formParam("Rule.Actions.member.1.AddHeaderAction.HeaderValue", "v1") + .formParam("Rule.Actions.member.2.StopAction.Scope", "RuleSet") + .when().post("/").then().statusCode(200) + .body(containsString("CreateReceiptRuleResponse")); + } + + @Test + @Order(2) + void describeRule_roundTripsSortedRecipientsAndOrderedActions() { + String body = req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "rich") + .when().post("/").then().statusCode(200) + .body(containsString("rich")) + .body(containsString("true")) + .body(containsString("Require")) + .body(containsString("true")) + .body(containsString("X-Floci")) + .body(containsString("RuleSet")) + .extract().asString(); + // Recipients render sorted regardless of the order they were sent in (probed). + assertTrue(body.indexOf("other@example.org") < body.indexOf("probe@example.com")); + // Actions keep their submitted order. + assertTrue(body.indexOf("AddHeaderAction") < body.indexOf("StopAction")); + } + + @Test + @Order(3) + void createWithoutAfter_insertsAtFront_andAfterInsertsBehind() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "first") + .when().post("/").then().statusCode(200); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "middle") + .formParam("After", "first") + .when().post("/").then().statusCode(200); + + String body = req("DescribeReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200).extract().asString(); + assertTrue(body.indexOf("first") < body.indexOf("middle")); + assertTrue(body.indexOf("middle") < body.indexOf("rich")); + } + + @Test + @Order(4) + void minimalRule_getsAwsDefaults() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "minimal") + .when().post("/").then().statusCode(200); + + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "minimal") + .when().post("/").then().statusCode(200) + .body(containsString("false")) + .body(containsString("Optional")) + .body(containsString("false")) + .body(containsString("")); + } + + @Test + @Order(5) + void duplicateCreate_returnsAlreadyExists() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "rich") + .when().post("/").then().statusCode(400) + .body(containsString("AlreadyExists")) + .body(containsString("Rule already exists: rich")); + } + + @Test + @Order(6) + void missingSetAndMissingRule_errors() { + req("CreateReceiptRule").formParam("RuleSetName", "floci-v1-nope") + .formParam("Rule.Name", "r") + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")); + + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "ghost") + .when().post("/").then().statusCode(400) + .body(containsString("RuleDoesNotExist")) + .body(containsString("Rule does not exist: ghost")); + } + + @Test + @Order(7) + void invalidRuleShape_returnsSmithyValidationError() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "bad!name") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("'rule.name'")) + .body(containsString("^[a-zA-Z0-9_.-]+$")); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "badtls") + .formParam("Rule.TlsPolicy", "Bogus") + .when().post("/").then().statusCode(400) + .body(containsString("'rule.tlsPolicy'")) + .body(containsString("[Optional, Require]")); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "badlambda") + .formParam("Rule.Actions.member.1.LambdaAction.InvocationType", "Event") + .when().post("/").then().statusCode(400) + .body(containsString("'rule.actions.1.member.lambdaAction.functionArn'")) + .body(containsString("Member must not be null")); + } + + @Test + @Order(8) + void actionTargets_areValidatedAgainstLocalServices() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "s3neg") + .formParam("Rule.Actions.member.1.S3Action.BucketName", "floci-no-such-bucket") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidS3Configuration")) + .body(containsString("No such bucket: floci-no-such-bucket")); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "snsneg") + .formParam("Rule.Actions.member.1.SNSAction.TopicArn", + "arn:aws:sns:us-west-2:000000000000:floci-no-such-topic") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidSnsTopic")) + .body(containsString("Could not publish to SNS topic: " + + "arn:aws:sns:us-west-2:000000000000:floci-no-such-topic")); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "lamneg") + .formParam("Rule.Actions.member.1.LambdaAction.FunctionArn", + "arn:aws:lambda:us-west-2:000000000000:function:floci-no-such-fn") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidLambdaFunction")) + .body(containsString("Could not invoke Lambda function: " + + "arn:aws:lambda:us-west-2:000000000000:function:floci-no-such-fn")); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "bounceneg") + .formParam("Rule.Actions.member.1.BounceAction.SmtpReplyCode", "550") + .formParam("Rule.Actions.member.1.BounceAction.Message", "unavailable") + .formParam("Rule.Actions.member.1.BounceAction.Sender", "stranger@example.net") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Identity is not verified: stranger@example.net")); + } + + @Test + @Order(9) + void verifiedBounceSender_andLocalSnsTopic_areAccepted() { + req("VerifyEmailIdentity").formParam("EmailAddress", BOUNCE_SENDER) + .when().post("/").then().statusCode(200); + + snsTopicArn = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/sns/aws4_request") + .formParam("Action", "CreateTopic") + .formParam("Name", "floci-receipt-rule-topic") + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn"); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "actions-ok") + .formParam("Rule.Actions.member.1.BounceAction.SmtpReplyCode", "550") + .formParam("Rule.Actions.member.1.BounceAction.Message", "unavailable") + .formParam("Rule.Actions.member.1.BounceAction.Sender", BOUNCE_SENDER) + .formParam("Rule.Actions.member.2.SNSAction.TopicArn", snsTopicArn) + .when().post("/").then().statusCode(200); + + // The stored SNS action picks up AWS's UTF-8 encoding default (probed). + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "actions-ok") + .when().post("/").then().statusCode(200) + .body(containsString("" + snsTopicArn + "")) + .body(containsString("UTF-8")) + .body(containsString("" + BOUNCE_SENDER + "")); + } + + @Test + @Order(9) + void sparseActionIndexes_areRejectedAsEmptySlots() { + // An action serialized as an empty structure contributes no keys, so a list can arrive + // starting at member.2. AWS pads the gap into an empty action slot and rejects it + // because the slot carries no action type (probed). + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "sparse") + .formParam("Rule.Actions.member.2.StopAction.Scope", "RuleSet") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Exactly one action type must be specified for each ReceiptAction")); + } + + @Test + @Order(9) + void leadingZeroIndex_isParsedUnderItsOriginalSpelling() { + // Probed: member.01 on its own is a valid slot 1 and the action must not be dropped. + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "leadzero") + .formParam("Rule.Actions.member.01.StopAction.Scope", "RuleSet") + .when().post("/").then().statusCode(200); + + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "leadzero") + .when().post("/").then().statusCode(200) + .body(containsString("RuleSet")); + + // Probed: mixed spellings order by (length, lex), so 01 followed by 2 puts the + // one-digit token first and slot 1 is an empty pad. + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "leadzero2") + .formParam("Rule.Actions.member.01.AddHeaderAction.HeaderName", "X-A") + .formParam("Rule.Actions.member.01.AddHeaderAction.HeaderValue", "v") + .formParam("Rule.Actions.member.2.AddHeaderAction.HeaderName", "X-B") + .formParam("Rule.Actions.member.2.AddHeaderAction.HeaderValue", "v") + .when().post("/").then().statusCode(400) + .body(containsString("Exactly one action type must be specified for each ReceiptAction")); + } + + @Test + @Order(9) + void stopAction_mustBeLast() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "stopfirst") + .formParam("Rule.Actions.member.1.StopAction.Scope", "RuleSet") + .formParam("Rule.Actions.member.2.AddHeaderAction.HeaderName", "X-A") + .formParam("Rule.Actions.member.2.AddHeaderAction.HeaderValue", "v") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Stop action, if any, must be placed at the end of the actions list")); + } + + @Test + @Order(9) + void nonAsciiDigitIndex_isIgnoredLikeAnUnmodeledParameter() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "fwidx") + .formParam("Rule.Actions.member.1.StopAction.Scope", "RuleSet") + .when().post("/").then().statusCode(200); + + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "fwidx") + .when().post("/").then().statusCode(200) + .body(containsString("")); + } + + @Test + @Order(9) + void actionIndexZero_isRejectedAsMalformedInput() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "zeroidx") + .formParam("Rule.Actions.member.0.StopAction.Scope", "RuleSet") + .when().post("/").then().statusCode(400) + .body(containsString("MalformedInput")) + .body(containsString("0 is not a valid index")); + } + + @Test + @Order(9) + void malformedWireBoolean_isRejectedAsMalformedInput() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "badbool") + .formParam("Rule.Enabled", "bogus") + .when().post("/").then().statusCode(400) + .body(containsString("MalformedInput")) + .body(containsString("boolean must follow xsd1.1 definition")); + + // Uppercase TRUE is rejected too (probed); the numeric forms are accepted. + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "badbool") + .formParam("Rule.ScanEnabled", "TRUE") + .when().post("/").then().statusCode(400) + .body(containsString("MalformedInput")); + + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "numbool") + .formParam("Rule.Enabled", "1") + .when().post("/").then().statusCode(200); + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "numbool") + .when().post("/").then().statusCode(200) + .body(containsString("true")); + } + + @Test + @Order(9) + void twoActionTypesInOneMember_areRejected() { + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "multitype") + .formParam("Rule.Actions.member.1.StopAction.Scope", "RuleSet") + .formParam("Rule.Actions.member.1.AddHeaderAction.HeaderName", "X-A") + .formParam("Rule.Actions.member.1.AddHeaderAction.HeaderValue", "v") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Exactly one action type must be specified for each ReceiptAction")); + } + + @Test + @Order(9) + void overflowingActionIndex_isRejectedNotAServerError() { + // A digit run that overflows int implies an index far beyond any contiguous list; the + // gap padding turns it into the probed empty-slot rejection instead of a 500. + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "hugeidx") + .formParam("Rule.Actions.member.999999999999999999999.StopAction.Scope", "RuleSet") + .when().post("/").then().statusCode(400) + .body(containsString("Exactly one action type must be specified for each ReceiptAction")); + } + + @Test + @Order(9) + void topLevelRuleNameParam_getsSmithyValidation() { + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "bad name") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("'ruleName'")); + } + + @Test + @Order(10) + void updateRule_isFullReplace_andKeepsPosition() { + req("UpdateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "rich") + .when().post("/").then().statusCode(200); + + req("DescribeReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "rich") + .when().post("/").then().statusCode(200) + .body(containsString("false")) + .body(containsString("Optional")) + .body(containsString("")); + + req("UpdateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", "ghost") + .when().post("/").then().statusCode(400) + .body(containsString("RuleDoesNotExist")); + } + + @Test + @Order(11) + void setRulePosition_movesToFrontWithoutAfter() { + req("SetReceiptRulePosition").formParam("RuleSetName", RS) + .formParam("RuleName", "rich") + .when().post("/").then().statusCode(200); + + String body = req("DescribeReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200).extract().asString(); + assertTrue(body.indexOf("rich") < body.indexOf("first")); + } + + @Test + @Order(12) + void deleteRule_isIdempotent_andRuleSetDeleteCascades() { + req("DeleteReceiptRule").formParam("RuleSetName", RS) + .formParam("RuleName", "ghost") + .when().post("/").then().statusCode(200); + + req("DeleteReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200); + + req("DescribeReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java index ac694a9271..dd9de75d82 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java @@ -2,6 +2,9 @@ package io.github.hectorvent.floci.services.ses; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.sns.SnsService; import io.github.hectorvent.floci.services.ses.model.AccountDetails; import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes; @@ -125,7 +128,8 @@ final class SesServiceTestBuilder { new SesDedicatedIpService(dedicatedIpPoolStore), new SesContactService(contactListStore, contactStore, clock), new SesPolicyService(policyStore, objectMapper), - new SesReceiptRuleService(receiptRuleStore, clock), + new SesReceiptRuleService(receiptRuleStore, mock(S3Service.class), + mock(SnsService.class), mock(LambdaService.class), clock), new SesCvetService(cvetStore), new SesTenantService(tenantStore, tenantAssociationStore, clock, new SecureRandom()), smtpRelay); diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java index bd617f1492..6ee77dc46e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java @@ -481,4 +481,14 @@ class SnsServiceTest { assertTrue(snsService.matchesFilterPolicy(sub, null, matching)); assertFalse(snsService.matchesFilterPolicy(sub, null, nonMatching)); } + + @Test + void topicExists_reportsPresenceWithoutThrowing() { + Topic topic = snsService.createTopic("exists-topic", null, null, REGION); + assertTrue(snsService.topicExists(topic.getTopicArn(), REGION)); + assertFalse(snsService.topicExists(topic.getTopicArn(), "eu-west-1")); + assertFalse(snsService.topicExists( + "arn:aws:sns:us-east-1:000000000000:ghost-topic", REGION)); + } + }