:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): email admins on AWS SES tenant reputation changes (#78182)
Daniel Marchuka5603d0b5eb6
diff --git a/posthog/settings/ses.py b/posthog/settings/ses.pyindex 6d3f3e34da2c..659ff307e428 100644--- a/posthog/settings/ses.py+++ b/posthog/settings/ses.py@@ -26,3 +26,10 @@ SES_TENANT_CONFIGURATION_SETS: list[str] = [for cs in os.getenv("SES_TENANT_CONFIGURATION_SETS", "posthog-messaging,posthog-messaging-untracked").split(",")if cs.strip()]++# SNS topics allowed to deliver SES tenant reputation events (EventBridge -> SNS -> webhook).+# Empty (the default) leaves the webhook inert: the SNS signature proves a message came from AWS,+# but only the allowlist proves it came from *our* topic.+WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS: list[str] = [+ arn.strip() for arn in os.getenv("WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS", "").split(",") if arn.strip()+]diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 21fc95e4b479..42ac4099eb45 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -690,6 +690,44 @@ def send_email_sending_suspended(team_id: int, reason: str, suspended_at: str) -message.send()+@shared_task(**EMAIL_TASK_KWARGS)+@with_team_scope()+def send_email_sending_reputation_finding(+ team_id: int, impact: str, found_at: str, findings: list[dict[str, str]] | None = None+) -> None:+ """+ Warn a team's admins that our email provider raised reputation findings against their+ project's sending. LOW impact is a fix-this warning; HIGH impact means sending can be+ paused automatically. Not gated by notification settings — inaction escalates to a pause.+ """+ if not is_email_available(with_absolute_urls=True):+ return+ team = Team.objects.get(id=team_id)+ memberships_to_email = _get_project_admins_to_notify_of_email_sending_suspension(team)+ if not memberships_to_email:+ return+ high_impact = impact == "HIGH"+ subject = (+ f"[Action required] Email sending for project '{team}' is at risk of being paused"+ if high_impact+ else f"Reputation warning for email sending in project '{team}'"+ )+ message = EmailMessage(+ campaign_key=f"email_sending_reputation_finding_{team_id}_{impact}_{found_at}",+ subject=subject,+ template_name="email_sending_reputation_finding",+ template_context={+ "team": team,+ "high_impact": high_impact,+ "findings": findings or [],+ "reputation_path": f"/project/{team.id}/workflows/reputation",+ },+ )+ for membership in memberships_to_email:+ message.add_user_recipient(membership.user)+ message.send()++@shared_task(**EMAIL_TASK_KWARGS)@with_team_scope()def send_email_sending_unsuspended(team_id: int, unsuspended_at: str) -> None:diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex af5151356fc1..7ba7baaac9bd 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -126,6 +126,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (report_stuck_heatmap_screenshots,)from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation+from products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_statesTWENTY_FOUR_HOURS = 24 * 60 * 60@@ -246,6 +247,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="team metadata expiry tracking cleanup",)+ # SES tenant reputation reconciliation - daily at 6:30 AM UTC. EventBridge events are the+ # real-time path; this sweep catches missed deliveries. Sequential SES API calls per team+ # with an SES email integration, so kept daily to stay well inside SES API rate limits.+ sender.add_periodic_task(+ crontab(hour="6", minute="30"),+ reconcile_ses_tenant_states.s(),+ name="ses tenant reputation reconciliation",+ )+# LLM gateway policy cache sync - hourly at :05 to stagger from team_metadata at :00sender.add_periodic_task(crontab(hour="*", minute="5"),diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 175f51fa9b02..a37ec2b010b5 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -33,6 +33,7 @@'posthog.tasks.email.send_conversation_restore_email','posthog.tasks.email.send_discussions_mentioned','posthog.tasks.email.send_email_change_emails',+ 'posthog.tasks.email.send_email_sending_reputation_finding','posthog.tasks.email.send_email_sending_suspended','posthog.tasks.email.send_email_sending_unsuspended','posthog.tasks.email.send_email_verification',diff --git a/posthog/templates/email/email_sending_reputation_finding.html b/posthog/templates/email/email_sending_reputation_finding.htmlnew file mode 100644index 000000000000..de2dd2b29038--- /dev/null+++ b/posthog/templates/email/email_sending_reputation_finding.html@@ -0,0 +1,46 @@+{% extends "email/base.html" %} {% load posthog_assets %}+{% block heading %}{% if high_impact %}Email sending is at risk of being paused{% else %}Reputation warning for your email sending{% endif %}{% endblock %}+{% block section %}+<!-- prettier-ignore -->+<p>+ Our email provider has raised {% if high_impact %}<b>high-impact</b>{% else %}low-impact{% endif %} reputation findings against workflow email sending in project <b>{{ team }}</b>.+</p>+{% if high_impact %}+<p>+ At this level, email sending for your project can be <b>paused automatically</b> to protect deliverability. Fix the findings below to avoid an interruption.+</p>+{% else %}+<p>+ Sending still works, but if these findings are not fixed they can escalate and email sending for your project can be paused.+</p>+{% endif %}+{% if findings %}+<p><b>What the provider flagged</b></p>+<ul>+ {% for finding in findings %}+ <li>{{ finding.description }}</li>+ {% endfor %}+</ul>+{% endif %}+<p>+ Common fixes: remove old or purchased addresses from your lists, and stop sending to recipients who never engage. The Reputation tab shows which workflows have the highest bounce and spam complaint rates.+</p>+<div class="mb mt text-center">+ <a class="button" href="{% absolute_uri reputation_path %}">View sending health</a>+</div>+<div class="mt">+ <p>+ If the button above doesn't work, paste this link into your browser:<br />+ <a href="{% absolute_uri reputation_path %}">{% absolute_uri reputation_path %}</a>+ </p>+</div>+{% endblock %}++{% block footer %}+Need help?+<a href="https://posthog.com/questions?{{ utm_tags }}"+ target="_blank"><b>Contact support</b></a>+or+<a href="https://posthog.com/docs?{{ utm_tags }}"+ target="_blank"><b>read our documentation</b></a>.+{% endblock %}diff --git a/posthog/urls.py b/posthog/urls.pyindex 97c8f7c86d02..9f5d4b88c2b2 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -84,6 +84,7 @@ from products.user_interviews.backend.presentation.webhooks import ()from products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSetfrom products.workflows.backend.api import hog_flow, hog_flow_template+from products.workflows.backend.api.ses_events_webhook import ses_tenant_events_webhookfrom .utils import opt_slash_path, render_templatefrom .views import (@@ -697,6 +698,8 @@ urlpatterns = [opt_slash_path("webhooks/github", github_webhook),# Stamphog runs as its own GitHub App with a dedicated inbound endpoint (not the fan-out above)opt_slash_path("webhooks/stamphog/github", stamphog_github_webhook),+ # AWS SES tenant reputation events (EventBridge -> SNS HTTPS subscription)+ opt_slash_path("webhooks/workflows/ses-events", ses_tenant_events_webhook),# Message preferencespath("messaging-preferences/<str:token>/", preferences_page, name="message_preferences"),opt_slash_path("messaging-preferences/update", update_preferences, name="message_preferences_update"),diff --git a/products/workflows/backend/api/ses_events_webhook.py b/products/workflows/backend/api/ses_events_webhook.pynew file mode 100644index 000000000000..92ba3b0a6ccf--- /dev/null+++ b/products/workflows/backend/api/ses_events_webhook.py@@ -0,0 +1,109 @@+"""+Inbound webhook for AWS SES tenant reputation events, delivered via EventBridge → SNS HTTPS+subscription. Events are treated as change signals only — the handler never trusts the payload's+state; it enqueues a sync that reads the authoritative tenant state from the SES API. That makes+duplicate, reordered, or partially-shaped events harmless.++Authentication is the SNS message signature (proves "from AWS") plus a topic-ARN allowlist+(proves "from our topic"). AWS-side wiring: an EventBridge rule on `source = aws.ses` for the+tenant detail-types, targeting an SNS topic with an HTTPS subscription to this endpoint.+"""++import re+import json+from typing import Any++from django.conf import settings+from django.http import HttpRequest, HttpResponse+from django.views.decorators.csrf import csrf_exempt++import requests+import structlog++from products.workflows.backend.services.sns_verification import is_valid_sns_url, verify_sns_message+from products.workflows.backend.tasks.ses_tenant_state import sync_ses_tenant_state_task++logger = structlog.get_logger(__name__)++_TENANT_TEAM_RE = re.compile(r"\bteam-(\d+)\b")+++def _extract_team_id(event: dict[str, Any]) -> int | None:+ """Pull the `team-<id>` tenant name out of an EventBridge event, wherever AWS put it."""+ detail = event.get("detail") or {}+ candidates: list[Any] = [+ detail.get("tenantName"),+ detail.get("tenant-name"),+ detail.get("reputationEntityReference"),+ ]+ resources = event.get("resources")+ if isinstance(resources, list):+ candidates.extend(resources)+ for candidate in candidates:+ if isinstance(candidate, str) and (match := _TENANT_TEAM_RE.search(candidate)):+ return int(match.group(1))+ return None+++@csrf_exempt+def ses_tenant_events_webhook(request: HttpRequest) -> HttpResponse:+ """Verify an SNS delivery and enqueue a tenant-state sync for the affected team."""+ if request.method != "POST":+ return HttpResponse(status=405)++ allowed_topics = {arn for arn in settings.WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS if arn}+ if not allowed_topics:+ # Unconfigured means the endpoint doesn't exist yet as far as callers are concerned. 404+ # rather than 500 so that probes of a public URL can't flood error logs, and warning+ # rather than error for the same reason.+ logger.warning("ses_tenant_events_webhook_not_configured")+ return HttpResponse("Not found", status=404)++ try:+ # RecursionError: deeply nested JSON from an unauthenticated caller must 400, not 500.+ message = json.loads(request.body)+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):+ return HttpResponse("Invalid payload", status=400)+ if not isinstance(message, dict):+ return HttpResponse("Invalid payload", status=400)++ if message.get("TopicArn") not in allowed_topics:+ logger.warning("ses_tenant_events_webhook_unknown_topic", topic=message.get("TopicArn"))+ return HttpResponse("Unknown topic", status=403)+ if not verify_sns_message(message):+ logger.warning("ses_tenant_events_webhook_invalid_signature", message_id=message.get("MessageId"))+ return HttpResponse("Invalid signature", status=403)++ message_type = message.get("Type")+ if message_type == "SubscriptionConfirmation":+ subscribe_url = message.get("SubscribeURL")+ if not isinstance(subscribe_url, str) or not is_valid_sns_url(subscribe_url):+ return HttpResponse("Invalid subscribe URL", status=400)+ try:+ requests.get(subscribe_url, timeout=5).raise_for_status()+ except requests.RequestException:+ # Non-2xx makes SNS retry the confirmation later.+ logger.exception("ses_tenant_events_webhook_subscription_confirm_failed", topic=message.get("TopicArn"))+ return HttpResponse("Subscription confirmation failed", status=502)+ logger.info("ses_tenant_events_webhook_subscription_confirmed", topic=message.get("TopicArn"))+ return HttpResponse(status=200)++ if message_type != "Notification":+ # UnsubscribeConfirmation and anything unknown: ack so SNS stops retrying.+ return HttpResponse(status=200)++ try:+ event = json.loads(message.get("Message", ""))+ except (json.JSONDecodeError, TypeError):+ return HttpResponse(status=200)+ if not isinstance(event, dict) or event.get("source") != "aws.ses":+ return HttpResponse(status=200)++ team_id = _extract_team_id(event)+ if team_id is None:+ logger.warning("ses_tenant_events_webhook_no_tenant", detail_type=event.get("detail-type"))+ return HttpResponse(status=200)++ # Ack fast; the sync fetches authoritative state and sends any transition emails.+ sync_ses_tenant_state_task.delay(team_id)+ return HttpResponse(status=202)diff --git a/products/workflows/backend/migrations/0018_teamworkflowsconfig_ses_tenant_state.py b/products/workflows/backend/migrations/0018_teamworkflowsconfig_ses_tenant_state.pynew file mode 100644index 000000000000..112599a33795--- /dev/null+++ b/products/workflows/backend/migrations/0018_teamworkflowsconfig_ses_tenant_state.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.14 on 2026-07-30 08:27++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("workflows", "0017_drop_emailreputationsnapshot_table"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="ses_tenant_reputation_impact",+ field=models.CharField(blank=True, db_default="", default="", max_length=32),+ ),+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="ses_tenant_sending_status",+ field=models.CharField(blank=True, db_default="", default="", max_length=32),+ ),+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="ses_tenant_state_synced_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txtindex 862851e8e8bd..e31fa678ee93 100644--- a/products/workflows/backend/migrations/max_migration.txt+++ b/products/workflows/backend/migrations/max_migration.txt@@ -1 +1 @@-0017_drop_emailreputationsnapshot_table+0018_teamworkflowsconfig_ses_tenant_statediff --git a/products/workflows/backend/models/team_workflows_config.py b/products/workflows/backend/models/team_workflows_config.pyindex e13c994ae0ea..c273b3fedb99 100644--- a/products/workflows/backend/models/team_workflows_config.py+++ b/products/workflows/backend/models/team_workflows_config.py@@ -35,5 +35,16 @@ class TeamWorkflowsConfig(models.Model):email_sending_suspended_at = models.DateTimeField(null=True, blank=True)email_sending_suspension_reason = models.TextField(blank=True, default="")+ # Last-known state of the team's AWS SES tenant, mirrored so state *changes* can trigger+ # customer emails exactly once (EventBridge events are best-effort; a periodic sweep+ # reconciles). Empty string = never synced; the first sync only notifies a tenant that is+ # already paused or already carries high-impact findings.+ # Both fields mirror AWS enums verbatim, so they're sized well past today's longest value+ # ("REINSTATED", "NONE") — a new level must not start failing writes.+ # db_default so raw INSERTs from non-Django writers keep working.+ ses_tenant_sending_status = models.CharField(max_length=32, blank=True, default="", db_default="")+ ses_tenant_reputation_impact = models.CharField(max_length=32, blank=True, default="", db_default="")+ ses_tenant_state_synced_at = models.DateTimeField(null=True, blank=True)+register_team_extension_signal(TeamWorkflowsConfig, logger=logger)diff --git a/products/workflows/backend/services/ses_tenant_state.py b/products/workflows/backend/services/ses_tenant_state.pynew file mode 100644index 000000000000..485011e9a6ca--- /dev/null+++ b/products/workflows/backend/services/ses_tenant_state.py@@ -0,0 +1,193 @@+from collections.abc import Callable+from typing import Any++from django.db import transaction+from django.utils import timezone++import structlog++from posthog.models.team import Team+from posthog.tasks.email import (+ send_email_sending_reputation_finding,+ send_email_sending_suspended,+ send_email_sending_unsuspended,+)++from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.providers.ses import SESProvider++logger = structlog.get_logger(__name__)++PROVIDER_PAUSE_REASON = "Our email provider paused sending for this project because of high-impact reputation findings"+# A tenant can also be paused without high-impact findings: someone pausing it directly in the+# provider console shows up here identically. Don't assert a cause we can't see.+PROVIDER_PAUSE_REASON_UNSPECIFIED = "Our email provider paused sending for this project"++# AWS reports "NONE" for a tenant with no findings; "" is our own never-synced sentinel. Unknown+# values sort below LOW so a new AWS level can't be mistaken for an escalation we understand.+_IMPACT_SEVERITY = {"": 0, "NONE": 0, "LOW": 1, "HIGH": 2}++_MAX_FINDINGS_IN_EMAIL = 5++# Our wording for each type AWS can raise (its RecommendationType enum). The provider's own+# Description is its copy in its voice, and it arrives empty often enough to be unusable as-is.+_FINDING_DESCRIPTIONS = {+ "BOUNCE": "Stop sending to addresses that have bounced",+ "COMPLAINT": "Too many recipients are marking these emails as spam",+ "IP_LISTING": "A sending IP has been added to a blocklist",+ "FEEDBACK_3P": "A mailbox provider has flagged your sending",+ "DKIM": "Set up DKIM for your sending domain",+ "SPF": "Set up SPF for your sending domain",+ "DMARC": "Set up DMARC for your sending domain",+ "BIMI": "Set up BIMI for your sending domain",+}++_STATE_FIELDS = ["ses_tenant_sending_status", "ses_tenant_reputation_impact", "ses_tenant_state_synced_at"]+++def sync_ses_tenant_state(team_id: int, provider: SESProvider | None = None, *, verify_team: bool = True) -> None:+ """+ Fetch the authoritative AWS SES tenant state for a team and apply it. Called from the+ EventBridge webhook (events only say "something changed" — the API is the source of truth)+ and from the periodic reconciliation sweep (event delivery is best-effort).+ """+ # SES holds tenants for teams that no longer exist here (a deleted project keeps its tenant),+ # and the webhook takes its team id from whatever AWS sent. Without this the config row's FK to+ # posthog_team fails and the task retries a write that can never succeed. The sweep passes+ # verify_team=False: it reads team ids off integration rows, so the team exists by construction.+ if verify_team and not Team.objects.filter(id=team_id).exists():+ logger.warning("Skipping SES tenant state sync for unknown team", team_id=team_id)+ return++ tenant = (provider or SESProvider()).get_tenant_reputation(team_id)+ if tenant is None:+ return+ apply_ses_tenant_state(+ team_id,+ sending_status=tenant["sending_status"],+ reputation_impact=tenant["reputation_impact"],+ findings=tenant["findings"],+ )+++def apply_ses_tenant_state(+ team_id: int,+ *,+ sending_status: str,+ reputation_impact: str | None,+ findings: list[dict[str, Any]] | None = None,+) -> None:+ """+ Persist the tenant state and email the project's admins on meaningful transitions:+ sending paused, sending re-enabled, or reputation findings escalating. The stored state is+ the dedupe mechanism — the row is locked for the read-compare-write so overlapping syncs+ (webhook + sweep, or duplicate events) serialize, and the loser sees an unchanged state.+ """+ impact = reputation_impact or ""+ if impact and impact not in _IMPACT_SEVERITY:+ logger.warning("Unknown SES reputation impact", team_id=team_id, impact=impact)+ TeamWorkflowsConfig.objects.get_or_create(team_id=team_id)++ with transaction.atomic():+ config = TeamWorkflowsConfig.objects.select_for_update().get(team_id=team_id)+ previous_status = config.ses_tenant_sending_status+ previous_impact = config.ses_tenant_reputation_impact+ if previous_status == sending_status and previous_impact == impact:+ config.ses_tenant_state_synced_at = timezone.now()+ config.save(update_fields=["ses_tenant_state_synced_at"])+ return++ now = timezone.now()+ config.ses_tenant_sending_status = sending_status+ config.ses_tenant_reputation_impact = impact+ config.ses_tenant_state_synced_at = now+ config.save(update_fields=_STATE_FIELDS)+ logger.info(+ "SES tenant state changed",+ team_id=team_id,+ from_status=previous_status,+ to_status=sending_status,+ from_impact=previous_impact,+ to_impact=impact,+ )++ notify = _pick_notification(+ previous_status=previous_status,+ previous_impact=previous_impact,+ sending_status=sending_status,+ impact=impact,+ team_id=team_id,+ now_iso=now.isoformat(),+ findings=_findings_for_email(findings),+ staff_suspended=config.email_sending_suspended_at is not None,+ )+ if notify is not None:+ # Dispatch after commit so a rollback can't leave an email claiming a state+ # that was never persisted.+ transaction.on_commit(notify)+++def _findings_for_email(findings: list[dict[str, Any]] | None) -> list[dict[str, str]]:+ """+ What the provider flagged, in our words, worst first, trimmed to what fits an email. Carrying+ it in the message keeps the email useful on its own: the Reputation tab is flag-gated, so a+ recipient may not be able to open the link at all.+ """+ if not findings:+ return []+ # AWS can raise several recommendations of one type (DKIM for each domain, say), which would+ # render as repeated identical lines now that the wording comes from the type. Keep the worst.+ impact_by_type: dict[str, str] = {}+ for finding in findings:+ finding_type = str(finding.get("finding_type") or "")+ if finding_type not in _FINDING_DESCRIPTIONS:+ logger.warning("Omitting SES finding of unknown type from email", finding_type=finding_type)+ continue+ impact = str(finding.get("impact") or "")+ known = impact_by_type.get(finding_type)+ if known is None or _IMPACT_SEVERITY.get(impact, 0) > _IMPACT_SEVERITY.get(known, 0):+ impact_by_type[finding_type] = impact+ ordered = sorted(impact_by_type.items(), key=lambda item: _IMPACT_SEVERITY.get(item[1], 0), reverse=True)+ return [+ {"impact": impact, "description": _FINDING_DESCRIPTIONS[finding_type]}+ for finding_type, impact in ordered[:_MAX_FINDINGS_IN_EMAIL]+ ]+++def _pick_notification(+ *,+ previous_status: str,+ previous_impact: str,+ sending_status: str,+ impact: str,+ team_id: int,+ now_iso: str,+ findings: list[dict[str, str]],+ staff_suspended: bool,+) -> Callable[[], None] | None:+ pause_reason = PROVIDER_PAUSE_REASON if impact == "HIGH" else PROVIDER_PAUSE_REASON_UNSPECIFIED++ if previous_status == "":+ # First sync is baseline adoption, not a transition — healthy teams stay silent so+ # rollout doesn't mass-email. But a tenant that is ALREADY paused or already carries+ # high-impact findings is exactly who this feature exists to tell, so those do notify.+ if sending_status == "DISABLED":+ return lambda: send_email_sending_suspended.delay(team_id, pause_reason, now_iso)+ if impact == "HIGH":+ return lambda: send_email_sending_reputation_finding.delay(team_id, impact, now_iso, findings)+ return None++ if sending_status == "DISABLED" and previous_status != "DISABLED":+ return lambda: send_email_sending_suspended.delay(team_id, pause_reason, now_iso)+ if previous_status == "DISABLED" and sending_status in ("ENABLED", "REINSTATED"):+ if staff_suspended:+ # The staff kill switch (email_sending_suspended_at) still blocks delivery, so+ # sending is not actually restored — a "re-enabled" email would contradict it. The+ # admin unsuspend action sends its own re-enabled email when that switch clears.+ return None+ return lambda: send_email_sending_unsuspended.delay(team_id, now_iso)+ if sending_status != "DISABLED" and _IMPACT_SEVERITY.get(impact, 0) > _IMPACT_SEVERITY.get(previous_impact, 0):+ # Escalation only, and only while still sending — a paused tenant already got the+ # suspension email, and de-escalations don't need action.+ return lambda: send_email_sending_reputation_finding.delay(team_id, impact, now_iso, findings)+ return Nonediff --git a/products/workflows/backend/services/sns_verification.py b/products/workflows/backend/services/sns_verification.pynew file mode 100644index 000000000000..e17d95386b35--- /dev/null+++ b/products/workflows/backend/services/sns_verification.py@@ -0,0 +1,175 @@+import re+import time+import base64+import hashlib+import logging+from typing import Any+from urllib.parse import urlparse++from django.core.cache import cache++import requests+from cryptography.exceptions import InvalidSignature+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.asymmetric import padding+from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey+from cryptography.x509 import load_pem_x509_certificate++logger = logging.getLogger(__name__)++# The signing cert must come from SNS itself — a signature check against an attacker-supplied cert+# proves nothing. Mirrors the cert-URL validation in the Node SES webhook+# (nodejs/src/cdp/services/messaging/helpers/ses.ts).+_SNS_HOST_RE = re.compile(r"^sns\.[a-z0-9-]+\.amazonaws\.com$")++# Cert URLs are one fixed shape; a message whose path is anything else cannot be from SNS, and+# checking it here means such a message is rejected without an outbound request.+_CERT_PATH_RE = re.compile(r"^/SimpleNotificationService-[A-Za-z0-9]{8,64}\.pem$")++_CERT_CACHE_SECONDS = 60 * 60+_CERT_FAILURE_CACHE_SECONDS = 60+_FETCH_TIMEOUT_SECONDS = 5+# Bounds what a flood of varied cert URLs can make us do: over budget we fail closed. The budget+# covers only URLs that have never verified a message, so exhausting it cannot stop the certificate+# a real topic signs with from being refreshed — see _fetch_signing_cert.+_MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE = 10+# A cert URL that has verified a message came from SNS, so it stays trusted well past the rotation+# interval and its refetch is never rationed.+_KNOWN_CERT_URL_SECONDS = 60 * 60 * 24 * 30+_FETCH_FAILED = "failed"++# Per https://docs.aws.amazon.com/sns/latest/dg/sns-verify-signature-of-message.html the string to+# sign is "Key\nValue\n" pairs in this exact order, skipping absent keys.+_SIGNED_KEYS_BY_TYPE = {+ "Notification": ["Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type"],+ "SubscriptionConfirmation": ["Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"],+ "UnsubscribeConfirmation": ["Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"],+}+++def is_valid_sns_url(url: str | None) -> bool:+ """True when the URL is HTTPS on a real *.amazonaws.com SNS host (cert or subscribe URL)."""+ if not url:+ return False+ parsed = urlparse(url)+ if parsed.scheme != "https" or not parsed.hostname or not _SNS_HOST_RE.match(parsed.hostname):+ return False+ # SNS only ever serves 443. Without this an SNS hostname on a dead port passes validation, and+ # each such URL holds a request for the full fetch timeout.+ try:+ return parsed.port in (None, 443)+ except ValueError:+ # urlparse defers parsing the port, so a non-numeric one raises here rather than above.+ return False+++def is_valid_sns_cert_url(url: str | None) -> bool:+ """True when the URL is one SNS could actually serve a signing certificate from."""+ return is_valid_sns_url(url) and bool(_CERT_PATH_RE.match(urlparse(url or "").path))+++def _url_digest(cert_url: str) -> str:+ # Hashed: the URL's path is caller-supplied and unbounded, and cache backends reject or mangle+ # over-long keys.+ return hashlib.sha256(cert_url.encode()).hexdigest()+++def _claim_unknown_cert_fetch_slot() -> bool:+ # One counter shared across web workers, so the ceiling holds for the deployment rather than+ # per process.+ bucket_key = f"sns_cert_fetch_budget_{int(time.time()) // 60}"+ cache.add(bucket_key, 0, 120)+ try:+ return cache.incr(bucket_key) <= _MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE+ except ValueError:+ # The bucket expired between the add and the incr, so this is effectively a fresh minute.+ return True+++def remember_verified_cert_url(cert_url: str) -> None:+ """Record that this URL served a certificate that verified a message, exempting its refetches."""+ cache.set(f"sns_known_cert_url_{_url_digest(cert_url)}", True, _KNOWN_CERT_URL_SECONDS)+++def _fetch_signing_cert(cert_url: str) -> bytes | None:+ cache_key = f"sns_signing_cert_{_url_digest(cert_url)}"+ cached = cache.get(cache_key)+ if cached is not None:+ return None if cached == _FETCH_FAILED else cached+ # Only novel URLs are rationed. Rationing every fetch would hand an attacker an outage: spend the+ # budget on well-shaped junk URLs each minute, and the real certificate could not be refreshed+ # once its hour expired.+ is_known = cache.get(f"sns_known_cert_url_{_url_digest(cert_url)}") is not None+ if not is_known and not _claim_unknown_cert_fetch_slot():+ logger.warning("Skipped SNS signing certificate fetch, per-minute budget for new URLs exhausted")+ return None+ try:+ response = requests.get(cert_url, timeout=_FETCH_TIMEOUT_SECONDS)+ response.raise_for_status()+ except requests.RequestException:+ logger.exception("Failed to fetch SNS signing certificate", extra={"cert_url": cert_url})+ # Remember the failure, or a repeated bad URL buys a fresh request every time.+ cache.set(cache_key, _FETCH_FAILED, _CERT_FAILURE_CACHE_SECONDS)+ return None+ cache.set(cache_key, response.content, _CERT_CACHE_SECONDS)+ return response.content+++def _string_to_sign(message: dict[str, Any]) -> str | None:+ keys = _SIGNED_KEYS_BY_TYPE.get(message.get("Type", ""))+ if keys is None:+ return None+ parts = []+ for key in keys:+ value = message.get(key)+ if value is None:+ continue+ parts.append(f"{key}\n{value}\n")+ return "".join(parts)+++def verify_sns_message(message: dict[str, Any]) -> bool:+ """+ Verify an SNS message's authenticity: signing cert served by SNS over HTTPS, RSA signature over+ the canonical string-to-sign. Returns False (never raises) on any mismatch so callers fail+ closed. Signature proves "from AWS SNS" — callers must still check TopicArn against an+ allowlist to prove "from *our* topic".+ """+ # Only SignatureVersion 2 (SHA256) is accepted. Version 1 signs with SHA1, which is not+ # collision resistant — and since we own the SNS topic, we simply configure it with+ # SignatureVersion=2 (a one-time SetTopicAttributes call, in the rollout runbook) instead of+ # ever verifying SHA1 here.+ if message.get("SignatureVersion") != "2":+ # SNS defaults topics to version 1, so this is the shape a missing SetTopicAttributes step+ # takes: every delivery rejected. Logged distinctly so that reads as misconfiguration+ # rather than as an attack.+ logger.warning(+ "Rejected SNS message with unsupported signature version",+ extra={"signature_version": message.get("SignatureVersion")},+ )+ return False+ cert_url = message.get("SigningCertURL")+ if not isinstance(cert_url, str) or not is_valid_sns_cert_url(cert_url):+ return False+ string_to_sign = _string_to_sign(message)+ if string_to_sign is None:+ return False+ try:+ signature = base64.b64decode(message.get("Signature", ""))+ except (ValueError, TypeError):+ return False+ cert_pem = _fetch_signing_cert(cert_url)+ if cert_pem is None:+ return False+ try:+ public_key = load_pem_x509_certificate(cert_pem).public_key()+ if not isinstance(public_key, RSAPublicKey):+ return False+ public_key.verify(signature, string_to_sign.encode(), padding.PKCS1v15(), hashes.SHA256())+ remember_verified_cert_url(cert_url)+ return True+ except InvalidSignature:+ return False+ except Exception:+ logger.exception("SNS signature verification errored")+ return Falsediff --git a/products/workflows/backend/tasks/ses_tenant_state.py b/products/workflows/backend/tasks/ses_tenant_state.pynew file mode 100644index 000000000000..55b41d59978f--- /dev/null+++ b/products/workflows/backend/tasks/ses_tenant_state.py@@ -0,0 +1,56 @@+from celery import shared_task+from structlog import get_logger++from posthog.models.integration import Integration+from posthog.scoping_audit import skip_team_scope_audit+from posthog.tasks.utils import CeleryQueue++from products.workflows.backend.providers.ses import SESProvider+from products.workflows.backend.services.ses_tenant_state import sync_ses_tenant_state++logger = get_logger(__name__)+++@shared_task(+ ignore_result=True,+ queue=CeleryQueue.DEFAULT.value,+ # The sync hits the SES API; transient throttling/outages should retry with backoff instead+ # of dropping the event (the daily sweep would catch it, but a day late).+ autoretry_for=(Exception,),+ retry_backoff=60,+ retry_backoff_max=600,+ max_retries=5,+ retry_jitter=True,+)+def sync_ses_tenant_state_task(team_id: int) -> None:+ """Webhook-triggered: an EventBridge event said this team's tenant changed — fetch and apply."""+ sync_ses_tenant_state(team_id)+++@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)+@skip_team_scope_audit+def reconcile_ses_tenant_states() -> None:+ """+ Periodic backstop: EventBridge delivery is best-effort, so sweep every team that has an SES+ tenant (i.e. a verified email integration) and apply the authoritative state. The transition+ logic dedupes against stored state, so overlap with webhook-triggered syncs is harmless.+ """+ team_ids = (+ Integration.objects.filter(kind="email", config__provider="ses")+ .values_list("team_id", flat=True)+ .distinct()+ .order_by("team_id")+ )+ # One provider for the whole sweep: a fresh SESProvider per team would rebuild its boto3+ # clients (and re-resolve credentials) thousands of times.+ provider = SESProvider()+ synced = 0+ failed = 0+ for team_id in team_ids.iterator(chunk_size=500):+ try:+ sync_ses_tenant_state(team_id, provider=provider, verify_team=False)+ synced += 1+ except Exception:+ failed += 1+ logger.exception("SES tenant reconciliation failed for team", team_id=team_id)+ logger.info("SES tenant reconciliation finished", synced=synced, failed=failed)diff --git a/products/workflows/backend/test/test_ses_events_webhook.py b/products/workflows/backend/test/test_ses_events_webhook.pynew file mode 100644index 000000000000..108356c751d0--- /dev/null+++ b/products/workflows/backend/test/test_ses_events_webhook.py@@ -0,0 +1,132 @@+import json+from typing import Any++from unittest.mock import patch++from django.http.response import HttpResponseBase+from django.test import Client, TestCase, override_settings++TOPIC = "arn:aws:sns:us-east-1:123456789012:ses-tenant-events"+WEBHOOK_PATH = "/webhooks/workflows/ses-events"+++def _sns_notification(event: dict[str, Any], topic: str = TOPIC) -> dict[str, Any]:+ return {+ "Type": "Notification",+ "MessageId": "mid-1",+ "TopicArn": topic,+ "Message": json.dumps(event),+ "Timestamp": "2026-07-30T00:00:00.000Z",+ "SignatureVersion": "1",+ "Signature": "sig",+ "SigningCertURL": "https://sns.us-east-1.amazonaws.com/cert.pem",+ }+++def _eventbridge_event(**overrides: Any) -> dict[str, Any]:+ event: dict[str, Any] = {+ "version": "0",+ "source": "aws.ses",+ "detail-type": "Sending Status Disabled",+ "resources": [],+ "detail": {"tenantName": "team-42"},+ }+ event.update(overrides)+ return event+++@override_settings(WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS=[TOPIC])+class TestSesTenantEventsWebhook(TestCase):+ def setUp(self) -> None:+ self.client = Client()+ verify = patch("products.workflows.backend.api.ses_events_webhook.verify_sns_message", return_value=True)+ self.verify_mock = verify.start()+ self.addCleanup(verify.stop)+ sync = patch("products.workflows.backend.api.ses_events_webhook.sync_ses_tenant_state_task")+ self.sync_mock = sync.start()+ self.addCleanup(sync.stop)++ def _post(self, payload: dict[str, Any]) -> HttpResponseBase:+ return self.client.post(WEBHOOK_PATH, data=json.dumps(payload), content_type="text/plain")++ def test_enqueues_a_sync_for_the_tenant_named_in_the_event(self) -> None:+ response = self._post(_sns_notification(_eventbridge_event()))++ assert response.status_code == 202+ self.sync_mock.delay.assert_called_once_with(42)++ def test_finds_the_tenant_in_resource_arns_when_detail_has_no_name(self) -> None:+ event = _eventbridge_event(detail={}, resources=["arn:aws:ses:us-east-1:123456789012:tenant/team-7/deadbeef"])++ response = self._post(_sns_notification(event))++ assert response.status_code == 202+ self.sync_mock.delay.assert_called_once_with(7)++ def test_acks_but_ignores_events_from_other_sources(self) -> None:+ response = self._post(_sns_notification(_eventbridge_event(source="aws.health")))++ assert response.status_code == 200+ assert not self.sync_mock.delay.called++ def test_rejects_messages_from_unknown_topics(self) -> None:+ response = self._post(_sns_notification(_eventbridge_event(), topic="arn:aws:sns:us-east-1:999:other"))++ assert response.status_code == 403+ assert not self.sync_mock.delay.called++ def test_rejects_messages_with_invalid_signatures(self) -> None:+ self.verify_mock.return_value = False++ response = self._post(_sns_notification(_eventbridge_event()))++ assert response.status_code == 403+ assert not self.sync_mock.delay.called++ @override_settings(WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS=[])+ def test_is_inert_when_no_topic_is_allowlisted(self) -> None:+ response = self._post(_sns_notification(_eventbridge_event()))++ assert response.status_code == 404+ assert not self.sync_mock.delay.called++ def test_confirms_subscriptions_by_fetching_the_subscribe_url(self) -> None:+ subscribe_url = "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&Token=tok"+ payload = {+ "Type": "SubscriptionConfirmation",+ "MessageId": "mid-2",+ "TopicArn": TOPIC,+ "Token": "tok",+ "Message": "You have chosen to subscribe...",+ "SubscribeURL": subscribe_url,+ "Timestamp": "2026-07-30T00:00:00.000Z",+ "SignatureVersion": "1",+ "Signature": "sig",+ "SigningCertURL": "https://sns.us-east-1.amazonaws.com/cert.pem",+ }++ with patch("products.workflows.backend.api.ses_events_webhook.requests.get") as get_mock:+ response = self._post(payload)++ assert response.status_code == 200+ get_mock.assert_called_once_with(subscribe_url, timeout=5)++ def test_rejects_subscription_confirmations_pointing_off_aws(self) -> None:+ payload = {+ "Type": "SubscriptionConfirmation",+ "MessageId": "mid-3",+ "TopicArn": TOPIC,+ "Token": "tok",+ "Message": "...",+ "SubscribeURL": "https://attacker.example.com/confirm",+ "Timestamp": "2026-07-30T00:00:00.000Z",+ "SignatureVersion": "1",+ "Signature": "sig",+ "SigningCertURL": "https://sns.us-east-1.amazonaws.com/cert.pem",+ }++ with patch("products.workflows.backend.api.ses_events_webhook.requests.get") as get_mock:+ response = self._post(payload)++ assert response.status_code == 400+ assert not get_mock.calleddiff --git a/products/workflows/backend/test/test_ses_tenant_state.py b/products/workflows/backend/test/test_ses_tenant_state.pynew file mode 100644index 000000000000..e00b17a1df33--- /dev/null+++ b/products/workflows/backend/test/test_ses_tenant_state.py@@ -0,0 +1,185 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from parameterized import parameterized++from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.services.ses_tenant_state import (+ PROVIDER_PAUSE_REASON,+ PROVIDER_PAUSE_REASON_UNSPECIFIED,+ apply_ses_tenant_state,+ sync_ses_tenant_state,+)+++class TestApplySesTenantState(BaseTest):+ def _apply(self, sending_status: str, reputation_impact: str | None) -> dict:+ with (+ patch("products.workflows.backend.services.ses_tenant_state.send_email_sending_suspended") as suspended,+ patch("products.workflows.backend.services.ses_tenant_state.send_email_sending_unsuspended") as unsuspended,+ patch(+ "products.workflows.backend.services.ses_tenant_state.send_email_sending_reputation_finding"+ ) as finding,+ self.captureOnCommitCallbacks(execute=True),+ ):+ apply_ses_tenant_state(self.team.id, sending_status=sending_status, reputation_impact=reputation_impact)+ return {"suspended": suspended.delay, "unsuspended": unsuspended.delay, "finding": finding.delay}++ def _seed(self, sending_status: str, reputation_impact: str = "") -> None:+ TeamWorkflowsConfig.objects.update_or_create(+ team=self.team,+ defaults={+ "ses_tenant_sending_status": sending_status,+ "ses_tenant_reputation_impact": reputation_impact,+ },+ )++ @parameterized.expand(+ [+ # A healthy or low-impact baseline is silent (rollout must not mass-email)...+ ("healthy", "ENABLED", None, None),+ ("low_findings", "ENABLED", "LOW", None),+ # ...but a tenant that is already paused or already critical is exactly who this+ # feature exists to tell — the first sync must not swallow that.+ ("already_paused", "DISABLED", "HIGH", "suspended"),+ ("already_critical", "ENABLED", "HIGH", "finding"),+ ]+ )+ def test_first_sync_baseline_notifies_only_already_bad_tenants(+ self, _name: str, sending_status: str, impact: str | None, expected_email: str | None+ ) -> None:+ emails = self._apply(sending_status, impact)++ config = TeamWorkflowsConfig.objects.get(team=self.team)+ assert config.ses_tenant_sending_status == sending_status+ assert config.ses_tenant_state_synced_at is not None+ for kind, mock in emails.items():+ assert mock.called == (kind == expected_email), f"{kind} called={mock.called}"++ def test_unchanged_state_only_refreshes_synced_at(self) -> None:+ self._seed("ENABLED", "LOW")++ emails = self._apply("ENABLED", "LOW")++ assert all(not mock.called for mock in emails.values())+ assert TeamWorkflowsConfig.objects.get(team=self.team).ses_tenant_state_synced_at is not None++ @parameterized.expand(+ [+ # (previous_status, previous_impact, new_status, new_impact, expected_email)+ ("pause", "ENABLED", "", "DISABLED", "HIGH", "suspended"),+ ("pause_from_reinstated", "REINSTATED", "LOW", "DISABLED", "HIGH", "suspended"),+ ("unpause", "DISABLED", "HIGH", "ENABLED", "", "unsuspended"),+ ("reinstate", "DISABLED", "HIGH", "REINSTATED", "HIGH", "unsuspended"),+ ("first_finding", "ENABLED", "", "ENABLED", "LOW", "finding"),+ # AWS reports "NONE" rather than an empty impact, so the healthy-to-finding and+ # finding-to-resolved transitions really look like these two rows in production.+ ("first_finding_from_none", "ENABLED", "NONE", "ENABLED", "LOW", "finding"),+ ("finding_resolved_to_none", "ENABLED", "HIGH", "ENABLED", "NONE", None),+ ("escalation", "ENABLED", "LOW", "ENABLED", "HIGH", "finding"),+ ("deescalation", "ENABLED", "HIGH", "ENABLED", "LOW", None),+ # Impact escalating while already paused: the suspension email already covers it+ ("escalation_while_paused", "DISABLED", "LOW", "DISABLED", "HIGH", None),+ ("finding_resolved", "ENABLED", "LOW", "ENABLED", "", None),+ ]+ )+ def test_transitions_send_the_right_email(+ self,+ _name: str,+ previous_status: str,+ previous_impact: str,+ new_status: str,+ new_impact: str,+ expected_email: str | None,+ ) -> None:+ self._seed(previous_status, previous_impact)++ emails = self._apply(new_status, new_impact or None)++ for kind, mock in emails.items():+ assert mock.called == (kind == expected_email), f"{kind} called={mock.called}"++ def test_restore_is_silent_while_staff_kill_switch_still_blocks_sending(self) -> None:+ # AWS reinstating the tenant does not restore delivery while the staff kill switch is set,+ # so a "re-enabled" email would tell admins something false. The admin unsuspend action+ # sends that email when the switch clears.+ TeamWorkflowsConfig.objects.update_or_create(+ team=self.team,+ defaults={"ses_tenant_sending_status": "DISABLED", "email_sending_suspended_at": timezone.now()},+ )++ emails = self._apply("ENABLED", None)++ assert not emails["unsuspended"].called++ def test_provider_pause_email_carries_the_provider_reason(self) -> None:+ self._seed("ENABLED")++ emails = self._apply("DISABLED", "HIGH")++ args = emails["suspended"].call_args.args+ assert args[0] == self.team.id+ assert args[1] == PROVIDER_PAUSE_REASON++ def test_finding_email_carries_the_new_impact(self) -> None:+ self._seed("ENABLED", "LOW")++ emails = self._apply("ENABLED", "HIGH")++ assert emails["finding"].call_args.args[:2] == (self.team.id, "HIGH")++ def test_pause_without_high_impact_does_not_blame_reputation_findings(self) -> None:+ self._seed("ENABLED", "NONE")++ emails = self._apply("DISABLED", "NONE")++ assert emails["suspended"].call_args.args[1] == PROVIDER_PAUSE_REASON_UNSPECIFIED++ def _findings_sent_for(self, findings: list[dict[str, str]]) -> list[dict[str, str]]:+ self._seed("ENABLED", "NONE")+ with (+ patch(+ "products.workflows.backend.services.ses_tenant_state.send_email_sending_reputation_finding"+ ) as finding,+ self.captureOnCommitCallbacks(execute=True),+ ):+ apply_ses_tenant_state(self.team.id, sending_status="ENABLED", reputation_impact="HIGH", findings=findings)+ return finding.delay.call_args.args[3]++ def test_finding_email_uses_our_wording_worst_first_and_drops_unknown_types(self) -> None:+ sent = self._findings_sent_for(+ [+ {"finding_type": "DKIM", "impact": "LOW", "description": "Provider prose we do not show"},+ {"finding_type": "BOUNCE", "impact": "HIGH", "description": ""},+ {"finding_type": "A_TYPE_AWS_ADDED_LATER", "impact": "HIGH", "description": "Unmapped"},+ ]+ )++ assert sent == [+ {"impact": "HIGH", "description": "Stop sending to addresses that have bounced"},+ {"impact": "LOW", "description": "Set up DKIM for your sending domain"},+ ]++ def test_repeated_finding_type_is_collapsed_to_its_worst_impact(self) -> None:+ sent = self._findings_sent_for(+ [+ {"finding_type": "DKIM", "impact": "LOW", "description": ""},+ {"finding_type": "DKIM", "impact": "HIGH", "description": ""},+ ]+ )++ assert sent == [{"impact": "HIGH", "description": "Set up DKIM for your sending domain"}]+++class TestSyncSesTenantState(BaseTest):+ def test_unknown_team_is_skipped_without_calling_ses(self) -> None:+ # SES keeps tenants for deleted projects, and the webhook trusts AWS for the team id. A+ # write here would fail the config row's FK and retry forever.+ provider = MagicMock()++ sync_ses_tenant_state(self.team.id + 99_999, provider=provider)++ provider.get_tenant_reputation.assert_not_called()+ assert not TeamWorkflowsConfig.objects.filter(team_id=self.team.id + 99_999).exists()diff --git a/products/workflows/backend/test/test_sns_verification.py b/products/workflows/backend/test/test_sns_verification.pynew file mode 100644index 000000000000..0785244dec56--- /dev/null+++ b/products/workflows/backend/test/test_sns_verification.py@@ -0,0 +1,178 @@+import base64+import datetime+from typing import Any++from unittest import TestCase+from unittest.mock import patch++from django.core.cache import cache+from django.test import SimpleTestCase, override_settings++import requests+from cryptography import x509+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import padding, rsa+from cryptography.x509.oid import NameOID+from parameterized import parameterized++from products.workflows.backend.services.sns_verification import (+ _MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE,+ _fetch_signing_cert,+ is_valid_sns_cert_url,+ is_valid_sns_url,+ remember_verified_cert_url,+ verify_sns_message,+)++_CERT_URL = "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-01d088a6f77103d0fe307c0069e40ed6.pem"++_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+_SUBJECT = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "sns.amazonaws.com")])+_CERT_PEM = (+ x509.CertificateBuilder()+ .subject_name(_SUBJECT)+ .issuer_name(_SUBJECT)+ .public_key(_KEY.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(datetime.datetime(2020, 1, 1))+ .not_valid_after(datetime.datetime(2040, 1, 1))+ .sign(_KEY, hashes.SHA256())+ .public_bytes(serialization.Encoding.PEM)+)+++def _signed_notification(tamper: dict[str, Any] | None = None) -> dict[str, Any]:+ message = {+ "Type": "Notification",+ "MessageId": "mid-1",+ "TopicArn": "arn:aws:sns:us-east-1:123456789012:topic",+ "Message": '{"source":"aws.ses"}',+ "Timestamp": "2026-07-30T00:00:00.000Z",+ "SignatureVersion": "2",+ "SigningCertURL": _CERT_URL,+ }+ string_to_sign = "".join(+ f"{key}\n{message[key]}\n" for key in ["Message", "MessageId", "Timestamp", "TopicArn", "Type"]+ )+ signature = _KEY.sign(string_to_sign.encode(), padding.PKCS1v15(), hashes.SHA256())+ message["Signature"] = base64.b64encode(signature).decode()+ message.update(tamper or {})+ return message+++class TestSnsVerification(TestCase):+ def _verify(self, message: dict[str, Any]) -> bool:+ with patch("products.workflows.backend.services.sns_verification._fetch_signing_cert", return_value=_CERT_PEM):+ return verify_sns_message(message)++ def test_accepts_a_correctly_signed_notification(self) -> None:+ assert self._verify(_signed_notification()) is True++ @parameterized.expand(+ [+ ("tampered_message", {"Message": '{"source":"aws.ses","evil":true}'}),+ ("tampered_topic", {"TopicArn": "arn:aws:sns:us-east-1:666:other"}),+ ("garbage_signature", {"Signature": base64.b64encode(b"nope").decode()}),+ ("cert_not_from_sns", {"SigningCertURL": "https://attacker.example.com/cert.pem"}),+ ("cert_over_http", {"SigningCertURL": f"http{_CERT_URL[5:]}"}),+ # Right host, but not a path SNS serves a certificate from.+ ("cert_path_not_a_cert", {"SigningCertURL": "https://sns.us-east-1.amazonaws.com/evil.pem"}),+ ("unknown_type", {"Type": "SomethingElse"}),+ # SignatureVersion 1 is SHA1-signed and rejected outright; the topic must be+ # configured with SignatureVersion=2+ ("sha1_signature_version", {"SignatureVersion": "1"}),+ ]+ )+ def test_rejects(self, _name: str, tamper: dict[str, Any]) -> None:+ assert self._verify(_signed_notification(tamper)) is False++ @parameterized.expand(+ [+ ("sns_regional", "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService.pem", True),+ ("subdomain_spoof", "https://sns.us-east-1.amazonaws.com.evil.com/cert.pem", False),+ ("wrong_service", "https://s3.us-east-1.amazonaws.com/cert.pem", False),+ # An SNS host on a port SNS does not serve: the fetch would just hang out the timeout.+ ("dead_port", "https://sns.us-east-1.amazonaws.com:81/SimpleNotificationService-abcdef1234.pem", False),+ ("explicit_443", "https://sns.us-east-1.amazonaws.com:443/SimpleNotificationService-abcdef1234.pem", True),+ ("non_numeric_port", "https://sns.us-east-1.amazonaws.com:port/cert.pem", False),+ ("empty", "", False),+ ("none", None, False),+ ]+ )+ def test_url_validation(self, _name: str, url: str | None, expected: bool) -> None:+ assert is_valid_sns_url(url) is expected++ @parameterized.expand(+ [+ ("real_cert_path", _CERT_URL, True),+ ("arbitrary_path", "https://sns.us-east-1.amazonaws.com/evil.pem", False),+ # The subscribe URL is a different shape and must not pass as a cert URL.+ ("subscribe_url", "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription", False),+ ]+ )+ def test_cert_url_validation(self, _name: str, url: str, expected: bool) -> None:+ assert is_valid_sns_cert_url(url) is expected+++@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})+class TestSigningCertFetch(SimpleTestCase):+ """An unauthenticated caller who learns the topic ARN reaches the fetch, so it stays cheap."""++ def setUp(self) -> None:+ cache.clear()++ def test_a_cert_url_sns_could_not_serve_is_rejected_without_fetching(self) -> None:+ message = _signed_notification({"SigningCertURL": "https://sns.us-east-1.amazonaws.com/evil.pem"})++ with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ assert verify_sns_message(message) is False++ assert get.call_count == 0++ def test_a_failed_fetch_is_not_retried_for_the_same_url(self) -> None:+ with patch(+ "products.workflows.backend.services.sns_verification.requests.get",+ side_effect=requests.RequestException("boom"),+ ) as get:+ assert _fetch_signing_cert(_CERT_URL) is None+ assert _fetch_signing_cert(_CERT_URL) is None++ assert get.call_count == 1++ def _spend_the_budget(self) -> None:+ with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ get.return_value.content = _CERT_PEM+ for index in range(_MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE):+ _fetch_signing_cert(f"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-{index:032x}.pem")++ def test_fetching_a_new_url_stops_once_the_minute_budget_is_spent(self) -> None:+ self._spend_the_budget()++ with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ get.return_value.content = _CERT_PEM+ assert _fetch_signing_cert(_CERT_URL) is None++ assert get.call_count == 0++ def test_a_url_that_has_verified_before_is_refetched_even_with_the_budget_spent(self) -> None:+ # Otherwise junk URLs could spend the budget every minute and starve the real certificate's+ # hourly refresh, taking the webhook down for as long as the flood lasted.+ remember_verified_cert_url(_CERT_URL)+ self._spend_the_budget()++ with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ get.return_value.content = _CERT_PEM+ assert _fetch_signing_cert(_CERT_URL) == _CERT_PEM++ assert get.call_count == 1++ def test_a_verified_message_marks_its_cert_url_known(self) -> None:+ with patch("products.workflows.backend.services.sns_verification._fetch_signing_cert", return_value=_CERT_PEM):+ assert verify_sns_message(_signed_notification()) is True++ self._spend_the_budget()+ with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ get.return_value.content = _CERT_PEM+ assert _fetch_signing_cert(_CERT_URL) == _CERT_PEM++ assert get.call_count == 1