Skip to content

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

feat(cloudformation): update SES configuration sets in place (#2183)

iot-rocketdd020411b199
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14c604e2..fcb3c55c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,14 +27,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
-- **Cognito — `UpdateUserPoolDomain` and `AWS::Cognito::UserPoolDomain` stack updates** — `UpdateUserPoolDomain` was an unknown action; it now changes a domain's `ManagedLoginVersion` and a custom domain's certificate, `CreateUserPoolDomain` and `DescribeUserPoolDomain` return the version, and a second prefix domain on a pool is refused as on AWS. A stack update applies `ManagedLoginVersion` and `CustomDomainConfig` through it instead of running the create again, a `Domain` or `UserPoolId` change replaces the domain, the create keeps `CustomDomainConfig`, `Ref` returns the domain name and `Fn::GetAtt` returns `CloudFrontDistribution`. Contributed by @iot-rocket.
-- **IoT — provisioning template versions** — `CreateProvisioningTemplateVersion`, `ListProvisioningTemplateVersions`, `DescribeProvisioningTemplateVersion` and `DeleteProvisioningTemplateVersion` answered `Unsupported IoT path` and `UpdateProvisioningTemplate` refused every `defaultVersionId` but 1; a template now keeps up to five versions whose ids are never reused, `setAsDefault` and `defaultVersionId` choose the version that `DescribeProvisioningTemplate` returns and `RegisterThing` applies, the default version cannot be deleted, and an `AWS::IoT::ProvisioningTemplate` whose `TemplateBody` changes gets a new default version (deleting the oldest at the limit), all with AWS's errors, including its message for a body that is not JSON. Contributed by @iot-rocket.
-- **IoT — pre-provisioning hook** — `RegisterThing` over MQTT now invokes the template's `preProvisioningHook` Lambda before the template is resolved and applies its answer the way AWS does: `parameterOverrides` are merged into the device's parameters, `allowProvisioning: false` is rejected as `AccessDenied`, and a function that fails, answers in another shape, takes longer than six seconds or may not be invoked gets AWS's `InvocationError` or `InvalidResult`. `CreateProvisioningTemplate` and `UpdateProvisioningTemplate` check the hook like AWS (a Lambda function ARN, payload version `2020-04-01`, no hook on JITP templates, and an invoke permission for `iot.amazonaws.com` that covers the template) and store the default payload version. Contributed by @iot-rocket.
-- **IoT — fleet provisioning by claim** — `CreateProvisioningClaim` issues a five-minute claim certificate that the mTLS listener accepts until it expires, and a device connected with it (or with any registered certificate) gets a certificate from `$aws/certificates/create/json` and registers itself through `$aws/provisioning-templates/<name>/provision/json`: the template's parameters, `Ref` and `Fn::Join` are resolved, the thing is created or checked against its `OverrideSettings`, and the certificate is activated and attached to the thing and the template's policies, with AWS's replies and rejections on the requesting connection; with `AUTH=true` a claim connection is limited to the certificate topics and its own template's, as on AWS. Contributed by @iot-rocket.
-- **IoT — presigned URLs in job documents** — devices got `${aws:iot:s3-presigned-url:<url>}` and `${aws:iot:s3-presigned-url-v2:<url>}` placeholders as written; the `iot-jobs-data` API and the MQTT jobs topics now replace each with a SigV4 presigned GET URL of MiniStack's S3, signed with a session of `presignedUrlConfig.roleArn` and valid for `expiresInSec`, and `CreateJob` and `CreateJobTemplate` refuse a placeholder without a role or an S3 object URL with AWS's messages. Contributed by @iot-rocket.
-- **IoT — job documents from S3** — `CreateJob` and `CreateJobTemplate` read a `documentSource` (`s3://` or an S3 object URL) from MiniStack's S3 once, at creation, where they stored a `{"documentSource": "<url>"}` placeholder. A missing bucket or object, an object that is not JSON or is over 32 KB and a URL that names no S3 host are refused with AWS's messages, and `CreateJob` refuses `document` together with `documentSource`. Devices get every job document re-serialized as AWS sends it, without spaces and without object members that are null, while `GetJobDocument` keeps the stored text. Contributed by @iot-rocket.
-- **IoT — `SetDefaultPolicyVersion`** — the call was missing (`PATCH /policies/{policyName}/version/{policyVersionId}` answered `Unsupported policy path`), so only `CreatePolicyVersion` with `setAsDefault` could move a policy's default version; it now sets the default that `GetPolicy`, `GetPolicyVersion`, `ListPolicyVersions` and the MQTT policy evaluation under `AUTH=true` use, deleting the default version answers `DeleteConflictException` (409) instead of 400, and `ListPolicyVersions` lists the newest version first. Contributed by @iot-rocket.
-- **IoT — `EnableTopicRule` and `DisableTopicRule`** — both calls were missing (`POST /rules/{ruleName}/enable` answered `Invalid ruleName`), so a rule could only be switched off by replacing it; they now set `ruleDisabled`, which `GetTopicRule` and `ListTopicRules` report and which stops the rule from acting on matching publishes and Basic Ingest until it is enabled again. Contributed by @iot-rocket.
+- **CloudFormation — SES configuration set updates** — `AWS::SES::ConfigurationSet` and `AWS::SES::ConfigurationSetEventDestination` stored none of their options, tags or destinations, and a change re-ran the create; both now provision through the SES v2 calls and update in place, a removed option goes back to its default as on AWS, and only a `Name` or `ConfigurationSetName` change replaces them. Contributed by @iot-rocket.
+- **SES v2 — configuration set options and event destinations** — `GetConfigurationSet` returned only the name and the tags given at creation; it now returns the tracking, delivery, reputation, sending, suppression, VDM and archiving options that `CreateConfigurationSet` and the seven `PutConfigurationSet*Options` calls set, and a call clears the members it leaves out, as on AWS. `CreateConfigurationSetEventDestination`, `GetConfigurationSetEventDestinations`, `UpdateConfigurationSetEventDestination` and `DeleteConfigurationSetEventDestination` are new. `CreateConfigurationSet` with a name already in use is refused with `AlreadyExistsException` instead of replacing the set. Contributed by @iot-rocket.
- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.
- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.
### Fixed
diff --git a/README.md b/README.md
index 2d68a50a..9f622d2e 100644
--- a/README.md
+++ b/README.md
@@ -425,7 +425,7 @@ subnet = ec2.create_subnet(
| **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, 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 sets and ordered rules, with every action type, are stored and persisted; inbound email receiving is not emulated; a send publishes a `Delivery`, `Bounce` or `Complaint` notification per recipient to the identity's `SetIdentityNotificationTopic` SNS topic, following the mailbox simulator |
-| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountDetails, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource, CreateTenant, GetTenant, ListTenants, DeleteTenant, CreateTenantResourceAssociation, DeleteTenantResourceAssociation, ListTenantResources, ListResourceTenants, PutTenantSuppressionAttributes, CreateDedicatedIpPool, GetDedicatedIpPool, ListDedicatedIpPools, DeleteDedicatedIpPool | 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; a configuration set, identity or template associated with a tenant cannot be deleted until the association is removed; dedicated IP pools are records only, with no IP addresses behind them |
+| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, PutConfigurationSetTrackingOptions, PutConfigurationSetDeliveryOptions, PutConfigurationSetReputationOptions, PutConfigurationSetSendingOptions, PutConfigurationSetSuppressionOptions, PutConfigurationSetVdmOptions, PutConfigurationSetArchivingOptions, CreateConfigurationSetEventDestination, GetConfigurationSetEventDestinations, UpdateConfigurationSetEventDestination, DeleteConfigurationSetEventDestination, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountDetails, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource, CreateTenant, GetTenant, ListTenants, DeleteTenant, CreateTenantResourceAssociation, DeleteTenantResourceAssociation, ListTenantResources, ListResourceTenants, PutTenantSuppressionAttributes, CreateDedicatedIpPool, GetDedicatedIpPool, ListDedicatedIpPools, DeleteDedicatedIpPool | 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; a configuration set, identity or template associated with a tenant cannot be deleted until the association is removed; dedicated IP pools are records only, with no IP addresses behind them |
| **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 |
| **Bedrock** | 66 operations — foundation-model catalog (real model IDs), inference profiles (system + application-managed), guardrails with versioning, custom models, imported models, provisioned model throughput, model customization / import / copy / batch-invocation job families, tagging | All 66 operations verified against botocore `bedrock-2023-04-20`; camelCase wire format per `locationName`; account- and region-scoped state |
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 7f80a5ff..2f1b4f34 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1154,6 +1154,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::DocDB::DBInstance": ("Tags", "list"),
"AWS::DocDB::DBSubnetGroup": ("Tags", "list"),
"AWS::DocDB::DBClusterParameterGroup": ("Tags", "list"),
+ "AWS::SES::ConfigurationSet": ("Tags", "list"),
"AWS::SNS::Topic": ("Tags", "list"),
"AWS::SQS::Queue": ("Tags", "list"),
"AWS::SSM::Parameter": ("Tags", "map"),
@@ -10694,51 +10695,120 @@ def _ses_email_identity_update(physical_id, old_props, new_props, stack_name,
# SES ConfigurationSet
# ---------------------------------------------------------------------------
+def _ses_configuration_set_members(props):
+ """The SES v2 CreateConfigurationSet members of a template's properties."""
+ members = {k: copy.deepcopy(props[k]) for k in _ses_v2._CONFIG_SET_OPTIONS.values()
+ if isinstance(props.get(k), dict)}
+ for key, member in (("ReputationOptions", "ReputationMetricsEnabled"), ("SendingOptions", "SendingEnabled")):
+ if member in members.get(key, {}):
+ members[key][member] = _cfn_bool(members[key][member])
+ members["Tags"] = [{"Key": k, "Value": v} for k, v in _tag_map(props.get("Tags")).items()]
+ return members
+
+
def _ses_configuration_set_create(logical_id, props, stack_name):
- # AWS::SES::ConfigurationSet Ref returns the configuration set name; when the
- # template omits Name, CloudFormation generates one from the stack/logical id.
- name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
+ """Ref is the set name; a generated name is <LogicalId>- + 12 random letters and digits."""
+ suffix = "".join(random.choices(string.ascii_letters + string.digits, k=12))
+ name = props.get("Name") or f"{logical_id[:51]}-{suffix}"
# Register with both the classic (v1) and v2 SES stores so DescribeConfigurationSet
# (Query API) and GetConfigurationSet (v2 REST API) both see the set.
_ses._configuration_sets[name] = {
"Name": name,
"CreatedTimestamp": _ses._iso_now(),
}
- _ses_v2._config_sets[name] = {"ConfigurationSetName": name, "Tags": []}
+ _ses_v2._create_config_set(name, _ses_configuration_set_members(props))
# Real AWS AWS::SES::ConfigurationSet supports Ref (the set name) only; it
# exposes no Fn::GetAtt attributes, so return none.
return name, {}
+def _ses_configuration_set_update(physical_id, old_props, new_props, stack_name):
+ """Put every option again, a removed one as a new set has it; a Name change replaces the set."""
+ rec = _ses_v2._config_sets.get(physical_id)
+ if rec is None:
+ return _ses_configuration_set_create(None, {**new_props, "Name": physical_id}, stack_name)
+ members = _ses_configuration_set_members(new_props)
+ for key in _ses_v2._CONFIG_SET_OPTIONS.values():
+ _ses_v2._put_config_set_option(rec, key, members.get(key) or _ses_v2._CONFIG_SET_DEFAULTS.get(key, {}))
+ rec["Tags"] = members["Tags"]
+ _ses_v2._ses_tags[_ses_v2._resource_arn("configuration-set", physical_id)] = list(members["Tags"])
+ return physical_id, {}
+
+
def _ses_configuration_set_delete(physical_id, props):
_ses._configuration_sets.pop(physical_id, None)
_ses_v2._config_sets.pop(physical_id, None)
+ _ses_v2._ses_tags.pop(_ses_v2._resource_arn("configuration-set", physical_id), None)
# ---------------------------------------------------------------------------
# SES ConfigurationSetEventDestination
# ---------------------------------------------------------------------------
+def _ses_v2_enum(value):
+ """A v1 camelCase name as its SES v2 enum value: renderingFailure is RENDERING_FAILURE."""
+ return re.sub(r"([a-z])([A-Z])", r"\1_\2", str(value)).upper()
+
+
+def _ses_event_destination_definition(destination):
+ """The SES v2 EventDestinationDefinition of a template's EventDestination."""
+ definition = {
+ "Enabled": _cfn_bool(destination.get("Enabled", False)),
+ "MatchingEventTypes": [_ses_v2_enum(t) for t in destination.get("MatchingEventTypes") or []],
+ }
+ cloudwatch = destination.get("CloudWatchDestination")
+ if isinstance(cloudwatch, dict):
+ definition["CloudWatchDestination"] = {"DimensionConfigurations": [
+ {**d, "DimensionValueSource": _ses_v2_enum(d.get("DimensionValueSource", ""))}
+ for d in cloudwatch.get("DimensionConfigurations") or []
+ ]}
+ firehose = destination.get("KinesisFirehoseDestination")
+ if isinstance(firehose, dict):
+ definition["KinesisFirehoseDestination"] = {
+ "IamRoleArn": firehose.get("IAMRoleARN"), "DeliveryStreamArn": firehose.get("DeliveryStreamARN")}
+ if isinstance(destination.get("SnsDestination"), dict):
+ definition["SnsDestination"] = {"TopicArn": destination["SnsDestination"].get("TopicARN")}
+ if isinstance(destination.get("EventBridgeDestination"), dict):
+ definition["EventBridgeDestination"] = {
+ "EventBusArn": destination["EventBridgeDestination"].get("EventBusArn")}
+ return definition
+
+
+def _ses_event_destination_put(config_set, dest_name, props, *, create):
+ if config_set not in _ses_v2._config_sets:
+ # A set the v2 store does not know: the destination is not recorded.
+ return
+ err = _ses_v2._put_event_destination(
+ config_set, dest_name, _ses_event_destination_definition(props.get("EventDestination") or {}),
+ create=create)
+ if err:
+ raise ValueError(json.loads(err[2])["message"])
+
+
def _ses_configuration_set_event_destination_create(logical_id, props, stack_name):
config_set = props.get("ConfigurationSetName", "")
destination = props.get("EventDestination", {}) or {}
dest_name = destination.get("Name") or _physical_name(
stack_name, logical_id, max_len=64)
- # Record the event destination against its configuration set (if present) so
- # the set round-trips with its destinations; the emulator does not deliver
- # SES events, this is CFN provisioning fidelity only.
- record = _ses._configuration_sets.get(config_set)
- if record is not None:
- record.setdefault("EventDestinations", {})[dest_name] = destination
+ # Recorded through the SES v2 API; the emulator does not deliver SES events.
+ _ses_event_destination_put(config_set, dest_name, props, create=True)
# The physical id encodes both names so delete can locate the destination.
return f"{config_set}|{dest_name}", {"Id": dest_name}
+def _ses_configuration_set_event_destination_update(physical_id, old_props, new_props, stack_name):
+ """Replace the destination's content in place; the physical id keeps its name, as on AWS."""
+ config_set, _, dest_name = physical_id.partition("|")
+ destinations = (_ses_v2._config_sets.get(config_set) or {}).get("EventDestinations") or {}
+ _ses_event_destination_put(config_set, dest_name, new_props, create=dest_name not in destinations)
+ return physical_id, {"Id": dest_name}
+
+
def _ses_configuration_set_event_destination_delete(physical_id, props):
config_set, _, dest_name = physical_id.partition("|")
- record = _ses._configuration_sets.get(config_set)
+ record = _ses_v2._config_sets.get(config_set)
if record is not None:
- record.get("EventDestinations", {}).pop(dest_name, None)
+ (record.get("EventDestinations") or {}).pop(dest_name, None)
# ---------------------------------------------------------------------------
@@ -14281,6 +14351,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::CertificateManager::Certificate": _ACM_REPLACEMENT_PROPERTIES,
"AWS::CloudFront::Function": ("Name",),
"AWS::SSM::Parameter": ("Name",),
+ "AWS::SES::ConfigurationSet": ("Name",),
+ "AWS::SES::ConfigurationSetEventDestination": ("ConfigurationSetName",),
"AWS::SQS::Queue": ("QueueName", "FifoQueue"),
"AWS::SNS::Topic": ("TopicName", "FifoTopic"),
"AWS::Signer::SigningProfile": ("ProfileName", "PlatformId", "SignatureValidityPeriod"),
@@ -15056,8 +15128,16 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _ses_email_identity_delete,
},
- "AWS::SES::ConfigurationSet": {"create": _ses_configuration_set_create, "delete": _ses_configuration_set_delete},
- "AWS::SES::ConfigurationSetEventDestination": {"create": _ses_configuration_set_event_destination_create, "delete": _ses_configuration_set_event_destination_delete},
+ "AWS::SES::ConfigurationSet": {
+ "create": _ses_configuration_set_create,
+ "update": _ses_configuration_set_update,
+ "delete": _ses_configuration_set_delete,
+ },
+ "AWS::SES::ConfigurationSetEventDestination": {
+ "create": _ses_configuration_set_event_destination_create,
+ "update": _ses_configuration_set_event_destination_update,
+ "delete": _ses_configuration_set_event_destination_delete,
+ },
"AWS::Signer::SigningProfile": {
"create": _signer_signing_profile_create,
"update": _signer_signing_profile_update,
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 638151f7..935ad7bd 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -5,7 +5,13 @@ SES v2 Service Emulator.
REST/JSON API via path /v2/email/...
Supports: SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity,
ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet,
- DeleteConfigurationSet, ListConfigurationSets, CreateEmailTemplate,
+ DeleteConfigurationSet, ListConfigurationSets,
+ PutConfigurationSetTrackingOptions, PutConfigurationSetDeliveryOptions,
+ PutConfigurationSetReputationOptions, PutConfigurationSetSendingOptions,
+ PutConfigurationSetSuppressionOptions, PutConfigurationSetVdmOptions,
+ PutConfigurationSetArchivingOptions, CreateConfigurationSetEventDestination,
+ GetConfigurationSetEventDestinations, UpdateConfigurationSetEventDestination,
+ DeleteConfigurationSetEventDestination, CreateEmailTemplate,
GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate,
ListEmailTemplates, GetAccount, ListSuppressedDestinations,
PutAccountSuppressionAttributes, TagResource, UntagResource,
@@ -615,6 +621,166 @@ def _tenant_request(method, sub, data):
return json_response({})
+# Configuration set options by the path of their Put call, as GetConfigurationSet returns them.
+_CONFIG_SET_OPTIONS = {
+ "tracking-options": "TrackingOptions",
+ "delivery-options": "DeliveryOptions",
+ "reputation-options": "ReputationOptions",
+ "sending": "SendingOptions",
+ "suppression-options": "SuppressionOptions",
+ "vdm-options": "VdmOptions",
+ "archiving-options": "ArchivingOptions",
+}
+_CONFIG_SET_OPTION_MEMBERS = {
+ "TrackingOptions": ("CustomRedirectDomain", "HttpsPolicy"),
+ "DeliveryOptions": ("TlsPolicy", "SendingPoolName", "MaxDeliverySeconds"),
+ "SuppressionOptions": ("SuppressedReasons", "ValidationOptions"),
+ "VdmOptions": ("DashboardOptions", "GuardianOptions"),
+ "ArchivingOptions": ("ArchiveArn",),
+}
+_CONFIG_SET_DEFAULTS = {
+ "ReputationOptions": {"ReputationMetricsEnabled": True},
+ "SendingOptions": {"SendingEnabled": True},
+}
+_EVENT_TYPES = (
+ "SEND", "REJECT", "BOUNCE", "COMPLAINT", "DELIVERY", "OPEN", "CLICK",
+ "RENDERING_FAILURE", "DELIVERY_DELAY", "SUBSCRIPTION",
+)
+_EVENT_DESTINATION_TARGETS = (
+ "KinesisFirehoseDestination", "CloudWatchDestination", "SnsDestination",
+ "EventBridgeDestination", "PinpointDestination",
+)
+
+
+def _missing_config_set(name):
+ return _json_err("NotFoundException", f"Configuration set <{name}> does not exist.", 404)
+
+
+def _put_config_set_option(rec, key, value):
+ """Apply one option the way its Put call does: a member left out is cleared."""
+ if key == "ReputationOptions":
+ rec[key] = {**rec.get(key, {}), "ReputationMetricsEnabled": bool(value.get("ReputationMetricsEnabled"))}
+ elif key == "SendingOptions":
+ enabled = bool(value.get("SendingEnabled"))
+ if enabled and not rec.get(key, _CONFIG_SET_DEFAULTS[key])["SendingEnabled"]:
+ # Sending enabled again gives the reputation metrics a fresh start.
+ rec["ReputationOptions"] = {
+ **rec.get("ReputationOptions", _CONFIG_SET_DEFAULTS["ReputationOptions"]),
+ "LastFreshStart": int(time.time()),
+ }
+ rec[key] = {"SendingEnabled": enabled}
+ else:
+ members = {k: value[k] for k in _CONFIG_SET_OPTION_MEMBERS[key] if value.get(k) is not None}
+ if members:
+ rec[key] = members
+ else:
+ rec.pop(key, None)
+
+
+def _create_config_set(name, data):
+ """Store a configuration set from CreateConfigurationSet members."""
+ rec = {"ConfigurationSetName": name, "Tags": list(data.get("Tags") or []), **copy.deepcopy(_CONFIG_SET_DEFAULTS)}
+ for key in _CONFIG_SET_OPTIONS.values():
+ if isinstance(data.get(key), dict):
+ _put_config_set_option(rec, key, data[key])
+ _config_sets[name] = rec
+ _ses_tags[_resource_arn("configuration-set", name)] = list(rec["Tags"])
+ return rec
+
+
+def _config_set_view(name, rec):
+ out = {"ConfigurationSetName": name}
+ for key in _CONFIG_SET_OPTIONS.values():
+ value = rec.get(key, _CONFIG_SET_DEFAULTS.get(key))
+ if value is not None:
+ out[key] = copy.deepcopy(value)
+ out["Tags"] = _ses_tags.get(_resource_arn("configuration-set", name), rec.get("Tags", []))
+ return out
+
+
+def _event_destination(definition):
+ """The stored form of an EventDestinationDefinition, or an error response."""
+ types = definition.get("MatchingEventTypes") or []
+ if not types:
+ return None, _json_err("BadRequestException", "At least one event type must be specified.")
+ if any(t not in _EVENT_TYPES for t in types):
+ return None, _json_err("BadRequestException", "The event destination contains an invalid event type.")
+ targets = {k: definition[k] for k in _EVENT_DESTINATION_TARGETS if definition.get(k)}
+ if not targets:
+ return None, _json_err("BadRequestException", "Event destination is not provided.")
+ if len(targets) > 1:
+ return None, _json_err(
+ "BadRequestException",
+ "Please provide only one destination with each request. Either a Firehose Destination or a "
+ "Cloudwatch Destination or an SNS Destination or an EventBridge Destination.",
+ )
+ dimensions = (targets.get("CloudWatchDestination") or {}).get("DimensionConfigurations") or []
+ if any(d.get("DimensionValueSource") not in ("MESSAGE_TAG", "EMAIL_HEADER", "LINK_TAG") for d in dimensions):
+ return None, _json_err("BadRequestException", "invalid CloudWatch dimension source")
+ return {"Enabled": bool(definition.get("Enabled")), "MatchingEventTypes": sorted(set(types)), **targets}, None
+
+
+def _put_event_destination(name, dest_name, definition, *, create):
+ """Create or replace one event destination; an error response or None."""
+ rec = _config_sets.get(name)
+ if rec is None:
+ return _missing_config_set(name)
+ destinations = rec.get("EventDestinations") or {}
+ if create and not re.fullmatch(r"[A-Za-z0-9_-]+", dest_name):
+ return _json_err(
+ "BadRequestException",
+ f"Invalid event destination name <{dest_name}>: "
+ "only alphanumeric ASCII characters, '_', and '-' are allowed.",
+ )
+ if create and dest_name in destinations:
+ return _json_err(
+ "AlreadyExistsException",
+ f"An event destination with name <{dest_name}> already exists for configuration set <{name}>.",
+ )
+ if not create and dest_name not in destinations:
+ return _missing_event_destination(name, dest_name)
+ stored, err = _event_destination(definition if isinstance(definition, dict) else {})
+ if err:
+ return err
+ # An updated destination is listed last.
+ destinations.pop(dest_name, None)
+ destinations[dest_name] = stored
+ rec["EventDestinations"] = destinations
+ return None
+
+
+def _missing_event_destination(name, dest_name):
+ return _json_err(
+ "NotFoundException",
+ f"An event destination with name <{dest_name}> does not exist for configuration set <{name}>.",
+ 404,
+ )
+
+
+def _event_destinations_request(method, name, dest_name, data):
+ rec = _config_sets.get(name)
+ if rec is None:
+ return _missing_config_set(name)
+ destinations = rec.get("EventDestinations") or {}
+ if dest_name is None and method == "GET":
+ if not destinations:
+ return json_response({})
+ return json_response({"EventDestinations": [{"Name": n, **copy.deepcopy(d)} for n, d in destinations.items()]})
+ if dest_name is None and method == "POST":
+ err = _put_event_destination(name, data.get("EventDestinationName", ""), data.get("EventDestination"),
+ create=True)
+ return err or json_response({})
+ if dest_name is not None and method == "PUT":
+ err = _put_event_destination(name, dest_name, data.get("EventDestination"), create=False)
+ return err or json_response({})
+ if dest_name is not None and method == "DELETE":
+ if dest_name not in destinations:
+ return _missing_event_destination(name, dest_name)
+ destinations.pop(dest_name)
+ return json_response({})
+ return None
+
+
async def handle_request(method, path, headers, body, query_params):
# The SES dispatcher also accepts unprefixed REST paths when selected by
# a SESv2 target header. Preserve those paths and trailing-slash handling
@@ -919,8 +1085,9 @@ async def handle_request(method, path, headers, body, query_params):
name = data.get("ConfigurationSetName", "")
if not name:
return _json_err("BadRequestException", "ConfigurationSetName is required")
- _config_sets[name] = {"ConfigurationSetName": name, "Tags": data.get("Tags", [])}
- _ses_tags[_resource_arn("configuration-set", name)] = list(data.get("Tags", []))
+ if name in _config_sets:
+ return _json_err("AlreadyExistsException", f"Configuration set <{name}> already exists.")
+ _create_config_set(name, data)
return json_response({})
# ListConfigurationSets: GET /v2/email/configuration-sets, or
@@ -939,6 +1106,26 @@ async def handle_request(method, path, headers, body, query_params):
out["NextToken"] = next_token
return json_response(out)
+ # PUT /v2/email/configuration-sets/{name}/{option} (PutConfigurationSet*Options)
+ m = re.match(r"^/configuration-sets/([^/]+)/([a-z-]+)$", sub)
+ if m and method == "PUT" and m.group(2) in _CONFIG_SET_OPTIONS:
+ name, option = m.groups()
+ rec = _config_sets.get(name)
+ if rec is None:
+ return _missing_config_set(name)
+ value = (data.get("VdmOptions") or {}) if option == "vdm-options" else data
+ if option == "tracking-options" and value.get("HttpsPolicy") and not value.get("CustomRedirectDomain"):
+ return _json_err("BadRequestException", "CustomRedirectDomain must be specified.")
+ _put_config_set_option(rec, _CONFIG_SET_OPTIONS[option], value)
+ return json_response({})
+
+ # /v2/email/configuration-sets/{name}/event-destinations[/{destination}]
+ m = re.match(r"^/configuration-sets/([^/]+)/event-destinations(?:/([^/]+))?$", sub)
+ if m:
+ result = _event_destinations_request(method, m.group(1), m.group(2), data)
+ if result is not None:
+ return result
+
# GET/DELETE /v2/email/configuration-sets/{name}
m = re.match(r"^/configuration-sets/([^/]+)$", sub)
if m:
@@ -946,8 +1133,8 @@ async def handle_request(method, path, headers, body, query_params):
if method == "GET":
rec = _config_sets.get(name)
if not rec:
- return _json_err("NotFoundException", f"ConfigurationSet {name} not found", 404)
- return json_response(rec)
+ return _missing_config_set(name)
+ return json_response(_config_set_view(name, rec))
if method == "DELETE":
arn = _resource_arn("configuration-set", name)
blocked = _tenant_delete_block(arn)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 27e64c78..f38458fa 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -19274,6 +19274,178 @@ def test_cfn_ses_configuration_set_and_event_destination(cfn, ses, sesv2):
ses.describe_configuration_set(ConfigurationSetName=cs_name)
+_SES_SET_V1 = {
+ "DeliveryOptions": {"TlsPolicy": "REQUIRE", "MaxDeliverySeconds": 900},
+ "ReputationOptions": {"ReputationMetricsEnabled": False},
+ "SendingOptions": {"SendingEnabled": False},
+ "SuppressionOptions": {"SuppressedReasons": ["BOUNCE", "COMPLAINT"]},
+ "VdmOptions": {"DashboardOptions": {"EngagementMetrics": "DISABLED"}},
+ "Tags": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}],
+}
+_SES_DEST_V1 = {
+ "Name": "dest", "Enabled": True, "MatchingEventTypes": ["send", "bounce"],
+ "CloudWatchDestination": {"DimensionConfigurations": [{
+ "DimensionName": "campaign", "DimensionValueSource": "messageTag", "DefaultDimensionValue": "none"}]},
+}
+_SES_SET_V2 = {"DeliveryOptions": {"TlsPolicy": "OPTIONAL"},
+ "Tags": [{"Key": "a", "Value": "10"}, {"Key": "c", "Value": "3"}]}
+_SES_DEST_V2 = {"Name": "dest", "MatchingEventTypes": ["delivery", "complaint", "reject"],
+ "SnsDestination": {"TopicARN": {"Ref": "Topic"}}}
+
+
+def _cfn_ses_template(uid, set_props, dest, name=None):
+ return json.dumps({
+ "Resources": {
+ "Topic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": f"cfn-ses-{uid}"}},
+ "Set": {"Type": "AWS::SES::ConfigurationSet",
+ "Properties": {"Name": name or f"cfn-ses-{uid}", **set_props}},
+ "Bare": {"Type": "AWS::SES::ConfigurationSet"},
+ "Dest": {"Type": "AWS::SES::ConfigurationSetEventDestination",
+ "Properties": {"ConfigurationSetName": {"Ref": "Set"}, "EventDestination": dest}},
+ },
+ "Outputs": {"BareRef": {"Value": {"Ref": "Bare"}}, "DestRef": {"Value": {"Ref": "Dest"}}},
+ })
+
+
+def _ses_set(sesv2, name):
+ out = sesv2.get_configuration_set(ConfigurationSetName=name)
+ out.pop("ResponseMetadata")
+ out["Tags"] = sorted((t["Key"], t["Value"]) for t in out["Tags"] if not t["Key"].startswith("aws:"))
+ return out
+
+
+def _ses_destinations(sesv2, name):
+ return sesv2.get_configuration_set_event_destinations(ConfigurationSetName=name)["EventDestinations"]
+
+
+def test_cfn_ses_configuration_set_updates_in_place(cfn, sesv2):
+ """A removed option goes back to its default, the destination changes in place and a rollback restores both."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name, name = f"cfn-ses-upd-{uid}", f"cfn-ses-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_ses_template(uid, _SES_SET_V1, _SES_DEST_V1))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ bare = _output(stack, "BareRef")
+ assert re.fullmatch(r"Bare-[A-Za-z0-9]{12}", bare)
+ assert _ses_set(sesv2, bare) == {
+ "ConfigurationSetName": bare, "ReputationOptions": {"ReputationMetricsEnabled": True},
+ "SendingOptions": {"SendingEnabled": True}, "Tags": []}
+ tags = sesv2.get_configuration_set(ConfigurationSetName=name)["Tags"]
+ assert {t["Key"]: t["Value"] for t in tags}["aws:cloudformation:logical-id"] == "Set"
+ assert _ses_set(sesv2, name) == {
+ "ConfigurationSetName": name,
+ "DeliveryOptions": {"TlsPolicy": "REQUIRE", "MaxDeliverySeconds": 900},
+ "ReputationOptions": {"ReputationMetricsEnabled": False},
+ "SendingOptions": {"SendingEnabled": False},
+ "SuppressionOptions": {"SuppressedReasons": ["BOUNCE", "COMPLAINT"]},
+ "VdmOptions": {"DashboardOptions": {"EngagementMetrics": "DISABLED"}},
+ "Tags": [("a", "1"), ("b", "2")]}
+ assert _ses_destinations(sesv2, name) == [{
+ "Name": "dest", "Enabled": True, "MatchingEventTypes": ["BOUNCE", "SEND"],
+ "CloudWatchDestination": {"DimensionConfigurations": [{
+ "DimensionName": "campaign", "DimensionValueSource": "MESSAGE_TAG",
+ "DefaultDimensionValue": "none"}]}}]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_ses_template(uid, _SES_SET_V2, _SES_DEST_V2))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert (_output(stack, "BareRef"), _output(stack, "DestRef")) == (bare, f"{name}|dest")
+ updated = _ses_set(sesv2, name)
+ assert "LastFreshStart" in updated["ReputationOptions"]
+ updated["ReputationOptions"].pop("LastFreshStart")
+ assert updated == {
+ "ConfigurationSetName": name, "DeliveryOptions": {"TlsPolicy": "OPTIONAL"},
+ "ReputationOptions": {"ReputationMetricsEnabled": True}, "SendingOptions": {"SendingEnabled": True},
+ "Tags": [("a", "10"), ("c", "3")]}
+ destinations = _ses_destinations(sesv2, name)
+ assert destinations == [{
+ "Name": "dest", "Enabled": False, "MatchingEventTypes": ["COMPLAINT", "DELIVERY", "REJECT"],
+ "SnsDestination": {"TopicArn": destinations[0]["SnsDestination"]["TopicArn"]}}]
+ assert destinations[0]["SnsDestination"]["TopicArn"].endswith(f":cfn-ses-{uid}")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_with_failing_resource(
+ _cfn_ses_template(uid, _SES_SET_V1, _SES_DEST_V1), ["Set", "Dest"]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ restored = _ses_set(sesv2, name)
+ restored["ReputationOptions"].pop("LastFreshStart")
+ assert restored == {**updated, "ReputationOptions": {"ReputationMetricsEnabled": True}}
+ assert _ses_destinations(sesv2, name) == destinations
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ for set_name in (name, bare):
+ with pytest.raises(ClientError):
+ sesv2.get_configuration_set(ConfigurationSetName=set_name)
+
+
+def test_cfn_ses_configuration_set_rename_and_destination_changes(cfn, sesv2):
+ """A Name change replaces both; a destination keeps its first Name; an invalid destination rolls back."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name, name, renamed = f"cfn-ses-ren-{uid}", f"cfn-ses-{uid}", f"cfn-ses-renamed-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_ses_template(uid, _SES_SET_V2, _SES_DEST_V2))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.create_change_set(StackName=stack_name, ChangeSetName="rename",
+ TemplateBody=_cfn_ses_template(uid, _SES_SET_V2, _SES_DEST_V2, name=renamed))
+ described = _wait_change_set(cfn, stack_name, "rename")
+ assert sorted((c["ResourceChange"]["LogicalResourceId"], c["ResourceChange"]["Replacement"])
+ for c in described["Changes"]) == [("Dest", "True"), ("Set", "True")]
+ cfn.execute_change_set(StackName=stack_name, ChangeSetName="rename")
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "DestRef") == f"{renamed}|dest"
+ assert _ses_set(sesv2, renamed)["Tags"] == [("a", "10"), ("c", "3")]
+ assert [d["MatchingEventTypes"] for d in _ses_destinations(sesv2, renamed)] == [
+ ["COMPLAINT", "DELIVERY", "REJECT"]]
+ with pytest.raises(ClientError):
+ sesv2.get_configuration_set(ConfigurationSetName=name)
+
+ third = {**_SES_DEST_V1, "Name": "dest2", "MatchingEventTypes": ["send"]}
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_ses_template(uid, _SES_SET_V2, third, name=renamed))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "DestRef") == f"{renamed}|dest"
+ expected = [{"Name": "dest", "Enabled": True, "MatchingEventTypes": ["SEND"],
+ "CloudWatchDestination": {"DimensionConfigurations": [{
+ "DimensionName": "campaign", "DimensionValueSource": "MESSAGE_TAG",
+ "DefaultDimensionValue": "none"}]}}]
+ assert _ses_destinations(sesv2, renamed) == expected
+
+ for dest, reason in (
+ ({**third, "MatchingEventTypes": ["sent"]}, "The event destination contains an invalid event type."),
+ ({k: v for k, v in third.items() if k != "CloudWatchDestination"}, "Event destination is not provided."),
+ ):
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_ses_template(uid, _SES_SET_V2, dest, name=renamed))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert reason in _stack_event_reasons(cfn, stack_name)
+ assert _ses_destinations(sesv2, renamed) == expected
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_ses_configuration_set_long_logical_id(cfn, sesv2):
+ """A generated name keeps the first 51 characters of the logical id, so it stays within 64."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name, logical_id = f"cfn-ses-long-{uid}", "Long" * 18
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(
+ {"Resources": {logical_id: {"Type": "AWS::SES::ConfigurationSet"}}}))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ name = cfn.describe_stack_resource(StackName=stack_name, LogicalResourceId=logical_id)[
+ "StackResourceDetail"]["PhysicalResourceId"]
+ assert re.fullmatch(logical_id[:51] + r"-[A-Za-z0-9]{12}", name)
+ assert sesv2.get_configuration_set(ConfigurationSetName=name)["ConfigurationSetName"] == name
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
def _signer_template(named, validity=30, tags=None, named_validity=None,
action="signer:StartSigningJob"):
named_props = {"ProfileName": named, "PlatformId": "AWSLambda-SHA384-ECDSA"}
diff --git a/tests/test_ses.py b/tests/test_ses.py
index 4d405786..1b9b2efe 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -301,6 +301,182 @@ def test_ses_v2_configuration_set_crud(sesv2):
lst2 = sesv2.list_configuration_sets()
assert "my-cfg-set" not in lst2["ConfigurationSets"]
+
+def _sesv2_error(call, **kwargs):
+ with pytest.raises(ClientError) as exc:
+ call(**kwargs)
+ return exc.value.response["Error"]["Code"], exc.value.response["Error"]["Message"]
+
+
+def test_ses_v2_configuration_set_options(sesv2):
+ """GetConfigurationSet returns the options; each Put call replaces its option and clears what it leaves out."""
+ bare, name = f"cs-bare-{_uuid_mod.uuid4().hex[:8]}", f"cs-opts-{_uuid_mod.uuid4().hex[:8]}"
+ sesv2.create_configuration_set(ConfigurationSetName=bare)
+ sesv2.create_configuration_set(
+ ConfigurationSetName=name,
+ DeliveryOptions={"TlsPolicy": "REQUIRE", "MaxDeliverySeconds": 600},
+ ReputationOptions={"ReputationMetricsEnabled": False},
+ SendingOptions={"SendingEnabled": False},
+ SuppressionOptions={"SuppressedReasons": ["BOUNCE", "COMPLAINT"]},
+ VdmOptions={"DashboardOptions": {"EngagementMetrics": "DISABLED"}},
+ Tags=[{"Key": "team", "Value": "a"}])
+
+ def get(set_name=name):
+ out = sesv2.get_configuration_set(ConfigurationSetName=set_name)
+ out.pop("ResponseMetadata")
+ return out
+
+ try:
+ assert get(bare) == {
+ "ConfigurationSetName": bare, "ReputationOptions": {"ReputationMetricsEnabled": True},
+ "SendingOptions": {"SendingEnabled": True}, "Tags": []}
+ assert get() == {
+ "ConfigurationSetName": name,
+ "DeliveryOptions": {"TlsPolicy": "REQUIRE", "MaxDeliverySeconds": 600},
+ "ReputationOptions": {"ReputationMetricsEnabled": False},
+ "SendingOptions": {"SendingEnabled": False},
+ "SuppressionOptions": {"SuppressedReasons": ["BOUNCE", "COMPLAINT"]},
+ "VdmOptions": {"DashboardOptions": {"EngagementMetrics": "DISABLED"}},
+ "Tags": [{"Key": "team", "Value": "a"}]}
+ assert _sesv2_error(sesv2.create_configuration_set, ConfigurationSetName=name) == (
+ "AlreadyExistsException", f"Configuration set <{name}> already exists.")
+ assert get()["DeliveryOptions"] == {"TlsPolicy": "REQUIRE", "MaxDeliverySeconds": 600}
+
+ sesv2.put_configuration_set_delivery_options(ConfigurationSetName=name, TlsPolicy="OPTIONAL")
+ assert get()["DeliveryOptions"] == {"TlsPolicy": "OPTIONAL"}
+ sesv2.put_configuration_set_delivery_options(ConfigurationSetName=name)
+ assert "DeliveryOptions" not in get()
+ sesv2.put_configuration_set_reputation_options(ConfigurationSetName=name, ReputationMetricsEnabled=True)
+ sesv2.put_configuration_set_reputation_options(ConfigurationSetName=name)
+ assert get()["ReputationOptions"] == {"ReputationMetricsEnabled": False}
+
+ # Sending enabled again gives the reputation metrics a fresh start.
+ sesv2.put_configuration_set_sending_options(ConfigurationSetName=name, SendingEnabled=True)
+ reputation = get()["ReputationOptions"]
+ assert reputation["ReputationMetricsEnabled"] is False
+ assert isinstance(reputation["LastFreshStart"], datetime)
+ assert get()["SendingOptions"] == {"SendingEnabled": True}
+ sesv2.put_configuration_set_sending_options(ConfigurationSetName=name)
+ assert get()["SendingOptions"] == {"SendingEnabled": False}
+
+ sesv2.put_configuration_set_suppression_options(ConfigurationSetName=name, SuppressedReasons=[])
+ assert get()["SuppressionOptions"] == {"SuppressedReasons": []}
+ sesv2.put_configuration_set_suppression_options(ConfigurationSetName=name)
+ assert "SuppressionOptions" not in get()
+ sesv2.put_configuration_set_vdm_options(
+ ConfigurationSetName=name, VdmOptions={"GuardianOptions": {"OptimizedSharedDelivery": "DISABLED"}})
+ assert get()["VdmOptions"] == {"GuardianOptions": {"OptimizedSharedDelivery": "DISABLED"}}
+ sesv2.put_configuration_set_vdm_options(ConfigurationSetName=name)
+ sesv2.put_configuration_set_archiving_options(ConfigurationSetName=name)
+ sesv2.put_configuration_set_tracking_options(ConfigurationSetName=name)
+ assert set(get()) == {"ConfigurationSetName", "ReputationOptions", "SendingOptions", "Tags"}
+
+ assert _sesv2_error(sesv2.put_configuration_set_tracking_options,
+ ConfigurationSetName=name, HttpsPolicy="REQUIRE") == (
+ "BadRequestException", "CustomRedirectDomain must be specified.")
+ missing = f"cs-missing-{_uuid_mod.uuid4().hex[:8]}"
+ for call, kwargs in ((sesv2.get_configuration_set, {}),
+ (sesv2.put_configuration_set_sending_options, {"SendingEnabled": True})):
+ assert _sesv2_error(call, ConfigurationSetName=missing, **kwargs) == (
+ "NotFoundException", f"Configuration set <{missing}> does not exist.")
+ finally:
+ sesv2.delete_configuration_set(ConfigurationSetName=bare)
+ sesv2.delete_configuration_set(ConfigurationSetName=name)
+
+
+def test_ses_v2_configuration_set_event_destinations(sesv2, sns):
+ """Event types are sorted, Enabled defaults to false, an updated destination is replaced and listed last."""
+ name = f"cs-dest-{_uuid_mod.uuid4().hex[:8]}"
+ topic = sns.create_topic(Name=f"{name}-events")["TopicArn"]
+ cloudwatch = {"CloudWatchDestination": {"DimensionConfigurations": [{
+ "DimensionName": "campaign", "DimensionValueSource": "MESSAGE_TAG", "DefaultDimensionValue": "none"}]}}
+ sesv2.create_configuration_set(ConfigurationSetName=name)
+
+ def destinations():
+ out = sesv2.get_configuration_set_event_destinations(ConfigurationSetName=name)
+ out.pop("ResponseMetadata")
+ return out
+
+ def create(dest, **definition):
+ return sesv2.create_configuration_set_event_destination(
+ ConfigurationSetName=name, EventDestinationName=dest, EventDestination=definition)
+
+ try:
+ assert destinations() == {}
+ create("cw", MatchingEventTypes=["SEND", "OPEN", "DELIVERY", "BOUNCE"], **cloudwatch)
+ create("sns", Enabled=True, MatchingEventTypes=["COMPLAINT"], SnsDestination={"TopicArn": topic})
+ assert destinations() == {"EventDestinations": [
+ {"Name": "cw", "Enabled": False, "MatchingEventTypes": ["BOUNCE", "DELIVERY", "OPEN", "SEND"],
+ **cloudwatch},
+ {"Name": "sns", "Enabled": True, "MatchingEventTypes": ["COMPLAINT"],
+ "SnsDestination": {"TopicArn": topic}},
+ ]}
+ assert _sesv2_error(create, dest="cw", MatchingEventTypes=["SEND"], **cloudwatch) == (
+ "AlreadyExistsException",
+ f"An event destination with name <cw> already exists for configuration set <{name}>.")
+
+ sesv2.update_configuration_set_event_destination(
+ ConfigurationSetName=name, EventDestinationName="cw",
+ EventDestination={"Enabled": True, "MatchingEventTypes": ["REJECT"],
+ "SnsDestination": {"TopicArn": topic}})
+ assert [d["Name"] for d in destinations()["EventDestinations"]] == ["sns", "cw"]
+ assert destinations()["EventDestinations"][1] == {
+ "Name": "cw", "Enabled": True, "MatchingEventTypes": ["REJECT"], "SnsDestination": {"TopicArn": topic}}
+
+ refused = [
+ (sesv2.update_configuration_set_event_destination,
+ {"EventDestinationName": "sns", "EventDestination": {"Enabled": False}},
+ ("BadRequestException", "At least one event type must be specified.")),
+ (sesv2.update_configuration_set_event_destination,
+ {"EventDestinationName": "nope", "EventDestination": {"MatchingEventTypes": ["SEND"], **cloudwatch}},
+ ("NotFoundException",
+ f"An event destination with name <nope> does not exist for configuration set <{name}>.")),
+ (sesv2.delete_configuration_set_event_destination, {"EventDestinationName": "nope"},
+ ("NotFoundException",
+ f"An event destination with name <nope> does not exist for configuration set <{name}>.")),
+ (sesv2.create_configuration_set_event_destination,
+ {"EventDestinationName": "low", "EventDestination": {"MatchingEventTypes": ["send"], **cloudwatch}},
+ ("BadRequestException", "The event destination contains an invalid event type.")),
+ (sesv2.create_configuration_set_event_destination,
+ {"EventDestinationName": "none", "EventDestination": {"Enabled": True, **cloudwatch}},
+ ("BadRequestException", "At least one event type must be specified.")),
+ (sesv2.create_configuration_set_event_destination,
+ {"EventDestinationName": "none", "EventDestination": {"MatchingEventTypes": ["SEND"]}},
+ ("BadRequestException", "Event destination is not provided.")),
+ (sesv2.create_configuration_set_event_destination,
+ {"EventDestinationName": "two", "EventDestination": {
+ "MatchingEventTypes": ["SEND"], "SnsDestination": {"TopicArn": topic}, **cloudwatch}},
+ ("BadRequestException", "Please provide only one destination with each request. Either a Firehose "
+ "Destination or a Cloudwatch Destination or an SNS Destination or an EventBridge Destination.")),
+ (sesv2.create_configuration_set_event_destination,
+ {"EventDestinationName": "dim", "EventDestination": {
+ "MatchingEventTypes": ["SEND"], "CloudWatchDestination": {"DimensionConfigurations": [{
+ "DimensionName": "campaign", "DimensionValueSource": "messageTag",
+ "DefaultDimensionValue": "none"}]}}},
+ ("BadRequestException", "invalid CloudWatch dimension source")),
+ (sesv2.create_configuration_set_event_destination,
+ {"EventDestinationName": "bad name!", "EventDestination": {"MatchingEventTypes": ["SEND"], **cloudwatch}},
+ ("BadRequestException", "Invalid event destination name <bad name!>: "
+ "only alphanumeric ASCII characters, '_', and '-' are allowed.")),
+ ]
+ for call, kwargs, expected in refused:
+ assert _sesv2_error(call, ConfigurationSetName=name, **kwargs) == expected
+ assert _sesv2_error(sesv2.get_configuration_set_event_destinations,
+ ConfigurationSetName=f"{name}-missing") == (
+ "NotFoundException", f"Configuration set <{name}-missing> does not exist.")
+
+ sesv2.delete_configuration_set_event_destination(ConfigurationSetName=name, EventDestinationName="sns")
+ assert [d["Name"] for d in destinations()["EventDestinations"]] == ["cw"]
+ sesv2.delete_configuration_set(ConfigurationSetName=name)
+ assert _sesv2_error(sesv2.get_configuration_set_event_destinations, ConfigurationSetName=name)[0] == (
+ "NotFoundException")
+ finally:
+ try:
+ sesv2.delete_configuration_set(ConfigurationSetName=name)
+ except ClientError:
+ pass
+ sns.delete_topic(TopicArn=topic)
+
def test_ses_v2_list_routes_old_and_new(sesv2):
"""SDKs since botocore 1.43.106 list with POST /v2/email/list-identities and
/list-configuration-sets (paging and Filter in the body); older ones GET."""
diff --git a/tests/test_ses_v2.py b/tests/test_ses_v2.py
index 52f53014..43e0daf1 100644
--- a/tests/test_ses_v2.py
+++ b/tests/test_ses_v2.py
@@ -259,6 +259,30 @@ def test_ses_v2_configuration_set_tag_resource_uses_parser_backed_resource_arn(s
]
+def test_ses_v2_configuration_set_options_and_destinations_survive_persistence(ses_v2):
+ from ministack.core.persistence import _json_default, _json_object_hook
+
+ path = "/v2/email/configuration-sets"
+ assert _call(ses_v2, "POST", path, body={
+ "ConfigurationSetName": "persisted", "SendingOptions": {"SendingEnabled": False},
+ "DeliveryOptions": {"TlsPolicy": "REQUIRE"}})[0] == 200
+ assert _call(ses_v2, "PUT", f"{path}/persisted/sending", body={"SendingEnabled": True})[0] == 200
+ destination = {"MatchingEventTypes": ["SEND"], "SnsDestination": {"TopicArn": "arn:aws:sns:x"}}
+ assert _call(ses_v2, "POST", f"{path}/persisted/event-destinations",
+ body={"EventDestinationName": "sns", "EventDestination": destination})[0] == 200
+ before = (_call(ses_v2, "GET", f"{path}/persisted")[1],
+ _call(ses_v2, "GET", f"{path}/persisted/event-destinations")[1])
+ assert "LastFreshStart" in before[0]["ReputationOptions"]
+ assert before[1]["EventDestinations"][0]["Name"] == "sns"
+
+ saved = json.loads(json.dumps(ses_v2.get_state(), default=_json_default), object_hook=_json_object_hook)
+ ses_v2.reset()
+ assert _call(ses_v2, "GET", f"{path}/persisted")[0] == 404
+ ses_v2.load_persisted_state(saved)
+ assert (_call(ses_v2, "GET", f"{path}/persisted")[1],
+ _call(ses_v2, "GET", f"{path}/persisted/event-destinations")[1]) == before
+
+
@pytest.mark.parametrize(
"bad_arn",
[