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 f450ad4970..19255e938c 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 @@ -43,6 +43,7 @@ class SesReceiptRuleSetTest { private static SesClient ses; private static SnsClient sns; private static String ruleSet; + private static String cloneRuleSet; private static String topicArn; private static String blockFilter; private static String allowFilter; @@ -53,6 +54,7 @@ class SesReceiptRuleSetTest { sns = TestFixtures.snsClient(); String unique = TestFixtures.uniqueName(); ruleSet = "sdk-v1-rule-set-" + unique; + cloneRuleSet = "sdk-v1-rule-set-copy-" + 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(); @@ -66,11 +68,13 @@ class SesReceiptRuleSetTest { } 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 e) { - System.err.println("Best-effort cleanup of rule set " + ruleSet - + " failed (its rules cascade with it): " + e.getMessage()); + for (String name : new String[] {ruleSet, cloneRuleSet}) { + try { + ses.deleteReceiptRuleSet(b -> b.ruleSetName(name)); + } catch (RuntimeException e) { + System.err.println("Best-effort cleanup of rule set " + name + + " failed (its rules cascade with it): " + e.getMessage()); + } } for (String name : new String[] {blockFilter, allowFilter}) { try { @@ -238,6 +242,56 @@ class SesReceiptRuleSetTest { @Test @Order(12) + void reorder_requiresExactPermutation_andApplies() { + // The set holds [rich, first] here; reorder demands every rule exactly once. + ses.reorderReceiptRuleSet(b -> b.ruleSetName(ruleSet).ruleNames("first", "rich")); + assertThat(ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet)).rules()) + .extracting(ReceiptRule::name) + .containsExactly("first", "rich"); + + // A duplicate name is rejected before the missing-rule check, both as the wire's + // unmodeled InvalidParameterValue. + assertThatThrownBy(() -> ses.reorderReceiptRuleSet( + b -> b.ruleSetName(ruleSet).ruleNames("rich", "rich"))) + .isInstanceOfSatisfying(SesException.class, e -> assertThat( + e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue")) + .hasMessageContaining("Multiple positions found for rule: rich"); + + assertThatThrownBy(() -> ses.reorderReceiptRuleSet( + b -> b.ruleSetName(ruleSet).ruleNames("rich"))) + .hasMessageContaining("Positions for rules not found: first"); + + assertThatThrownBy(() -> ses.reorderReceiptRuleSet( + b -> b.ruleSetName(ruleSet).ruleNames("first", "rich", "ghost"))) + .isInstanceOf(RuleDoesNotExistException.class) + .hasMessageContaining("Rule does not exist: ghost"); + } + + @Test + @Order(13) + void clone_copiesRules_leavesActiveFlagBehind() { + ses.cloneReceiptRuleSet(b -> b.ruleSetName(cloneRuleSet).originalRuleSetName(ruleSet)); + + assertThat(ses.describeReceiptRuleSet(b -> b.ruleSetName(cloneRuleSet)).rules()) + .extracting(ReceiptRule::name) + .containsExactly("first", "rich"); + // The source was set active in an earlier test; the clone does not inherit that. + assertThat(ses.describeActiveReceiptRuleSet(b -> { }).metadata().name()) + .isEqualTo(ruleSet); + + assertThatThrownBy(() -> ses.cloneReceiptRuleSet( + b -> b.ruleSetName(cloneRuleSet).originalRuleSetName(ruleSet))) + .isInstanceOf(AlreadyExistsException.class) + .hasMessageContaining("Rule set already exists: " + cloneRuleSet); + + assertThatThrownBy(() -> ses.cloneReceiptRuleSet( + b -> b.ruleSetName("sdk-v1-fresh").originalRuleSetName("sdk-v1-nope"))) + .isInstanceOf(RuleSetDoesNotExistException.class) + .hasMessageContaining("Rule set does not exist: sdk-v1-nope"); + } + + @Test + @Order(14) void unsetActive_leavesNoActiveRuleSet() { ses.setActiveReceiptRuleSet(b -> { }); // no name clears the active rule set DescribeActiveReceiptRuleSetResponse a = ses.describeActiveReceiptRuleSet(b -> { }); @@ -245,7 +299,7 @@ class SesReceiptRuleSetTest { } @Test - @Order(13) + @Order(15) void delete_isIdempotent_andCascadesRemainingRules() { ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)); // Deleting an already-absent rule set still succeeds (matches AWS). @@ -255,7 +309,7 @@ class SesReceiptRuleSetTest { } @Test - @Order(14) + @Order(16) void createFilterAndList_roundTrip() { ses.createReceiptFilter(b -> b.filter(f -> f.name(blockFilter) .ipFilter(ip -> ip.policy(ReceiptFilterPolicy.BLOCK).cidr("10.0.0.0/24")))); @@ -271,7 +325,7 @@ class SesReceiptRuleSetTest { } @Test - @Order(15) + @Order(17) 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"))))) @@ -288,7 +342,7 @@ class SesReceiptRuleSetTest { } @Test - @Order(16) + @Order(18) void deleteFilter_isIdempotent() { ses.deleteReceiptFilter(b -> b.filterName(allowFilter)); ses.deleteReceiptFilter(b -> b.filterName(allowFilter)); diff --git a/docs/services/ses.md b/docs/services/ses.md index a3083a385b..1e749f0a86 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -69,6 +69,8 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an | `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 | +| `ReorderReceiptRuleSet` | Reposition every rule in a set (exact permutation required) | +| `CloneReceiptRuleSet` | Copy a rule set and its rules under a new name | | `CreateReceiptRule` | Add a receipt rule (stored inertly, action targets validated) | | `DescribeReceiptRule` | Read a receipt rule | | `UpdateReceiptRule` | Replace a receipt rule in place | @@ -183,7 +185,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 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. +- Receipt rule sets and receipt rules are stored inertly: Floci has no inbound-mail endpoint, so stored rules route no mail and their actions never execute, but the management API round-trips with AWS ordering, validation, and error semantics (probe-verified). Action targets are validated against the local emulator with the AWS error codes: an SNS `TopicArn`, S3 `BucketName`, or Lambda `FunctionArn` must reference an existing local resource, and a `BounceAction` `Sender` must be a verified identity. Deviations: S3 bucket write permissions, KMS keys, and `ConnectAction` role assumability are not verified (AWS checks these); `WorkmailAction` gets no resource validation (neither does AWS). Receipt IP filters are stored the same way, with the probed AWS validation and the 100-filter limit, but no inbound connection is ever filtered. `ReorderReceiptRuleSet` requires an exact permutation of the set's rules; `CloneReceiptRuleSet` copies them under a new creation timestamp, leaving the active flag behind. - Custom verification email templates are stored and returned; `Create`/`Update` require the `FromEmailAddress` to be a verified identity (or a verified domain) and reject an invalid redirection URL, matching AWS. `SendCustomVerificationEmail` renders the template into the `/_aws/ses` inspection mailbox (and the SMTP relay, when configured) and registers the recipient as a pending-verification identity, matching AWS. The template body has no placeholder that AWS substitutes, so it is passed through verbatim with the same fixed disclaimer AWS always appends; the unique verification link AWS appends is not reproduced because Floci has no verification-click flow. The `SuccessRedirectionURL` / `FailureRedirectionURL` are stored and returned by Get/List but are the post-click redirect targets, so they are not used at send time. - 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 621078cc7f..fb1e9d9b00 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 @@ -577,6 +577,7 @@ public class AwsQueryController { "PutConfigurationSetDeliveryOptions", "CreateReceiptRuleSet", "DescribeReceiptRuleSet", "ListReceiptRuleSets", "DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet", + "ReorderReceiptRuleSet", "CloneReceiptRuleSet", "CreateReceiptRule", "DescribeReceiptRule", "UpdateReceiptRule", "DeleteReceiptRule", "SetReceiptRulePosition", "CreateReceiptFilter", "ListReceiptFilters", "DeleteReceiptFilter" 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 8ce22954ec..613b835fb7 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 @@ -133,6 +133,8 @@ public class SesQueryHandler { case "DeleteReceiptRuleSet" -> handleDeleteReceiptRuleSet(params, region); case "SetActiveReceiptRuleSet" -> handleSetActiveReceiptRuleSet(params, region); case "DescribeActiveReceiptRuleSet" -> handleDescribeActiveReceiptRuleSet(region); + case "ReorderReceiptRuleSet" -> handleReorderReceiptRuleSet(params, region); + case "CloneReceiptRuleSet" -> handleCloneReceiptRuleSet(params, region); case "CreateReceiptRule" -> handleCreateReceiptRule(params, region); case "DescribeReceiptRule" -> handleDescribeReceiptRule(params, region); case "UpdateReceiptRule" -> handleUpdateReceiptRule(params, region); @@ -1032,6 +1034,75 @@ public class SesQueryHandler { "DescribeActiveReceiptRuleSet", AwsNamespaces.SES, xml.build())).build(); } + private Response handleReorderReceiptRuleSet(MultivaluedMap params, String region) { + sesService.reorderReceiptRuleSet(getParam(params, "RuleSetName"), + parseReorderRuleNames(params), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "ReorderReceiptRuleSet", AwsNamespaces.SES)).build(); + } + + // Probed boundary of the RuleNames index grammar: 214748369 is the largest index the parser + // accepts (larger is MalformedInput "Index N is illegal"), found by bisection; it is near but + // not at Integer.MAX_VALUE / 10, so it is pinned as a literal rather than derived. + private static final int MAX_RULE_NAMES_INDEX = 214748369; + private static final int MAX_RULE_NAMES_INDEX_SKIP = 10; + + /** + * Parses the ReorderReceiptRuleSet RuleNames flattened string list with the probed AWS + * grammar, which differs from the receipt-action struct list: an index gap is padded with + * empty members (up to a skip of {@value MAX_RULE_NAMES_INDEX_SKIP}, counted from the + * previous index, or from 1 for a leading gap), which then fail the ruleNames Smithy + * constraint downstream; a larger gap, index 0, a leading-zero spelling, a non-numeric + * token, and an index beyond {@value MAX_RULE_NAMES_INDEX} are each their own probed + * MalformedInput. A repeated index keeps its first value. + */ + private List parseReorderRuleNames(MultivaluedMap params) { + String prefix = "RuleNames.member."; + Map byIndex = new java.util.TreeMap<>(); + for (String key : params.keySet()) { + if (!key.startsWith(prefix)) { + continue; + } + String token = key.substring(prefix.length()); + if (token.isEmpty() || !token.chars().allMatch(c -> c >= '0' && c <= '9')) { + throw new AwsException("MalformedInput", "Start of list found where not expected", 400); + } + if ("0".equals(token)) { + throw new AwsException("MalformedInput", "0 is not a valid index", 400); + } + if (token.charAt(0) == '0') { + throw new AwsException("MalformedInput", "Value found where not expected", 400); + } + if (token.length() > 9 || Integer.parseInt(token) > MAX_RULE_NAMES_INDEX) { + throw new AwsException("MalformedInput", "Index " + token + " is illegal", 400); + } + byIndex.putIfAbsent(Integer.parseInt(token), getParam(params, key)); + } + List names = new ArrayList<>(); + int previous = 0; + for (Map.Entry member : byIndex.entrySet()) { + int index = member.getKey(); + int skip = index - Math.max(previous, 1); + if (skip > MAX_RULE_NAMES_INDEX_SKIP) { + throw new AwsException("MalformedInput", String.format(java.util.Locale.ROOT, + "Excessively sparse input would skip %,d list elements", skip), 400); + } + while (names.size() < index - 1) { + names.add(""); + } + names.add(member.getValue()); + previous = index; + } + return names; + } + + private Response handleCloneReceiptRuleSet(MultivaluedMap params, String region) { + sesService.cloneReceiptRuleSet(getParam(params, "RuleSetName"), + getParam(params, "OriginalRuleSetName"), region); + return Response.ok(AwsQueryResponse.envelopeEmptyResult( + "CloneReceiptRuleSet", AwsNamespaces.SES)).build(); + } + private Response handleCreateReceiptRule(MultivaluedMap params, String region) { sesService.createReceiptRule(getParam(params, "RuleSetName"), parseReceiptRule(params), getParam(params, "After"), region); 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 d5f2c6231b..84c50ac0c2 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 @@ -19,6 +19,7 @@ import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; @@ -49,6 +50,9 @@ public class SesReceiptRuleService { // 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; + // The Smithy cap on a ReorderReceiptRuleSet RuleNames member (probed 2026-09: distinct from + // the 64-char service-level name checks; see ruleNamesMemberViolation). + private static final int MAX_REORDER_RULE_NAME_LENGTH = 100; 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 @@ -282,6 +286,92 @@ public class SesReceiptRuleService { LOG.infov("Positioned SES receipt rule {0} in rule set {1} ({2})", ruleName, ruleSetName, region); } + public void reorderReceiptRuleSet(String ruleSetName, List ruleNames, String region) { + if (ruleSetName == null) { + throw new AwsException("InvalidParameterValue", "RuleSetName is required.", 400); + } + List violations = new ArrayList<>(); + collectRuleNameParamViolations(ruleSetName, "ruleSetName", violations); + // Probed: RuleNames members validate under the bare 'ruleNames' path with a nested + // list-member constraint whose length cap is 100 (not the 64 of the service-level + // name checks), and there is no "Not a valid ruleName" stage after it: a 65-char + // pattern-valid name falls through to RuleDoesNotExist. The violation carries no + // member index and appears at most once, however many members are malformed. + if (ruleNames.stream().anyMatch(name -> name.isEmpty() + || name.length() > MAX_REORDER_RULE_NAME_LENGTH + || !RULE_SET_NAME_CHARS.matcher(name).matches())) { + violations.add(ruleNamesMemberViolation()); + } + throwViolations(violations); + requireValidRuleSetName(ruleSetName); + synchronized (receiptRuleSetLock) { + ReceiptRuleSet ruleSet = requireRuleSet(ruleSetName, region); + // Probed precedence, matching a build-the-position-map-first algorithm: a duplicate + // request name is rejected before anything else (even when the duplicated name is not + // in the set), then set rules absent from the request, then request names not in the + // set (first in request order). + Map positions = new HashMap<>(); + for (int i = 0; i < ruleNames.size(); i++) { + if (positions.putIfAbsent(ruleNames.get(i), i) != null) { + throw new AwsException("InvalidParameterValue", + "Multiple positions found for rule: " + ruleNames.get(i), 400); + } + } + List rules = ruleSet.getRules(); + List missing = rules.stream() + .map(ReceiptRule::getName) + .filter(name -> !positions.containsKey(name)) + .toList(); + if (!missing.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "Positions for rules not found: " + String.join(", ", missing), 400); + } + if (positions.size() > rules.size()) { + for (String name : ruleNames) { + if (rules.stream().noneMatch(r -> name.equals(r.getName()))) { + throw new AwsException("RuleDoesNotExist", "Rule does not exist: " + name, 400); + } + } + } + List reordered = new ArrayList<>(rules); + reordered.sort(Comparator.comparingInt(rule -> positions.get(rule.getName()))); + replaceRules(ruleSet, reordered, ruleSetName, region); + } + LOG.infov("Reordered SES receipt rule set {0} in region {1}", ruleSetName, region); + } + + public ReceiptRuleSet cloneReceiptRuleSet(String ruleSetName, String originalRuleSetName, String region) { + if (ruleSetName == null) { + throw new AwsException("InvalidParameterValue", "RuleSetName is required.", 400); + } + if (originalRuleSetName == null) { + throw new AwsException("InvalidParameterValue", "OriginalRuleSetName is required.", 400); + } + List violations = new ArrayList<>(); + // Probed: with both members malformed, the combined message lists originalRuleSetName + // before ruleSetName; the service-level checks then run target before source. + collectRuleNameParamViolations(originalRuleSetName, "originalRuleSetName", violations); + collectRuleNameParamViolations(ruleSetName, "ruleSetName", violations); + throwViolations(violations); + requireValidRuleSetName(ruleSetName); + requireValidRuleSetName(originalRuleSetName); + // The clone gets its own creation time and starts inactive; neither is copied (probed: + // cloning the active rule set leaves the clone inactive and the active set unchanged). + ReceiptRuleSet clone = new ReceiptRuleSet(ruleSetName, Instant.now(clock)); + synchronized (receiptRuleSetLock) { + if (receiptRuleSetStore.get(receiptRuleSetKey(region, ruleSetName)).isPresent()) { + // Probed: an existing target wins over a missing source. + throw new AwsException("AlreadyExists", "Rule set already exists: " + ruleSetName, 400); + } + ReceiptRuleSet original = requireRuleSet(originalRuleSetName, region); + clone.setRules(original.getRules().stream().map(ReceiptRule::copy).toList()); + receiptRuleSetStore.put(receiptRuleSetKey(region, ruleSetName), clone); + } + LOG.infov("Cloned SES receipt rule set {0} from {1} in region {2}", + ruleSetName, originalRuleSetName, region); + return clone; + } + /** * 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 @@ -443,6 +533,18 @@ public class SesReceiptRuleService { + "Member must satisfy enum value set: " + valueSet; } + /** + * The one violation shape a malformed ReorderReceiptRuleSet RuleNames member produces, + * probed: empty, longer than 100, and pattern-breaking names all get this same nested + * list-member constraint under the bare 'ruleNames' path, with no member index. + */ + private static String ruleNamesMemberViolation() { + return "Value at 'ruleNames' failed to satisfy constraint: Member must satisfy constraint: " + + "[Member must have length less than or equal to " + MAX_REORDER_RULE_NAME_LENGTH + + ", Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$]"; + } + /** * 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 @@ -768,6 +870,15 @@ public class SesReceiptRuleService { "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: " + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$", 400); } + requireValidRuleSetName(name); + } + + /** + * The service-level rule set name check that runs after the Smithy pattern passes. Reorder + * and clone reach it directly: their empty-name case is a Smithy length violation on the + * wire (probed), not the "RuleSetName is required." of {@link #requireRuleSetName}. + */ + private static void requireValidRuleSetName(String name) { if (name.length() > 64 || !Character.isLetterOrDigit(name.charAt(0)) || !Character.isLetterOrDigit(name.charAt(name.length() - 1))) { 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 3ad3ab715b..1baabe80db 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 @@ -1155,6 +1155,14 @@ public class SesService { return receiptRuleService.describeActiveReceiptRuleSet(region); } + public void reorderReceiptRuleSet(String ruleSetName, List ruleNames, String region) { + receiptRuleService.reorderReceiptRuleSet(ruleSetName, ruleNames, region); + } + + public ReceiptRuleSet cloneReceiptRuleSet(String ruleSetName, String originalRuleSetName, String region) { + return receiptRuleService.cloneReceiptRuleSet(ruleSetName, originalRuleSetName, 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. 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 index 2b4dc8bd7c..37bb9d447f 100644 --- 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 @@ -75,6 +75,13 @@ public class ReceiptAction { return getProperties().get(name); } + /** Deep copy; the property map is mutable. */ + public ReceiptAction copy() { + ReceiptAction copy = new ReceiptAction(type); + copy.properties = new LinkedHashMap<>(getProperties()); + return copy; + } + 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 index d04dcdae18..ac818b5f7a 100644 --- 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 @@ -82,4 +82,16 @@ public class ReceiptRule { public void setActions(List actions) { this.actions = actions; } + + /** Deep copy, so a cloned rule set never aliases the mutable state of the original's rules. */ + public ReceiptRule copy() { + ReceiptRule copy = new ReceiptRule(); + copy.name = name; + copy.enabled = enabled; + copy.tlsPolicy = tlsPolicy; + copy.scanEnabled = scanEnabled; + copy.recipients = new ArrayList<>(getRecipients()); + copy.actions = new ArrayList<>(getActions().stream().map(ReceiptAction::copy).toList()); + return copy; + } } 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 ca323ea4c1..33e1c6a1ca 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 @@ -585,6 +585,209 @@ class SesReceiptRuleServiceTest { assertEquals("RuleSetDoesNotExist", e.getErrorCode()); } + // ---- reorder / clone ---- + + private void createThreeRuleSet(String name) { + service.createReceiptRuleSet(name, REGION); + service.createReceiptRule(name, rule("r1"), null, REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule(name, rule("r2"), "r1", REGION, ANY_SENDER_VERIFIED); + service.createReceiptRule(name, rule("r3"), "r2", REGION, ANY_SENDER_VERIFIED); + } + + @Test + void reorder_appliesFullPermutation() { + createThreeRuleSet("rules-a"); + service.reorderReceiptRuleSet("rules-a", List.of("r3", "r1", "r2"), REGION); + assertEquals(List.of("r3", "r1", "r2"), ruleNames("rules-a")); + } + + @Test + void reorder_identityOrder_isNoOp() { + createThreeRuleSet("rules-a"); + service.reorderReceiptRuleSet("rules-a", List.of("r1", "r2", "r3"), REGION); + assertEquals(List.of("r1", "r2", "r3"), ruleNames("rules-a")); + } + + @Test + void reorder_unknownSet_throwsBeforeRuleNameProblems() { + AwsException e = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("ghost", List.of("rX", "rX"), REGION)); + assertEquals("RuleSetDoesNotExist", e.getErrorCode()); + } + + @Test + void reorder_duplicateName_winsOverMissingAndUnknown() { + createThreeRuleSet("rules-a"); + + // Duplicate of an existing name, with the set only partially covered. + AwsException dup = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", List.of("r1", "r1"), REGION)); + assertEquals("InvalidParameterValue", dup.getErrorCode()); + assertEquals("Multiple positions found for rule: r1", dup.getMessage()); + + // Duplicate of a name that is not in the set at all still takes the duplicate error. + AwsException dupUnknown = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", + List.of("r1", "r2", "r3", "rX", "rX"), REGION)); + assertEquals("Multiple positions found for rule: rX", dupUnknown.getMessage()); + } + + @Test + void reorder_missingRules_listedInSetOrder_beforeUnknownNames() { + createThreeRuleSet("rules-a"); + service.reorderReceiptRuleSet("rules-a", List.of("r3", "r1", "r2"), REGION); + + // Unknown rX does not surface while set rules are missing; the list follows set order. + AwsException e = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", List.of("r2", "rX"), REGION)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals("Positions for rules not found: r3, r1", e.getMessage()); + + // An empty RuleNames list is the same error naming every rule. + AwsException empty = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", List.of(), REGION)); + assertEquals("Positions for rules not found: r3, r1, r2", empty.getMessage()); + } + + @Test + void reorder_unknownName_reportsFirstInRequestOrder_andLeavesOrderUnchanged() { + createThreeRuleSet("rules-a"); + AwsException e = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", + List.of("r1", "r2", "r3", "rX", "rY"), REGION)); + assertEquals("RuleDoesNotExist", e.getErrorCode()); + assertEquals("Rule does not exist: rX", e.getMessage()); + assertEquals(List.of("r1", "r2", "r3"), ruleNames("rules-a")); + } + + @Test + void reorder_ruleNamesMembers_getNestedSmithyViolation_beforeSetExistence() { + AwsException badChar = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("ghost", List.of("bad name!"), REGION)); + assertEquals("ValidationError", badChar.getErrorCode()); + assertEquals("1 validation error detected: Value at 'ruleNames' failed to satisfy " + + "constraint: Member must satisfy constraint: " + + "[Member must have length less than or equal to 100, " + + "Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$]", + badChar.getMessage()); + + // Empty and >100 take the same violation; a 65-char name passes (the cap here is 100, + // not the 64 of the service-level name checks) and lands on RuleDoesNotExist instead. + createThreeRuleSet("rules-a"); + AwsException empty = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", List.of(""), REGION)); + assertEquals("ValidationError", empty.getErrorCode()); + AwsException tooLong = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", List.of("a".repeat(101)), REGION)); + assertEquals("ValidationError", tooLong.getErrorCode()); + AwsException longButLegal = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", + List.of("r1", "r2", "r3", "a".repeat(65)), REGION)); + assertEquals("RuleDoesNotExist", longButLegal.getErrorCode()); + + // Several malformed members still produce the single index-less violation (probed). + AwsException manyBad = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("rules-a", + List.of("bad name!", "", "a".repeat(101)), REGION)); + assertTrue(manyBad.getMessage().startsWith("1 validation error detected: ")); + } + + @Test + void reorder_ruleSetName_getsSmithyThenServiceValidation() { + AwsException empty = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("", List.of("r1"), REGION)); + assertEquals("ValidationError", empty.getErrorCode()); + assertTrue(empty.getMessage().startsWith("2 validation errors detected: ")); + assertTrue(empty.getMessage().contains("'ruleSetName'")); + + AwsException tooLong = assertThrows(AwsException.class, + () -> service.reorderReceiptRuleSet("a".repeat(65), List.of("r1"), REGION)); + assertEquals("InvalidParameterValue", tooLong.getErrorCode()); + assertEquals("Not a valid ruleSetName: " + "a".repeat(65), tooLong.getMessage()); + } + + @Test + void clone_deepCopiesRulesWithNewTimestampAndInactive() { + createThreeRuleSet("rules-src"); + service.createReceiptRule("rules-src", + rule("r0", action("S3Action", "BucketName", "inbox", "ObjectKeyPrefix", "mail/")), + null, REGION, ANY_SENDER_VERIFIED); + service.setActiveReceiptRuleSet("rules-src", REGION); + ReceiptRuleSet original = service.describeReceiptRuleSet("rules-src", REGION); + + ReceiptRuleSet clone = service.cloneReceiptRuleSet("rules-copy", "rules-src", REGION); + + assertEquals("rules-copy", clone.getName()); + assertEquals(List.of("r0", "r1", "r2", "r3"), ruleNames("rules-copy")); + assertEquals("inbox", service.describeReceiptRule("rules-copy", "r0", REGION) + .getActions().get(0).property("BucketName")); + assertNotNull(clone.getCreatedTimestamp()); + assertFalse(clone.getCreatedTimestamp().isBefore(original.getCreatedTimestamp())); + // The active flag stays with the original. + assertFalse(clone.isActive()); + assertEquals("rules-src", service.describeActiveReceiptRuleSet(REGION).getName()); + } + + @Test + void clone_isIndependentOfLaterSourceMutations() { + createThreeRuleSet("rules-src"); + service.cloneReceiptRuleSet("rules-copy", "rules-src", REGION); + + service.deleteReceiptRule("rules-src", "r1", REGION); + service.describeReceiptRule("rules-src", "r2", REGION) + .getActions().add(action("StopAction", "Scope", "RuleSet")); + + assertEquals(List.of("r1", "r2", "r3"), ruleNames("rules-copy")); + assertTrue(service.describeReceiptRule("rules-copy", "r2", REGION).getActions().isEmpty()); + } + + @Test + void clone_emptySet_succeeds() { + service.createReceiptRuleSet("rules-empty", REGION); + service.cloneReceiptRuleSet("rules-copy", "rules-empty", REGION); + assertEquals(List.of(), ruleNames("rules-copy")); + } + + @Test + void clone_missingSource_throwsRuleSetDoesNotExist() { + AwsException e = assertThrows(AwsException.class, + () -> service.cloneReceiptRuleSet("rules-copy", "ghost", REGION)); + assertEquals("RuleSetDoesNotExist", e.getErrorCode()); + assertEquals("Rule set does not exist: ghost", e.getMessage()); + } + + @Test + void clone_existingTarget_winsOverMissingSource() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.cloneReceiptRuleSet("rules-a", "ghost", REGION)); + assertEquals("AlreadyExists", e.getErrorCode()); + assertEquals("Rule set already exists: rules-a", e.getMessage()); + } + + @Test + void clone_nameValidation_isTwoLayer_targetBeforeSource() { + // Smithy pattern layer combines both members, original first. + AwsException bothBad = assertThrows(AwsException.class, + () -> service.cloneReceiptRuleSet("bad target!", "bad source!", REGION)); + assertEquals("ValidationError", bothBad.getErrorCode()); + assertTrue(bothBad.getMessage().startsWith("2 validation errors detected: ")); + assertTrue(bothBad.getMessage().indexOf("'originalRuleSetName'") + < bothBad.getMessage().indexOf("'ruleSetName'")); + + // The service-level length check reports the target before the source and does not + // name the member. + AwsException bothLong = assertThrows(AwsException.class, + () -> service.cloneReceiptRuleSet("a".repeat(65), "b".repeat(65), REGION)); + assertEquals("InvalidParameterValue", bothLong.getErrorCode()); + assertEquals("Not a valid ruleSetName: " + "a".repeat(65), bothLong.getMessage()); + + AwsException sourceLong = assertThrows(AwsException.class, + () -> service.cloneReceiptRuleSet("rules-copy", "b".repeat(65), REGION)); + assertEquals("Not a valid ruleSetName: " + "b".repeat(65), sourceLong.getMessage()); + } + // ---- receipt filters ---- @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetReorderCloneV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetReorderCloneV1IntegrationTest.java new file mode 100644 index 0000000000..3962016974 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetReorderCloneV1IntegrationTest.java @@ -0,0 +1,213 @@ +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 ReorderReceiptRuleSet and CloneReceiptRuleSet + * actions. Wire behavior follows real AWS as probed (2026-09): reorder demands an exact + * permutation of the set with a duplicate-then-missing-then-unknown error precedence, and clone + * deep-copies the rules under a new creation timestamp while the active flag stays behind. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesReceiptRuleSetReorderCloneV1IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-2/email/aws4_request"; + private static final String RS = "floci-v1-reorder"; + private static final String CLONE = "floci-v1-reorder-copy"; + + 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 String describeRuleNames(String ruleSetName) { + return req("DescribeReceiptRuleSet").formParam("RuleSetName", ruleSetName) + .when().post("/").then().statusCode(200).extract().asString(); + } + + @Test + @Order(1) + void reorder_appliesPermutation_andAnswersEmptyResult() { + req("CreateReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200); + for (String name : new String[] {"r3", "r2", "r1"}) { + // Without After each create lands at the front, so the set reads r1, r2, r3. + req("CreateReceiptRule").formParam("RuleSetName", RS) + .formParam("Rule.Name", name) + .when().post("/").then().statusCode(200); + } + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r2") + .formParam("RuleNames.member.2", "r3") + .formParam("RuleNames.member.3", "r1") + .when().post("/").then().statusCode(200) + .body(containsString("ReorderReceiptRuleSetResponse")); + + String body = describeRuleNames(RS); + assertTrue(body.indexOf("r2") < body.indexOf("r3")); + assertTrue(body.indexOf("r3") < body.indexOf("r1")); + } + + @Test + @Order(2) + void reorder_errorPrecedence_onTheWire() { + req("ReorderReceiptRuleSet").formParam("RuleSetName", "floci-v1-ghost") + .formParam("RuleNames.member.1", "r1") + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")) + .body(containsString("Rule set does not exist: floci-v1-ghost")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r1") + .formParam("RuleNames.member.2", "r1") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Multiple positions found for rule: r1")); + + // Missing set rules (listed in set order) win over the unknown name. + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r3") + .formParam("RuleNames.member.2", "rX") + .when().post("/").then().statusCode(400) + .body(containsString("Positions for rules not found: r2, r1")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r1") + .formParam("RuleNames.member.2", "r2") + .formParam("RuleNames.member.3", "r3") + .formParam("RuleNames.member.4", "rX") + .when().post("/").then().statusCode(400) + .body(containsString("RuleDoesNotExist")) + .body(containsString("Rule does not exist: rX")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "bad name!") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("Value at 'ruleNames' failed to satisfy constraint: " + + "Member must satisfy constraint: " + + "[Member must have length less than or equal to 100")); + } + + @Test + @Order(3) + void clone_deepCopies_andActiveStaysBehind() { + req("SetActiveReceiptRuleSet").formParam("RuleSetName", RS) + .when().post("/").then().statusCode(200); + + req("CloneReceiptRuleSet").formParam("RuleSetName", CLONE) + .formParam("OriginalRuleSetName", RS) + .when().post("/").then().statusCode(200) + .body(containsString("CloneReceiptRuleSetResponse")); + + String body = describeRuleNames(CLONE); + assertTrue(body.contains("" + CLONE + "")); + assertTrue(body.indexOf("r2") < body.indexOf("r3")); + + req("DescribeActiveReceiptRuleSet") + .when().post("/").then().statusCode(200) + .body(containsString("" + RS + "")); + + // Clear the active flag so the shared-state teardown delete succeeds. + req("SetActiveReceiptRuleSet") + .when().post("/").then().statusCode(200); + } + + @Test + @Order(4) + void clone_targetConflictAndMissingSource_errors() { + req("CloneReceiptRuleSet").formParam("RuleSetName", CLONE) + .formParam("OriginalRuleSetName", "floci-v1-ghost") + .when().post("/").then().statusCode(400) + .body(containsString("AlreadyExists")) + .body(containsString("Rule set already exists: " + CLONE)); + + req("CloneReceiptRuleSet").formParam("RuleSetName", "floci-v1-fresh") + .formParam("OriginalRuleSetName", "floci-v1-ghost") + .when().post("/").then().statusCode(400) + .body(containsString("RuleSetDoesNotExist")) + .body(containsString("Rule set does not exist: floci-v1-ghost")); + } + + @Test + @Order(5) + void reorder_ruleNamesIndexGrammar_matchesProbedWire() { + // A gap of up to 10 is padded with empty members, which then fail the ruleNames + // Smithy constraint; nothing is truncated. + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r1") + .formParam("RuleNames.member.3", "r3") + .when().post("/").then().statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("Value at 'ruleNames' failed to satisfy constraint")); + + // A larger gap is its own MalformedInput; the skip counts from the previous index. + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r1") + .formParam("RuleNames.member.2", "r2") + .formParam("RuleNames.member.3", "r3") + .formParam("RuleNames.member.14", "rX") + .when().post("/").then().statusCode(400) + .body(containsString("MalformedInput")) + .body(containsString("Excessively sparse input would skip 11 list elements")); + + // The skip count is comma-grouped like AWS renders it. + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r1") + .formParam("RuleNames.member.1500", "rX") + .when().post("/").then().statusCode(400) + .body(containsString("Excessively sparse input would skip 1,499 list elements")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.0", "r1") + .when().post("/").then().statusCode(400) + .body(containsString("MalformedInput")) + .body(containsString("0 is not a valid index")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.01", "r1") + .when().post("/").then().statusCode(400) + .body(containsString("Value found where not expected")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.x", "r1") + .when().post("/").then().statusCode(400) + .body(containsString("Start of list found where not expected")); + + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.999999999", "r1") + .when().post("/").then().statusCode(400) + .body(containsString("Index 999999999 is illegal")); + + // A repeated index keeps its first value: the list reads r1, r1, r3 and trips the + // duplicate-name check, proving the second value never displaced the first. + req("ReorderReceiptRuleSet").formParam("RuleSetName", RS) + .formParam("RuleNames.member.1", "r1", "r2") + .formParam("RuleNames.member.2", "r1") + .formParam("RuleNames.member.3", "r3") + .when().post("/").then().statusCode(400) + .body(containsString("Multiple positions found for rule: r1")); + } + + @Test + @Order(6) + void cleanup_deletesBothSets() { + for (String name : new String[] {RS, CLONE}) { + req("DeleteReceiptRuleSet").formParam("RuleSetName", name) + .when().post("/").then().statusCode(200); + } + } +}