feat(ses): implement v1 receipt rules with locally validated action targets (#3119)

* feat(ses): implement v1 receipt rules with locally validated action targets

Adds the five v1 receipt-rule actions (CreateReceiptRule, DescribeReceiptRule,
UpdateReceiptRule, DeleteReceiptRule, SetReceiptRulePosition) on top of the
stored-but-inert receipt-rule-set domain. Rules route no mail, but ordering
semantics follow real AWS as probed: a rule created without After is inserted
at the front, SetReceiptRulePosition without After moves a rule to the front,
update replaces the whole rule in place, and rule delete is idempotent while
rule-set delete cascades.

Action targets are validated against the local emulator the way real SES
validates them against the account: any TopicArn must be an existing SNS
topic, an S3 BucketName an existing bucket, a Lambda FunctionArn an existing
function, and a BounceAction Sender a verified identity, using the probed
error codes (InvalidSnsTopic, InvalidS3Configuration, InvalidLambdaFunction,
InvalidParameterValue). Smithy-layer validation reproduces the probed member
paths and combined violation messages; only the members real SES enforces are
required (S3 BucketName, SNS TopicArn, and Stop Scope may be absent).

Covered by unit tests with mocked resource services, Query-protocol
integration tests, an AWS SDK compatibility test, and Terraform/OpenTofu
compat coverage for aws_ses_receipt_rule.

* fix(ses): match probed AWS semantics for action-list gaps and present-struct required members

Probing triggered by the upstream review corrected two earlier conclusions.
A gap in the action list (an empty struct serializes to no Query keys) is
not compacted by AWS: the gap is padded into an empty action slot and
rejected with InvalidParameterValue "Exactly one action type must be
specified for each ReceiptAction", with Smithy paths keeping the wire
index. member.0 is rejected outright with MalformedInput
"0 is not a valid index".

The earlier "optional" verdict for S3Action.BucketName, SNSAction.TopicArn,
and StopAction.Scope was an artifact of empty structs never reaching the
wire: once an action carries any member, the type's required members are
enforced as Smithy violations. BounceAction violations are reported in the
probed smtpReplyCode, sender, message order, and SNSAction reports a bad
Encoding enum before the missing TopicArn.

* fix(ses): honor original receipt-action index spellings and require stop actions last

Probing the leading-zero report pinned AWS's index semantics exactly: index
tokens are grouped by numeric value, ordered by length then lexicographically,
and the i-th token must parse to i, or the padded empty slot is rejected with
the exactly-one-action-type error. member.01 alone is therefore a valid slot 1
whose action must be parsed under its original spelling instead of a rebuilt
canonical one, while mixed spellings such as member.01 plus member.2 are
rejected because the one-digit token sorts first.

The same probes surfaced an unrelated service-level rule now reproduced too:
a stop action anywhere but the last position is rejected with
"Stop action, if any, must be placed at the end of the actions list".

* chore(ses): log best-effort compat-test cleanup failures with resource context

The three cleanup catches in the receipt-rule compatibility suite swallowed
failures silently. They now report the failed step and resource on stderr,
the form the other suites in this module already use, so leaked test
resources stay diagnosable.

* chore(lambda): log functionExists resolution failures at debug level

The catch converts a resolution failure into the predicate's negative
answer; the debug line keeps a surprising false diagnosable (which
reference was rejected, and why) without turning ordinary existence
misses on a query path into log noise.

* fix(ses): restrict receipt-action index tokens to ASCII digits

Character.isDigit also accepts non-ASCII Unicode digits, so a key such as
Rule.Actions.member.<fullwidth 1> parsed as a real index. No AWS Query
index grammar recognizes those spellings; the key is now skipped like any
other unmodeled parameter, pinned by an integration test.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
Kenshin OkinakaandPriamo authored and GitHub committed 2026-09-06 18:01:33 -04:00
1 parent 4570bf62c5
commit fd665a08cc
22 files changed
+2040 -37

No files matched your search

@@ -12,30 +12,42 @@ import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.AlreadyExistsException;
import software.amazon.awssdk.services.ses.model.CannotDeleteException;
import software.amazon.awssdk.services.ses.model.DescribeActiveReceiptRuleSetResponse;
import software.amazon.awssdk.services.ses.model.DescribeReceiptRuleResponse;
import software.amazon.awssdk.services.ses.model.DescribeReceiptRuleSetResponse;
import software.amazon.awssdk.services.ses.model.InvalidSnsTopicException;
import software.amazon.awssdk.services.ses.model.ListReceiptRuleSetsResponse;
import software.amazon.awssdk.services.ses.model.ReceiptRule;
import software.amazon.awssdk.services.ses.model.RuleDoesNotExistException;
import software.amazon.awssdk.services.ses.model.RuleSetDoesNotExistException;
import software.amazon.awssdk.services.ses.model.TlsPolicy;
import software.amazon.awssdk.services.sns.SnsClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* SDK compatibility test for the SES V1 receipt-rule-set actions. Floci stores rule sets inertly
* (no rules, no mail routing), but the management API must still round-trip through the real AWS SDK
* client — the same surface Terraform's {@code aws_ses_receipt_rule_set} /
* {@code aws_ses_active_receipt_rule_set} drive — including AWS error mapping and idempotent delete.
* SDK compatibility test for the SES V1 receipt-rule-set and receipt-rule actions, the surface
* Terraform's {@code aws_ses_receipt_rule_set} / {@code aws_ses_active_receipt_rule_set} /
* {@code aws_ses_receipt_rule} drive. Rule sets and rules are stored without routing any mail,
* but AWS error mapping, ordering semantics (front insert, After placement,
* SetReceiptRulePosition), full-replace update, idempotent deletes, and local validation of
* action targets all follow behavior probed against real AWS.
*/
@DisplayName("SES V1 ReceiptRuleSet")
@DisplayName("SES V1 ReceiptRuleSet and ReceiptRule")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesReceiptRuleSetTest {
private static SesClient ses;
private static SnsClient sns;
private static String ruleSet;
private static String topicArn;
@BeforeAll
static void setup() {
ses = TestFixtures.sesClient();
sns = TestFixtures.snsClient();
ruleSet = "sdk-v1-rule-set-" + TestFixtures.uniqueName();
topicArn = sns.createTopic(b -> b.name("sdk-v1-receipt-rule-topic")).topicArn();
}
@AfterAll
@@ -43,16 +55,26 @@ class SesReceiptRuleSetTest {
if (ses != null) {
try {
ses.setActiveReceiptRuleSet(b -> { });
} catch (RuntimeException ignored) {
// best-effort: clearing the active rule set
} catch (RuntimeException e) {
System.err.println("Best-effort clearing of the active rule set failed: " + e.getMessage());
}
try {
ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet));
} catch (RuntimeException ignored) {
// best-effort: removing the throwaway rule set
} catch (RuntimeException e) {
System.err.println("Best-effort cleanup of rule set " + ruleSet
+ " failed (its rules cascade with it): " + e.getMessage());
}
ses.close();
}
if (sns != null) {
try {
sns.deleteTopic(b -> b.topicArn(topicArn));
} catch (RuntimeException e) {
System.err.println("Best-effort cleanup of topic " + topicArn
+ " failed: " + e.getMessage());
}
sns.close();
}
}
@Test
@@ -62,7 +84,7 @@ class SesReceiptRuleSetTest {
DescribeReceiptRuleSetResponse d = ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet));
assertThat(d.metadata().name()).isEqualTo(ruleSet);
assertThat(d.metadata().createdTimestamp()).isNotNull();
assertThat(d.rules()).isEmpty(); // stored-but-inert: never holds rules
assertThat(d.rules()).isEmpty(); // no rules yet
}
@Test
@@ -81,11 +103,111 @@ class SesReceiptRuleSetTest {
@Test
@Order(4)
void createRuleAndDescribe_roundTripsActions() {
ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r
.name("rich")
.enabled(true)
.tlsPolicy(TlsPolicy.REQUIRE)
.scanEnabled(true)
.recipients("probe@example.com", "other@example.org")
.actions(
a -> a.addHeaderAction(h -> h.headerName("X-Floci").headerValue("v1")),
a -> a.snsAction(s -> s.topicArn(topicArn)),
a -> a.stopAction(s -> s.scope("RuleSet")))));
DescribeReceiptRuleResponse described = ses.describeReceiptRule(
b -> b.ruleSetName(ruleSet).ruleName("rich"));
ReceiptRule rule = described.rule();
assertThat(rule.enabled()).isTrue();
assertThat(rule.tlsPolicy()).isEqualTo(TlsPolicy.REQUIRE);
assertThat(rule.scanEnabled()).isTrue();
// Recipients come back sorted; actions keep their submitted order and the SNS action
// picks up the UTF-8 encoding default (probed against real AWS).
assertThat(rule.recipients()).containsExactly("other@example.org", "probe@example.com");
assertThat(rule.actions()).hasSize(3);
assertThat(rule.actions().get(0).addHeaderAction().headerName()).isEqualTo("X-Floci");
assertThat(rule.actions().get(1).snsAction().encodingAsString()).isEqualTo("UTF-8");
assertThat(rule.actions().get(2).stopAction().scopeAsString()).isEqualTo("RuleSet");
}
@Test
@Order(5)
void createRuleOrdering_frontInsertAndAfter() {
ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r.name("first")));
ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r.name("middle")).after("first"));
DescribeReceiptRuleSetResponse described = ses.describeReceiptRuleSet(
b -> b.ruleSetName(ruleSet));
assertThat(described.rules()).extracting(ReceiptRule::name)
.containsExactly("first", "middle", "rich");
}
@Test
@Order(6)
void duplicateRuleCreate_andUnknownRules_mapToTypedExceptions() {
assertThatThrownBy(() -> ses.createReceiptRule(
b -> b.ruleSetName(ruleSet).rule(r -> r.name("rich"))))
.isInstanceOf(AlreadyExistsException.class)
.hasMessageContaining("Rule already exists: rich");
assertThatThrownBy(() -> ses.describeReceiptRule(
b -> b.ruleSetName(ruleSet).ruleName("ghost")))
.isInstanceOf(RuleDoesNotExistException.class)
.hasMessageContaining("Rule does not exist: ghost");
assertThatThrownBy(() -> ses.createReceiptRule(
b -> b.ruleSetName("sdk-v1-nope").rule(r -> r.name("r"))))
.isInstanceOf(RuleSetDoesNotExistException.class);
}
@Test
@Order(7)
void ruleWithMissingTopic_failsWithInvalidSnsTopic() {
assertThatThrownBy(() -> ses.createReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r
.name("snsneg")
.actions(a -> a.snsAction(s -> s.topicArn(
"arn:aws:sns:us-east-1:000000000000:sdk-v1-no-such-topic"))))))
.isInstanceOf(InvalidSnsTopicException.class)
.hasMessageContaining("Could not publish to SNS topic");
}
@Test
@Order(8)
void updateRule_isFullReplace_andSetPositionMovesToFront() {
ses.updateReceiptRule(b -> b.ruleSetName(ruleSet).rule(r -> r.name("rich")));
ReceiptRule updated = ses.describeReceiptRule(
b -> b.ruleSetName(ruleSet).ruleName("rich")).rule();
assertThat(updated.enabled()).isFalse();
assertThat(updated.tlsPolicy()).isEqualTo(TlsPolicy.OPTIONAL);
assertThat(updated.actions()).isEmpty();
assertThat(updated.recipients()).isEmpty();
ses.setReceiptRulePosition(b -> b.ruleSetName(ruleSet).ruleName("rich"));
assertThat(ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet)).rules())
.extracting(ReceiptRule::name)
.containsExactly("rich", "first", "middle");
}
@Test
@Order(9)
void deleteRule_isIdempotent() {
ses.deleteReceiptRule(b -> b.ruleSetName(ruleSet).ruleName("middle"));
ses.deleteReceiptRule(b -> b.ruleSetName(ruleSet).ruleName("middle"));
assertThat(ses.describeReceiptRuleSet(b -> b.ruleSetName(ruleSet)).rules())
.extracting(ReceiptRule::name)
.containsExactly("rich", "first");
}
@Test
@Order(10)
void setActive_thenDescribeActive() {
ses.setActiveReceiptRuleSet(b -> b.ruleSetName(ruleSet));
DescribeActiveReceiptRuleSetResponse a = ses.describeActiveReceiptRuleSet(b -> { });
assertThat(a.metadata()).isNotNull();
assertThat(a.metadata().name()).isEqualTo(ruleSet);
// The active describe renders the set's remaining rules too.
assertThat(a.rules()).extracting(ReceiptRule::name).containsExactly("rich", "first");
// The active rule set can't be deleted (matches AWS) — a caller must unset it first.
assertThatThrownBy(() -> ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet)))
@@ -93,14 +215,14 @@ class SesReceiptRuleSetTest {
}
@Test
@Order(5)
@Order(11)
void describeNonExistent_throwsRuleSetDoesNotExist() {
assertThatThrownBy(() -> ses.describeReceiptRuleSet(b -> b.ruleSetName("sdk-v1-nope")))
.isInstanceOf(RuleSetDoesNotExistException.class);
}
@Test
@Order(6)
@Order(12)
void unsetActive_leavesNoActiveRuleSet() {
ses.setActiveReceiptRuleSet(b -> { }); // no name clears the active rule set
DescribeActiveReceiptRuleSetResponse a = ses.describeActiveReceiptRuleSet(b -> { });
@@ -108,8 +230,8 @@ class SesReceiptRuleSetTest {
}
@Test
@Order(7)
void delete_isIdempotent() {
@Order(13)
void delete_isIdempotent_andCascadesRemainingRules() {
ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet));
// Deleting an already-absent rule set still succeeds (matches AWS).
ses.deleteReceiptRuleSet(b -> b.ruleSetName(ruleSet));