Skip to content

: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.

fix(ingress): answer 503 when the SNS signing certificate cannot be fetched (#102261)

Julian Bez6ca0b9f91ac7
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 9160f1787379..2090817107b9 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -106,6 +106,7 @@ A consumer that wants asynchronous work enqueues its own task and answers immedi
The HTTP response is a transport receipt: the verification result, the method, and the payload decide the status, and consumer return values are ignored.
If a provider's protocol needs the response body to say something, the incarnation answers that handshake before dispatch.
A verification that could not run is its own answer rather than a verdict: a scheme with a network step returns `UNAVAILABLE` when that step fails on transport, and the view answers 503 with outcome `verify_unavailable`, so a sender that retries a server error sends the delivery again.
+`BearerJwt` answers it when the JWKS could not be fetched, and `SnsSignature` when its verifier raises `VerifierUnavailable` because the signing certificate could not be fetched.
What the transport does decide is whether it can vouch that the delivery was taken.
It cannot when an ownership lookup failed, when the forward to the owning region failed, when a consumer raised, or when the budget skipped a consumer — in each case some of the work never ran, or ingress cannot tell whether it ran in the right region.
diff --git a/posthog/ingress/sns/README.md b/posthog/ingress/sns/README.md
index cd2bbd1afc19..3fc9cb0bcbae 100644
--- a/posthog/ingress/sns/README.md
+++ b/posthog/ingress/sns/README.md
@@ -13,6 +13,8 @@ The envelope fields `Type`, `MessageId` and `TopicArn` all come from the JSON bo
Not 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 `TopicArn` allowlist proves the message is from our topic.
An empty allowlist reads as unconfigured.
A body that is not a JSON object is invalid, and there is no replay window.
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index c790a7311db2..5ed4c285afbb 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -2,7 +2,9 @@ import re
import hmac
import time
import base64
+from collections.abc import Mapping
from types import SimpleNamespace
+from typing import Any
from unittest.mock import patch
@@ -13,6 +15,7 @@ from cryptography.hazmat.primitives.asymmetric import rsa
from jwt.algorithms import RSAAlgorithm
from parameterized import parameterized
+from posthog.ingress.verify.errors import VerifierUnavailable
from posthog.ingress.verify.jwt import _JWKS_CLIENTS, SIGNING_KEY_FACT, BearerJwt, _jwks_client
from posthog.ingress.verify.schemes import HmacSha256, HmacSignature, SnsSignature, Verification, VerificationOutcome
@@ -262,6 +265,15 @@ class TestSnsSignature(SimpleTestCase):
def test_unparseable_body_is_invalid_rather_than_raising(self) -> None:
self.assertEqual(self._scheme().verify(body=b"not json", headers={}).outcome, 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)
+
JWKS_URI = "https://login.example.com/v1/.well-known/keys"
AUDIENCE = "00000000-0000-0000-0000-000000000001"
diff --git a/posthog/ingress/verify/errors.py b/posthog/ingress/verify/errors.py
new file mode 100644
index 000000000000..1a4f808286ac
--- /dev/null
+++ b/posthog/ingress/verify/errors.py
@@ -0,0 +1,14 @@
+"""What a verifier raises when it cannot say anything about a signature."""
+
+
+class VerifierUnavailable(Exception):
+ """The material a verifier checks signatures against could not be obtained.
+
+ Raised instead of answering "not verified", because a fetch that never completed proves
+ nothing about the caller. The scheme turns this into `VerificationOutcome.UNAVAILABLE`,
+ which the view answers with 503, so a sender that retries a server error sends the
+ delivery again rather than dropping it as forged.
+
+ This lives apart from the schemes, so a verifier module a scheme imports can raise it
+ without importing the schemes back.
+ """
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index c5ffdcba11b6..962198d2c92e 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -2,7 +2,8 @@
A scheme with a network step answers `UNAVAILABLE` when that step fails on transport rather than
on the signature, because a fetch that never completed proves nothing about the caller. `BearerJwt`
-does this for a JWKS fetch failure, and `SnsSignature` owes the same for its certificate fetch.
+does this for a JWKS fetch failure, and `SnsSignature` for a signing certificate its verifier
+could not fetch.
"""
import re
@@ -18,6 +19,7 @@ from typing import Any, Literal, Protocol
import structlog
from posthog.dataclasses import frozen
+from posthog.ingress.verify.errors import VerifierUnavailable
logger = structlog.get_logger(__name__)
@@ -208,7 +210,8 @@ class SnsSignature:
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.
+ owns the certificate fetch and its own cache. That verifier raises `VerifierUnavailable`
+ when it could not obtain the certificate at all.
"""
verify_message: Callable[[Mapping[str, Any]], bool]
@@ -233,7 +236,14 @@ class SnsSignature:
if message.get("TopicArn") not in allowed:
logger.warning("ingress_sns_unknown_topic", topic=message.get("TopicArn"))
return VerificationOutcome.INVALID
- if not self.verify_message(message):
+ try:
+ verified = self.verify_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.
+ logger.warning("ingress_sns_signing_certificate_unavailable", message_id=message.get("MessageId"))
+ return VerificationOutcome.UNAVAILABLE
+ if not verified:
logger.warning("ingress_sns_invalid_signature", message_id=message.get("MessageId"))
return VerificationOutcome.INVALID
return VerificationOutcome.VERIFIED
diff --git a/products/workflows/backend/api/ses_events_webhook.py b/products/workflows/backend/api/ses_events_webhook.py
index b1df4f1c1e60..b800af5d50df 100644
--- a/products/workflows/backend/api/ses_events_webhook.py
+++ b/products/workflows/backend/api/ses_events_webhook.py
@@ -20,6 +20,8 @@ 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
@@ -70,7 +72,14 @@ def ses_tenant_events_webhook(request: HttpRequest) -> HttpResponse:
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):
+ 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)
diff --git a/products/workflows/backend/services/sns_verification.py b/products/workflows/backend/services/sns_verification.py
index e17d95386b35..07a57e48ed70 100644
--- a/products/workflows/backend/services/sns_verification.py
+++ b/products/workflows/backend/services/sns_verification.py
@@ -15,6 +15,8 @@ from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from cryptography.x509 import load_pem_x509_certificate
+from posthog.ingress.verify.errors import VerifierUnavailable
+
logger = logging.getLogger(__name__)
# The signing cert must come from SNS itself — a signature check against an attacker-supplied cert
@@ -131,9 +133,10 @@ def _string_to_sign(message: dict[str, Any]) -> str | None:
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".
+ the canonical string-to-sign. Returns False on any mismatch so callers fail closed, and raises
+ `VerifierUnavailable` when the certificate could not be obtained at all, which says nothing
+ about the signature. 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
@@ -160,7 +163,10 @@ def verify_sns_message(message: dict[str, Any]) -> bool:
return False
cert_pem = _fetch_signing_cert(cert_url)
if cert_pem is None:
- return False
+ # No certificate means no check ran, whether the fetch failed, a recent failure is still
+ # cached, or the budget for new URLs is spent. False would report a message AWS may have
+ # signed correctly as forged.
+ raise VerifierUnavailable("SNS signing certificate could not be obtained")
try:
public_key = load_pem_x509_certificate(cert_pem).public_key()
if not isinstance(public_key, RSAPublicKey):
diff --git a/products/workflows/backend/test/test_ses_events_webhook.py b/products/workflows/backend/test/test_ses_events_webhook.py
index 108356c751d0..eb139a6cfe48 100644
--- a/products/workflows/backend/test/test_ses_events_webhook.py
+++ b/products/workflows/backend/test/test_ses_events_webhook.py
@@ -6,6 +6,8 @@ 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"
@@ -83,6 +85,14 @@ class TestSesTenantEventsWebhook(TestCase):
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()))
diff --git a/products/workflows/backend/test/test_sns_verification.py b/products/workflows/backend/test/test_sns_verification.py
index 0785244dec56..1a441fb6d02e 100644
--- a/products/workflows/backend/test/test_sns_verification.py
+++ b/products/workflows/backend/test/test_sns_verification.py
@@ -15,6 +15,8 @@ from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.x509.oid import NameOID
from parameterized import parameterized
+from posthog.ingress.verify.errors import VerifierUnavailable
+
from products.workflows.backend.services.sns_verification import (
_MAX_UNKNOWN_CERT_FETCHES_PER_MINUTE,
_fetch_signing_cert,
@@ -121,14 +123,37 @@ class TestSigningCertFetch(SimpleTestCase):
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"})
+ @parameterized.expand(
+ [
+ ("path_sns_does_not_serve", "https://sns.us-east-1.amazonaws.com/evil.pem"),
+ ("host_outside_sns", "https://attacker.example.com/SimpleNotificationService-0123456789ab.pem"),
+ ]
+ )
+ 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:
assert verify_sns_message(message) is False
assert get.call_count == 0
+ @parameterized.expand(
+ [
+ ("connection_error", requests.ConnectionError("boom"), None),
+ ("timeout", requests.Timeout("too slow"), None),
+ ("server_error", None, requests.HTTPError("503 Server Error", response=requests.Response())),
+ ]
+ )
+ 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:
+ get.side_effect = fetch_error
+ get.return_value.raise_for_status.side_effect = status_error
+
+ with self.assertRaises(VerifierUnavailable):
+ verify_sns_message(_signed_notification())
+
def test_a_failed_fetch_is_not_retried_for_the_same_url(self) -> None:
with patch(
"products.workflows.backend.services.sns_verification.requests.get",