Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(ses): publish identity notifications to SNS on send (#2041)
kjdevd15b6b1613c2
diff --git a/ministack/services/ses.py b/ministack/services/ses.pyindex 246608c6..4c07478a 100644--- a/ministack/services/ses.py+++ b/ministack/services/ses.py@@ -45,6 +45,7 @@ from ministack.core.concurrency import spawn_backgroundfrom ministack.core.responses import (AccountRegionScopedDict,AccountScopedDict,+ get_account_id,get_region,new_uuid,)@@ -538,6 +539,7 @@ def _record_send(source, to_addrs, cc_addrs=None, bcc_addrs=None,mime_str = _build_mime_message(source, to_addrs, cc_addrs, bcc_addrs,subject, body_text, body_html, msg_id)_smtp_relay(source, all_addrs, mime_str)+ _send_notifications(msg_id, source, all_addrs)return msg_id@@ -620,6 +622,7 @@ def _send_raw_email(params):_smtp_relay(actual_source, relay_addrs, raw_str)except Exception:logger.warning('SMTP relay failed for SendRawEmail: %s', msg_id, exc_info=True)+ _send_notifications(msg_id, actual_source, relay_addrs)return _xml(200, "SendRawEmailResponse",f"<SendRawEmailResult><MessageId>{msg_id}</MessageId></SendRawEmailResult>")@@ -668,6 +671,7 @@ def _send_templated_email(params):rendered.get("Text", ""),rendered.get("Html", ""), msg_id)_smtp_relay(source, all_addrs, mime_str)+ _send_notifications(msg_id, source, all_addrs)return _xml(200, "SendTemplatedEmailResponse",f"<SendTemplatedEmailResult><MessageId>{msg_id}</MessageId></SendTemplatedEmailResult>")@@ -724,6 +728,7 @@ def _send_bulk_templated_email(params):rendered.get("Text", ""),rendered.get("Html", ""), msg_id)_smtp_relay(source, dest["To"], mime_str)+ _send_notifications(msg_id, source, dest["To"])statuses.append(f"<member><Status>Success</Status>"f"<MessageId>{msg_id}</MessageId></member>")@@ -1029,6 +1034,12 @@ def _production_access_enabled() -> bool:return (_account_details.get("account") or {}).get("ProductionAccessEnabled", True)+def _domain_and_parents(domain: str):+ """`a.b.com` -> `a.b.com`, `b.com` (the bare TLD is never an identity)."""+ labels = domain.split(".")+ return (".".join(labels[i:]) for i in range(len(labels) - 1))++def _identity_verified(address: str, *, simulator: bool = False) -> bool:"""A verified address identity (case-sensitive) or a verified domain identityfor the address's domain or any parent domain (case-insensitive), in v1 or v2."""@@ -1049,8 +1060,7 @@ def _identity_verified(address: str, *, simulator: bool = False) -> bool:return Truev1 = {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)))+ return any(ok(v1.get(d), v2.get(d)) for d in _domain_and_parents(domain))def _message_rejection(sender, recipients=()) -> str | None:@@ -1065,6 +1075,93 @@ def _message_rejection(sender, recipients=()) -> str | None:f"in region {get_region().upper()}: {', '.join(failed)}")+# Mailbox simulator: local part -> notification type. success@ and ooto@ are+# delivered; bounce@ is a hard bounce; complaint@ is reported as spam.+_SIMULATOR_OUTCOMES = {"bounce": "Bounce", "complaint": "Complaint"}+++def _notification_identity(source: str) -> dict | None:+ """The identity whose notification topics apply to a sender: the address+ identity if verified, else the nearest verified parent domain."""+ addr = parseaddr(source or "")[1]+ if not addr:+ return None+ if addr in _identities:+ return _identities[addr]+ domains = {k.lower(): r for k, r in _identities.items() if "@" not in k}+ for d in _domain_and_parents(addr.rpartition("@")[2].lower()):+ rec = domains.get(d)+ if rec is not None:+ return rec+ return None+++def _publish_notification(topic_arn: str, payload: dict) -> None:+ from ministack.services import sns++ try:+ sns.publish_internal(topic_arn, json.dumps(payload),+ "Amazon SES Email Event Notification")+ except Exception:+ logger.warning("SES notification publish to %s failed", topic_arn, exc_info=True)+++def _notification_detail(kind: str, rcpt: str, ts: str) -> dict:+ if kind == "Delivery":+ return {"delivery": {+ "timestamp": ts, "processingTimeMillis": 0, "recipients": [rcpt],+ "smtpResponse": "250 2.6.0 Message received",+ "reportingMTA": "a0-0.smtp-out.amazonses.com"}}+ if kind == "Bounce":+ return {"bounce": {+ "bounceType": "Permanent", "bounceSubType": "General",+ "bouncedRecipients": [{+ "emailAddress": rcpt, "action": "failed", "status": "5.1.1",+ "diagnosticCode": "smtp; 550 5.1.1 user unknown"}],+ "timestamp": ts, "feedbackId": new_uuid(),+ "reportingMTA": "dsn; a0-0.smtp-out.amazonses.com"}}+ return {"complaint": {+ "complainedRecipients": [{"emailAddress": rcpt}],+ "timestamp": ts, "feedbackId": new_uuid(),+ "userAgent": "Amazon SES Mailbox Simulator",+ "complaintFeedbackType": "abuse", "arrivalDate": ts}}+++def _send_notifications(msg_id, source, recipients):+ """Publish the Delivery / Bounce / Complaint notification of each recipient+ to the SNS topic set on the sender's identity (SetIdentityNotificationTopic)."""+ identity = _notification_identity(source)+ if not identity:+ return+ topics = identity.get("NotificationTopics", {})+ if not any(topics.values()):+ return+ recipients = [a for a in (parseaddr(r)[1] for r in recipients) if a]+ now = datetime.now(timezone.utc)+ ts = now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"+ mail = {+ "timestamp": ts,+ "source": source,+ "sendingAccountId": get_account_id(),+ "messageId": msg_id,+ "destination": recipients,+ }+ src_addr = parseaddr(source or "")[1]+ if src_addr:+ mail["sourceArn"] = (f"arn:aws:ses:{get_region()}:{get_account_id()}:"+ f"identity/{src_addr}")+ for rcpt in recipients:+ local, _, domain = rcpt.partition("@")+ kind = "Delivery"+ if domain.lower() == _SIMULATOR_DOMAIN:+ kind = _SIMULATOR_OUTCOMES.get(local.lower().split("+")[0], "Delivery")+ topic = topics.get(kind)+ if not topic:+ continue+ detail = _notification_detail(kind, rcpt, ts)+ _publish_notification(topic, {"notificationType": kind, "mail": mail, **detail})++def _make_identity(identity, identity_type):return {"VerificationStatus": "Success",diff --git a/tests/test_ses.py b/tests/test_ses.pyindex 69594c9f..6f7b4f9b 100644--- a/tests/test_ses.py+++ b/tests/test_ses.py@@ -1091,3 +1091,141 @@ def test_ses_send_from_an_unverified_sender_is_rejected():v1.send_email(Source=unverified, Destination={"ToAddresses": ["[email protected]"]},Message={"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}})assert exc.value.response["Error"]["Code"] == "MessageRejected"+++def ses_notify_queue(ses, sns, sqs):+ """An SNS topic subscribed by an SQS queue, plus a `drain(n)` collector of the+ notifications received so far."""+ from conftest import sqs_policy_allow_sns++ suffix = _uuid_mod.uuid4().hex[:8]+ topic_arn = sns.create_topic(Name=f"ses-notify-{suffix}")["TopicArn"]+ queue_url = sqs.create_queue(QueueName=f"ses-notify-{suffix}")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ sqs.set_queue_attributes(QueueUrl=queue_url, Attributes={+ "Policy": json.dumps(sqs_policy_allow_sns(queue_arn, topic_arn))})+ sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)+ identities = []++ def bind(identity):+ identities.append(identity)+ for kind in ("Delivery", "Bounce", "Complaint"):+ ses.set_identity_notification_topic(+ Identity=identity, NotificationType=kind, SnsTopic=topic_arn)++ def drain(expected):+ got = []+ for _ in range(10):+ for m in sqs.receive_message(+ QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=1).get("Messages", []):+ env = json.loads(m["Body"])+ assert env["Type"] == "Notification"+ got.append(json.loads(env["Message"]))+ if len(got) >= expected:+ break+ return got++ yield suffix, bind, drain+ for identity in identities:+ ses.delete_identity(Identity=identity)+ sqs.delete_queue(QueueUrl=queue_url)+ sns.delete_topic(TopicArn=topic_arn)+++_NOTIFY_MSG = {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}+++def test_ses_identity_notifications_published_to_sns_sqs(ses, ses_notify_queue):+ suffix, bind, drain = ses_notify_queue+ sender = f"notify-{suffix}@example.com"+ ses.verify_email_identity(EmailAddress=sender)+ bind(sender)++ dest = ["[email protected]", "[email protected]",+ "[email protected]"]+ msg_id = ses.send_email(+ Source=sender, Destination={"ToAddresses": dest}, Message=_NOTIFY_MSG,+ )["MessageId"]++ got = {n["notificationType"]: n for n in drain(3)}+ assert set(got) == {"Delivery", "Bounce", "Complaint"}+ assert got["Delivery"]["mail"]["messageId"] == msg_id+ assert got["Delivery"]["mail"]["source"] == sender+ assert got["Delivery"]["mail"]["destination"] == dest+ assert got["Delivery"]["delivery"]["recipients"] == ["[email protected]"]+ assert got["Bounce"]["bounce"]["bouncedRecipients"][0]["emailAddress"] == dest[1]+ assert got["Complaint"]["complaint"]["complainedRecipients"][0]["emailAddress"] == dest[2]+++def test_ses_identity_notifications_fall_back_to_domain_identity(ses, ses_notify_queue):+ suffix, bind, drain = ses_notify_queue+ domain = f"notify-{suffix}.example.com"+ ses.verify_domain_identity(Domain=domain)+ bind(domain)++ msg_id = ses.send_email(+ Source=f"anyone@sub.{domain}", Destination={"ToAddresses": ["[email protected]"]},+ Message=_NOTIFY_MSG,+ )["MessageId"]++ got = drain(1)+ assert [n["mail"]["messageId"] for n in got if n["notificationType"] == "Delivery"] == [msg_id]+++def test_ses_identity_notifications_simulator_subaddress(ses, ses_notify_queue):+ suffix, bind, drain = ses_notify_queue+ sender = f"notify-{suffix}@example.com"+ ses.verify_email_identity(EmailAddress=sender)+ bind(sender)++ ses.send_email(+ Source=sender, Destination={"ToAddresses": ["[email protected]"]},+ Message=_NOTIFY_MSG,+ )++ got = drain(1)+ assert [n["notificationType"] for n in got] == ["Bounce"]+++def test_ses_identity_notifications_other_send_paths(ses, ses_notify_queue):+ suffix, bind, drain = ses_notify_queue+ sender = f"notify-{suffix}@example.com"+ ses.verify_email_identity(EmailAddress=sender)+ bind(sender)+ tpl = f"notify-tpl-{suffix}"+ ses.create_template(Template={"TemplateName": tpl, "SubjectPart": "s", "TextPart": "t"})+ raw = f"From: {sender}\r\nTo: [email protected]\r\nSubject: s\r\n\r\nb"+ try:+ ids = {+ ses.send_raw_email(RawMessage={"Data": raw})["MessageId"],+ ses.send_templated_email(+ Source=sender, Destination={"ToAddresses": ["[email protected]"]},+ Template=tpl, TemplateData="{}")["MessageId"],+ }+ bulk = ses.send_bulk_templated_email(+ Source=sender, Template=tpl, DefaultTemplateData="{}",+ Destinations=[{"Destination": {"ToAddresses": ["[email protected]"]}}],+ )+ ids.update(s["MessageId"] for s in bulk["Status"])++ got = drain(len(ids))+ assert {n["mail"]["messageId"] for n in got} == ids+ assert {n["notificationType"] for n in got} == {"Delivery"}+ finally:+ ses.delete_template(TemplateName=tpl)+++def test_ses_identity_notifications_not_published_without_topic(ses, sns, ses_notify_queue):+ suffix, bind, drain = ses_notify_queue+ sender = f"notify-{suffix}@example.com"+ ses.verify_email_identity(EmailAddress=sender)+ bind(sender)+ for kind in ("Delivery", "Bounce", "Complaint"):+ ses.set_identity_notification_topic(Identity=sender, NotificationType=kind)++ ses.send_email(+ Source=sender, Destination={"ToAddresses": ["[email protected]"]}, Message=_NOTIFY_MSG)++ assert drain(1) == []