Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(ses): add validated receipt-rule metadata lifecycle (#2017)

Adrian-Ryan Acalac8cb0c97f751
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a5c600e..07156794 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — `https://<endpointAddress>` verifies under `USE_SSL=1`** — `DescribeEndpoint` hands out `<prefix>-ats.iot.<region>.<MINISTACK_HOST>` and `<prefix>.credentials.iot.<region>.<MINISTACK_HOST>`, which SDKs dial over HTTPS as on AWS, but the generated gateway certificate did not name them, so the handshake failed hostname verification. The certificate now carries `*.iot.<region>.<MINISTACK_HOST>` and `*.credentials.iot.<region>.<MINISTACK_HOST>` for every region, and a cached certificate without them is regenerated. Contributed by @iot-rocket.
### Added
+- **SES — receipt-rule metadata** — Receipt rule sets can be created, activated, described, listed and deleted, and rules can be created in order, described and deleted through signed or unsigned Query requests. Resources are isolated by account and region and persisted. Names and recipients are validated; headers that cannot be represented in XML return AWS-shaped readback errors. Receipt actions are limited to AddHeader and Stop without an SNS topic; unsupported actions fail explicitly. Inbound email receiving is not emulated.
- **CloudFront — custom error responses on the data plane** — a distribution's `CustomErrorResponses` were stored but never applied, so an origin error reached the viewer unchanged. When the origin answers a configured `ErrorCode`, the data plane now fetches `ResponsePagePath` through the cache behavior that path matches and returns it with `ResponseCode`; a page that cannot be fetched is answered with the status its origin returned, as the Developer Guide describes. `ErrorCachingMinTTL` is stored only, since the data plane does not cache.
- **IoT — job templates and `AWS::IoT::JobTemplate`** — `CreateJobTemplate`, `DescribeJobTemplate`, `ListJobTemplates` and `DeleteJobTemplate` were missing, so a `jobTemplateArn` could not be created or used. Templates now store a document or a `documentSource` (not fetched, like `CreateJob`'s), every job configuration member, maintenance windows and tags, can be copied from a job through `jobArn`, list newest first with `maxResults` / `nextToken` paging, and answer AWS's errors and messages. `CreateJob` with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a member the request names replaces the template's. CloudFormation creates and deletes `AWS::IoT::JobTemplate` (Ref is the id, `Fn::GetAtt` `Arn`); every property is create-only, so an update under the same `JobTemplateId` fails with AWS's custom-name sentence and a new id replaces the template. Contributed by @iot-rocket.
### Fixed
diff --git a/README.md b/README.md
index 29ad48fb..e0909d0f 100644
--- a/README.md
+++ b/README.md
@@ -424,7 +424,7 @@ subnet = ec2.create_subnet(
| **EventBridge** | CreateEventBus, UpdateEventBus, DeleteEventBus, ListEventBuses, DescribeEventBus, PutRule, DeleteRule, ListRules, DescribeRule, EnableRule, DisableRule, PutTargets, RemoveTargets, ListTargetsByRule, ListRuleNamesByTarget, PutEvents, TestEventPattern, TagResource, UntagResource, ListTagsForResource, CreateArchive, DeleteArchive, DescribeArchive, UpdateArchive, ListArchives, PutPermission, RemovePermission, CreateConnection, DescribeConnection, DeleteConnection, UpdateConnection, DeauthorizeConnection, ListConnections, CreateApiDestination, DescribeApiDestination, DeleteApiDestination, UpdateApiDestination, ListApiDestinations, StartReplay, DescribeReplay, ListReplays, CancelReplay, CreateEndpoint, DeleteEndpoint, DescribeEndpoint, ListEndpoints, UpdateEndpoint, ActivateEventSource, DeactivateEventSource, DescribeEventSource, CreatePartnerEventSource, DeletePartnerEventSource, DescribePartnerEventSource, ListPartnerEventSources, ListPartnerEventSourceAccounts, ListEventSources, PutPartnerEvents | Lambda target dispatch on PutEvents; S3 EventBridge notifications; archives capture matching events and `StartReplay` re-dispatches them to the destination bus in a background thread; API destination targets are **invoked over HTTP** on PutEvents — connection auth (Basic, API Key, OAuth client-credentials with token caching and 401/407 refresh), connection/target header/query/body parameter merging with connection precedence, `*` path parameters, dynamic JSON-path parameter values resolved from the untransformed event, and the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations`, default `Content-Type: application/json; charset=utf-8`), which connection and target parameters cannot override; redirects are not followed (a `3xx` is a non-retryable delivery failure), only `http(s)` invocation and OAuth authorization endpoints are accepted, `HttpMethod` and `AuthorizationType` are validated against their enums, and a connection that is not `AUTHORIZED` is not invoked (`DeauthorizeConnection` clears its stored credentials) — the 24h retry pipeline, rate limiting, and DLQs are not modeled; SaaS/partner APIs are otherwise control-plane stubs. Event patterns are **validated** — `PutRule`, `TestEventPattern`, `CreateArchive` and `UpdateArchive` reject a malformed pattern with `InvalidEventPatternException` carrying AWS's own reason text — and evaluate `prefix`/`suffix` (plain or case-insensitive via a nested `equals-ignore-case`), `wildcard` (AWS semantics — only `*` is special, `\` escapes — with catastrophic backtracking ruled out), `equals-ignore-case` (AWS's per-character case alternation), `exactly`, `cidr` (IPv4/IPv6, host bits floored, `/32` and `/128` refused as AWS refuses them), `numeric` (as the grammar it is: one comparison or a lower-then-upper bound), `exists` (leaf nodes only, so an object or an empty array does not exist), `anything-but` (a literal, a list, or a nested `prefix`/`suffix`/`wildcard`/`equals-ignore-case`, singly or as a list), and `$or` at any field position — expanded into flat alternatives at rule creation, so AWS's per-leaf last-write-wins collision rule and its 1000-combination cap both hold. All ten envelope fields are filterable, an unmodelled key is a path the event lacks rather than an error, `resources` is an intersection, array values are matched per element (with AWS's array-consistency rule), and values compare as JSON so a string never equals a number. An operand or key the matcher cannot evaluate never matches, rather than raising or matching everything. Not modeled: the 4096-character pattern limit, the wildcard-complexity refusal, and the 256-leaf rule-size cap |
| **Kinesis** | CreateStream, DeleteStream, DescribeStream, DescribeStreamSummary, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, IncreaseStreamRetentionPeriod, DecreaseStreamRetentionPeriod, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, SubscribeToShard, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing; AWS limits enforced (1 MB/record, 500 records/batch, 5 MB payload, 256-char partition key); SubscribeToShard pushes `SubscribeToShardEvent`s over HTTP/1.1 or HTTP/2 (h2c) for up to 5 minutes, JSON or CBOR |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
-| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent; the sender must be a verified identity (`MessageRejected` otherwise), and a sandboxed account sends only to verified or `@simulator.amazonses.com` recipients |
+| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, ListVerifiedEmailAddresses, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates, CreateReceiptRuleSet, DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet, SetActiveReceiptRuleSet, DescribeActiveReceiptRuleSet, CreateReceiptRule, DescribeReceiptRule, DeleteReceiptRule | Emails stored in-memory, not sent; the sender must be a verified identity (`MessageRejected` otherwise), and a sandboxed account sends only to verified or `@simulator.amazonses.com` recipients; receipt rule metadata is stored and persisted, with ordered AddHeader and Stop actions (without SNS topics); inbound email receiving is not emulated |
| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountDetails, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent; `PutAccountDetails` with `ProductionAccessEnabled=false` puts the account in the sandbox; email templates share the v1 store, so `SendEmail` with `Content.Template` renders a template created through either API version |
| **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |
| **Backup** | CreateBackupVault, DescribeBackupVault, DeleteBackupVault, ListBackupVaults, CreateBackupPlan, GetBackupPlan, UpdateBackupPlan, DeleteBackupPlan, ListBackupPlans, ListBackupPlanVersions, CreateBackupSelection, GetBackupSelection, DeleteBackupSelection, ListBackupSelections, StartBackupJob, StopBackupJob, DescribeBackupJob, ListBackupJobs, TagResource, UntagResource, ListTags | In-memory; jobs complete immediately; vaults and plans participate in Resource Groups Tagging API |
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 811e5873..65387cf2 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -964,6 +964,15 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"UpdateTemplate": "ses",
"SendTemplatedEmail": "ses",
"SendBulkTemplatedEmail": "ses",
+ "CreateReceiptRuleSet": "ses",
+ "ListReceiptRuleSets": "ses",
+ "DescribeReceiptRuleSet": "ses",
+ "DeleteReceiptRuleSet": "ses",
+ "SetActiveReceiptRuleSet": "ses",
+ "DescribeActiveReceiptRuleSet": "ses",
+ "CreateReceiptRule": "ses",
+ "DescribeReceiptRule": "ses",
+ "DeleteReceiptRule": "ses",
# RDS actions
"CreateDBInstance": "rds",
"DeleteDBInstance": "rds",
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index daa1fcdd..246608c6 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -14,7 +14,11 @@ v1 actions: SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail,
DeleteConfigurationSet, DescribeConfigurationSet,
ListConfigurationSets, CreateTemplate, GetTemplate, DeleteTemplate,
ListTemplates, UpdateTemplate, GetIdentityDkimAttributes,
- SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled.
+ SetIdentityNotificationTopic, SetIdentityFeedbackForwardingEnabled,
+ CreateReceiptRuleSet, ListReceiptRuleSets, DescribeReceiptRuleSet,
+ DeleteReceiptRuleSet, SetActiveReceiptRuleSet,
+ DescribeActiveReceiptRuleSet, CreateReceiptRule, DescribeReceiptRule,
+ DeleteReceiptRule.
All emails stored in-memory for test inspection.
Send statistics aggregated into 15-minute buckets per AWS spec.
@@ -26,6 +30,7 @@ import hashlib
import json
import logging
import os
+import re
import smtplib
import time
from datetime import datetime, timezone
@@ -56,6 +61,8 @@ _templates = AccountRegionScopedDict()
_configuration_sets = AccountRegionScopedDict()
# SESv2 PutAccountDetails, under "account": ProductionAccessEnabled and the details.
_account_details = AccountRegionScopedDict()
+_receipt_rule_sets = AccountRegionScopedDict()
+_active_receipt_rule_set = AccountRegionScopedDict()
_SIMULATOR_DOMAIN = "simulator.amazonses.com"
@@ -77,6 +84,8 @@ def get_state() -> dict:
"_templates": _templates,
"_configuration_sets": _configuration_sets,
"_account_details": _account_details,
+ "_receipt_rule_sets": _receipt_rule_sets,
+ "_active_receipt_rule_set": _active_receipt_rule_set,
})
@@ -91,6 +100,10 @@ def _restore_state(data: dict):
_configuration_sets, data.get("_configuration_sets", {})
)
_restore_regional_store(_account_details, data.get("_account_details", {}))
+ _restore_regional_store(_receipt_rule_sets, data.get("_receipt_rule_sets", {}))
+ _restore_regional_store(
+ _active_receipt_rule_set, data.get("_active_receipt_rule_set", {})
+ )
def _restore_regional_store(store, restored):
@@ -124,13 +137,22 @@ async def handle_request(method, path, headers, body, query_params):
params = dict(query_params)
if method == "POST" and body:
- form_params = parse_qs(body.decode("utf-8", errors="replace"))
+ form_params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)
for k, v in form_params.items():
params[k] = v
action = _p(params, "Action")
handlers = {
+ "CreateReceiptRuleSet": _create_receipt_rule_set,
+ "ListReceiptRuleSets": _list_receipt_rule_sets,
+ "DescribeReceiptRuleSet": _describe_receipt_rule_set,
+ "DeleteReceiptRuleSet": _delete_receipt_rule_set,
+ "SetActiveReceiptRuleSet": _set_active_receipt_rule_set,
+ "DescribeActiveReceiptRuleSet": _describe_active_receipt_rule_set,
+ "CreateReceiptRule": _create_receipt_rule,
+ "DescribeReceiptRule": _describe_receipt_rule,
+ "DeleteReceiptRule": _delete_receipt_rule,
"SendEmail": _send_email,
"SendRawEmail": _send_raw_email,
"SendTemplatedEmail": _send_templated_email,
@@ -165,6 +187,289 @@ async def handle_request(method, path, headers, body, query_params):
return handler(params)
+# ---------------------------------------------------------------------------
+# v1 — Receipt-rule metadata (AddHeader/Stop only; no receiving execution)
+# ---------------------------------------------------------------------------
+
+_RECEIPT_ACTION_FIELDS = {
+ "S3Action": ("TopicArn", "BucketName", "ObjectKeyPrefix", "KmsKeyArn", "IamRoleArn"),
+ "BounceAction": ("TopicArn", "SmtpReplyCode", "StatusCode", "Message", "Sender"),
+ "WorkmailAction": ("TopicArn", "OrganizationArn"),
+ "LambdaAction": ("TopicArn", "FunctionArn", "InvocationType"),
+ "StopAction": ("Scope", "TopicArn"),
+ "AddHeaderAction": ("HeaderName", "HeaderValue"),
+ "SNSAction": ("TopicArn", "Encoding"),
+ "ConnectAction": ("InstanceARN", "IAMRoleARN"),
+}
+
+
+def _receipt_error(code, message):
+ return _error(code, message, 400, "Sender")
+
+
+def _receipt_result(action, data=None):
+ inner = _receipt_element(f"{action}Result", data or {})
+ # AWS stores headers containing NUL but returns InternalFailure when the
+ # metadata cannot be serialized as XML. Do not emit malformed success XML.
+ if re.search(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]", inner):
+ return _error("InternalFailure", None, 500, "Receiver")
+ return _xml(200, f"{action}Response", inner)
+
+
+def _receipt_element(name, value):
+ if isinstance(value, dict):
+ inner = "".join(_receipt_element(k, v) for k, v in value.items())
+ elif isinstance(value, list):
+ inner = "".join(_receipt_element("member", v) for v in value)
+ elif isinstance(value, bool):
+ inner = str(value).lower()
+ else:
+ inner = _esc(str(value))
+ return f"<{name}>{inner}</{name}>"
+
+
+def _receipt_name_error(params, key, field, business_field=None):
+ if key not in params:
+ return _receipt_error("ValidationError", (
+ f"1 validation error detected: Value at '{field}' failed to satisfy "
+ "constraint: Member must not be null"))
+ name = _p(params, key)
+ if not name:
+ return _receipt_error("ValidationError", (
+ f"2 validation errors detected: Value at '{field}' failed to satisfy "
+ "constraint: Member must have length greater than or equal to 1; "
+ f"Value at '{field}' failed to satisfy constraint: Member must satisfy "
+ "regular expression pattern: ^[a-zA-Z0-9_.-]+$"))
+ if not re.fullmatch(r"[a-zA-Z0-9_.-]+", name):
+ return _receipt_error("ValidationError", (
+ f"1 validation error detected: Value at '{field}' failed to satisfy "
+ "constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$"))
+ if business_field and (len(name) > 64 or not re.fullmatch(
+ r"[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?", name)):
+ return _receipt_error("InvalidParameterValue", f"Not a valid {business_field}: {name}")
+ return None
+
+
+def _receipt_missing_set(name):
+ return _receipt_error("RuleSetDoesNotExist", f"Rule set does not exist: {name}")
+
+
+def _create_receipt_rule_set(params):
+ error = _receipt_name_error(params, "RuleSetName", "ruleSetName", "ruleSetName")
+ if error:
+ return error
+ name = _p(params, "RuleSetName")
+ if name in _receipt_rule_sets:
+ return _receipt_error("AlreadyExists", f"Rule set already exists: {name}")
+ _receipt_rule_sets[name] = {
+ "Metadata": {"Name": name, "CreatedTimestamp": datetime.now(timezone.utc).isoformat()},
+ "Rules": [],
+ }
+ return _receipt_result("CreateReceiptRuleSet")
+
+
+def _list_receipt_rule_sets(params):
+ names = sorted(_receipt_rule_sets)
+ token = _p(params, "NextToken")
+ if token:
+ try:
+ last = base64.b64decode(token, validate=True).decode("utf-8")
+ start = names.index(last) + 1
+ except (ValueError, UnicodeError):
+ return _receipt_error("InvalidParameterValue", f"Invalid token: {token}")
+ else:
+ start = 0
+ page = names[start:start + 100]
+ result = {"RuleSets": [_receipt_rule_sets[n]["Metadata"] for n in page]}
+ if start + len(page) < len(names):
+ result["NextToken"] = base64.b64encode(page[-1].encode()).decode()
+ return _receipt_result("ListReceiptRuleSets", result)
+
+
+def _describe_receipt_rule_set(params):
+ name = _p(params, "RuleSetName")
+ error = _receipt_name_error(params, "RuleSetName", "ruleSetName", "ruleSetName")
+ if error:
+ return error
+ if name not in _receipt_rule_sets:
+ return _receipt_missing_set(name)
+ return _receipt_result("DescribeReceiptRuleSet", _receipt_rule_sets[name])
+
+
+def _delete_receipt_rule_set(params):
+ name = _p(params, "RuleSetName")
+ error = _receipt_name_error(params, "RuleSetName", "ruleSetName", "ruleSetName")
+ if error:
+ return error
+ if _active_receipt_rule_set.get("name") == name:
+ return _receipt_error("CannotDelete", f"Cannot delete active rule set: {name}")
+ _receipt_rule_sets.pop(name, None)
+ return _receipt_result("DeleteReceiptRuleSet")
+
+
+def _set_active_receipt_rule_set(params):
+ if "RuleSetName" not in params:
+ _active_receipt_rule_set.pop("name", None)
+ else:
+ error = _receipt_name_error(params, "RuleSetName", "ruleSetName", "ruleSetName")
+ if error:
+ return error
+ name = _p(params, "RuleSetName")
+ if name not in _receipt_rule_sets:
+ return _receipt_missing_set(name)
+ _active_receipt_rule_set["name"] = name
+ return _receipt_result("SetActiveReceiptRuleSet")
+
+
+def _describe_active_receipt_rule_set(params):
+ name = _active_receipt_rule_set.get("name")
+ return _receipt_result("DescribeActiveReceiptRuleSet", _receipt_rule_sets.get(name, {}))
+
+
+def _receipt_rule_from_params(params):
+ rule = {
+ "Name": _p(params, "Rule.Name"),
+ "Enabled": _p(params, "Rule.Enabled").lower() == "true",
+ "TlsPolicy": _p(params, "Rule.TlsPolicy", "Optional"),
+ "Actions": [],
+ "ScanEnabled": _p(params, "Rule.ScanEnabled").lower() == "true",
+ }
+ if any(k == "Rule.Recipients" or k.startswith("Rule.Recipients.member.") for k in params):
+ recipients = []
+ i = 1
+ while f"Rule.Recipients.member.{i}" in params:
+ recipients.append(_p(params, f"Rule.Recipients.member.{i}"))
+ i += 1
+ rule["Recipients"] = recipients
+ indexes = sorted({int(k.split(".")[3]) for k in params
+ if re.match(r"^Rule\.Actions\.member\.\d+\.", k)})
+ for i in indexes:
+ action = {}
+ for name, fields in _RECEIPT_ACTION_FIELDS.items():
+ prefix = f"Rule.Actions.member.{i}.{name}."
+ values = {f: _p(params, prefix + f) for f in fields if prefix + f in params}
+ if values:
+ action[name] = values
+ rule["Actions"].append(action)
+ return rule
+
+
+def _receipt_rule_error(rule):
+ tls = rule["TlsPolicy"]
+ if tls not in ("Optional", "Require"):
+ return _receipt_error("ValidationError", (
+ "1 validation error detected: Value at 'rule.tlsPolicy' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [Optional, Require]"))
+ for i, action in enumerate(rule["Actions"], 1):
+ if len(action) != 1:
+ return _receipt_error("InvalidParameterValue", (
+ "Exactly one action type must be specified for each ReceiptAction"))
+ action_type = next(iter(action))
+ if action_type not in ("AddHeaderAction", "StopAction"):
+ return _receipt_error("InvalidAction", (
+ f"Receipt action {action_type} is not implemented"))
+ if "StopAction" in action:
+ if "TopicArn" in action["StopAction"]:
+ return _receipt_error("InvalidAction", (
+ "Receipt action StopAction with TopicArn is not implemented"))
+ if action["StopAction"].get("Scope") != "RuleSet":
+ return _receipt_error("ValidationError", (
+ f"1 validation error detected: Value at 'rule.actions.{i}.member.stopAction.scope' "
+ "failed to satisfy constraint: Member must satisfy enum value set: [RuleSet]"))
+ if i != len(rule["Actions"]):
+ return _receipt_error("InvalidParameterValue", (
+ "Stop action, if any, must be placed at the end of the actions list"))
+ header = action.get("AddHeaderAction")
+ if header is not None:
+ for field in ("HeaderName", "HeaderValue"):
+ if field not in header:
+ return _receipt_error("ValidationError", (
+ f"1 validation error detected: Value at 'rule.actions.{i}.member."
+ f"addHeaderAction.{field[0].lower() + field[1:]}' failed to satisfy "
+ "constraint: Member must not be null"))
+ name, value = header["HeaderName"], header["HeaderValue"]
+ if not re.fullmatch(r"[a-zA-Z0-9-]{1,50}", name):
+ return _receipt_error("InvalidParameterValue", f"Invalid header name: {name}")
+ if len(value) > 2048 or "\n" in value or "\r" in value:
+ printable = value.replace("\n", "0x000a").replace("\r", "0x000d")
+ return _receipt_error("InvalidParameterValue", f"Invalid header value: {printable}")
+ recipients = rule.get("Recipients", [])
+ for i, recipient in enumerate(recipients):
+ parts = recipient.rsplit("@", 1)
+ domain = parts[-1]
+ if (len(parts) == 2 and not parts[0]) or not re.fullmatch(
+ r"\.?[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?"
+ r"(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)+", domain) or (
+ len(parts) == 2 and ("@" in parts[0] or re.search(r"\s", parts[0]))):
+ return _receipt_error("InvalidParameterValue", f"Invalid recipient: {recipient}")
+ recipients[i] = recipient.lower()
+ if "Recipients" in rule:
+ rule["Recipients"] = sorted(set(recipients))
+ return None
+
+
+def _create_receipt_rule(params):
+ if not any(key.startswith("Rule.") for key in params):
+ return _receipt_error("ValidationError", (
+ "1 validation error detected: Value at 'rule' failed to satisfy "
+ "constraint: Member must not be null"))
+ error = _receipt_name_error(params, "Rule.Name", "rule.name", "ruleName")
+ if error:
+ return error
+ error = _receipt_name_error(params, "RuleSetName", "ruleSetName", "ruleSetName")
+ if error:
+ return error
+ if "After" in params:
+ error = _receipt_name_error(params, "After", "after")
+ if error:
+ return error
+ rule = _receipt_rule_from_params(params)
+ error = _receipt_rule_error(rule)
+ if error:
+ return error
+ name = _p(params, "RuleSetName")
+ if name not in _receipt_rule_sets:
+ return _receipt_missing_set(name)
+ rules = _receipt_rule_sets[name]["Rules"]
+ if any(r["Name"] == rule["Name"] for r in rules):
+ return _receipt_error("AlreadyExists", f"Rule already exists: {rule['Name']}")
+ after = _p(params, "After")
+ position = 0
+ if after:
+ position = next((i + 1 for i, r in enumerate(rules) if r["Name"] == after), None)
+ if position is None:
+ return _receipt_error("RuleDoesNotExist", f"Rule does not exist: {after}")
+ rules.insert(position, rule)
+ return _receipt_result("CreateReceiptRule")
+
+
+def _describe_receipt_rule(params):
+ for key, field in (("RuleSetName", "ruleSetName"), ("RuleName", "ruleName")):
+ error = _receipt_name_error(params, key, field, field)
+ if error:
+ return error
+ name, rule_name = _p(params, "RuleSetName"), _p(params, "RuleName")
+ if name not in _receipt_rule_sets:
+ return _receipt_missing_set(name)
+ rule = next((r for r in _receipt_rule_sets[name]["Rules"] if r["Name"] == rule_name), None)
+ if rule is None:
+ return _receipt_error("RuleDoesNotExist", f"Rule does not exist: {rule_name}")
+ return _receipt_result("DescribeReceiptRule", {"Rule": rule})
+
+
+def _delete_receipt_rule(params):
+ for key, field in (("RuleSetName", "ruleSetName"), ("RuleName", "ruleName")):
+ error = _receipt_name_error(params, key, field, field)
+ if error:
+ return error
+ name, rule_name = _p(params, "RuleSetName"), _p(params, "RuleName")
+ if name not in _receipt_rule_sets:
+ return _receipt_missing_set(name)
+ rules = _receipt_rule_sets[name]["Rules"]
+ rules[:] = [r for r in rules if r["Name"] != rule_name]
+ return _receipt_result("DeleteReceiptRule")
+
+
# ---------------------------------------------------------------------------
# v1 — Send operations
# ---------------------------------------------------------------------------
@@ -944,10 +1249,12 @@ def _xml(status, root_tag, inner):
return status, {"Content-Type": "application/xml"}, body
-def _error(code, message, status):
+def _error(code, message, status, error_type=""):
+ type_xml = f"<Type>{error_type}</Type>" if error_type else ""
+ message_xml = f"<Message>{_esc(message)}</Message>" if message is not None else ""
body = (f'<?xml version="1.0" encoding="UTF-8"?>'
f'<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">'
- f'<Error><Code>{code}</Code><Message>{_esc(message)}</Message></Error>'
+ f'<Error>{type_xml}<Code>{code}</Code>{message_xml}</Error>'
f'<RequestId>{new_uuid()}</RequestId>'
f'</ErrorResponse>').encode("utf-8")
return status, {"Content-Type": "application/xml"}, body
@@ -959,3 +1266,5 @@ def reset():
_templates.clear()
_configuration_sets.clear()
_account_details.clear()
+ _receipt_rule_sets.clear()
+ _active_receipt_rule_set.clear()
diff --git a/tests/test_router.py b/tests/test_router.py
index 630b12d7..ddb7b80b 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -16,6 +16,21 @@ from ministack.core.router import detect_service
_HEADERS = {"host": "localhost:4566"}
[email protected]("action", [
+ "CreateReceiptRuleSet", "ListReceiptRuleSets", "DescribeReceiptRuleSet",
+ "DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet",
+ "CreateReceiptRule", "DescribeReceiptRule", "DeleteReceiptRule",
+])
[email protected]("method", ["GET", "POST"])
+def test_ses_receipt_actions_route_without_signature(action, method):
+ headers = dict(_HEADERS)
+ if method == "POST":
+ headers["content-type"] = "application/x-www-form-urlencoded"
+ # app.py passes parsed POST form parameters to the same router argument
+ # that holds GET query parameters.
+ assert detect_service(method, "/", headers, {"Action": [action], "Version": ["2010-12-01"]}) == "ses"
+
+
@pytest.mark.parametrize("path", [
# 2015-03-31 — Functions, ESM, Layers, Tags
"/2015-03-31/functions/foo",
diff --git a/tests/test_ses_receipts.py b/tests/test_ses_receipts.py
new file mode 100644
index 00000000..f2e8c74f
--- /dev/null
+++ b/tests/test_ses_receipts.py
@@ -0,0 +1,417 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+"""SES receipt metadata through the SDK's Query serializer and XML parser."""
+
+import asyncio
+from datetime import datetime
+from urllib.parse import urlencode
+from uuid import uuid4
+
+import pytest
+from botocore import UNSIGNED
+from botocore.exceptions import ClientError
+from botocore.parsers import create_parser
+from botocore.serialize import create_serializer
+from botocore.session import Session
+
+from ministack.core import persistence
+from ministack.core.responses import (
+ AccountRegionScopedDict,
+ set_request_account_id,
+ set_request_region,
+)
+from ministack.services import ses
+
+
+def receipt_api(monkeypatch):
+ # Private stores keep in-process reset/persistence tests independent of the
+ # running integration server and other services' fixtures on this worker.
+ for name in (
+ "_identities", "_sent_emails", "_templates", "_configuration_sets",
+ "_account_details", "_receipt_rule_sets", "_active_receipt_rule_set",
+ ):
+ monkeypatch.setattr(ses, name, AccountRegionScopedDict())
+ model = Session().get_service_model("ses")
+ # Exercise service-side required-field errors instead of SDK validation.
+ serializer = create_serializer("query", include_validation=False)
+ parser = create_parser("query")
+
+ def call(action, **params):
+ operation = model.operation_model(action)
+ request = serializer.serialize_to_request(params, operation)
+ status, headers, body = asyncio.run(ses.handle_request(
+ "POST", "/", {}, urlencode(request["body"]).encode(), {}
+ ))
+ result = parser.parse(
+ {"status_code": status, "headers": headers, "body": body},
+ operation.output_shape,
+ )
+ if status >= 400:
+ raise ClientError(result, action)
+ assert status == 200
+ return {key: value for key, value in result.items() if key != "ResponseMetadata"}
+
+ return call
+
+
+def assert_error(api, action, code, message, **params):
+ with pytest.raises(ClientError) as exc:
+ api(action, **params)
+ response = exc.value.response
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert response["Error"] == {"Code": code, "Message": message, "Type": "Sender"}
+
+
+def test_receipt_rule_set_and_rule_lifecycle(receipt_api):
+ api = receipt_api
+ assert api("DescribeActiveReceiptRuleSet") == {}
+ api("CreateReceiptRuleSet", RuleSetName="set.with-periods")
+ empty = api("DescribeReceiptRuleSet", RuleSetName="set.with-periods")
+ assert empty["Metadata"]["Name"] == "set.with-periods"
+ assert isinstance(empty["Metadata"]["CreatedTimestamp"], datetime)
+ assert empty["Rules"] == []
+ assert api("ListReceiptRuleSets")["RuleSets"] == [empty["Metadata"]]
+
+ api("CreateReceiptRule", RuleSetName="set.with-periods", Rule={"Name": "first"})
+ assert api("DescribeReceiptRule", RuleSetName="set.with-periods", RuleName="first")["Rule"] == {
+ "Name": "first", "Enabled": False, "ScanEnabled": False,
+ "TlsPolicy": "Optional", "Actions": [],
+ }
+ rule = {
+ "Name": "second", "Enabled": True, "ScanEnabled": True,
+ "TlsPolicy": "Require", "Recipients": ["EXAMPLE.COM", "[email protected]", ".EXAMPLE.COM", "foo.example-test.com"],
+ "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "value<&"}},
+ {"StopAction": {"Scope": "RuleSet"}},
+ ],
+ }
+ api("CreateReceiptRule", RuleSetName="set.with-periods", Rule=rule)
+ rule["Recipients"] = [".example.com", "example.com", "foo.example-test.com", "[email protected]"]
+ assert api("DescribeReceiptRule", RuleSetName="set.with-periods", RuleName="second")["Rule"] == rule
+ api("CreateReceiptRule", RuleSetName="set.with-periods", After="second", Rule={"Name": "third"})
+ described = api("DescribeReceiptRuleSet", RuleSetName="set.with-periods")
+ assert [r["Name"] for r in described["Rules"]] == ["second", "third", "first"]
+ api("SetActiveReceiptRuleSet", RuleSetName="set.with-periods")
+ assert api("DescribeActiveReceiptRuleSet") == described
+ assert_error(api, "DeleteReceiptRuleSet", "CannotDelete",
+ "Cannot delete active rule set: set.with-periods", RuleSetName="set.with-periods")
+ api("DeleteReceiptRule", RuleSetName="set.with-periods", RuleName="third")
+ assert [r["Name"] for r in api("DescribeActiveReceiptRuleSet")["Rules"]] == ["second", "first"]
+ api("SetActiveReceiptRuleSet")
+ assert api("DescribeActiveReceiptRuleSet") == {}
+ api("DeleteReceiptRuleSet", RuleSetName="set.with-periods")
+ api("DeleteReceiptRuleSet", RuleSetName="set.with-periods")
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+
+
+def test_receipt_duplicate_and_missing_resource_errors_leave_order_unchanged(receipt_api):
+ api = receipt_api
+ for action, params in (
+ ("DescribeReceiptRuleSet", {}), ("SetActiveReceiptRuleSet", {}),
+ ("CreateReceiptRule", {"Rule": {"Name": "first"}}),
+ ("DescribeReceiptRule", {"RuleName": "first"}),
+ ("DeleteReceiptRule", {"RuleName": "first"}),
+ ):
+ assert_error(api, action, "RuleSetDoesNotExist", "Rule set does not exist: missing",
+ RuleSetName="missing", **params)
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRuleSet", "AlreadyExists", "Rule set already exists: rules",
+ RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "first"})
+ assert_error(api, "CreateReceiptRule", "AlreadyExists", "Rule already exists: first",
+ RuleSetName="rules", Rule={"Name": "first"}, After="missing")
+ assert_error(api, "CreateReceiptRule", "RuleDoesNotExist", "Rule does not exist: missing",
+ RuleSetName="rules", Rule={"Name": "second"}, After="missing")
+ assert_error(api, "DescribeReceiptRule", "RuleDoesNotExist", "Rule does not exist: missing",
+ RuleSetName="rules", RuleName="missing")
+ api("DeleteReceiptRule", RuleSetName="rules", RuleName="missing")
+ assert [r["Name"] for r in api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"]] == ["first"]
+ assert_error(api, "ListReceiptRuleSets", "InvalidParameterValue", "Invalid token: invalid", NextToken="invalid")
+
+
[email protected]("name", ["-bad", "bad-", "a" * 65])
+def test_receipt_invalid_names(receipt_api, name):
+ api = receipt_api
+ assert_error(api, "CreateReceiptRuleSet", "InvalidParameterValue",
+ f"Not a valid ruleSetName: {name}", RuleSetName=name)
+ # AWS validates rule metadata before looking up the parent rule set.
+ assert_error(api, "CreateReceiptRule", "InvalidParameterValue",
+ f"Not a valid ruleName: {name}", RuleSetName="missing", Rule={"Name": name})
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+
+
[email protected]("name", ["-bad", "bad-", "a" * 65])
[email protected]("action,params,field", [
+ ("DescribeReceiptRuleSet", {}, "ruleSetName"),
+ ("DeleteReceiptRuleSet", {}, "ruleSetName"),
+ ("SetActiveReceiptRuleSet", {}, "ruleSetName"),
+ ("CreateReceiptRule", {"Rule": {"Name": "valid"}}, "ruleSetName"),
+ ("DescribeReceiptRule", {"RuleName": "valid"}, "ruleSetName"),
+ ("DeleteReceiptRule", {"RuleName": "valid"}, "ruleSetName"),
+ ("DescribeReceiptRule", {"RuleSetName": "rules"}, "ruleName"),
+ ("DeleteReceiptRule", {"RuleSetName": "rules"}, "ruleName"),
+])
+def test_receipt_lookup_delete_and_activation_validate_names(receipt_api, name, action, params, field):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "valid"})
+ api("SetActiveReceiptRuleSet", RuleSetName="rules")
+ before = api("DescribeActiveReceiptRuleSet")
+ key = "RuleSetName" if field == "ruleSetName" else "RuleName"
+ assert_error(api, action, "InvalidParameterValue",
+ f"Not a valid {field}: {name}", **{**params, key: name})
+ assert api("DescribeActiveReceiptRuleSet") == before
+ assert api("ListReceiptRuleSets")["RuleSets"] == [before["Metadata"]]
+
+
[email protected]("action,params", [
+ ("CreateReceiptRuleSet", {}),
+ ("DescribeReceiptRuleSet", {}),
+ ("DeleteReceiptRuleSet", {}),
+ ("CreateReceiptRule", {"Rule": {"Name": "valid"}}),
+ ("DescribeReceiptRule", {"RuleName": "valid"}),
+ ("DeleteReceiptRule", {"RuleName": "valid"}),
+])
+def test_receipt_missing_rule_set_name_error(receipt_api, action, params):
+ assert_error(receipt_api, action, "ValidationError",
+ "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: Member must not be null",
+ **params)
+ assert receipt_api("ListReceiptRuleSets") == {"RuleSets": []}
+
+
[email protected]("action,params,field", [
+ ("CreateReceiptRule", {}, "rule"),
+ ("CreateReceiptRule", {"Rule": {}}, "rule"),
+ ("CreateReceiptRule", {"Rule": {"Enabled": True}}, "rule.name"),
+ ("DescribeReceiptRule", {}, "ruleName"),
+ ("DeleteReceiptRule", {}, "ruleName"),
+])
+def test_receipt_missing_rule_fields_error(receipt_api, action, params, field):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, action, "ValidationError",
+ f"1 validation error detected: Value at '{field}' failed to satisfy constraint: Member must not be null",
+ RuleSetName="rules", **params)
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("recipients", [
+])
+def test_receipt_empty_recipient_is_rejected_without_creating_a_rule(receipt_api, recipients):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", "InvalidParameterValue", "Invalid recipient: ",
+ RuleSetName="rules", Rule={"Name": "invalid", "Recipients": recipients})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("value", ["a\tb", "café 雪 😀 <&>"])
+def test_receipt_header_tab_and_unicode_round_trip(receipt_api, value):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ actions = [{"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": value}}]
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "header", "Actions": actions})
+ api("SetActiveReceiptRuleSet", RuleSetName="rules")
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="header")["Rule"]["Actions"] == actions
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"][0]["Actions"] == actions
+ assert api("DescribeActiveReceiptRuleSet")["Rules"][0]["Actions"] == actions
+
+
+def test_receipt_nul_header_is_created_but_readback_fails_until_deleted(receipt_api):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "valid"})
+ api("SetActiveReceiptRuleSet", RuleSetName="rules")
+ before = api("DescribeActiveReceiptRuleSet")
+ assert api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "broken", "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "a\x00b"}},
+ ]}) == {}
+ for action, params in (
+ ("DescribeReceiptRule", {"RuleSetName": "rules", "RuleName": "broken"}),
+ ("DescribeReceiptRuleSet", {"RuleSetName": "rules"}),
+ ("DescribeActiveReceiptRuleSet", {}),
+ ):
+ with pytest.raises(ClientError) as exc:
+ api(action, **params)
+ response = exc.value.response
+ assert response["ResponseMetadata"]["HTTPStatusCode"] == 500
+ assert response["Error"] == {"Type": "Receiver", "Code": "InternalFailure"}
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="valid")["Rule"] == before["Rules"][0]
+ assert api("ListReceiptRuleSets")["RuleSets"] == [before["Metadata"]]
+ api("DeleteReceiptRule", RuleSetName="rules", RuleName="broken")
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules") == before
+ assert api("DescribeActiveReceiptRuleSet") == before
+
+
[email protected]("rule,code,message", [
+ ({"Name": "tls", "TlsPolicy": "Invalid"}, "ValidationError",
+ "1 validation error detected: Value at 'rule.tlsPolicy' failed to satisfy constraint: Member must satisfy enum value set: [Optional, Require]"),
+ ({"Name": "recipient", "Recipients": ["not valid"]}, "InvalidParameterValue", "Invalid recipient: not valid"),
+ ({"Name": "scope", "Actions": [{"StopAction": {"Scope": "Invalid"}}]}, "ValidationError",
+ "1 validation error detected: Value at 'rule.actions.1.member.stopAction.scope' failed to satisfy constraint: Member must satisfy enum value set: [RuleSet]"),
+ ({"Name": "ordering", "Actions": [{"StopAction": {"Scope": "RuleSet"}},
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "ok"}}]}, "InvalidParameterValue",
+ "Stop action, if any, must be placed at the end of the actions list"),
+ ({"Name": "multiple", "Actions": [{"StopAction": {"Scope": "RuleSet"},
+ "AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "ok"}}]}, "InvalidParameterValue",
+ "Exactly one action type must be specified for each ReceiptAction"),
+ ({"Name": "header", "Actions": [{"AddHeaderAction": {"HeaderName": "X bad", "HeaderValue": "ok"}}]},
+ "InvalidParameterValue", "Invalid header name: X bad"),
+ ({"Name": "newline", "Actions": [{"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "a\nb"}}]},
+ "InvalidParameterValue", "Invalid header value: a0x000ab"),
+])
+def test_receipt_invalid_rule_metadata_is_atomic(receipt_api, rule, code, message):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", code, message, RuleSetName="rules", Rule=rule)
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("header,missing", [
+ ({"HeaderName": "X-Test"}, "headerValue"),
+ ({"HeaderValue": "value"}, "headerName"),
+])
+def test_receipt_missing_header_fields_are_rejected_without_creating_a_rule(receipt_api, header, missing):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", "ValidationError",
+ f"1 validation error detected: Value at 'rule.actions.1.member.addHeaderAction.{missing}' failed to satisfy constraint: Member must not be null",
+ RuleSetName="rules", Rule={"Name": "missing", "Actions": [{"AddHeaderAction": header}]})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
[email protected]("recipient", [
+ "example..com", "example.-com", "example-.com", "foo..example.com",
+ "foo.-example.com", "foo.example-.com", "example.com-",
+])
+def test_receipt_invalid_domain_labels_are_rejected_without_creating_a_rule(receipt_api, recipient):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ assert_error(api, "CreateReceiptRule", "InvalidParameterValue", f"Invalid recipient: {recipient}",
+ RuleSetName="rules", Rule={"Name": "invalid", "Recipients": [recipient]})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
+def test_receipt_recipients_are_lowercased_deduplicated_and_sorted(receipt_api):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "recipients", "Recipients": [
+ "example.com", ".EXAMPLE.COM", ".example.com",
+ ]})
+ recipients = [".example.com", "[email protected]", "example.com", "[email protected]"]
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="recipients")["Rule"]["Recipients"] == recipients
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"][0]["Recipients"] == recipients
+
+
[email protected]("action", [
+ {"S3Action": {"BucketName": "bucket"}},
+ {"SNSAction": {"TopicArn": "arn:aws:sns:us-east-1:111111111111:topic"}},
+ {"LambdaAction": {"FunctionArn": "arn:aws:lambda:us-east-1:111111111111:function:test"}},
+ {"BounceAction": {"SmtpReplyCode": "550", "Message": "no", "Sender": "[email protected]"}},
+ {"WorkmailAction": {"OrganizationArn": "arn:aws:workmail:us-east-1:111111111111:organization/m-test"}},
+ {"ConnectAction": {"InstanceARN": "arn:aws:connect:us-east-1:111111111111:instance/test",
+ "IAMRoleARN": "arn:aws:iam::111111111111:role/test"}},
+ {"StopAction": {"Scope": "RuleSet", "TopicArn": "arn:aws:sns:us-east-1:111111111111:topic"}},
+])
+def test_receipt_external_actions_are_explicitly_unsupported(receipt_api, action):
+ # Intentional supported-subset boundary: destination/permission validation
+ # and receiving execution have not been implemented for these action types.
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ name = next(iter(action))
+ if name == "StopAction":
+ name += " with TopicArn"
+ assert_error(api, "CreateReceiptRule", "InvalidAction",
+ f"Receipt action {name} is not implemented",
+ RuleSetName="rules", Rule={"Name": "unsupported", "Actions": [action]})
+ assert api("DescribeReceiptRuleSet", RuleSetName="rules")["Rules"] == []
+
+
+def test_receipt_explicit_empty_fields_are_preserved_and_after_is_validated(receipt_api):
+ api = receipt_api
+ api("CreateReceiptRuleSet", RuleSetName="rules")
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "empty", "Recipients": [], "Actions": [{}]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="empty")["Rule"]["Recipients"] == []
+ for name, action in (("empty-stop", {"StopAction": {}}), ("empty-header", {"AddHeaderAction": {}})):
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": name, "Actions": [action]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName=name)["Rule"]["Actions"] == []
+ api("CreateReceiptRule", RuleSetName="rules", Rule={"Name": "header", "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": ""}},
+ ]})
+ assert api("DescribeReceiptRule", RuleSetName="rules", RuleName="header")["Rule"]["Actions"] == [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": ""}},
+ ]
+ assert_error(api, "CreateReceiptRule", "ValidationError",
+ "2 validation errors detected: Value at 'after' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'after' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$",
+ RuleSetName="rules", After="", Rule={"Name": "after"})
+
+
+def test_receipt_metadata_and_active_selection_survive_all_tenant_persistence_and_reset(receipt_api, monkeypatch, tmp_path):
+ api = receipt_api
+ scopes = [("111111111111", "us-east-1"), ("111111111111", "us-west-2"), ("222222222222", "us-east-1")]
+ expected = {}
+ for i, (account, region) in enumerate(scopes):
+ set_request_account_id(account)
+ set_request_region(region)
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+ api("CreateReceiptRuleSet", RuleSetName="same-name")
+ api("CreateReceiptRule", RuleSetName="same-name", Rule={"Name": f"rule-{i}"})
+ api("SetActiveReceiptRuleSet", RuleSetName="same-name")
+ expected[account, region] = api("DescribeActiveReceiptRuleSet")
+ snapshot = ses.get_state()
+ monkeypatch.setattr(persistence, "PERSIST_STATE", True)
+ monkeypatch.setattr(persistence, "STATE_DIR", str(tmp_path))
+ persistence.save_state("ses", snapshot)
+ ses.reset()
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ assert api("ListReceiptRuleSets") == {"RuleSets": []}
+ assert api("DescribeActiveReceiptRuleSet") == {}
+ ses.load_persisted_state(persistence.load_state("ses"))
+ for account, region in scopes:
+ set_request_account_id(account)
+ set_request_region(region)
+ assert api("DescribeActiveReceiptRuleSet") == expected[account, region]
+ api("SetActiveReceiptRuleSet")
+ api("DeleteReceiptRuleSet", RuleSetName="same-name")
+ set_request_account_id(scopes[0][0])
+ set_request_region(scopes[0][1])
+ assert api("DescribeActiveReceiptRuleSet") == expected[scopes[0]]
+ assert snapshot["_receipt_rule_sets"].get_scoped(*scopes[-1], "same-name")["Rules"]
+
+
+def test_receipt_unsigned_sdk_lifecycle():
+ # The endpoint comes from conftest so this uses the same isolated local
+ # server as the integration suite. Activation changes shared server state.
+ from conftest import make_client
+
+ client = make_client("ses", additional_config_kwargs={"signature_version": UNSIGNED})
+ name = f"unsigned-receipts-{uuid4().hex[:12]}"
+ previous = client.describe_active_receipt_rule_set().get("Metadata", {}).get("Name")
+ client.create_receipt_rule_set(RuleSetName=name)
+ try:
+ assert name in {item["Name"] for item in client.list_receipt_rule_sets()["RuleSets"]}
+ client.create_receipt_rule(RuleSetName=name, Rule={"Name": "first"})
+ client.create_receipt_rule(RuleSetName=name, After="first", Rule={"Name": "second", "Actions": [
+ {"AddHeaderAction": {"HeaderName": "X-Test", "HeaderValue": "value<&"}},
+ {"StopAction": {"Scope": "RuleSet"}},
+ ]})
+ described = client.describe_receipt_rule_set(RuleSetName=name)
+ assert [rule["Name"] for rule in described["Rules"]] == ["first", "second"]
+ assert client.describe_receipt_rule(RuleSetName=name, RuleName="second")["Rule"] == described["Rules"][1]
+ client.set_active_receipt_rule_set(RuleSetName=name)
+ active = client.describe_active_receipt_rule_set()
+ assert active["Metadata"] == described["Metadata"]
+ assert active["Rules"] == described["Rules"]
+ client.delete_receipt_rule(RuleSetName=name, RuleName="second")
+ assert [rule["Name"] for rule in client.describe_active_receipt_rule_set()["Rules"]] == ["first"]
+ finally:
+ client.set_active_receipt_rule_set(**({"RuleSetName": previous} if previous else {}))
+ client.delete_receipt_rule_set(RuleSetName=name)
+ assert name not in {item["Name"] for item in client.list_receipt_rule_sets()["RuleSets"]}