Skip to content

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

feat(SES): add sandbox mode (#1934)

Nahuel Nucera206f0030f4c3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d2f97950..32d31bf9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **SES — a sandboxed account sends only to verified or simulator recipients** — SES v2 `PutAccountDetails` with `ProductionAccessEnabled=false` puts the account (per region) in the sandbox, as on AWS, and `GetAccount` reports it with the submitted `Details`. A sandboxed send to a recipient that is neither a verified address or domain identity nor a `@simulator.amazonses.com` address fails with `MessageRejected` "Email address is not verified. The following identities failed the check in region …" for v1 `SendEmail`, `SendRawEmail` and `SendTemplatedEmail` and v2 `SendEmail`; bulk sends reject only the affected entries. Accounts stay in production by default. Reported by @skialpine.
+
+### Fixed
+
+- **SES — a send from an unverified sender is rejected** — v1 `SendEmail`, `SendRawEmail`, `SendTemplatedEmail` and `SendBulkTemplatedEmail` and v2 `SendEmail` and `SendBulkEmail` accepted any `Source` / `FromEmailAddress`. AWS requires the sender to be a verified identity in the account and region, in production as well as the sandbox, and now so does MiniStack: the send fails with `MessageRejected` "Email address is not verified. The following identities failed the check in region …". A verified domain covers its addresses and subdomains, domain names compare case-insensitively and email addresses case-sensitively, as AWS documents. Tests that send from an address they never created as an identity need a `VerifyEmailIdentity` / `CreateEmailIdentity` first. Reported by @skialpine.
- **CloudFront — serves distribution traffic, plus the AWS-managed policy catalog and monitoring subscriptions** — MiniStack's CloudFront was control-plane only: a distribution's `DomainName` stored nothing a client could reach. A viewer request to `<label>.cloudfront.net` (or the resolvable `<label>.cloudfront.<MINISTACK_HOST>` form) is now actually served — ordered cache-behavior path-pattern matching, `ViewerProtocolPolicy`/`AllowedMethods`/`DefaultRootObject`, cache-policy and origin-request-policy header/cookie/query-string forwarding (plus legacy `ForwardedValues`), `viewer-request`/`viewer-response` CloudFront Functions (`cloudfront-js-1.0`/`-2.0`, on a shared Node worker pool also used by AppSync resolvers), a response-headers policy's custom/security/CORS headers, an S3 or custom origin fetch (a custom origin is dialed at its own `DomainName`/port exactly as configured, trusting the gateway's own TLS cert alongside system roots under `USE_SSL`; a stacked distribution — an origin that is itself a CloudFront distribution — is refused with a 403 instead of recursing), and CloudFront's own added headers. `X-Forwarded-For` always carries the viewer's chain plus the client IP regardless of forwarding policy, a function event's `viewer.ip` is the real TCP peer, and a header with several values is forwarded to the origin as one comma-joined line (RFC 9110 §5.3). `DomainName` is now the real `d` + 13-character shape, independent of the distribution's Id. `ListCachePolicies`/`ListOriginRequestPolicies`/`ListResponseHeadersPolicies` seed the AWS-managed catalog (7 cache, 8 origin-request, 5 response-headers policies with a published configuration), so the Terraform data sources that resolve them by name (e.g. `Managed-CachingDisabled`) now find them. `CreateMonitoringSubscription`/`GetMonitoringSubscription`/`DeleteMonitoringSubscription` store a distribution's real-time-metrics subscription status. Not modelled: caching itself, WAF, logging, geo/IP restrictions, custom error pages, signed URLs/cookies, Lambda@Edge, CORS preflight responses, and origins addressed by an AWS hostname (ALB, Function URL, execute-api, S3 website endpoints) — refused with a 502 before a socket opens. Contributed by @skialpine (#1852).
### Fixed
- **API Gateway v2 (WebSocket API) — `$connect` authorization** — a `CUSTOM` `$connect` route ran no authorizer. It now runs its REQUEST authorizer, refuses the handshake with 401, 403 or 500 and passes `principalId` and the context to `requestContext.authorizer` of the connection's events. `CreateAuthorizer`, `CreateRoute`, `UpdateRoute` and the CloudFormation resources refuse a JWT authorizer, JWT route authorization and authorization on a route other than `$connect` with `BadRequestException`, as AWS does; a JWT `$connect` route kept in saved state refuses the handshake with 500 instead of validating the token. `requestContext.stage` names the stage in the connection URL instead of `$default`.
diff --git a/README.md b/README.md
index 9af035e5..c8c7ce86 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 | Emails stored in-memory, not sent |
-| **SES v2** | SendEmail, CreateEmailIdentity, GetEmailIdentity, DeleteEmailIdentity, ListEmailIdentities, CreateConfigurationSet, GetConfigurationSet, DeleteConfigurationSet, ListConfigurationSets, CreateEmailTemplate, GetEmailTemplate, UpdateEmailTemplate, DeleteEmailTemplate, ListEmailTemplates, GetAccount, PutAccountSuppressionAttributes, ListSuppressedDestinations, TagResource, UntagResource, ListTagsForResource | REST API (`/v2/email/`); identities auto-verified; emails stored in-memory, not sent; email templates share the v1 store, so `SendEmail` with `Content.Template` renders a template created through either API version |
+| **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; 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 |
| **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/ses.py b/ministack/services/ses.py
index 1e3d2b55..0aee7d98 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -33,6 +33,7 @@ from email import message_from_bytes
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.policy import default as default_policy
+from email.utils import parseaddr
from urllib.parse import parse_qs
from ministack.core.responses import (
@@ -52,6 +53,9 @@ _identities = AccountRegionScopedDict()
_sent_emails = AccountRegionScopedDict()
_templates = AccountRegionScopedDict()
_configuration_sets = AccountRegionScopedDict()
+# SESv2 PutAccountDetails, under "account": ProductionAccessEnabled and the details.
+_account_details = AccountRegionScopedDict()
+_SIMULATOR_DOMAIN = "simulator.amazonses.com"
def _sent_emails_list() -> list:
@@ -71,6 +75,7 @@ def get_state() -> dict:
"_identities": _identities,
"_templates": _templates,
"_configuration_sets": _configuration_sets,
+ "_account_details": _account_details,
})
@@ -84,6 +89,7 @@ def _restore_state(data: dict):
_restore_regional_store(
_configuration_sets, data.get("_configuration_sets", {})
)
+ _restore_regional_store(_account_details, data.get("_account_details", {}))
def _restore_regional_store(store, restored):
@@ -172,6 +178,9 @@ def _send_email(params):
to_addrs = _collect_list(params, "Destination.ToAddresses.member")
cc_addrs = _collect_list(params, "Destination.CcAddresses.member")
bcc_addrs = _collect_list(params, "Destination.BccAddresses.member")
+ rejected = _message_rejection(source, to_addrs + cc_addrs + bcc_addrs)
+ if rejected:
+ return _error("MessageRejected", rejected, 400)
msg_id = _record_send(
source=source,
@@ -250,6 +259,12 @@ def _send_raw_email(params):
msg_id = f"{new_uuid()}@email.amazonses.com"
parsed = _parse_raw_mime(raw_b64)
+ rejected = _message_rejection(
+ source or parsed.get("From", ""),
+ _collect_list(params, "Destinations.member")
+ or [a.strip() for h in ("To", "Cc", "Bcc") for a in parsed.get(h, "").split(",") if a.strip()])
+ if rejected:
+ return _error("MessageRejected", rejected, 400)
# Extract from body parts if available
subject = ""
@@ -316,6 +331,9 @@ def _send_templated_email(params):
if template_name not in _templates:
return _error("TemplateDoesNotExist",
f"Template {template_name} does not exist", 400)
+ rejected = _message_rejection(source, to_addrs + cc_addrs + bcc_addrs)
+ if rejected:
+ return _error("MessageRejected", rejected, 400)
rendered = _render_template(_templates[template_name], template_data)
msg_id = f"{new_uuid()}@email.amazonses.com"
@@ -369,8 +387,16 @@ def _send_bulk_templated_email(params):
destinations.append({"To": to_addrs, "TemplateData": replacement})
i += 1
+ rejected = _message_rejection(source)
+ if rejected:
+ return _error("MessageRejected", rejected, 400)
statuses = []
for dest in destinations:
+ rejected = _message_rejection(None, dest["To"])
+ if rejected:
+ statuses.append(f"<member><Status>MessageRejected</Status>"
+ f"<Error>{_esc(rejected)}</Error></member>")
+ continue
msg_id = f"{new_uuid()}@email.amazonses.com"
rendered = _render_template(template, dest["TemplateData"])
record = {
@@ -689,6 +715,50 @@ def _update_template(params):
# Shared helpers
# ---------------------------------------------------------------------------
+# ---------------------------------------------------------------------------
+# Sandbox (SESv2 PutAccountDetails ProductionAccessEnabled=false)
+# ---------------------------------------------------------------------------
+
+def _production_access_enabled() -> bool:
+ return (_account_details.get("account") or {}).get("ProductionAccessEnabled", True)
+
+
+def _identity_verified(address: str, *, simulator: bool = False) -> bool:
+ """A verified address identity (case-sensitive) or a verified domain identity
+ for the address's domain or any parent domain (case-insensitive), in v1 or v2."""
+ from ministack.services import ses_v2
+
+ addr = parseaddr(address)[1]
+ if not addr:
+ return False
+ domain = addr.rpartition("@")[2].lower()
+ if simulator and domain == _SIMULATOR_DOMAIN:
+ return True
+
+ def ok(v1_rec, v2_rec):
+ return ((v1_rec or {}).get("VerificationStatus") == "Success"
+ or bool((v2_rec or {}).get("VerifiedForSendingStatus")))
+
+ if ok(_identities.get(addr), ses_v2._identities.get(addr)):
+ return True
+ v1 = {k.lower(): r for k, r in _identities.items() if "@" not in k}
+ v2 = {k.lower(): r for k, r in ses_v2._identities.items() if "@" not in k}
+ labels = domain.split(".")
+ return any(ok(v1.get(d), v2.get(d)) for d in (".".join(labels[i:]) for i in range(len(labels) - 1)))
+
+
+def _message_rejection(sender, recipients=()) -> str | None:
+ """The MessageRejected message for an unverified sender, or, in the sandbox,
+ unverified recipients."""
+ failed = [sender] if sender and not _identity_verified(sender) else []
+ if not _production_access_enabled():
+ failed += [r for r in recipients if r and not _identity_verified(r, simulator=True)]
+ if not failed:
+ return None
+ return ("Email address is not verified. The following identities failed the check "
+ f"in region {get_region().upper()}: {', '.join(failed)}")
+
+
def _make_identity(identity, identity_type):
return {
"VerificationStatus": "Success",
@@ -880,3 +950,4 @@ def reset():
_sent_emails.clear()
_templates.clear()
_configuration_sets.clear()
+ _account_details.clear()
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 576816da..4ddb75dc 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -32,8 +32,10 @@ from ministack.core.responses import (
now_iso,
)
from ministack.services.ses import (
+ _account_details,
_build_mime_message,
_dkim_tokens,
+ _message_rejection,
_parse_raw_mime,
_render_template,
_restore_regional_store,
@@ -313,14 +315,33 @@ async def handle_request(method, path, headers, body, query_params):
cutoff = time.time() - 86400
sent_list = _sent_emails_list()
sent_24h = sum(1 for e in sent_list if e["Timestamp"] >= cutoff)
- return json_response({
+ account = _account_details.get("account") or {}
+ out = {
"DedicatedIpAutoWarmupEnabled": False,
"EnforcementStatus": "HEALTHY",
- "ProductionAccessEnabled": True,
+ "ProductionAccessEnabled": account.get("ProductionAccessEnabled", True),
"SendQuota": {"Max24HourSend": 50000.0, "MaxSendRate": 14.0, "SentLast24Hours": float(sent_24h)},
"SendingEnabled": True,
"SuppressionAttributes": {"SuppressedReasons": []},
- })
+ }
+ if account.get("Details"):
+ out["Details"] = account["Details"]
+ return json_response(out)
+
+ # POST /v2/email/account/details (PutAccountDetails)
+ if sub == "/account/details" and method == "POST":
+ if data.get("MailType") not in ("MARKETING", "TRANSACTIONAL"):
+ return _json_err("BadRequestException", "MailType must be MARKETING or TRANSACTIONAL")
+ if not data.get("WebsiteURL"):
+ return _json_err("BadRequestException", "WebsiteURL is required")
+ account = dict(_account_details.get("account") or {})
+ account["Details"] = {k: data[k] for k in (
+ "MailType", "WebsiteURL", "ContactLanguage", "UseCaseDescription",
+ "AdditionalContactEmailAddresses") if k in data}
+ if "ProductionAccessEnabled" in data:
+ account["ProductionAccessEnabled"] = bool(data["ProductionAccessEnabled"])
+ _account_details["account"] = account
+ return json_response({})
# PUT /v2/email/account/suppression
if sub == "/account/suppression" and method == "PUT":
@@ -377,6 +398,9 @@ async def handle_request(method, path, headers, body, query_params):
body_html = rendered.get("Html", "")
all_addrs = to_addrs + cc_addrs + bcc_addrs
+ rejected = _message_rejection(source or (parsed.get("From", "") if raw else ""), all_addrs)
+ if rejected:
+ return _json_err("MessageRejected", rejected)
if source and all_addrs:
mime_str = _build_mime_message(source, to_addrs, cc_addrs, bcc_addrs,
subj, body_text, body_html, msg_id)
@@ -420,6 +444,9 @@ async def handle_request(method, path, headers, body, query_params):
if not entries:
return _json_err("BadRequestException", "BulkEmailEntries is required")
+ rejected = _message_rejection(source)
+ if rejected:
+ return _json_err("MessageRejected", rejected)
results = []
for entry in entries:
dest = entry.get("Destination", {})
@@ -431,6 +458,10 @@ async def handle_request(method, path, headers, body, query_params):
.get("ReplacementTemplate", {})
.get("ReplacementTemplateData", default_data)
)
+ rejected = _message_rejection(None, to_addrs + cc_addrs + bcc_addrs)
+ if rejected:
+ results.append({"Status": "MESSAGE_REJECTED", "Error": rejected})
+ continue
rendered = _render_template(stored, template_data)
subj = rendered.get("Subject", "")
body_text = rendered.get("Text", "")
diff --git a/tests/test_ses.py b/tests/test_ses.py
index 9c9501db..0c9455b6 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -407,7 +407,14 @@ def test_ses_smtp_relay_error_is_logged_not_raised():
# SendEmail with SMTP relay
# ---------------------------------------------------------------------------
+def _verify_example_com(monkeypatch):
+ """Senders must be verified identities, as on AWS."""
+ from ministack.services import ses
+ monkeypatch.setitem(ses._identities, "example.com", ses._make_identity("example.com", "Domain"))
+
+
def test_ses_smtp_relay_send_email(monkeypatch):
+ _verify_example_com(monkeypatch)
monkeypatch.setenv('SMTP_HOST', '127.0.0.1:1025')
from ministack.services.ses import _send_email
mock_smtp = MagicMock()
@@ -433,7 +440,8 @@ def test_ses_smtp_relay_send_email(monkeypatch):
assert msg.get_content_type() == 'multipart/alternative'
-def test_ses_smtp_relay_send_email_no_relay_without_host():
+def test_ses_smtp_relay_send_email_no_relay_without_host(monkeypatch):
+ _verify_example_com(monkeypatch)
from ministack.services.ses import _send_email
with patch('ministack.services.ses.smtplib.SMTP') as mock_cls:
params = {
@@ -452,6 +460,7 @@ def test_ses_smtp_relay_send_email_no_relay_without_host():
# ---------------------------------------------------------------------------
def test_ses_smtp_relay_send_raw_email(monkeypatch):
+ _verify_example_com(monkeypatch)
monkeypatch.setenv('SMTP_HOST', 'localhost:2525')
from ministack.services.ses import _send_raw_email
mock_smtp = MagicMock()
@@ -483,6 +492,7 @@ def test_ses_smtp_relay_send_raw_email(monkeypatch):
# ---------------------------------------------------------------------------
def test_ses_smtp_relay_send_templated_email(monkeypatch):
+ _verify_example_com(monkeypatch)
monkeypatch.setenv('SMTP_HOST', 'localhost:1025')
from ministack.services.ses import _send_templated_email, _templates
_templates['MyTemplate'] = {
@@ -793,6 +803,7 @@ def test_ses_resources_and_send_statistics_are_region_scoped():
east_before = east.get_send_quota()["SentLast24Hours"]
west_before = west.get_send_quota()["SentLast24Hours"]
for client, label in ((east, "east"), (west, "west")):
+ client.verify_email_identity(EmailAddress=f"{label}-{identity}")
client.send_email(
Source=f"{label}-{identity}",
Destination={"ToAddresses": ["[email protected]"]},
@@ -965,3 +976,94 @@ def test_ses_v2_restore_legacy_state_maps_unregionalized_values_to_boot_region()
assert store.get_scoped(account_id, foreign_region, resource_key) is None
finally:
service.reset()
+
+
+def _ses_clients(region):
+ import boto3
+ from botocore.config import Config
+
+ kw = dict(endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ aws_access_key_id="test", aws_secret_access_key="test", region_name=region,
+ config=Config(retries={"mode": "standard"}))
+ return boto3.client("ses", **kw), boto3.client("sesv2", **kw)
+
+
+def test_ses_sandbox_account_only_sends_to_verified_or_simulator_recipients():
+ # Account state is per region; a region of its own keeps other tests in production.
+ v1, v2 = _ses_clients("ap-southeast-4")
+ s = _uuid_mod.uuid4().hex[:8]
+ sender, verified = f"sender-{s}.example.com", f"ok-{s}@example.com"
+ v2.create_email_identity(EmailIdentity=sender)
+ v2.create_email_identity(EmailIdentity=verified)
+ assert v2.get_account()["ProductionAccessEnabled"] is True
+ content = {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
+ try:
+ v2.put_account_details(MailType="TRANSACTIONAL", WebsiteURL="https://example.com",
+ ProductionAccessEnabled=False)
+ account = v2.get_account()
+ assert account["ProductionAccessEnabled"] is False
+ assert account["Details"]["MailType"] == "TRANSACTIONAL"
+
+ def v2_send(to):
+ return v2.send_email(FromEmailAddress=f"app@{sender}",
+ Destination={"ToAddresses": [to]}, Content=content)
+
+ v2_send(verified)
+ v2_send("[email protected]")
+ unverified = f"nobody-{s}@unverified.example.invalid"
+ message = ("Email address is not verified. The following identities failed the check "
+ f"in region AP-SOUTHEAST-4: {unverified}")
+ with pytest.raises(ClientError) as exc:
+ v2_send(unverified)
+ assert exc.value.response["Error"]["Code"] == "MessageRejected"
+ assert exc.value.response["Error"]["Message"] == message
+ with pytest.raises(ClientError) as exc:
+ v1.send_email(Source=f"app@{sender}", Destination={"ToAddresses": [unverified]},
+ Message={"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}})
+ assert exc.value.response["Error"]["Code"] == "MessageRejected"
+
+ tpl = f"tpl-{s}"
+ v2.create_email_template(TemplateName=tpl, TemplateContent={"Subject": "s", "Text": "b"})
+ results = v2.send_bulk_email(
+ FromEmailAddress=f"app@{sender}",
+ DefaultContent={"Template": {"TemplateName": tpl, "TemplateData": "{}"}},
+ BulkEmailEntries=[{"Destination": {"ToAddresses": [verified]}},
+ {"Destination": {"ToAddresses": [unverified]}}])["BulkEmailEntryResults"]
+ assert [r["Status"] for r in results] == ["SUCCESS", "MESSAGE_REJECTED"]
+ assert results[1]["Error"] == message
+
+ v2.put_account_details(MailType="TRANSACTIONAL", WebsiteURL="https://example.com",
+ ProductionAccessEnabled=True)
+ v2_send(unverified)
+ finally:
+ v2.put_account_details(MailType="TRANSACTIONAL", WebsiteURL="https://example.com",
+ ProductionAccessEnabled=True)
+
+
+def test_ses_send_from_an_unverified_sender_is_rejected():
+ v1, v2 = _ses_clients("ap-southeast-5")
+ s = _uuid_mod.uuid4().hex[:8]
+ domain, address = f"verified-{s}.example.com", f"Person-{s}@other.example.org"
+ v2.create_email_identity(EmailIdentity=domain)
+ v1.verify_email_identity(EmailAddress=address)
+ content = {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
+
+ def send(sender):
+ return v2.send_email(FromEmailAddress=sender, Destination={"ToAddresses": ["[email protected]"]},
+ Content=content)
+
+ send(f"app@{domain}")
+ send(f"app@mail.{domain}") # a verified domain covers its subdomains
+ send(address)
+ unverified = f"person-{s}@other.example.org" # address identities are case-sensitive
+ for sender in (unverified, f"app@unverified-{s}.example.invalid"):
+ with pytest.raises(ClientError) as exc:
+ send(sender)
+ assert exc.value.response["Error"]["Code"] == "MessageRejected"
+ assert exc.value.response["Error"]["Message"] == (
+ "Email address is not verified. The following identities failed the check "
+ f"in region AP-SOUTHEAST-5: {sender}")
+ with pytest.raises(ClientError) as exc:
+ v1.send_email(Source=unverified, Destination={"ToAddresses": ["[email protected]"]},
+ Message={"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}})
+ assert exc.value.response["Error"]["Code"] == "MessageRejected"
diff --git a/tests/test_ses_v2.py b/tests/test_ses_v2.py
index 83e8d512..93581f5b 100644
--- a/tests/test_ses_v2.py
+++ b/tests/test_ses_v2.py
@@ -26,6 +26,12 @@ def _reset(service):
service._sent_emails_list().clear()
+def _verify(service, identity="example.com"):
+ """Senders must be verified identities, as on AWS."""
+ status, _ = _call(service, "POST", "/v2/email/identities", body={"EmailIdentity": identity})
+ assert status == 200
+
+
def _arn(kind, name, *, partition="aws", service="ses", region=REGION, account=ACCOUNT_ID):
return f"arn:{partition}:{service}:{region}:{account}:{kind}/{name}"
@@ -75,6 +81,7 @@ def test_ses_v2_target_delegates_to_ses_v2_handler(monkeypatch):
@pytest.mark.parametrize("suffix", ["", "/"])
@pytest.mark.parametrize("bulk", [False, True])
def test_ses_target_send_uses_real_v2_handler(ses_v2, prefix, suffix, bulk):
+ _verify(ses_v2)
from ministack.services import ses
template = {"TemplateContent": {"Subject": "Hello {{name}}", "Text": "Welcome"},
@@ -479,6 +486,7 @@ def test_ses_v2_email_template_apis_reject_missing_templates(ses_v2, method, bod
def test_ses_v2_send_email_renders_stored_templates(ses_v2):
+ _verify(ses_v2)
_call(
ses_v2,
"POST",
@@ -513,6 +521,7 @@ def test_ses_v2_send_email_renders_stored_templates(ses_v2):
def test_ses_v2_send_email_resolves_template_arns(ses_v2):
+ _verify(ses_v2)
_call(
ses_v2,
"POST",
@@ -531,6 +540,7 @@ def test_ses_v2_send_email_resolves_template_arns(ses_v2):
def test_ses_v2_send_email_renders_inline_template_content_without_storing_it(ses_v2):
+ _verify(ses_v2)
status, _body = _send_template(
ses_v2,
{"TemplateContent": {"Subject": "Inline {{v}}", "Text": "Body {{v}}"}},
@@ -626,6 +636,7 @@ def _bulk_entry(to, **replacement):
def test_ses_v2_send_bulk_email_via_app_router_with_inline_template(ses_v2):
+ _verify(ses_v2)
status, body = asyncio.run(
_post_via_app(
"/v2/email/outbound-bulk-emails",
@@ -654,6 +665,7 @@ def test_ses_v2_send_bulk_email_via_app_router_with_inline_template(ses_v2):
def test_ses_v2_send_bulk_email_via_app_router_with_stored_template(ses_v2):
+ _verify(ses_v2)
_call(
ses_v2,
"POST",