diff --git a/compatibility-tests/compat-opentofu/main.tf b/compatibility-tests/compat-opentofu/main.tf index 593336517b..ab420dca0d 100644 --- a/compatibility-tests/compat-opentofu/main.tf +++ b/compatibility-tests/compat-opentofu/main.tf @@ -328,3 +328,17 @@ resource "aws_kinesis_firehose_delivery_stream" "events" { output "firehose_stream_arn" { value = aws_kinesis_firehose_delivery_stream.events.arn } + +# ── SES Receipt Rule Set ─────────────────────────────────────────────────── +# floci stores it inertly (no inbound-mail routing); the management API just round-trips. +resource "aws_ses_receipt_rule_set" "compat" { + rule_set_name = "floci-compat-rule-set" +} + +resource "aws_ses_active_receipt_rule_set" "compat" { + rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name +} + +output "ses_rule_set_name" { + value = aws_ses_receipt_rule_set.compat.rule_set_name +} diff --git a/compatibility-tests/compat-opentofu/provider.tf b/compatibility-tests/compat-opentofu/provider.tf index f56825540c..a3d35ce3ad 100644 --- a/compatibility-tests/compat-opentofu/provider.tf +++ b/compatibility-tests/compat-opentofu/provider.tf @@ -36,5 +36,6 @@ provider "aws" { secretsmanager = var.endpoint ec2 = var.endpoint route53 = var.endpoint + ses = var.endpoint } } diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.bats index 123c043215..cfeedf2d79 100644 --- a/compatibility-tests/compat-opentofu/test/opentofu.bats +++ b/compatibility-tests/compat-opentofu/test/opentofu.bats @@ -78,6 +78,16 @@ setup() { assert_output --partial "floci-compat-events" } +@test "OpenTofu: SES receipt rule set created and active" { + run aws_cmd ses describe-receipt-rule-set --rule-set-name floci-compat-rule-set + assert_success + assert_output --partial "floci-compat-rule-set" + + run aws_cmd ses describe-active-receipt-rule-set + assert_success + assert_output --partial "floci-compat-rule-set" +} + @test "OpenTofu: DynamoDB table created" { run aws_cmd dynamodb describe-table --table-name floci-compat-items assert_success diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tf index b9e5e9eecc..057d57ab60 100644 --- a/compatibility-tests/compat-terraform/main.tf +++ b/compatibility-tests/compat-terraform/main.tf @@ -422,3 +422,17 @@ output "appautoscaling_target_arn" { output "appautoscaling_alb_policy_arn" { value = aws_appautoscaling_policy.ecs_alb_requests.arn } + +# ── SES Receipt Rule Set ─────────────────────────────────────────────────── +# floci stores it inertly (no inbound-mail routing); the management API just round-trips. +resource "aws_ses_receipt_rule_set" "compat" { + rule_set_name = "floci-compat-rule-set" +} + +resource "aws_ses_active_receipt_rule_set" "compat" { + rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name +} + +output "ses_rule_set_name" { + value = aws_ses_receipt_rule_set.compat.rule_set_name +} diff --git a/compatibility-tests/compat-terraform/provider.tf b/compatibility-tests/compat-terraform/provider.tf index ee78c1f248..4c653085d6 100644 --- a/compatibility-tests/compat-terraform/provider.tf +++ b/compatibility-tests/compat-terraform/provider.tf @@ -40,5 +40,6 @@ provider "aws" { ec2 = var.endpoint route53 = var.endpoint appautoscaling = var.endpoint + ses = var.endpoint } } diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.bats index d3de701ff7..c839c5003d 100644 --- a/compatibility-tests/compat-terraform/test/terraform.bats +++ b/compatibility-tests/compat-terraform/test/terraform.bats @@ -78,6 +78,16 @@ setup() { assert_output --partial "floci-compat-events" } +@test "Terraform: SES receipt rule set created and active" { + run aws_cmd ses describe-receipt-rule-set --rule-set-name floci-compat-rule-set + assert_success + assert_output --partial "floci-compat-rule-set" + + run aws_cmd ses describe-active-receipt-rule-set + assert_success + assert_output --partial "floci-compat-rule-set" +} + @test "Terraform: DynamoDB table created" { run aws_cmd dynamodb describe-table --table-name floci-compat-items assert_success 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 new file mode 100644 index 0000000000..2bff2075ee --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReceiptRuleSetTest.java @@ -0,0 +1,119 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +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 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.DescribeReceiptRuleSetResponse; +import software.amazon.awssdk.services.ses.model.ListReceiptRuleSetsResponse; +import software.amazon.awssdk.services.ses.model.RuleSetDoesNotExistException; + +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. + */ +@DisplayName("SES V1 ReceiptRuleSet") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesReceiptRuleSetTest { + + private static SesClient ses; + private static String ruleSet; + + @BeforeAll + static void setup() { + ses = TestFixtures.sesClient(); + ruleSet = "sdk-v1-rule-set-" + TestFixtures.uniqueName(); + } + + @AfterAll + static void cleanup() { + if (ses != null) { + try { + ses.setActiveReceiptRuleSet(b -> { }); + } catch (RuntimeException ignored) { + // best-effort: clearing the active rule set + } + try { + ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); + } catch (RuntimeException ignored) { + // best-effort: removing the throwaway rule set + } + ses.close(); + } + } + + @Test + @Order(1) + void createAndDescribe() { + ses.createReceiptRuleSet(b -> b.ruleSetName(ruleSet)); + 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 + } + + @Test + @Order(2) + void createDuplicate_throwsAlreadyExists() { + assertThatThrownBy(() -> ses.createReceiptRuleSet(b -> b.ruleSetName(ruleSet))) + .isInstanceOf(AlreadyExistsException.class); + } + + @Test + @Order(3) + void list_containsRuleSet() { + ListReceiptRuleSetsResponse r = ses.listReceiptRuleSets(b -> { }); + assertThat(r.ruleSets()).anyMatch(m -> ruleSet.equals(m.name())); + } + + @Test + @Order(4) + 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 rule set can't be deleted (matches AWS) — a caller must unset it first. + assertThatThrownBy(() -> ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet))) + .isInstanceOf(CannotDeleteException.class); + } + + @Test + @Order(5) + void describeNonExistent_throwsRuleSetDoesNotExist() { + assertThatThrownBy(() -> ses.describeReceiptRuleSet(b -> b.ruleSetName("sdk-v1-nope"))) + .isInstanceOf(RuleSetDoesNotExistException.class); + } + + @Test + @Order(6) + void unsetActive_leavesNoActiveRuleSet() { + ses.setActiveReceiptRuleSet(b -> { }); // no name clears the active rule set + DescribeActiveReceiptRuleSetResponse a = ses.describeActiveReceiptRuleSet(b -> { }); + assertThat(a.metadata()).isNull(); + } + + @Test + @Order(7) + void delete_isIdempotent() { + ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); + // Deleting an already-absent rule set still succeeds (matches AWS). + ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); + assertThatThrownBy(() -> ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet))) + .isInstanceOf(RuleSetDoesNotExistException.class); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index b08141443a..a50cc5f8c6 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -55,6 +55,12 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an | `DeleteConfigurationSetTrackingOptions` | Remove the custom tracking redirect domain | | `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) | +| `ListReceiptRuleSets` | List receipt rule sets | +| `DeleteReceiptRuleSet` | Delete a receipt rule set (idempotent) | +| `SetActiveReceiptRuleSet` | Mark a rule set active, or clear the active one | +| `DescribeActiveReceiptRuleSet` | Read the active receipt rule set | ## Configuration @@ -161,6 +167,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. - For the REST JSON API see [SES v2](#v2) below. ## SES v2 (REST JSON) {#v2} 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 9de15a43ce..7c364bd7ec 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 @@ -405,7 +405,9 @@ public class AwsQueryController { "UpdateConfigurationSetTrackingOptions", "DeleteConfigurationSetTrackingOptions", "UpdateConfigurationSetReputationMetricsEnabled", - "PutConfigurationSetDeliveryOptions" + "PutConfigurationSetDeliveryOptions", + "CreateReceiptRuleSet", "DescribeReceiptRuleSet", "ListReceiptRuleSets", + "DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet" ); private static final Set COGNITO_ACTIONS = Set.of( 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 00389ef832..fb46ee36d2 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 @@ -15,6 +15,7 @@ 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.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.SnsDestination; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -107,6 +108,12 @@ public class SesQueryHandler { handleUpdateConfigurationSetReputationMetricsEnabled(params, region); case "PutConfigurationSetDeliveryOptions" -> handlePutConfigurationSetDeliveryOptions(params, region); + case "CreateReceiptRuleSet" -> handleCreateReceiptRuleSet(params, region); + case "DescribeReceiptRuleSet" -> handleDescribeReceiptRuleSet(params, region); + case "ListReceiptRuleSets" -> handleListReceiptRuleSets(region); + case "DeleteReceiptRuleSet" -> handleDeleteReceiptRuleSet(params, region); + case "SetActiveReceiptRuleSet" -> handleSetActiveReceiptRuleSet(params, region); + case "DescribeActiveReceiptRuleSet" -> handleDescribeActiveReceiptRuleSet(region); default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported by SES.", AwsNamespaces.SES, 400); }; @@ -831,6 +838,71 @@ public class SesQueryHandler { "PutConfigurationSetDeliveryOptions", AwsNamespaces.SES)).build(); } + private Response handleCreateReceiptRuleSet(MultivaluedMap params, String region) { + sesService.createReceiptRuleSet(getParam(params, "RuleSetName"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "CreateReceiptRuleSet", AwsNamespaces.SES)).build(); + } + + private Response handleDescribeReceiptRuleSet(MultivaluedMap params, String region) { + ReceiptRuleSet ruleSet = sesService.describeReceiptRuleSet(getParam(params, "RuleSetName"), region); + XmlBuilder xml = new XmlBuilder(); + writeReceiptRuleSetMetadata(xml, ruleSet); + xml.start("Rules").end("Rules"); + return Response.ok(AwsQueryResponse.envelope( + "DescribeReceiptRuleSet", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleListReceiptRuleSets(String region) { + XmlBuilder xml = new XmlBuilder().start("RuleSets"); + for (ReceiptRuleSet rs : sesService.listReceiptRuleSets(region)) { + xml.start("member"); + writeReceiptRuleSetMetadataFields(xml, rs); + xml.end("member"); + } + xml.end("RuleSets"); + return Response.ok(AwsQueryResponse.envelope( + "ListReceiptRuleSets", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleDeleteReceiptRuleSet(MultivaluedMap params, String region) { + sesService.deleteReceiptRuleSet(getParam(params, "RuleSetName"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "DeleteReceiptRuleSet", AwsNamespaces.SES)).build(); + } + + private Response handleSetActiveReceiptRuleSet(MultivaluedMap params, String region) { + // RuleSetName is optional here: when absent, the account's active rule set is cleared. + sesService.setActiveReceiptRuleSet(getParam(params, "RuleSetName"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "SetActiveReceiptRuleSet", AwsNamespaces.SES)).build(); + } + + private Response handleDescribeActiveReceiptRuleSet(String region) { + ReceiptRuleSet active = sesService.describeActiveReceiptRuleSet(region); + XmlBuilder xml = new XmlBuilder(); + // 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"); + } + return Response.ok(AwsQueryResponse.envelope( + "DescribeActiveReceiptRuleSet", AwsNamespaces.SES, xml.build())).build(); + } + + private void writeReceiptRuleSetMetadata(XmlBuilder xml, ReceiptRuleSet ruleSet) { + xml.start("Metadata"); + writeReceiptRuleSetMetadataFields(xml, ruleSet); + xml.end("Metadata"); + } + + private void writeReceiptRuleSetMetadataFields(XmlBuilder xml, ReceiptRuleSet ruleSet) { + xml.elem("Name", ruleSet.getName()); + if (ruleSet.getCreatedTimestamp() != null) { + xml.elem("CreatedTimestamp", ruleSet.getCreatedTimestamp().toString()); + } + } + /** * AWS V1 SES uses lowercased event-type names on the wire (e.g. {@code send}, * {@code complaint}, {@code renderingFailure}) while V2 uses 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 dc4c177690..ca547fcf8a 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 @@ -24,6 +24,7 @@ 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.MessageHeader; import io.github.hectorvent.floci.services.ses.model.MessageTag; +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; import io.github.hectorvent.floci.services.ses.model.TrackingOptions; @@ -90,6 +91,7 @@ public class SesService { // Identity (sending authorization) policies: key policy::::::, // value the (normalized) policy JSON. One store shared by the v1 and v2 policy APIs. private final StorageBackend policyStore; + private final StorageBackend receiptRuleSetStore; // Guards the one-list-per-account check-then-create so concurrent creates can't both pass. private final Object contactListCreateLock = new Object(); // Serializes contact create/update against contact-list deletion so a concurrent delete @@ -98,6 +100,9 @@ public class SesService { // Serializes the per-identity policy count check-then-put so concurrent creates can't both pass. private final Object policyMutationLock = new Object(); static final int MAX_POLICIES_PER_IDENTITY = 20; + // 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. + private final Object receiptRuleSetLock = new Object(); private final SmtpRelay smtpRelay; private final ObjectMapper objectMapper; private final SesEventPublisher eventPublisher; @@ -132,6 +137,8 @@ public class SesService { new TypeReference>() {}); this.policyStore = storageFactory.create("ses", "ses-identity-policies.json", new TypeReference>() {}); + this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json", + new TypeReference>() {}); this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = eventPublisher; @@ -151,12 +158,13 @@ public class SesService { StorageBackend contactListStore, StorageBackend contactStore, StorageBackend policyStore, + StorageBackend receiptRuleSetStore, SmtpRelay smtpRelay, ObjectMapper objectMapper, Clock clock) { this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore, - accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, policyStore, smtpRelay, - objectMapper, null, clock); + accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, policyStore, + receiptRuleSetStore, smtpRelay, objectMapper, null, clock); } SesService(StorageBackend identityStore, @@ -170,6 +178,7 @@ public class SesService { StorageBackend contactListStore, StorageBackend contactStore, StorageBackend policyStore, + StorageBackend receiptRuleSetStore, SmtpRelay smtpRelay, ObjectMapper objectMapper, Route53Service route53Service, @@ -185,6 +194,7 @@ public class SesService { this.contactListStore = contactListStore; this.contactStore = contactStore; this.policyStore = policyStore; + this.receiptRuleSetStore = receiptRuleSetStore; this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = null; @@ -1283,6 +1293,135 @@ public class SesService { return "configSet::" + region + "::" + name; } + // ──────────────────────── Receipt rule sets (inbound) ──────────────────────── + // + // 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). + + public ReceiptRuleSet createReceiptRuleSet(String name, String region) { + requireRuleSetName(name); + String key = receiptRuleSetKey(region, name); + ReceiptRuleSet ruleSet = new ReceiptRuleSet(name, Instant.now(clock)); + synchronized (receiptRuleSetLock) { + if (receiptRuleSetStore.get(key).isPresent()) { + throw new AwsException("AlreadyExists", "Rule set already exists: " + name, 400); + } + receiptRuleSetStore.put(key, ruleSet); + } + LOG.infov("Created SES receipt rule set: {0} in region {1}", name, region); + return ruleSet; + } + + public ReceiptRuleSet describeReceiptRuleSet(String name, String region) { + requireRuleSetName(name); + return receiptRuleSetStore.get(receiptRuleSetKey(region, name)) + .orElseThrow(() -> ruleSetDoesNotExist(name)); + } + + public List listReceiptRuleSets(String region) { + String prefix = "receiptRuleSet::" + region + "::"; + List all = new ArrayList<>(receiptRuleSetStore.scan(k -> k.startsWith(prefix))); + all.sort(Comparator.comparing(ReceiptRuleSet::getCreatedTimestamp, + Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(ReceiptRuleSet::getName, Comparator.nullsLast(Comparator.naturalOrder()))); + return all; + } + + public void deleteReceiptRuleSet(String name, String region) { + requireRuleSetName(name); + // Hold the lock so the active-check-then-delete is atomic and a concurrent set-active/clear + // (which scans and re-puts active sets) can't resurrect the rule set we just deleted. + synchronized (receiptRuleSetLock) { + ReceiptRuleSet existing = receiptRuleSetStore.get(receiptRuleSetKey(region, name)).orElse(null); + if (existing != null && existing.isActive()) { + // AWS rejects deleting the active rule set (verified: CannotDelete / 400). + throw new AwsException("CannotDelete", "Cannot delete active rule set: " + name, 400); + } + // AWS is idempotent otherwise: deleting a non-existent rule set succeeds without error. + receiptRuleSetStore.delete(receiptRuleSetKey(region, name)); + } + LOG.infov("Deleted SES receipt rule set: {0} in region {1}", name, region); + } + + public void setActiveReceiptRuleSet(String name, String region) { + // No RuleSetName clears the account's active rule set (matches AWS). + boolean clearOnly = name == null || name.isBlank(); + if (!clearOnly) { + requireRuleSetName(name); + } + synchronized (receiptRuleSetLock) { + if (!clearOnly) { + ReceiptRuleSet target = receiptRuleSetStore.get(receiptRuleSetKey(region, name)) + .orElseThrow(() -> ruleSetDoesNotExist(name)); + clearActiveReceiptRuleSet(region); + target.setActive(true); + receiptRuleSetStore.put(receiptRuleSetKey(region, name), target); + } else { + clearActiveReceiptRuleSet(region); + } + } + if (clearOnly) { + LOG.infov("Cleared active SES receipt rule set in region {0}", region); + } else { + LOG.infov("Set active SES receipt rule set: {0} in region {1}", name, region); + } + } + + public ReceiptRuleSet describeActiveReceiptRuleSet(String region) { + String prefix = "receiptRuleSet::" + region + "::"; + // Read under the lock so a concurrent set-active replacement (clear-then-set) can't expose its + // intermediate no-active state — the reader sees either the old or the new active set. + synchronized (receiptRuleSetLock) { + return receiptRuleSetStore.scan(k -> k.startsWith(prefix)).stream() + .filter(ReceiptRuleSet::isActive) + .findFirst() + .orElse(null); + } + } + + private void clearActiveReceiptRuleSet(String region) { + String prefix = "receiptRuleSet::" + region + "::"; + for (ReceiptRuleSet rs : receiptRuleSetStore.scan(k -> k.startsWith(prefix))) { + if (rs.isActive()) { + rs.setActive(false); + receiptRuleSetStore.put(receiptRuleSetKey(region, rs.getName()), rs); + } + } + } + + // These RuleSetName constraints are not in the botocore model: service-2.json (SES 2010-12-01) + // declares ReceiptRuleSetName as a bare {"type": "string"} with no pattern or length. They were + // established by probing real SES in us-west-2 via boto3 (2026-08): a character outside + // ^[a-zA-Z0-9_.-]+$ is a Smithy ValidationError, and a name that is >64 chars or does not + // 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 void requireRuleSetName(String name) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", "RuleSetName is required.", 400); + } + if (!RULE_SET_NAME_CHARS.matcher(name).matches()) { + throw new AwsException("ValidationError", + "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$", 400); + } + if (name.length() > 64 + || !Character.isLetterOrDigit(name.charAt(0)) + || !Character.isLetterOrDigit(name.charAt(name.length() - 1))) { + throw new AwsException("InvalidParameterValue", "Not a valid ruleSetName: " + name, 400); + } + } + + private static AwsException ruleSetDoesNotExist(String name) { + return new AwsException("RuleSetDoesNotExist", "Rule set does not exist: " + name, 400); + } + + private static String receiptRuleSetKey(String region, String name) { + return "receiptRuleSet::" + region + "::" + name; + } + // ──────────────────────── Dedicated IP Pools ──────────────────────── private static final java.util.Set SCALING_MODES = java.util.Set.of("STANDARD", "MANAGED"); 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 new file mode 100644 index 0000000000..988fe5b907 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptRuleSet.java @@ -0,0 +1,61 @@ +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.time.Instant; + +/** + * 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. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ReceiptRuleSet { + + @JsonProperty("Name") + private String name; + + @JsonProperty("CreatedTimestamp") + private Instant createdTimestamp; + + // Whether this is the account's active rule set for its region. Internal bookkeeping — AWS tracks + // the active set separately and does not surface this flag on the rule-set object itself. + @JsonProperty("Active") + private boolean active; + + public ReceiptRuleSet() { + } + + public ReceiptRuleSet(String name, Instant createdTimestamp) { + this.name = name; + this.createdTimestamp = createdTimestamp; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Instant getCreatedTimestamp() { + return createdTimestamp; + } + + public void setCreatedTimestamp(Instant createdTimestamp) { + this.createdTimestamp = createdTimestamp; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.java new file mode 100644 index 0000000000..d77ee18a13 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.java @@ -0,0 +1,172 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * Integration tests for the SES V1 Query-protocol receipt-rule-set actions. Floci stores rule sets + * inertly (no rules, no mail routing); these tests pin the management-API round-trip and the + * probe-confirmed AWS error/idempotency behavior. Uses an isolated region so the account-level + * active rule set does not collide with other SES tests. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesReceiptRuleSetV1IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/email/aws4_request"; + private static final String RS = "floci-v1-rule-set"; + + 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 createReceiptRuleSet() { + req("CreateReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200) + .body(containsString("CreateReceiptRuleSetResponse")); + } + + @Test + @Order(2) + void createDuplicate_returnsAlreadyExists() { + req("CreateReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(400) + .body(containsString("AlreadyExists")) + .body(containsString("Rule set already exists: " + RS)); + } + + @Test + @Order(3) + void describeReceiptRuleSet_returnsMetadataWithEmptyRules() { + req("DescribeReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200) + .body(containsString("")) + .body(containsString("" + RS + "")) + .body(containsString("CreatedTimestamp")) + .body(containsString("Rules")); + } + + @Test + @Order(4) + void listReceiptRuleSets_containsTheRuleSet() { + req("ListReceiptRuleSets") + .when().post("/").then().statusCode(200) + .body(containsString("")) + .body(containsString("" + RS + "")); + } + + @Test + @Order(5) + void describeNonExistent_returnsRuleSetDoesNotExist() { + req("DescribeReceiptRuleSet").formParam("RuleSetName", "floci-v1-nope") + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")) + .body(containsString("Rule set does not exist: floci-v1-nope")); + } + + @Test + @Order(6) + void setActive_thenDescribeActive_returnsIt() { + req("SetActiveReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200); + + req("DescribeActiveReceiptRuleSet") + .when().post("/").then().statusCode(200) + .body(containsString("")) + .body(containsString("" + RS + "")); + + // While active, deleting the rule set is rejected (verified against AWS) and it is preserved. + req("DeleteReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(400) + .body(containsString("CannotDelete")) + .body(containsString("Cannot delete active rule set: " + RS)); + + req("DescribeReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200) + .body(containsString("" + RS + "")); + } + + @Test + @Order(7) + void setActiveNonExistent_returnsRuleSetDoesNotExist() { + req("SetActiveReceiptRuleSet").formParam("RuleSetName", "floci-v1-nope") + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")); + } + + @Test + @Order(8) + void setActiveWithoutName_clearsActive() { + req("SetActiveReceiptRuleSet") + .when().post("/").then().statusCode(200); + + // With no active rule set, AWS returns an empty result (no Metadata / Name). + req("DescribeActiveReceiptRuleSet") + .when().post("/").then().statusCode(200) + .body(containsString("DescribeActiveReceiptRuleSetResponse")) + .body(not(containsString(""))); + } + + @Test + @Order(9) + void deleteReceiptRuleSet_thenIdempotentDelete() { + req("DeleteReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200) + .body(containsString("DeleteReceiptRuleSetResponse")); + + // AWS delete is idempotent: deleting again (now absent) still succeeds. + req("DeleteReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200); + } + + @Test + @Order(10) + void describeAfterDelete_returnsRuleSetDoesNotExist() { + req("DescribeReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")); + } + + @Test + @Order(11) + void createRuleSet_charOutsideAllowedSet_returnsValidationError() { + // A character outside ^[a-zA-Z0-9_.-]+$ is a Smithy ValidationError (verified against AWS). + req("CreateReceiptRuleSet").formParam("RuleSetName", "floci bad name") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("ruleSetName")); + } + + @Test + @Order(12) + void createRuleSet_badFormat_returnsNotValidRuleSetName() { + // Valid characters, but a name must start/end with an alphanumeric (verified against AWS). + req("CreateReceiptRuleSet").formParam("RuleSetName", "-floci-bad") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Not a valid ruleSetName: -floci-bad")); + } + + @Test + @Order(13) + void createRuleSet_dottedName_isAccepted() { + // A dot is inside the allowed character set (verified against AWS). + req("CreateReceiptRuleSet").formParam("RuleSetName", "floci.v1.dotted") + .when().post("/").then().statusCode(200); + req("DeleteReceiptRuleSet").formParam("RuleSetName", "floci.v1.dotted") + .when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java index bc50f7b6d3..8b0cb275b1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttribute import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -58,6 +59,7 @@ class SesServiceDkimLookupCacheTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), route53Service, diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java index 71c061ff21..cb280cfd5c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttribute import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -47,6 +48,7 @@ class SesServiceLegacyDkimTokensTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java index b82649c466..ee79aace28 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttribute import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -46,6 +47,7 @@ class SesServiceSmtpTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), smtpRelay, new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java index 54ddd642b1..2b28c48e47 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttribute import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -54,6 +55,7 @@ class SesServiceSuppressionLegacyKeyTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java index 6a460401d3..6d26871e05 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttribute import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -54,6 +55,7 @@ class SesServiceSuppressionReasonTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC());