: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
chore(workflows): verify SES events through ingress (#101488)
Julian Bez26d4894d1a86
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex 27697d3ad869..c2a03329d49c 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -115,4 +115,3 @@ rules:# migrates that endpoint removes its line. The paths are the ones on master,# so the rule holds whether or not the migrations land with it.- /ee/api/vercel/vercel_webhooks.py- - /products/workflows/backend/api/ses_events_webhook.pydiff --git a/docs/internal/url-routing.md b/docs/internal/url-routing.mdindex 99515e824e39..8b8e08a71cdd 100644--- a/docs/internal/url-routing.md+++ b/docs/internal/url-routing.md@@ -39,4 +39,4 @@ Use `urlpatterns` only for a plain Django path that no router can carry, such asThe owner of the third-party App registration owns the route.The customer-facing GitHub App is shared: one endpoint fans out to several products, so core mounts it.An App a single product registers, such as Stamphog's GitHub App, is mounted by that product.-The SES topic behind `webhooks/workflows/ses-events` is the exception for now: its view still lives in `backend/api/`, so it waits for the change that moves it onto the ingress builders.+A topic a single product owns works the same way: `webhooks/workflows/ses-events` is mounted from `products/workflows/backend/routes.py`.diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 2090817107b9..a95923320ccc 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -5,7 +5,7 @@ A new inbound webhook that needs signature verification or fan-out belongs hereA verifier the vendor ships in its SDK is not hand-rolled and is not a migration: it stays, and a scheme here calls it rather than reimplementing the compare.Four lanes:-- **`verify/`** — signature schemes. HMAC-SHA256 in the shapes providers actually send (hex or base64, an optional prefix, an optional `v0:{timestamp}:{body}` input with a replay window), the SNS envelope check, and a bearer JWT checked against the issuer's published signing keys.+- **`verify/`** — signature schemes. HMAC-SHA256 in the shapes providers actually send (hex or base64, an optional prefix, an optional `v0:{timestamp}:{body}` input with a replay window), the SNS envelope check and the AWS SNS message signature it rests on, and a bearer JWT checked against the issuer's published signing keys.- **`dispatch/`** — the validated consumer registry, per-delivery dedup, the wall-clock budget, consumer isolation, and `bounded_statement_timeout()` for consumers that read the database.- **`observability/`** — Prometheus: delivery volume by transport outcome, and one metric set per consumer run.- **`views.py`** — the view that composes the other three: one request that is verified _and_ recorded by construction, so no incarnation can skip either.@@ -83,7 +83,6 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enfThe owner of the third-party App registration owns the route.The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.Every other endpoint is declared by the product that registered the App, in its own `routes.py`.-The SES endpoint is the exception for now, because its view still lives in `backend/api/` rather than behind the ingress builders.The Vapi endpoint is the only one that caps request volume: its provider sets `throttle_class` to a per-IP throttle, because the endpoint is public and Vapi's egress is shared across tenants.@@ -234,7 +233,7 @@ The same attribute answers a delivery whose consumers did not accept it, under oAdd a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):- `SPECS` — one `ProviderSpec` per app, naming the event types the app is subscribed to. The registry validates consumers against these.-- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack, Mailgun and Teams on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. Four more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted, and `reports_unconfigured`, which also sends a missing secret to error tracking. That last one is off by default, because an endpoint that answers an unconfigured request like an unknown route lets an unauthenticated prober fill error tracking from the outside; turn it on where the deliveries are lost while the secret is unset and nothing else would notice. See [The lanes one request runs through](#the-lanes-one-request-runs-through).+- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack, Mailgun and Teams on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. The unconfigured case of an incarnation that answers a 4xx is logged as a warning rather than an error, because an endpoint that an operator may never configure sees probes of a public URL. Four more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted, and `reports_unconfigured`, which also sends a missing secret to error tracking. That last one is off by default, because an endpoint that answers an unconfigured request like an unknown route lets an unauthenticated prober fill error tracking from the outside; turn it on where the deliveries are lost while the secret is unset and nothing else would notice. See [The lanes one request runs through](#the-lanes-one-request-runs-through).- A provider that lowers `unconfigured_status` to a 4xx, as Teams does, first checks that its scheme reaches `NOT_CONFIGURED` only for a value an operator sets, never for one a remote lookup produces. A 4xx the sender does not retry turns that lookup's outage into lost deliveries. This is why `BearerJwt` answers `UNAVAILABLE` for a signing-key URI it could not discover, and reads the values an operator sets before it.- A `build_<provider>_provider(...)` function returning that provider, which the URLconf hands to `build_webhook_view()`.A builder that takes an `app` name checks it with `require_known_app(provider, app, SPECS)` before anything else, so a typo raises `UnknownApp` at import. Without that check the endpoint builds and serves: consumers register against the declared app names, so nothing matches and every delivery is receipted and dropped, or the app has no secret getter and every delivery answers `NOT_CONFIGURED`.diff --git a/posthog/ingress/sns/README.md b/posthog/ingress/sns/README.mdindex 3fc9cb0bcbae..6601558a5388 100644--- a/posthog/ingress/sns/README.md+++ b/posthog/ingress/sns/README.md@@ -12,11 +12,13 @@ The envelope fields `Type`, `MessageId` and `TopicArn` all come from the JSON boNot HMAC.`SnsSignature` checks two things and needs both.-The message signature proves the message is from SNS, through a verifier the caller supplies, which owns the certificate fetch and its own cache.-A verifier that could not fetch the certificate raises `VerifierUnavailable`, and the scheme answers `UNAVAILABLE`, so the view replies 503 and SNS delivers again.-The certificate URL is checked against the SNS host and path shape before any fetch, and a URL that fails that check is a bad signature rather than an unavailable verification.+The message signature proves the message is from SNS: an RSA-SHA256 check over AWS's canonical string-to-sign, against a certificate fetched from a `sns.<region>.amazonaws.com` URL of the one shape SNS serves.+That half is the same for every SNS topic, so it lives in the verify lane (`verify/sns_signature.py`) with its certificate cache, its failure cache, and a per-minute budget on fetches for URLs that have never verified a message.+A certificate that could not be obtained raises `VerifierUnavailable`, and the scheme answers `UNAVAILABLE`, so the view replies 503 and SNS delivers again.+A certificate URL that fails the host and path check is a bad signature rather than an unavailable verification, and it is never fetched.+Only `SignatureVersion` 2 is accepted; a topic left on version 1 has every delivery rejected, logged as a misconfiguration rather than an attack.The `TopicArn` allowlist proves the message is from our topic.-An empty allowlist reads as unconfigured.+An empty allowlist reads as unconfigured, which answers 404 with an empty body and logs a warning, so a probe of this public URL learns nothing and cannot flood the error logs.A body that is not a JSON object is invalid, and there is no replay window.## Delivery id and event type@@ -27,17 +29,19 @@ The `TopicArn` goes into the delivery context.## Apps and secrets-One app, `default`, and no secret.-The verifier and the topic allowlist belong to whoever owns the topic, so `build_sns_provider()` takes both as callables.+One app, `default`, and no secret: SNS signs with its own certificate, so there is nothing for an operator to hold.+The topic allowlist is the only per-endpoint configuration, so `build_sns_provider()` takes the name of the Django setting that holds it and reads it per request.+The SES events endpoint names `WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS`.## QuirksThe subscription handshake is an event type, not a pre-dispatch response.Confirming a subscription means calling AWS back, which is a consumer's business rather than the transport's, so a consumer registers for `SubscriptionConfirmation` separately from `Notification`.An unknown topic logs `ingress_sns_unknown_topic` and answers like a bad signature.+SNS retries a delivery on a non-2xx, so this incarnation sets `retry_status` to 502.+A delivery no consumer accepted is then not receipted, which is what lets a failed confirmation callback be tried again.## Consumers-No product registers an SNS consumer yet.-The workflows SES events endpoint moves to ingress in its own PR.+`workflows_ses_events`, on the `default` app, for `SubscriptionConfirmation` and `Notification`.See the [Endpoints table](../README.md#endpoints).diff --git a/posthog/ingress/sns/provider.py b/posthog/ingress/sns/provider.pyindex c5fb29eca3a9..10cb35590d33 100644--- a/posthog/ingress/sns/provider.py+++ b/posthog/ingress/sns/provider.py@@ -5,9 +5,10 @@ subscription handshake and for notifications: confirming a subscription means caback, which is the consumer's business, not the transport's."""-from collections.abc import Callable, Mapping, Sequence+from collections.abc import Mapping, Sequencefrom typing import Any+from django.conf import settingsfrom django.http import HttpRequestfrom django.utils import timezone@@ -20,19 +21,27 @@ SNS_EVENT_TYPES = frozenset({"SubscriptionConfirmation", "Notification", "UnsubsSPECS = (ProviderSpec(provider="sns", app="default", event_types=SNS_EVENT_TYPES),)+def topic_arns_from_setting(setting_name: str) -> frozenset[str]:+ """The topics one endpoint accepts. Read per request, so an override takes effect at once."""+ return frozenset(arn for arn in getattr(settings, setting_name, ()) or () if arn)++class SnsProvider(WebhookProvider):provider = "sns"+ # An SNS endpoint is a public URL with no allowlisted topic until an operator sets one, so an+ # unconfigured one answers like a route that was never registered rather than confirming it+ # exists with a 500 a prober can flood the error logs with.+ unconfigured_status = 404+ # A body naming the reason would hand back the existence the 404 above withholds.+ explains_rejections = False+ # SNS retries a delivery on a non-2xx, and a subscription whose confirmation callback failed+ # stays unconfirmed until one is retried, so an unaccepted delivery must not be receipted.+ retry_status = 502- def __init__(- self,- *,- app: str = "default",- verify_message: Callable[[Mapping[str, Any]], bool],- allowed_topic_arns: Callable[[], frozenset[str]],- ) -> None:+ def __init__(self, *, app: str = "default", topic_arns_setting: str) -> None:require_known_app(self.provider, app, SPECS)self.app = app- self._scheme = SnsSignature(verify_message=verify_message, allowed_topic_arns=allowed_topic_arns)+ self._scheme = SnsSignature(allowed_topic_arns=lambda: topic_arns_from_setting(topic_arns_setting))def scheme(self) -> SignatureScheme:return self._scheme@@ -55,12 +64,6 @@ class SnsProvider(WebhookProvider):)-def build_sns_provider(- *,- verify_message: Callable[[Mapping[str, Any]], bool],- allowed_topic_arns: Callable[[], frozenset[str]],- app: str = "default",-) -> SnsProvider:- """The RSA verifier and the topic allowlist belong to whoever owns the topic, so both are- passed in rather than reached for from here."""- return SnsProvider(app=app, verify_message=verify_message, allowed_topic_arns=allowed_topic_arns)+def build_sns_provider(*, topic_arns_setting: str, app: str = "default") -> SnsProvider:+ """The topic allowlist belongs to whoever owns the topic, so the URLconf names its setting."""+ return SnsProvider(app=app, topic_arns_setting=topic_arns_setting)diff --git a/posthog/ingress/test/test_providers.py b/posthog/ingress/test/test_providers.pyindex 7a7a4e67277a..4ca1876c431b 100644--- a/posthog/ingress/test/test_providers.py+++ b/posthog/ingress/test/test_providers.py@@ -1,5 +1,4 @@-from collections.abc import Callable, Mapping-from typing import Any+from collections.abc import Callablefrom django.http import HttpRequestfrom django.test import RequestFactory, SimpleTestCase@@ -26,16 +25,8 @@ def _slack(app: str) -> WebhookProvider:return build_slack_provider(secret_getter=lambda: "signing-secret", app=app)-def _verified(message: Mapping[str, Any]) -> bool:- return True---def _no_topics() -> frozenset[str]:- return frozenset()--def _sns(app: str) -> WebhookProvider:- return build_sns_provider(verify_message=_verified, allowed_topic_arns=_no_topics, app=app)+ return build_sns_provider(topic_arns_setting="WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS", app=app)# One row per builder that takes an app name: the provider, the builder, a declared app, and adiff --git a/products/workflows/backend/test/test_sns_verification.py b/posthog/ingress/test/test_sns_signature.pysimilarity index 89%rename from products/workflows/backend/test/test_sns_verification.pyrename to posthog/ingress/test/test_sns_signature.pyindex 1a441fb6d02e..b62e82046d78 100644--- a/products/workflows/backend/test/test_sns_verification.py+++ b/posthog/ingress/test/test_sns_signature.py@@ -16,8 +16,7 @@ from cryptography.x509.oid import NameOIDfrom parameterized import parameterizedfrom posthog.ingress.verify.errors import VerifierUnavailable--from products.workflows.backend.services.sns_verification import (+from posthog.ingress.verify.sns_signature import (_MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE,_fetch_signing_cert,is_valid_sns_cert_url,@@ -64,7 +63,7 @@ def _signed_notification(tamper: dict[str, Any] | None = None) -> dict[str, Any]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):+ with patch("posthog.ingress.verify.sns_signature._fetch_signing_cert", return_value=_CERT_PEM):return verify_sns_message(message)def test_accepts_a_correctly_signed_notification(self) -> None:@@ -132,7 +131,7 @@ class TestSigningCertFetch(SimpleTestCase):def test_a_cert_url_sns_could_not_serve_is_rejected_without_fetching(self, _name: str, cert_url: str) -> None:message = _signed_notification({"SigningCertURL": cert_url})- with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ with patch("posthog.ingress.verify.sns_signature.requests.get") as get:assert verify_sns_message(message) is Falseassert get.call_count == 0@@ -147,7 +146,7 @@ class TestSigningCertFetch(SimpleTestCase):def test_a_certificate_that_could_not_be_fetched_is_unavailable_rather_than_a_bad_signature(self, _name: str, fetch_error: Exception | None, status_error: Exception | None) -> None:- with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ with patch("posthog.ingress.verify.sns_signature.requests.get") as get:get.side_effect = fetch_errorget.return_value.raise_for_status.side_effect = status_error@@ -156,7 +155,7 @@ class TestSigningCertFetch(SimpleTestCase):def test_a_failed_fetch_is_not_retried_for_the_same_url(self) -> None:with patch(- "products.workflows.backend.services.sns_verification.requests.get",+ "posthog.ingress.verify.sns_signature.requests.get",side_effect=requests.RequestException("boom"),) as get:assert _fetch_signing_cert(_CERT_URL) is None@@ -165,7 +164,7 @@ class TestSigningCertFetch(SimpleTestCase):assert get.call_count == 1def _spend_the_budget(self) -> None:- with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ with patch("posthog.ingress.verify.sns_signature.requests.get") as get:get.return_value.content = _CERT_PEMfor index in range(_MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE):_fetch_signing_cert(f"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-{index:032x}.pem")@@ -173,7 +172,7 @@ class TestSigningCertFetch(SimpleTestCase):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:+ with patch("posthog.ingress.verify.sns_signature.requests.get") as get:get.return_value.content = _CERT_PEMassert _fetch_signing_cert(_CERT_URL) is None@@ -185,18 +184,18 @@ class TestSigningCertFetch(SimpleTestCase):remember_verified_cert_url(_CERT_URL)self._spend_the_budget()- with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ with patch("posthog.ingress.verify.sns_signature.requests.get") as get:get.return_value.content = _CERT_PEMassert _fetch_signing_cert(_CERT_URL) == _CERT_PEMassert get.call_count == 1def 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):+ with patch("posthog.ingress.verify.sns_signature._fetch_signing_cert", return_value=_CERT_PEM):assert verify_sns_message(_signed_notification()) is Trueself._spend_the_budget()- with patch("products.workflows.backend.services.sns_verification.requests.get") as get:+ with patch("posthog.ingress.verify.sns_signature.requests.get") as get:get.return_value.content = _CERT_PEMassert _fetch_signing_cert(_CERT_URL) == _CERT_PEMdiff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.pyindex 5ed4c285afbb..eb039e5b85ac 100644--- a/posthog/ingress/test/test_verify.py+++ b/posthog/ingress/test/test_verify.py@@ -2,9 +2,7 @@ import reimport hmacimport timeimport base64-from collections.abc import Mappingfrom types import SimpleNamespace-from typing import Anyfrom unittest.mock import patch@@ -234,11 +232,12 @@ class TestSnsSignature(SimpleTestCase):def setUp(self) -> None:self.allowed = frozenset({"arn:aws:sns:eu-west-1:1:ses-events"})- def _scheme(self, *, verified: bool = True, allowed: frozenset[str] | None = None) -> SnsSignature:- return SnsSignature(- verify_message=lambda message: verified,- allowed_topic_arns=lambda: self.allowed if allowed is None else allowed,- )+ def _scheme(self, *, allowed: frozenset[str] | None = None) -> SnsSignature:+ return SnsSignature(allowed_topic_arns=lambda: self.allowed if allowed is None else allowed)++ def _verify(self, scheme: SnsSignature, *, body: bytes, verified: bool = True) -> VerificationOutcome:+ with patch("posthog.ingress.verify.schemes.verify_sns_message", return_value=verified):+ return scheme.verify(body=body, headers={}).outcome@parameterized.expand([@@ -251,28 +250,27 @@ class TestSnsSignature(SimpleTestCase):self, _name: str, topic_arn: str, verified: bool, expected: str) -> None:body = f'{{"TopicArn": "{topic_arn}", "MessageId": "m1"}}'.encode()- self.assertEqual(- self._scheme(verified=verified).verify(body=body, headers={}).outcome, VerificationOutcome(expected)- )+ self.assertEqual(self._verify(self._scheme(), body=body, verified=verified), VerificationOutcome(expected))def test_empty_allowlist_is_not_configured(self) -> None:body = b'{"TopicArn": "arn:aws:sns:eu-west-1:1:ses-events"}'self.assertEqual(- self._scheme(allowed=frozenset()).verify(body=body, headers={}).outcome,+ self._verify(self._scheme(allowed=frozenset()), body=body),VerificationOutcome.NOT_CONFIGURED,)def test_unparseable_body_is_invalid_rather_than_raising(self) -> None:- self.assertEqual(self._scheme().verify(body=b"not json", headers={}).outcome, VerificationOutcome.INVALID)+ self.assertEqual(self._verify(self._scheme(), body=b"not json"), VerificationOutcome.INVALID)def test_a_verifier_that_could_not_fetch_the_certificate_is_unavailable(self) -> None:- def verify_message(message: Mapping[str, Any]) -> bool:- raise VerifierUnavailable("no certificate")-- scheme = SnsSignature(verify_message=verify_message, allowed_topic_arns=lambda: self.allowed)body = b'{"TopicArn": "arn:aws:sns:eu-west-1:1:ses-events", "MessageId": "m1"}'- self.assertEqual(scheme.verify(body=body, headers={}).outcome, VerificationOutcome.UNAVAILABLE)+ with patch(+ "posthog.ingress.verify.schemes.verify_sns_message", side_effect=VerifierUnavailable("no certificate")+ ):+ outcome = self._scheme().verify(body=body, headers={}).outcome++ self.assertEqual(outcome, VerificationOutcome.UNAVAILABLE)JWKS_URI = "https://login.example.com/v1/.well-known/keys"diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.pyindex eae01e729b1f..226dbc8d0b14 100644--- a/posthog/ingress/test/test_views.py+++ b/posthog/ingress/test/test_views.py@@ -318,10 +318,25 @@ class TestWebhookView(SimpleTestCase):request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})with patch("posthog.ingress.github.provider.get_instance_setting", return_value=""):- response = build_webhook_view(build_github_provider("posthog"))(request)+ with structlog.testing.capture_logs() as logs:+ response = build_webhook_view(build_github_provider("posthog"))(request)self.assertEqual(response.status_code, 500)self.assertEqual(response.content, b"Webhook not configured")+ missing = next(log for log in logs if log["event"] == "ingress_webhook_not_configured")+ self.assertEqual(missing["log_level"], "error")++ def test_an_unconfigured_provider_that_answers_a_4xx_logs_a_warning(self) -> None:+ # Slack answers 403 when its secret is unset, so an error line here would let an anonymous+ # prober of a self-hosted instance write to the error log at will.+ request = self.factory.post("/slack/events", data="{}", content_type="application/json")++ with structlog.testing.capture_logs() as logs:+ response = build_webhook_view(build_slack_provider(secret_getter=lambda: None))(request)++ self.assertEqual(response.status_code, 403)+ missing = next(log for log in logs if log["event"] == "ingress_webhook_not_configured")+ self.assertEqual(missing["log_level"], "warning")@parameterized.expand([diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.pyindex 962198d2c92e..8b321a6da023 100644--- a/posthog/ingress/verify/schemes.py+++ b/posthog/ingress/verify/schemes.py@@ -20,6 +20,7 @@ import structlogfrom posthog.dataclasses import frozenfrom posthog.ingress.verify.errors import VerifierUnavailable+from posthog.ingress.verify.sns_signature import verify_sns_messagelogger = structlog.get_logger(__name__)@@ -209,12 +210,11 @@ class SnsSignature:"""AWS SNS message signature plus a topic-ARN allowlist.The signature proves "from AWS SNS" and the allowlist proves "from our topic", so- neither half is optional. The RSA work stays with the caller-supplied verifier, which- owns the certificate fetch and its own cache. That verifier raises `VerifierUnavailable`- when it could not obtain the certificate at all.+ neither half is optional. The signature half is the same for every SNS topic and lives+ in `sns_signature.py`, which raises `VerifierUnavailable` when it could not obtain the+ certificate at all; only the allowlist belongs to the endpoint."""- verify_message: Callable[[Mapping[str, Any]], bool]allowed_topic_arns: Callable[[], frozenset[str]]def rejects_headers(self, headers: Mapping[str, str]) -> bool:@@ -237,7 +237,7 @@ class SnsSignature:logger.warning("ingress_sns_unknown_topic", topic=message.get("TopicArn"))return VerificationOutcome.INVALIDtry:- verified = self.verify_message(message)+ verified = verify_sns_message(message)except VerifierUnavailable:# UNAVAILABLE rather than INVALID: the signature was never checked, and SNS reads# the invalid-signature status as a verdict and stops delivering.diff --git a/products/workflows/backend/services/sns_verification.py b/posthog/ingress/verify/sns_signature.pysimilarity index 94%rename from products/workflows/backend/services/sns_verification.pyrename to posthog/ingress/verify/sns_signature.pyindex 07a57e48ed70..8aaec1489a58 100644--- a/products/workflows/backend/services/sns_verification.py+++ b/posthog/ingress/verify/sns_signature.py@@ -1,8 +1,16 @@+"""The AWS SNS message signature: the signing certificate, and the RSA check over it.++Nothing here is specific to one topic or one product. `SnsSignature` in `schemes.py` calls+`verify_sns_message()` to prove a message is from SNS, and then checks the `TopicArn` against+the endpoint's allowlist to prove it is from our topic.+"""+import reimport timeimport base64import hashlibimport logging+from collections.abc import Mappingfrom typing import Anyfrom urllib.parse import urlparse@@ -117,7 +125,7 @@ def _fetch_signing_cert(cert_url: str) -> bytes | None:return response.content-def _string_to_sign(message: dict[str, Any]) -> str | None:+def _string_to_sign(message: Mapping[str, Any]) -> str | None:keys = _SIGNED_KEYS_BY_TYPE.get(message.get("Type", ""))if keys is None:return None@@ -130,7 +138,7 @@ def _string_to_sign(message: dict[str, Any]) -> str | None:return "".join(parts)-def verify_sns_message(message: dict[str, Any]) -> bool:+def verify_sns_message(message: Mapping[str, Any]) -> bool:"""Verify an SNS message's authenticity: signing cert served by SNS over HTTPS, RSA signature overthe canonical string-to-sign. Returns False on any mismatch so callers fail closed, and raisesdiff --git a/posthog/ingress/views.py b/posthog/ingress/views.pyindex a5de9e8f8cee..74d0e50299ae 100644--- a/posthog/ingress/views.py+++ b/posthog/ingress/views.py@@ -92,7 +92,12 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httverification = provider.verify(request)if verification.outcome is VerificationOutcome.NOT_CONFIGURED:- logger.error("ingress_webhook_not_configured", provider=provider.provider, app=provider.app)+ # An incarnation that answers a 4xx may stay off until an operator configures it, and its+ # URL is public meanwhile, so what reaches this line is probe traffic. A warning still+ # reaches an operator, and at error level an anonymous prober would decide how much of+ # the error budget this endpoint spends.+ log = logger.warning if provider.unconfigured_status < 500 else logger.error+ log("ingress_webhook_not_configured", provider=provider.provider, app=provider.app)if provider.reports_unconfigured:capture_exception(Exception(f"Inbound webhook {provider.provider}/{provider.app} has no secret configured")diff --git a/posthog/urls.py b/posthog/urls.pyindex 09b87a1941f8..9ad290709288 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -77,7 +77,6 @@ from products.tasks.backend.facade.agent_proxy import agent_proxy_callbackfrom products.user_interviews.backend.presentation.webhooks import start_call as user_interviews_start_callfrom 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_pathfrom .views import (@@ -356,8 +355,6 @@ urlpatterns = [# It stays in core because the App is shared: no single product owns its registration.opt_slash_path("webhooks/github/pr", github_app_webhook),opt_slash_path("webhooks/github", github_app_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.pydeleted file mode 100644index b800af5d50df..000000000000--- a/products/workflows/backend/api/ses_events_webhook.py+++ /dev/null@@ -1,132 +0,0 @@-"""-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 posthog.ingress.verify.errors import VerifierUnavailable--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)- try:- verified = verify_sns_message(message)- except VerifierUnavailable:- # 503 asks SNS to deliver again, which its retry policy does for a server error. 403 would- # read as a verdict on a message whose signature was never checked.- logger.warning("ses_tenant_events_webhook_verification_unavailable", message_id=message.get("MessageId"))- return HttpResponse("Verification unavailable", status=503)- if not verified:- 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":- return _confirm_subscription(message)- if message_type != "Notification":- # UnsubscribeConfirmation and anything unknown: ack so SNS stops retrying.- return HttpResponse(status=200)- return _handle_notification(message)---def _confirm_subscription(message: dict[str, Any]) -> HttpResponse:- """Call back the SubscribeURL AWS sent, which completes the SNS subscription handshake."""- 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)---def _handle_notification(message: dict[str, Any]) -> HttpResponse:- """Enqueue a tenant-state sync for the team the EventBridge event names.-- Every unusable payload still acks, because a retry would deliver the same unusable payload.- """- 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)-- # Logged because the only other line on this path is the failure one, which leaves a handled- # delivery and an ignored one looking identical from outside: both answer 2xx.- logger.info("ses_tenant_events_webhook_accepted", team_id=team_id, detail_type=event.get("detail-type"))- # 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/facade/api.py b/products/workflows/backend/facade/api.pyindex 4558aed4f854..d35249cf7ad6 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -22,3 +22,11 @@ def accept_github_event(delivery: WebhookDelivery) -> None:from products.workflows.backend.github_workflow_events import emit_github_event # noqa: PLC0415emit_github_event(delivery.event_type, dict(delivery.payload), delivery.delivery_id or "")+++def accept_ses_event(delivery: WebhookDelivery) -> None:+ """The inbound SES events SNS topic enters workflows here, so its consumer needs no internal import."""+ # Deferred to keep the Celery task and the SNS callback client off the facade import path.+ from products.workflows.backend.services.ses_tenant_events import handle_ses_tenant_event # noqa: PLC0415++ handle_ses_tenant_event(delivery)diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.pyindex 98678f0e3527..e2ef426d81c2 100644--- a/products/workflows/backend/routes.py+++ b/products/workflows/backend/routes.py@@ -1,7 +1,21 @@+from django.urls import URLPattern+from posthog.api.routing import RouterRegistry+from posthog.ingress.sns.provider import build_sns_provider+from posthog.ingress.views import build_webhook_view+from posthog.utils import opt_slash_pathfrom products.workflows.backend.api import hog_flow, hog_flow_template, workflow_scout_runs, workflow_tasks+# AWS SES tenant reputation events, delivered EventBridge -> SNS HTTPS subscription. Workflows owns+# the topic and its allowlist setting, so the route is mounted here rather than in core.+urlpatterns: list[URLPattern] = [+ opt_slash_path(+ "webhooks/workflows/ses-events",+ build_webhook_view(build_sns_provider(topic_arns_setting="WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS")),+ ),+]+def register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"hog_flows", hog_flow.HogFlowViewSet, "project_hog_flows", ["team_id"])diff --git a/products/workflows/backend/services/ses_tenant_events.py b/products/workflows/backend/services/ses_tenant_events.pynew file mode 100644index 000000000000..77672ddc31cf--- /dev/null+++ b/products/workflows/backend/services/ses_tenant_events.py@@ -0,0 +1,93 @@+"""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.++The SNS message signature and the topic-ARN allowlist are checked by the ingress transport, which+reads the allowlist from `WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS`. 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 collections.abc import Mapping+from typing import Any++import requests+import structlog++from posthog.ingress.contracts import WebhookDelivery+from posthog.ingress.verify.sns_signature import is_valid_sns_url++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+++def _confirm_subscription(message: Mapping[str, Any]) -> None:+ """Call back the SubscribeURL AWS sent, which completes the SNS subscription handshake."""+ subscribe_url = message.get("SubscribeURL")+ if not isinstance(subscribe_url, str) or not is_valid_sns_url(subscribe_url):+ # Dropped rather than raised, like an unusable notification payload: a redelivery carries+ # the same URL, so retrying it can never confirm the subscription.+ logger.warning("ses_tenant_events_webhook_invalid_subscribe_url", topic=message.get("TopicArn"))+ return+ # A failed callback to AWS's own URL is raised rather than dropped: it leaves the subscription+ # unconfirmed, and raising costs the request its receipt, because the SNS incarnation sets a+ # retry status, so SNS sends the handshake again.+ requests.get(subscribe_url, timeout=5).raise_for_status()+ logger.info("ses_tenant_events_webhook_subscription_confirmed", topic=message.get("TopicArn"))+++def _handle_notification(message: Mapping[str, Any]) -> None:+ """Enqueue a tenant-state sync for the team the EventBridge event names.++ Every unusable payload is dropped rather than raised, because a redelivery would carry the+ same unusable payload.+ """+ try:+ event = json.loads(message.get("Message", ""))+ except (json.JSONDecodeError, TypeError):+ return+ if not isinstance(event, dict) or event.get("source") != "aws.ses":+ return++ 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++ # Logged because the only other line on this path is the failure one, which leaves a handled+ # delivery and an ignored one looking identical from outside: both answer 2xx.+ logger.info("ses_tenant_events_webhook_accepted", team_id=team_id, detail_type=event.get("detail-type"))+ # Ack fast; the sync fetches authoritative state and sends any transition emails.+ sync_ses_tenant_state_task.delay(team_id)+++def handle_ses_tenant_event(delivery: WebhookDelivery) -> None:+ """One SNS delivery: the subscription handshake, or a tenant reputation event."""+ if delivery.event_type == "SubscriptionConfirmation":+ _confirm_subscription(delivery.payload)+ elif delivery.event_type == "Notification":+ _handle_notification(delivery.payload)diff --git a/products/workflows/backend/test/test_github_workflow_events.py b/products/workflows/backend/test/test_github_workflow_events.pyindex bc3239c1192d..8b007ec1ad62 100644--- a/products/workflows/backend/test/test_github_workflow_events.py+++ b/products/workflows/backend/test/test_github_workflow_events.py@@ -307,7 +307,7 @@ def test_a_kafka_failure_does_not_reach_the_webhook(produce, integration) -> Nondef test_the_webhook_consumer_passes_the_whole_delivery_through_the_facade(produce, integration) -> None:# The facade unpacks the delivery into emit's three arguments. The delivery id only shows up# in the event uuid, so dropping it emits an event that looks correct and dedupes wrong.- (consumer,) = WEBHOOK_CONSUMERS+ (consumer,) = [consumer for consumer in WEBHOOK_CONSUMERS if consumer.name == "workflows"]delivery = WebhookDelivery(provider="github",app="posthog",diff --git a/products/workflows/backend/test/test_ses_events_webhook.py b/products/workflows/backend/test/test_ses_events_webhook.pydeleted file mode 100644index eb139a6cfe48..000000000000--- a/products/workflows/backend/test/test_ses_events_webhook.py+++ /dev/null@@ -1,142 +0,0 @@-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--from posthog.ingress.verify.errors import VerifierUnavailable--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-- def test_asks_sns_to_deliver_again_when_the_signing_certificate_is_unavailable(self) -> None:- self.verify_mock.side_effect = VerifierUnavailable("no certificate")-- response = self._post(_sns_notification(_eventbridge_event()))-- assert response.status_code == 503- 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_events.py b/products/workflows/backend/test/test_ses_tenant_events.pynew file mode 100644index 000000000000..8b4f7aa2d9e8--- /dev/null+++ b/products/workflows/backend/test/test_ses_tenant_events.py@@ -0,0 +1,232 @@+import json+import base64+import datetime+from typing import Any, cast++from unittest.mock import patch++from django.core.cache import cache+from django.http.response import HttpResponse+from django.test import Client, SimpleTestCase, TestCase, override_settings+from django.utils import timezone++import requests+import structlog.testing+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 posthog.ingress.contracts import WebhookDelivery++from products.workflows.backend.facade.api import accept_ses_event++TOPIC = "arn:aws:sns:us-east-1:123456789012:ses-tenant-events"+WEBHOOK_PATH = "/webhooks/workflows/ses-events"+SUBSCRIBE_URL = "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&Token=tok"+_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)+)+_SIGNED_KEYS = {+ "Notification": ("Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type"),+ "SubscriptionConfirmation": ("Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"),+}+++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+++def _notification(event: dict[str, Any], *, message_id: str = "mid-1", topic: str = TOPIC) -> dict[str, Any]:+ return {+ "Type": "Notification",+ "MessageId": message_id,+ "TopicArn": topic,+ "Message": json.dumps(event),+ "Timestamp": "2026-07-30T00:00:00.000Z",+ }+++def _subscription_confirmation(*, message_id: str = "mid-2", subscribe_url: str = SUBSCRIBE_URL) -> dict[str, Any]:+ return {+ "Type": "SubscriptionConfirmation",+ "MessageId": message_id,+ "TopicArn": TOPIC,+ "Token": "tok",+ "Message": "You have chosen to subscribe...",+ "SubscribeURL": subscribe_url,+ "Timestamp": "2026-07-30T00:00:00.000Z",+ }+++def _signed(message: dict[str, Any]) -> dict[str, Any]:+ """The message as AWS would send it: signature version 2 over the canonical string-to-sign."""+ signed = {**message, "SignatureVersion": "2", "SigningCertURL": _CERT_URL}+ string_to_sign = "".join(f"{key}\n{signed[key]}\n" for key in _SIGNED_KEYS[signed["Type"]] if key in signed)+ signature = _KEY.sign(string_to_sign.encode(), padding.PKCS1v15(), hashes.SHA256())+ signed["Signature"] = base64.b64encode(signature).decode()+ return signed+++def _delivery(message: dict[str, Any]) -> WebhookDelivery:+ return WebhookDelivery(+ provider="sns",+ app="default",+ delivery_id=str(message["MessageId"]),+ event_type=str(message["Type"]),+ payload=message,+ received_at=timezone.now(),+ context={"topic_arn": TOPIC},+ )+++class TestAcceptSesEvent(SimpleTestCase):+ def setUp(self) -> None:+ sync = patch("products.workflows.backend.services.ses_tenant_events.sync_ses_tenant_state_task")+ self.sync_mock = sync.start()+ self.addCleanup(sync.stop)++ def test_enqueues_a_sync_for_the_tenant_named_in_the_event(self) -> None:+ accept_ses_event(_delivery(_notification(_eventbridge_event())))++ 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"])++ accept_ses_event(_delivery(_notification(event)))++ self.sync_mock.delay.assert_called_once_with(7)++ def test_ignores_events_from_other_sources(self) -> None:+ accept_ses_event(_delivery(_notification(_eventbridge_event(source="aws.health"))))++ assert not self.sync_mock.delay.called++ def test_confirms_subscriptions_by_fetching_the_subscribe_url(self) -> None:+ with patch("products.workflows.backend.services.ses_tenant_events.requests.get") as get_mock:+ accept_ses_event(_delivery(_subscription_confirmation()))++ get_mock.assert_called_once_with(SUBSCRIBE_URL, timeout=5)++ @parameterized.expand(+ [+ ("off_aws", "https://attacker.example.com/confirm"),+ ("not_a_url", "not-a-url"),+ ]+ )+ def test_refuses_a_malformed_subscribe_url_without_raising(self, _name: str, subscribe_url: str) -> None:+ # Raising would cost the delivery its receipt and make SNS redeliver a handshake that can+ # never be confirmed.+ message = _subscription_confirmation(subscribe_url=subscribe_url)++ with patch("products.workflows.backend.services.ses_tenant_events.requests.get") as get_mock:+ accept_ses_event(_delivery(message))++ assert not get_mock.called++ def test_a_failed_confirmation_callback_is_raised_rather_than_swallowed(self) -> None:+ with patch(+ "products.workflows.backend.services.ses_tenant_events.requests.get",+ side_effect=requests.RequestException("boom"),+ ):+ with self.assertRaises(requests.RequestException):+ accept_ses_event(_delivery(_subscription_confirmation()))+++@override_settings(WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS=[TOPIC])+class TestSesTenantEventsEndpoint(TestCase):+ def setUp(self) -> None:+ self.client = Client()+ # The dedup mark outlives a test, so a shared one would make the second delivery a no-op.+ cache.clear()+ cert = patch("posthog.ingress.verify.sns_signature._fetch_signing_cert", return_value=_CERT_PEM)+ cert.start()+ self.addCleanup(cert.stop)+ sync = patch("products.workflows.backend.services.ses_tenant_events.sync_ses_tenant_state_task")+ self.sync_mock = sync.start()+ self.addCleanup(sync.stop)++ def _post(self, payload: dict[str, Any]) -> HttpResponse:+ return cast(HttpResponse, self.client.post(WEBHOOK_PATH, data=json.dumps(payload), content_type="text/plain"))++ def test_enqueues_a_sync_for_the_tenant_named_in_a_verified_event(self) -> None:+ response = self._post(_signed(_notification(_eventbridge_event())))++ assert response.status_code == 202+ self.sync_mock.delay.assert_called_once_with(42)++ def test_rejects_messages_from_unknown_topics(self) -> None:+ message = _signed(_notification(_eventbridge_event(), topic="arn:aws:sns:us-east-1:999:other"))++ response = self._post(message)++ assert response.status_code == 403+ assert not self.sync_mock.delay.called++ def test_rejects_messages_with_invalid_signatures(self) -> None:+ tampered = {**_signed(_notification(_eventbridge_event())), "Message": json.dumps(_eventbridge_event())[:-1]}++ response = self._post(tampered)++ 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:+ with structlog.testing.capture_logs() as logs:+ response = self._post(_signed(_notification(_eventbridge_event())))++ assert response.status_code == 404+ assert response.content == b""+ assert not self.sync_mock.delay.called+ unconfigured = next(log for log in logs if log["event"] == "ingress_webhook_not_configured")+ assert unconfigured["log_level"] == "warning"++ @parameterized.expand(+ [+ ("callback_succeeds", SUBSCRIBE_URL, None, 202, True),+ ("callback_fails", SUBSCRIBE_URL, requests.RequestException("boom"), 502, True),+ # Terminal, so SNS stops: a redelivery would carry the same unusable URL.+ ("subscribe_url_is_not_aws", "https://attacker.example.com/confirm", None, 202, False),+ ]+ )+ def test_confirms_a_verified_subscription(+ self,+ _name: str,+ subscribe_url: str,+ callback_error: Exception | None,+ expected_status: int,+ expect_callback: bool,+ ) -> None:+ with patch(+ "products.workflows.backend.services.ses_tenant_events.requests.get", side_effect=callback_error+ ) as get_mock:+ response = self._post(_signed(_subscription_confirmation(subscribe_url=subscribe_url)))++ assert response.status_code == expected_status+ if expect_callback:+ get_mock.assert_called_once_with(subscribe_url, timeout=5)+ else:+ assert not get_mock.calleddiff --git a/products/workflows/backend/webhook_consumers.py b/products/workflows/backend/webhook_consumers.pyindex 2c9be76e4624..66e5cb5c0bc1 100644--- a/products/workflows/backend/webhook_consumers.py+++ b/products/workflows/backend/webhook_consumers.py@@ -1,7 +1,7 @@-"""Workflows' consumer on the customer-facing GitHub App endpoint.+"""Workflows' consumers: the customer-facing GitHub App endpoint, and the SES events SNS topic.-The registry imports this module on the first delivery, so it stays cheap: the handler defers-its own product import.+The registry imports this module on the first delivery, so it stays cheap: both handlers defer+their own product import."""from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery@@ -13,6 +13,12 @@ def _run_workflows(delivery: WebhookDelivery) -> None:accept_github_event(delivery)+def _run_workflows_ses_events(delivery: WebhookDelivery) -> None:+ from products.workflows.backend.facade.api import accept_ses_event # noqa: PLC0415++ accept_ses_event(delivery)++WEBHOOK_CONSUMERS = (WebhookConsumer(name="workflows",@@ -21,4 +27,12 @@ WEBHOOK_CONSUMERS = (event_types=frozenset({"issues", "issue_comment", "pull_request", "pull_request_review", "push"}),handler=_run_workflows,),+ WebhookConsumer(+ name="workflows_ses_events",+ provider="sns",+ app="default",+ # Confirming the subscription is this consumer's business too: it means calling AWS back.+ event_types=frozenset({"SubscriptionConfirmation", "Notification"}),+ handler=_run_workflows_ses_events,+ ),)