Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ses): implement v1 receipt filters (CreateReceiptFilter, ListReceiptFilters, DeleteReceiptFilter) (#3163)
Kenshin Okinaka2c6a92c07dca
diff --git a/compatibility-tests/compat-opentofu/main.tf b/compatibility-tests/compat-opentofu/main.tfindex f06446bf13..e942776d49 100644--- a/compatibility-tests/compat-opentofu/main.tf+++ b/compatibility-tests/compat-opentofu/main.tf@@ -575,6 +575,12 @@ resource "aws_ses_active_receipt_rule_set" "compat" {rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name}+resource "aws_ses_receipt_filter" "compat" {+ name = "floci-compat-filter"+ cidr = "10.10.10.0/24"+ policy = "Block"+}+resource "aws_ses_receipt_rule" "compat" {rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_namename = "floci-compat-rule"diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.batsindex 41dc28c302..20c8f4762d 100644--- a/compatibility-tests/compat-opentofu/test/opentofu.bats+++ b/compatibility-tests/compat-opentofu/test/opentofu.bats@@ -148,6 +148,13 @@ sha256_composite_by_sizes() {assert_output --partial "floci-compat-events"}+@test "OpenTofu: SES receipt filter created" {+ run aws_cmd ses list-receipt-filters+ assert_success+ assert_output --partial "floci-compat-filter"+ assert_output --partial "10.10.10.0/24"+}+@test "OpenTofu: SES receipt rule set created and active" {run aws_cmd ses describe-receipt-rule-set --rule-set-name floci-compat-rule-setassert_successdiff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tfindex 68963001e3..9023d91fff 100644--- a/compatibility-tests/compat-terraform/main.tf+++ b/compatibility-tests/compat-terraform/main.tf@@ -665,6 +665,12 @@ resource "aws_ses_active_receipt_rule_set" "compat" {rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_name}+resource "aws_ses_receipt_filter" "compat" {+ name = "floci-compat-filter"+ cidr = "10.10.10.0/24"+ policy = "Block"+}+resource "aws_ses_receipt_rule" "compat" {rule_set_name = aws_ses_receipt_rule_set.compat.rule_set_namename = "floci-compat-rule"diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.batsindex 4b038edf6d..fb79293ef9 100644--- a/compatibility-tests/compat-terraform/test/terraform.bats+++ b/compatibility-tests/compat-terraform/test/terraform.bats@@ -148,6 +148,13 @@ sha256_composite_by_sizes() {assert_output --partial "floci-compat-events"}+@test "Terraform: SES receipt filter created" {+ run aws_cmd ses list-receipt-filters+ assert_success+ assert_output --partial "floci-compat-filter"+ assert_output --partial "10.10.10.0/24"+}+@test "Terraform: SES receipt rule set created and active" {run aws_cmd ses describe-receipt-rule-set --rule-set-name floci-compat-rule-setassert_successdiff --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.javaindex 2b3e4945ed..f450ad4970 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@@ -16,9 +16,12 @@ 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.ReceiptFilter;import software.amazon.awssdk.services.ses.model.ReceiptRule;import software.amazon.awssdk.services.ses.model.RuleDoesNotExistException;+import software.amazon.awssdk.services.ses.model.ReceiptFilterPolicy;import software.amazon.awssdk.services.ses.model.RuleSetDoesNotExistException;+import software.amazon.awssdk.services.ses.model.SesException;import software.amazon.awssdk.services.ses.model.TlsPolicy;import software.amazon.awssdk.services.sns.SnsClient;@@ -26,14 +29,14 @@ 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 and receipt-rule actions, the surface+ * SDK compatibility test for the SES V1 receipt-rule-set, receipt-rule, and receipt-filter+ * actions. Floci stores all of them inertly (no mail routing, no connection filtering), 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} /- * {@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.+ * {@code aws_ses_receipt_rule} / {@code aws_ses_receipt_filter} drive), including AWS error+ * mapping, ordering semantics, and idempotent deletes.*/-@DisplayName("SES V1 ReceiptRuleSet and ReceiptRule")+@DisplayName("SES V1 ReceiptRuleSet, ReceiptRule, and ReceiptFilter")@TestMethodOrder(MethodOrderer.OrderAnnotation.class)class SesReceiptRuleSetTest {@@ -41,12 +44,17 @@ class SesReceiptRuleSetTest {private static SnsClient sns;private static String ruleSet;private static String topicArn;+ private static String blockFilter;+ private static String allowFilter;@BeforeAllstatic void setup() {ses = TestFixtures.sesClient();sns = TestFixtures.snsClient();- ruleSet = "sdk-v1-rule-set-" + TestFixtures.uniqueName();+ String unique = TestFixtures.uniqueName();+ ruleSet = "sdk-v1-rule-set-" + unique;+ blockFilter = "sdk-v1-filter-block-" + unique;+ allowFilter = "sdk-v1-filter-allow-" + unique;topicArn = sns.createTopic(b -> b.name("sdk-v1-receipt-rule-topic")).topicArn();}@@ -64,6 +72,13 @@ class SesReceiptRuleSetTest {System.err.println("Best-effort cleanup of rule set " + ruleSet+ " failed (its rules cascade with it): " + e.getMessage());}+ for (String name : new String[] {blockFilter, allowFilter}) {+ try {+ ses.deleteReceiptFilter(b -> b.filterName(name));+ } catch (RuntimeException e) {+ System.err.println("Best-effort cleanup of filter " + name + " failed: " + e.getMessage());+ }+ }ses.close();}if (sns != null) {@@ -209,7 +224,7 @@ class SesReceiptRuleSetTest {// 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.+ // 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);}@@ -238,4 +253,47 @@ class SesReceiptRuleSetTest {assertThatThrownBy(() -> ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet))).isInstanceOf(RuleSetDoesNotExistException.class);}++ @Test+ @Order(14)+ void createFilterAndList_roundTrip() {+ ses.createReceiptFilter(b -> b.filter(f -> f.name(blockFilter)+ .ipFilter(ip -> ip.policy(ReceiptFilterPolicy.BLOCK).cidr("10.0.0.0/24"))));+ ses.createReceiptFilter(b -> b.filter(f -> f.name(allowFilter)+ .ipFilter(ip -> ip.policy(ReceiptFilterPolicy.ALLOW).cidr("192.0.2.10"))));++ var filters = ses.listReceiptFilters().filters();+ ReceiptFilter block = filters.stream()+ .filter(f -> blockFilter.equals(f.name())).findFirst().orElseThrow();+ assertThat(block.ipFilter().policy()).isEqualTo(ReceiptFilterPolicy.BLOCK);+ assertThat(block.ipFilter().cidr()).isEqualTo("10.0.0.0/24");+ assertThat(filters).anyMatch(f -> allowFilter.equals(f.name()));+ }++ @Test+ @Order(15)+ void duplicateFilterCreate_andInvalidCidr_mapToTypedExceptions() {+ assertThatThrownBy(() -> ses.createReceiptFilter(b -> b.filter(f -> f.name(blockFilter)+ .ipFilter(ip -> ip.policy(ReceiptFilterPolicy.ALLOW).cidr("10.9.9.9")))))+ .isInstanceOf(AlreadyExistsException.class)+ .hasMessageContaining("Filter already exists: " + blockFilter);++ // InvalidParameterValue is not a modeled SES v1 exception; the SDK surfaces the+ // generic SesException carrying the wire error code.+ assertThatThrownBy(() -> ses.createReceiptFilter(b -> b.filter(f -> f.name("sdk-v1-bad-cidr")+ .ipFilter(ip -> ip.policy(ReceiptFilterPolicy.BLOCK).cidr("not-a-cidr")))))+ .isInstanceOfSatisfying(SesException.class, e -> assertThat(+ e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"))+ .hasMessageContaining("Invalid CIDR block: not-a-cidr");+ }++ @Test+ @Order(16)+ void deleteFilter_isIdempotent() {+ ses.deleteReceiptFilter(b -> b.filterName(allowFilter));+ ses.deleteReceiptFilter(b -> b.filterName(allowFilter));+ assertThat(ses.listReceiptFilters().filters())+ .noneMatch(f -> allowFilter.equals(f.name()));+ }+}diff --git a/docs/services/ses.md b/docs/services/ses.mdindex 012051a1eb..a3083a385b 100644--- a/docs/services/ses.md+++ b/docs/services/ses.md@@ -74,6 +74,9 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an| `UpdateReceiptRule` | Replace a receipt rule in place || `DeleteReceiptRule` | Delete a receipt rule (idempotent) || `SetReceiptRulePosition` | Reorder a receipt rule within its set |+| `CreateReceiptFilter` | Create an IP address filter (stored inertly) |+| `ListReceiptFilters` | List IP address filters |+| `DeleteReceiptFilter` | Delete an IP address filter (idempotent) |## Configuration@@ -180,7 +183,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 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.+- Receipt rule sets and receipt rules are stored inertly: Floci has no inbound-mail endpoint, so stored rules route no mail and their actions never execute, but the management API round-trips with AWS ordering, validation, and error semantics (probe-verified). Action targets are validated against the local emulator with the AWS error codes: an SNS `TopicArn`, S3 `BucketName`, or Lambda `FunctionArn` must reference an existing local resource, and a `BounceAction` `Sender` must be a verified identity. Deviations: S3 bucket write permissions, KMS keys, and `ConnectAction` role assumability are not verified (AWS checks these); `WorkmailAction` gets no resource validation (neither does AWS). Receipt IP filters are stored the same way, with the probed AWS validation and the 100-filter limit, but no inbound connection is ever filtered. `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.javaindex 231977f3db..621078cc7f 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@@ -578,7 +578,8 @@ public class AwsQueryController {"CreateReceiptRuleSet", "DescribeReceiptRuleSet", "ListReceiptRuleSets","DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet","CreateReceiptRule", "DescribeReceiptRule", "UpdateReceiptRule",- "DeleteReceiptRule", "SetReceiptRulePosition"+ "DeleteReceiptRule", "SetReceiptRulePosition",+ "CreateReceiptFilter", "ListReceiptFilters", "DeleteReceiptFilter");private static final Set<String> 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.javaindex 1d3e90ab7a..8ce22954ec 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@@ -17,6 +17,7 @@ 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.ReceiptFilter;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;@@ -137,6 +138,9 @@ public class SesQueryHandler {case "UpdateReceiptRule" -> handleUpdateReceiptRule(params, region);case "DeleteReceiptRule" -> handleDeleteReceiptRule(params, region);case "SetReceiptRulePosition" -> handleSetReceiptRulePosition(params, region);+ case "CreateReceiptFilter" -> handleCreateReceiptFilter(params, region);+ case "ListReceiptFilters" -> handleListReceiptFilters(region);+ case "DeleteReceiptFilter" -> handleDeleteReceiptFilter(params, region);default -> AwsQueryResponse.error("UnsupportedOperation","Operation " + action + " is not supported by SES.", AwsNamespaces.SES, 400);};@@ -1204,6 +1208,41 @@ public class SesQueryHandler {xml.end(tag);}+ private Response handleCreateReceiptFilter(MultivaluedMap<String, String> params, String region) {+ String name = getParam(params, "Filter.Name");+ String policy = getParam(params, "Filter.IpFilter.Policy");+ String cidr = getParam(params, "Filter.IpFilter.Cidr");+ // A request with no Filter member at all is a single 'filter' violation (probed), not the+ // nested per-member ones, so the absent structure must stay distinguishable as null.+ ReceiptFilter filter = name == null && policy == null && cidr == null+ ? null : new ReceiptFilter(name, policy, cidr);+ sesService.createReceiptFilter(filter, region);+ return Response.ok(AwsQueryResponse.envelopeEmptyResult(+ "CreateReceiptFilter", AwsNamespaces.SES)).build();+ }++ private Response handleListReceiptFilters(String region) {+ XmlBuilder xml = new XmlBuilder().start("Filters");+ for (ReceiptFilter filter : sesService.listReceiptFilters(region)) {+ xml.start("member");+ xml.elem("Name", filter.getName());+ xml.start("IpFilter");+ xml.elem("Policy", filter.getPolicy());+ xml.elem("Cidr", filter.getCidr());+ xml.end("IpFilter");+ xml.end("member");+ }+ xml.end("Filters");+ return Response.ok(AwsQueryResponse.envelope(+ "ListReceiptFilters", AwsNamespaces.SES, xml.build())).build();+ }++ private Response handleDeleteReceiptFilter(MultivaluedMap<String, String> params, String region) {+ sesService.deleteReceiptFilter(getParam(params, "FilterName"), region);+ return Response.ok(AwsQueryResponse.envelopeEmptyResult(+ "DeleteReceiptFilter", AwsNamespaces.SES)).build();+ }+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.javaindex 2c6de6e2bd..d5f2c6231b 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@@ -7,6 +7,7 @@ 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.ReceiptFilter;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;@@ -24,15 +25,15 @@ import java.util.function.Predicate;import java.util.regex.Pattern;/**- * 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+ * Owns the SES inbound-mail management domain: receipt rule sets and their rules (the+ * {@code receiptRuleSetStore}) and receipt IP filters (the {@code receiptFilterStore}). 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.*- * <p>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+ * <p>Floci has no inbound-mail endpoint, so everything here is stored inertly: stored rules+ * route no mail, their actions never execute, and a filter never blocks or allows any connection. The management API round-trips (enough to unblock* tools such as Terraform that declare inbound configuration during bootstrap).*/@ApplicationScoped@@ -58,8 +59,12 @@ public class SesReceiptRuleService {// RFC 5322 ftext: printable US-ASCII excluding the colon. Real SES rejects anything else with// "Invalid header name: <name>" (probed 2026-09).private static final Pattern HEADER_NAME_CHARS = Pattern.compile("^[\\x21-\\x39\\x3B-\\x7E]+$");+ private static final Pattern IPV4_OCTETS = Pattern.compile(+ "^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$");+ private static final int MAX_FILTERS = 100;private final StorageBackend<String, ReceiptRuleSet> receiptRuleSetStore;+ private final StorageBackend<String, ReceiptFilter> receiptFilterStore;// 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. Rule// mutations (create/update/delete/set-position, all read-modify-write on the set record) take@@ -68,6 +73,8 @@ public class SesReceiptRuleService {private final S3Service s3Service;private final SnsService snsService;private final LambdaService lambdaService;+ // Serializes filter create (duplicate check, then the 100-filter cap, then put).+ private final Object receiptFilterLock = new Object();private final Clock clock;@Inject@@ -75,6 +82,8 @@ public class SesReceiptRuleService {SnsService snsService, LambdaService lambdaService, Clock clock) {this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json",new TypeReference<Map<String, ReceiptRuleSet>>() {});+ this.receiptFilterStore = storageFactory.create("ses", "ses-receipt-filters.json",+ new TypeReference<Map<String, ReceiptFilter>>() {});this.s3Service = s3Service;this.snsService = snsService;this.lambdaService = lambdaService;@@ -82,9 +91,11 @@ public class SesReceiptRuleService {}SesReceiptRuleService(StorageBackend<String, ReceiptRuleSet> receiptRuleSetStore,+ StorageBackend<String, ReceiptFilter> receiptFilterStore,S3Service s3Service, SnsService snsService, LambdaService lambdaService,Clock clock) {this.receiptRuleSetStore = receiptRuleSetStore;+ this.receiptFilterStore = receiptFilterStore;this.s3Service = s3Service;this.snsService = snsService;this.lambdaService = lambdaService;@@ -550,6 +561,194 @@ public class SesReceiptRuleService {}}+ public void createReceiptFilter(ReceiptFilter filter, String region) {+ validateFilterShape(filter);+ requireValidFilterName(filter.getName());+ requireValidCidr(filter.getCidr());+ String key = receiptFilterKey(region, filter.getName());+ synchronized (receiptFilterLock) {+ if (receiptFilterStore.get(key).isPresent()) {+ throw new AwsException("AlreadyExists",+ "Filter already exists: " + filter.getName(), 400);+ }+ // Probed: the account/region holds at most 100 filters; the next create is rejected.+ if (receiptFilterStore.scan(k -> k.startsWith(receiptFilterPrefix(region))).size()+ >= MAX_FILTERS) {+ throw new AwsException("LimitExceeded", "Too many filters", 400);+ }+ receiptFilterStore.put(key, filter);+ }+ LOG.infov("Created SES receipt filter: {0} in region {1}", filter.getName(), region);+ }++ public List<ReceiptFilter> listReceiptFilters(String region) {+ List<ReceiptFilter> all = new ArrayList<>(+ receiptFilterStore.scan(k -> k.startsWith(receiptFilterPrefix(region))));+ // The wire ordering is not pinned by the probe (creation order and name order coincided);+ // sorting by name keeps the response deterministic across storage backends.+ all.sort(Comparator.comparing(ReceiptFilter::getName, Comparator.nullsLast(Comparator.naturalOrder())));+ return all;+ }++ public void deleteReceiptFilter(String filterName, String region) {+ if (filterName == null) {+ // Probed: an absent FilterName is the one case the wire rejects; deleting a missing+ // or malformed name succeeds without error.+ throw new AwsException("ValidationError",+ "1 validation error detected: Value at 'filterName' failed to satisfy "+ + "constraint: Member must not be null", 400);+ }+ receiptFilterStore.delete(receiptFilterKey(region, filterName));+ LOG.infov("Deleted SES receipt filter: {0} in region {1}", filterName, region);+ }++ /**+ * The Smithy-model layer of filter validation, probed: an absent IpFilter, Policy, or Cidr+ * is a not-null violation under the 'filter.ipFilter' paths, and a present Policy outside+ * [Allow, Block] (the empty string included) is an enum violation. Unlike rule and+ * rule-set names, a PRESENT filter name has no Smithy layer: every malformed non-null+ * shape lands on the service-level messages in {@link #requireValidFilterName}. Only an+ * absent name takes the not-null violation above (extrapolated; the SDKs cannot put an+ * absent name on the wire to probe it).+ */+ private static void validateFilterShape(ReceiptFilter filter) {+ if (filter == null) {+ throw new AwsException("ValidationError",+ "1 validation error detected: " + notNullViolation("filter"), 400);+ }+ List<String> violations = new ArrayList<>();+ if (filter.getName() == null) {+ violations.add(notNullViolation("filter.name"));+ }+ boolean hasIpFilter = filter.getPolicy() != null || filter.getCidr() != null;+ if (!hasIpFilter) {+ violations.add(notNullViolation("filter.ipFilter"));+ } else {+ if (filter.getPolicy() == null) {+ violations.add(notNullViolation("filter.ipFilter.policy"));+ } else if (!"Allow".equals(filter.getPolicy()) && !"Block".equals(filter.getPolicy())) {+ violations.add("Value at 'filter.ipFilter.policy' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [Allow, Block]");+ }+ if (filter.getCidr() == null) {+ violations.add(notNullViolation("filter.ipFilter.cidr"));+ }+ }+ if (!violations.isEmpty()) {+ String label = violations.size() == 1 ? "1 validation error detected: "+ : violations.size() + " validation errors detected: ";+ throw new AwsException("ValidationError", label + String.join("; ", violations), 400);+ }+ }++ private static String notNullViolation(String path) {+ return "Value at '" + path + "' failed to satisfy constraint: Member must not be null";+ }++ /**+ * Service-level filter name checks, probed: empty gets its own message, and every other+ * malformed shape (bad character, longer than 64, non-alphanumeric start or end) shares+ * the "Not a valid filterName" message.+ */+ private static void requireValidFilterName(String name) {+ if (name.isEmpty()) {+ throw new AwsException("InvalidParameterValue", "filterName must not be empty", 400);+ }+ if (!RULE_SET_NAME_CHARS.matcher(name).matches()+ || name.length() > 64+ || !Character.isLetterOrDigit(name.charAt(0))+ || !Character.isLetterOrDigit(name.charAt(name.length() - 1))) {+ throw new AwsException("InvalidParameterValue", "Not a valid filterName: " + name, 400);+ }+ }++ /**+ * Probed CIDR acceptance: a single IPv4 or IPv6 address, or a CIDR block with an in-range+ * mask (0-32 for IPv4, 0-128 for IPv6). Everything else is the probed+ * "Invalid CIDR block" message, the empty string included.+ */+ private static void requireValidCidr(String cidr) {+ if (!isValidCidr(cidr)) {+ throw new AwsException("InvalidParameterValue", "Invalid CIDR block: " + cidr, 400);+ }+ }++ private static boolean isValidCidr(String cidr) {+ String address = cidr;+ int slash = cidr.indexOf('/');+ Integer mask = null;+ if (slash >= 0) {+ address = cidr.substring(0, slash);+ String maskPart = cidr.substring(slash + 1);+ if (maskPart.isEmpty() || maskPart.length() > 3+ || !maskPart.chars().allMatch(c -> c >= '0' && c <= '9')) {+ return false;+ }+ mask = Integer.parseInt(maskPart);+ }+ if (IPV4_OCTETS.matcher(address).matches()) {+ return mask == null || mask <= 32;+ }+ if (isValidIpv6(address)) {+ return mask == null || mask <= 128;+ }+ return false;+ }++ /**+ * Strict IPv6 literal check, probed: bracketed ({@code [2001:db8::1]}), zone-scoped+ * ({@code fe80::1%eth0}), and IPv4-mapped ({@code ::ffff:192.0.2.1}) spellings are all+ * rejected by real SES, so the lenient {@code InetAddress} parser cannot be used here.+ * Accepted: colon-separated 1-4 digit hex groups, eight of them, or fewer with a single+ * {@code ::} compression.+ */+ private static boolean isValidIpv6(String address) {+ if (address.isEmpty() || address.indexOf('%') >= 0 || address.indexOf('.') >= 0+ || address.indexOf('[') >= 0 || address.indexOf(']') >= 0) {+ return false;+ }+ int compression = address.indexOf("::");+ if (compression != address.lastIndexOf("::")) {+ return false;+ }+ if (compression < 0) {+ return hexGroupCount(address) == 8;+ }+ int headGroups = hexGroupCount(address.substring(0, compression));+ int tailGroups = hexGroupCount(address.substring(compression + 2));+ return headGroups >= 0 && tailGroups >= 0 && headGroups + tailGroups <= 7;+ }++ /** Returns the number of valid 1-4 digit hex groups, or -1 when any group is malformed. */+ private static int hexGroupCount(String colonSeparated) {+ if (colonSeparated.isEmpty()) {+ return 0;+ }+ String[] groups = colonSeparated.split(":", -1);+ for (String group : groups) {+ if (group.isEmpty() || group.length() > 4) {+ return -1;+ }+ for (int i = 0; i < group.length(); i++) {+ // Explicit ASCII grammar: Character.digit also recognizes non-ASCII Unicode+ // digits, which real SES rejects (probed with fullwidth digits).+ char c = group.charAt(i);+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {+ return -1;+ }+ }+ }+ return groups.length;+ }++ private static String receiptFilterPrefix(String region) {+ return "receiptFilter::" + region + "::";+ }++ private static String receiptFilterKey(String region, String name) {+ return receiptFilterPrefix(region) + name;+ }+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.javaindex 76e106b49b..8d5acf1b73 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.ReceiptFilter;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;@@ -1308,6 +1309,18 @@ public class SesService {receiptRuleService.setReceiptRulePosition(ruleSetName, ruleName, after, region);}+ public void createReceiptFilter(ReceiptFilter filter, String region) {+ receiptRuleService.createReceiptFilter(filter, region);+ }++ public List<ReceiptFilter> listReceiptFilters(String region) {+ return receiptRuleService.listReceiptFilters(region);+ }++ public void deleteReceiptFilter(String filterName, String region) {+ receiptRuleService.deleteReceiptFilter(filterName, region);+ }+// ──────────────────────── Dedicated IP Pools ────────────────────────// Storage lives in SesDedicatedIpService; the facade forwards.diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptFilter.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptFilter.javanew file mode 100644index 0000000000..f81986b460--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReceiptFilter.java@@ -0,0 +1,56 @@+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;++/**+ * A SES v1 IP address filter. The wire shape nests Policy and Cidr under an IpFilter member;+ * the stored form is flat because the nesting carries no extra state.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class ReceiptFilter {++ @JsonProperty("Name")+ private String name;++ @JsonProperty("Policy")+ private String policy;++ @JsonProperty("Cidr")+ private String cidr;++ public ReceiptFilter() {+ }++ public ReceiptFilter(String name, String policy, String cidr) {+ this.name = name;+ this.policy = policy;+ this.cidr = cidr;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getPolicy() {+ return policy;+ }++ public void setPolicy(String policy) {+ this.policy = policy;+ }++ public String getCidr() {+ return cidr;+ }++ public void setCidr(String cidr) {+ this.cidr = cidr;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptFilterV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptFilterV1IntegrationTest.javanew file mode 100644index 0000000000..c531f52b3e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptFilterV1IntegrationTest.java@@ -0,0 +1,127 @@+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;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Integration tests for the SES V1 Query-protocol receipt-filter actions. Filters are stored+ * inertly (Floci accepts no inbound connections to filter), but the wire behavior follows real+ * AWS as probed: single-layer filterName validation, Smithy violations for missing IpFilter+ * members, the "Invalid CIDR block" service check, AlreadyExists on duplicates, and an+ * idempotent delete.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesReceiptFilterV1IntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/email/aws4_request";++ private static io.restassured.specification.RequestSpecification req(String action) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", AUTH)+ .formParam("Action", action);+ }++ private static io.restassured.specification.RequestSpecification create(+ String name, String policy, String cidr) {+ return req("CreateReceiptFilter")+ .formParam("Filter.Name", name)+ .formParam("Filter.IpFilter.Policy", policy)+ .formParam("Filter.IpFilter.Cidr", cidr);+ }++ @Test+ @Order(1)+ void createAndList_roundTrip() {+ create("floci-filter-block", "Block", "10.0.0.0/24")+ .when().post("/").then().statusCode(200)+ .body(containsString("CreateReceiptFilterResponse"));+ create("floci-filter-allow", "Allow", "192.0.2.10")+ .when().post("/").then().statusCode(200);++ String body = req("ListReceiptFilters")+ .when().post("/").then().statusCode(200)+ .body(containsString("<Name>floci-filter-block</Name>"))+ .body(containsString("<Policy>Block</Policy>"))+ .body(containsString("<Cidr>10.0.0.0/24</Cidr>"))+ .body(containsString("<Cidr>192.0.2.10</Cidr>"))+ .extract().asString();+ assertTrue(body.indexOf("floci-filter-allow") < body.indexOf("floci-filter-block"));+ }++ @Test+ @Order(2)+ void duplicateCreate_returnsAlreadyExists() {+ create("floci-filter-block", "Allow", "10.9.9.9")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>AlreadyExists</Code>"))+ .body(containsString("Filter already exists: floci-filter-block"));+ }++ @Test+ @Order(3)+ void bareCreate_returnsSingleFilterViolation() {+ // Probed: with no Filter member at all, the whole structure is the one violation.+ req("CreateReceiptFilter")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>ValidationError</Code>"))+ .body(containsString("1 validation error detected"))+ .body(containsString("'filter'"));+ }++ @Test+ @Order(3)+ void invalidInputs_matchProbedErrors() {+ create("bad name", "Block", "10.0.0.0/24")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>InvalidParameterValue</Code>"))+ .body(containsString("Not a valid filterName: bad name"));++ create("floci-filter-x", "Bogus", "10.0.0.0/24")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>ValidationError</Code>"))+ .body(containsString("'filter.ipFilter.policy'"))+ .body(containsString("[Allow, Block]"));++ create("floci-filter-x", "Block", "not-a-cidr")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>InvalidParameterValue</Code>"))+ .body(containsString("Invalid CIDR block: not-a-cidr"));++ req("CreateReceiptFilter").formParam("Filter.Name", "floci-filter-x")+ .when().post("/").then().statusCode(400)+ .body(containsString("'filter.ipFilter'"))+ .body(containsString("Member must not be null"));+ }++ @Test+ @Order(4)+ void deleteFilter_isIdempotent_andRequiresName() {+ req("DeleteReceiptFilter").formParam("FilterName", "floci-filter-allow")+ .when().post("/").then().statusCode(200);+ req("DeleteReceiptFilter").formParam("FilterName", "floci-filter-allow")+ .when().post("/").then().statusCode(200);++ req("ListReceiptFilters")+ .when().post("/").then().statusCode(200)+ .body(not(containsString("floci-filter-allow")));++ req("DeleteReceiptFilter")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>ValidationError</Code>"))+ .body(containsString("'filterName'"));++ req("DeleteReceiptFilter").formParam("FilterName", "floci-filter-block")+ .when().post("/").then().statusCode(200);+ }+}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.javaindex 8074fa2a3f..ca323ea4c1 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@@ -5,6 +5,7 @@ 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.ReceiptFilter;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;@@ -48,8 +49,12 @@ class SesReceiptRuleServiceTest {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());+ service = new SesReceiptRuleService(new InMemoryStorage<>(), new InMemoryStorage<>(),+ s3Service, snsService, lambdaService, Clock.systemUTC());+ }++ private static ReceiptFilter filter(String name, String policy, String cidr) {+ return new ReceiptFilter(name, policy, cidr);}private static ReceiptRule rule(String name, ReceiptAction... actions) {@@ -579,4 +584,100 @@ class SesReceiptRuleServiceTest {() -> service.describeReceiptRuleSet("rules-a", REGION));assertEquals("RuleSetDoesNotExist", e.getErrorCode());}++ // ---- receipt filters ----++ @Test+ void createFilter_thenList_roundTripsSortedByName() {+ service.createReceiptFilter(filter("zulu", "Block", "10.0.0.0/24"), REGION);+ service.createReceiptFilter(filter("alpha", "Allow", "192.0.2.10"), REGION);++ List<ReceiptFilter> listed = service.listReceiptFilters(REGION);+ assertEquals(List.of("alpha", "zulu"), listed.stream().map(ReceiptFilter::getName).toList());+ assertEquals("Allow", listed.get(0).getPolicy());+ assertEquals("192.0.2.10", listed.get(0).getCidr());+ }++ @Test+ void createFilter_duplicate_throwsAlreadyExists() {+ service.createReceiptFilter(filter("f1", "Block", "10.0.0.0/24"), REGION);+ AwsException e = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("f1", "Allow", "10.9.9.9"), REGION));+ assertEquals("AlreadyExists", e.getErrorCode());+ assertEquals("Filter already exists: f1", e.getMessage());+ assertEquals("Block", service.listReceiptFilters(REGION).get(0).getPolicy());+ }++ @Test+ void filterName_isSingleLayerServiceValidation() {+ // Unlike rule and rule-set names there is no Smithy pattern layer (probed): bad chars,+ // overlength, and bad boundaries all share one message, and empty has its own.+ for (String bad : new String[] {"bad name", "a".repeat(65), "-abc"}) {+ AwsException e = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter(bad, "Block", "10.0.0.0/24"), REGION));+ assertEquals("InvalidParameterValue", e.getErrorCode());+ assertEquals("Not a valid filterName: " + bad, e.getMessage());+ }+ AwsException empty = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("", "Block", "10.0.0.0/24"), REGION));+ assertEquals("filterName must not be empty", empty.getMessage());+ }++ @Test+ void filterShape_missingMembers_areSmithyViolations() {+ AwsException noIpFilter = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("f1", null, null), REGION));+ assertEquals("ValidationError", noIpFilter.getErrorCode());+ assertTrue(noIpFilter.getMessage().contains("'filter.ipFilter'"));++ AwsException noCidr = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("f1", "Block", null), REGION));+ assertTrue(noCidr.getMessage().contains("'filter.ipFilter.cidr'"));++ AwsException badPolicy = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("f1", "Bogus", "10.0.0.0/24"), REGION));+ assertTrue(badPolicy.getMessage().contains("'filter.ipFilter.policy'"));+ assertTrue(badPolicy.getMessage().contains("[Allow, Block]"));+ }++ @Test+ void cidr_validation_matchesProbedAcceptance() {+ service.createReceiptFilter(filter("single-ip", "Allow", "192.0.2.10"), REGION);+ service.createReceiptFilter(filter("ipv6", "Block", "2001:db8::/32"), REGION);++ // Probed: bracketed, zone-scoped, and IPv4-mapped IPv6 spellings are rejected too,+ // so the lenient InetAddress parser must not be used for validation.+ for (String bad : new String[] {"not-a-cidr", "", "10.0.0.0/33", "10.0.0/24", "10.0.0.0/",+ "[2001:db8::1]", "fe80::1%eth0", "::ffff:192.0.2.1", "2001:db8::/129",+ "1:2:3:4:5:6:7:8:9", "2001:db8:::1", "10.0.0.0/24", "0:0:0:0:0:0:0:1"}) {+ AwsException e = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("f-bad", "Block", bad), REGION));+ assertEquals("InvalidParameterValue", e.getErrorCode());+ assertEquals("Invalid CIDR block: " + bad, e.getMessage());+ }+ }++ @Test+ void deleteFilter_isIdempotent_butRequiresName() {+ service.createReceiptFilter(filter("f1", "Block", "10.0.0.0/24"), REGION);+ service.deleteReceiptFilter("f1", REGION);+ service.deleteReceiptFilter("f1", REGION);+ assertTrue(service.listReceiptFilters(REGION).isEmpty());++ AwsException e = assertThrows(AwsException.class,+ () -> service.deleteReceiptFilter(null, REGION));+ assertEquals("ValidationError", e.getErrorCode());+ assertTrue(e.getMessage().contains("'filterName'"));+ }++ @Test+ void createFilter_beyond100_throwsLimitExceeded() {+ for (int i = 1; i <= 100; i++) {+ service.createReceiptFilter(filter("f" + i, "Block", "10.0.0.0/24"), REGION);+ }+ AwsException e = assertThrows(AwsException.class,+ () -> service.createReceiptFilter(filter("f101", "Block", "10.0.0.0/24"), REGION));+ assertEquals("LimitExceeded", e.getErrorCode());+ assertEquals("Too many filters", e.getMessage());+ }}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.javaindex dd9de75d82..fb47deb7c0 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@@ -128,7 +128,7 @@ final class SesServiceTestBuilder {new SesDedicatedIpService(dedicatedIpPoolStore),new SesContactService(contactListStore, contactStore, clock),new SesPolicyService(policyStore, objectMapper),- new SesReceiptRuleService(receiptRuleStore, mock(S3Service.class),+ new SesReceiptRuleService(receiptRuleStore, new InMemoryStorage<>(), mock(S3Service.class),mock(SnsService.class), mock(LambdaService.class), clock),new SesCvetService(cvetStore),new SesTenantService(tenantStore, tenantAssociationStore, clock, new SecureRandom()),