: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(ingress): add a bearer JWT scheme verified against a JWKS (#101491)
Julian Bez5491f4269122
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.mdindex 12dc199c4d13..a2affa826781 100644--- a/.agents/skills/adding-inbound-webhooks/SKILL.md+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md@@ -65,6 +65,14 @@ Copy `github/` for the full shape, or `vapi/` for a small one.- `retry_status` is the status answered instead of the receipt when ingress cannot vouch that the delivery was accepted: the forward to the owning region failed, a consumer raised, or the budget skipped a consumer. Set it when the provider redelivers on a non-2xx, and leave it `None` when it does not, because the non-2xx then only loses the delivery. A retry replays the delivery against every consumer on the endpoint, and dedup is what stops the ones that already accepted it from running twice.- A `build_<provider>_provider(...)` function returning it. Secrets and verifiers a product owns are **passed into this builder**, never imported: nothing under `posthog/ingress/` may import a product.+### Picking a scheme++Three exist. Configure one; do not write a fourth without reading [the Schemes section of the package README](../../../posthog/ingress/README.md#schemes).++- `HmacSha256` (`verify/schemes.py`) — a shared secret over the raw body. Covers hex or base64, an optional prefix, and the `v0:{timestamp}:{body}` input with a replay window that Slack and Customer.io sign. GitHub, Slack, PandaDoc, Vapi and Customer.io all use it.+- `SnsSignature` (`verify/schemes.py`) — the AWS SNS envelope check plus a topic-ARN allowlist. The RSA work stays with a caller-supplied verifier.+- `BearerJwt` (`verify/jwt.py`) — a `Bearer` token signed as a JWT, checked against the issuer's published JWKS. Its `facts` are the verified claims. The incarnation supplies the JWKS URI, the audience and the issuer allowlist as callables, and caches any discovery it does to find the URI. An endpoint on this scheme sets `throttle_class`, because an unsigned request costs a signing-key lookup.+Then:1. Add the module path to `_INCARNATION_MODULES` in `posthog/ingress/providers.py`, or the registry never sees its specs or core consumers.diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 3807d9c86dbf..9ad300471640 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -4,7 +4,7 @@ General-purpose controls for the webhooks third parties send _in_ to PostHog.A new inbound webhook that needs signature verification or fan-out belongs here as a `<provider>/` incarnation (see [Adding a provider](#adding-a-provider)), never hand-rolled around `hmac` in a view.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), plus the SNS envelope check.+- **`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.- **`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.@@ -41,6 +41,17 @@ A `Verification` carries the outcome and `facts`, a mapping of what the check prA scheme that validates a signed token knows who sent the delivery before the body is read, and `facts` is how those claims reach `deliveries`, so an incarnation can cross-check the body against what was actually signed rather than trusting a field of the body that claims the same thing.An HMAC over raw bytes proves only the signature, so its `facts` are empty and `deliveries` ignores the argument.+## Schemes++`verify/schemes.py` holds `HmacSha256` and `SnsSignature`; `verify/jwt.py` holds `BearerJwt`, for a provider that authenticates with a signed token instead of a shared secret.+Each class docstring carries its own reasoning.++Three duties fall on the incarnation rather than on `BearerJwt`, and none is enforced:++- **Key discovery.** The scheme takes a `jwks_uri_getter`, so a provider that publishes its `jwks_uri` inside an OpenID metadata document fetches that document in the getter.+- **Caching that discovery.** `verify` calls the getter on every delivery. A getter that fetches and does not cache puts an HTTP round trip on every request, which is what the `PyJWKClient` cache inside the scheme exists to avoid.+- **Validating a discovered URI.** A `jwks_uri` read out of a remote document is not a value an operator set, so the getter passes it through `is_url_allowed` before returning it, the way `posthog/api/id_jag.py` guards its own discovered JWKS URI. The check belongs next to the fetch, not in the scheme, because only the getter knows whether the URI came from configuration or from a third party.+## Endpoints| Provider | Path | App | Consumers | Product code |@@ -81,6 +92,7 @@ A consumer that wants asynchronous work enqueues its own task and answers immedi**Ingress does not let a consumer decide the response.**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.What the transport does decide is whether it can vouch that the delivery was taken.It cannot 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.@@ -239,7 +251,7 @@ A provider that sends no delivery id skips dedup entirely, and its own README sa## Observability-- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `throttled`, `not_configured`, `invalid_signature`, `invalid_payload`, `forward_failed`, `retry_requested`. A consumer failure lands here only on a provider that sets `retry_status`; everywhere else it is counted on the consumer metric alone, because the delivery still gets its receipt.+- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `throttled`, `not_configured`, `verify_unavailable`, `invalid_signature`, `invalid_payload`, `forward_failed`, `retry_requested`. A consumer failure lands here only on a provider that sets `retry_status`; everywhere else it is counted on the consumer metric alone, because the delivery still gets its receipt.- **`posthog_ingress_consumer_runs_total{provider,consumer,outcome}`** — `succeeded`, `failed`, `deduped`, `budget_exceeded`, `in_flight`.- **`posthog_ingress_consumer_duration_seconds{provider,consumer}`** — where a delivery's budget actually went.- **`posthog_ingress_ownership_total{provider,consumer,outcome}`** — what a consumer answered when asked which region owns the delivery: `local`, `elsewhere`, `undecided`, `failed`.diff --git a/posthog/ingress/observability/metrics.py b/posthog/ingress/observability/metrics.pyindex d1be84a48072..c42e4b64f0b4 100644--- a/posthog/ingress/observability/metrics.py+++ b/posthog/ingress/observability/metrics.py@@ -13,6 +13,7 @@ DeliveryOutcome = Literal["method_not_allowed","throttled","not_configured",+ "verify_unavailable","invalid_signature","invalid_payload","forward_failed",diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.pyindex 28919c6ff311..fc3b6b8c4ebd 100644--- a/posthog/ingress/test/test_verify.py+++ b/posthog/ingress/test/test_verify.py@@ -2,14 +2,18 @@ import reimport hmacimport timeimport base64+from types import SimpleNamespacefrom unittest.mock import patchfrom django.test import SimpleTestCase+import jwt+from cryptography.hazmat.primitives.asymmetric import rsafrom parameterized import parameterized-from posthog.ingress.verify.schemes import HmacSha256, SnsSignature, VerificationOutcome+from posthog.ingress.verify.jwt import _JWKS_CLIENTS, BearerJwt, _jwks_client+from posthog.ingress.verify.schemes import HmacSha256, SnsSignature, Verification, VerificationOutcomeSECRET = "s3cret"BODY = b'{"action":"opened"}'@@ -173,3 +177,137 @@ 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)+++JWKS_URI = "https://login.example.com/v1/.well-known/keys"+AUDIENCE = "00000000-0000-0000-0000-000000000001"+ISSUER = "https://api.issuer.example.com"+SERVICE_URL = "https://connector.example.com/emea/"+KEY_ID = "signing-key-1"+++class TestBearerJwt(SimpleTestCase):+ private_key: rsa.RSAPrivateKey++ @classmethod+ def setUpClass(cls) -> None:+ super().setUpClass()+ cls.private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)++ def setUp(self) -> None:+ # The client map is module-global, so a test must not inherit another test's clients.+ _JWKS_CLIENTS.clear()+ self.addCleanup(_JWKS_CLIENTS.clear)++ def _token(self, *, expires_in_seconds: int | None = 300, **claims: str) -> str:+ payload: dict[str, object] = {"iss": ISSUER, "aud": AUDIENCE, "serviceurl": SERVICE_URL, **claims}+ if expires_in_seconds is not None:+ payload["exp"] = int(time.time()) + expires_in_seconds+ return jwt.encode(payload, self.private_key, algorithm="RS256", headers={"kid": KEY_ID})++ def _scheme(+ self,+ *,+ jwks_uri: str | None = JWKS_URI,+ audience: str | None = AUDIENCE,+ issuers: frozenset[str] = frozenset({ISSUER}),+ ) -> BearerJwt:+ return BearerJwt(+ jwks_uri_getter=lambda: jwks_uri,+ audience_getter=lambda: audience,+ issuers_getter=lambda: issuers,+ )++ def _verify(self, scheme: BearerJwt, headers: dict[str, str]) -> Verification:+ # The JWKS fetch is the only boundary mocked here; the decode below it is the real one.+ signing_key = SimpleNamespace(key=self.private_key.public_key())+ with patch.object(jwt.PyJWKClient, "get_signing_key_from_jwt", return_value=signing_key):+ return scheme.verify(body=BODY, headers=headers)++ def test_verified_token_hands_its_claims_to_deliveries(self) -> None:+ verification = self._verify(self._scheme(), {"Authorization": "Bearer " + self._token()})++ self.assertEqual(verification.outcome, VerificationOutcome.VERIFIED)+ self.assertEqual(verification.facts["iss"], ISSUER)+ self.assertEqual(verification.facts["aud"], AUDIENCE)+ self.assertEqual(verification.facts["serviceurl"], SERVICE_URL)++ @parameterized.expand(+ [+ ("missing_header", None),+ ("another_auth_scheme", "Basic {token}"),+ ("token_without_the_bearer_prefix", "{token}"),+ ]+ )+ def test_rejects_a_request_that_carries_no_bearer_token(self, _name: str, template: str | None) -> None:+ headers = {} if template is None else {"Authorization": template.format(token=self._token())}++ self.assertEqual(self._verify(self._scheme(), headers).outcome, VerificationOutcome.INVALID)++ @parameterized.expand(+ [+ ("foreign_issuer", {"iss": "https://issuer.example.org"}, 300),+ ("audience_of_another_app", {"aud": "00000000-0000-0000-0000-000000000002"}, 300),+ ("expired_beyond_the_leeway", {}, -3600),+ ("no_expiry_claim", {}, None),+ ]+ )+ def test_rejects_a_token_this_app_must_not_accept(+ self, _name: str, claims: dict[str, str], expires_in_seconds: int | None+ ) -> None:+ token = self._token(expires_in_seconds=expires_in_seconds, **claims)++ headers = {"Authorization": "Bearer " + token}+ self.assertEqual(self._verify(self._scheme(), headers).outcome, VerificationOutcome.INVALID)++ def test_rejects_a_tampered_signature(self) -> None:+ header, payload, signature = self._token().split(".")+ # The first character, not the last: base64 drops the last one's padding bits, so+ # flipping it can leave the signature bytes unchanged.+ flipped = ("A" if signature[0] != "A" else "B") + signature[1:]++ headers = {"Authorization": f"Bearer {header}.{payload}.{flipped}"}+ self.assertEqual(self._verify(self._scheme(), headers).outcome, VerificationOutcome.INVALID)++ @parameterized.expand(+ [+ (+ "key_id_the_jwks_does_not_serve",+ jwt.PyJWKClientError("unable to find a key"),+ VerificationOutcome.INVALID,+ ),+ (+ "jwks_that_could_not_be_fetched",+ jwt.PyJWKClientConnectionError("connection error"),+ VerificationOutcome.UNAVAILABLE,+ ),+ ]+ )+ def test_a_signing_key_failure_separates_the_token_from_the_fetch(+ self, _name: str, error: Exception, expected: VerificationOutcome+ ) -> None:+ headers = {"Authorization": "Bearer " + self._token()}++ with patch.object(jwt.PyJWKClient, "get_signing_key_from_jwt", side_effect=error):+ outcome = self._scheme().verify(body=BODY, headers=headers).outcome+ self.assertEqual(outcome, expected)++ @parameterized.expand(+ [+ ("no_jwks_uri", None, AUDIENCE, frozenset({ISSUER})),+ ("no_audience", JWKS_URI, None, frozenset({ISSUER})),+ ("no_issuers", JWKS_URI, AUDIENCE, frozenset()),+ ]+ )+ def test_missing_configuration_is_not_configured_rather_than_invalid(+ self, _name: str, jwks_uri: str | None, audience: str | None, issuers: frozenset[str]+ ) -> None:+ scheme = self._scheme(jwks_uri=jwks_uri, audience=audience, issuers=issuers)++ headers = {"Authorization": "Bearer " + self._token()}+ self.assertEqual(self._verify(scheme, headers).outcome, VerificationOutcome.NOT_CONFIGURED)++ def test_reuses_one_jwks_client_per_uri(self) -> None:+ # The client holds the key cache, so a client per delivery is a JWKS fetch per delivery.+ self.assertIs(_jwks_client(JWKS_URI), _jwks_client(JWKS_URI))+ self.assertIsNot(_jwks_client(JWKS_URI), _jwks_client("https://login.example.org/keys"))diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.pyindex 4c13f3835426..95e5d2fb9793 100644--- a/posthog/ingress/test/test_views.py+++ b/posthog/ingress/test/test_views.py@@ -64,6 +64,12 @@ class _SlowForwardGitHubProvider(GitHubProvider):forward_timeout_seconds = 10.0+class _UnavailableVerifyGitHubProvider(GitHubProvider):+ # Stands in for a scheme whose network step failed, which is the JWKS fetch on `BearerJwt`.+ def verify(self, request: HttpRequest) -> Verification:+ return Verification(outcome=VerificationOutcome.UNAVAILABLE)++class _ClaimsGitHubProvider(GitHubProvider):# Stands in for a scheme that checks a signed token, which names the sender before the body# is parsed. The claims land in the delivery's context so the test can read them back.@@ -302,6 +308,18 @@ class TestWebhookView(SimpleTestCase):self.assertEqual(delivery.payload, {"action": "opened", "installation": {"id": 42}})self.assertEqual(delivery.context, {"installation_id": "42"})+ def test_a_verification_that_could_not_run_is_503_rather_than_the_invalid_signature_status(self) -> None:+ body = json.dumps({"action": "opened"}).encode()+ request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "issues"})++ with patch("posthog.ingress.views.observe_delivery") as observe:+ response = build_webhook_view(_UnavailableVerifyGitHubProvider("posthog"))(request)++ # 403 would tell a sender that retries server errors only to drop a valid delivery.+ self.assertEqual(response.status_code, 503)+ self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], ["verify_unavailable"])+ self.dispatcher.dispatch.assert_not_called()+def test_slack_url_verification_echoes_the_challenge_before_dispatch(self) -> None:body = json.dumps({"type": "url_verification", "challenge": "abc123"}).encode()timestamp = "1789000000"diff --git a/posthog/ingress/verify/jwt.py b/posthog/ingress/verify/jwt.pynew file mode 100644index 000000000000..489575eee242--- /dev/null+++ b/posthog/ingress/verify/jwt.py@@ -0,0 +1,102 @@+"""The bearer-token scheme: a provider that authenticates with a JWT rather than an HMAC."""++from collections.abc import Callable, Mapping++import jwt+import structlog++from posthog.dataclasses import frozen+from posthog.ingress.verify.schemes import Verification, VerificationOutcome, header_value++logger = structlog.get_logger(__name__)++# PyJWT defaults to 30 seconds, which holds a webhook request open long after the provider+# gave up on it. The same value guards the JWKS fetch in `posthog/api/id_jag.py`.+_JWKS_FETCH_TIMEOUT_SECONDS = 10++# The client holds the key cache, so one per URI rather than one per request. The URIs are fixed+# by the incarnations mounted in the process, which is why nothing evicts here.+_JWKS_CLIENTS: dict[str, jwt.PyJWKClient] = {}+++def _jwks_client(jwks_uri: str) -> jwt.PyJWKClient:+ client = _JWKS_CLIENTS.get(jwks_uri)+ if client is None:+ client = jwt.PyJWKClient(jwks_uri, timeout=_JWKS_FETCH_TIMEOUT_SECONDS)+ _JWKS_CLIENTS[jwks_uri] = client+ return client+++@frozen+class BearerJwt:+ """A bearer token signed as a JWT, checked against the signing keys the issuer publishes.++ Every provider-specific value arrives as a callable, so the scheme itself holds no URL, no+ app id and no issuer. That also keeps the provider's discovery out of here: Bot Framework+ publishes its `jwks_uri` in an OpenID metadata document, and fetching that document is the+ incarnation's `jwks_uri_getter`, not this scheme's job. A getter that fetches must cache its+ own answer, because `verify` calls it on every delivery.++ The verified claims become `facts`, because a signed token proves more than "this is really+ them". It names the sender and the audience, so `deliveries` can hold the body to what the+ issuer actually signed rather than to a field of the body that claims the same thing.+ """++ jwks_uri_getter: Callable[[], str | None]+ audience_getter: Callable[[], str | None]+ issuers_getter: Callable[[], frozenset[str]]+ algorithms: tuple[str, ...] = ("RS256",)+ leeway_seconds: int = 300+ token_header: str = "Authorization"+ token_prefix: str = "Bearer "++ def _token(self, headers: Mapping[str, str]) -> str | None:+ provided = header_value(headers, self.token_header)+ if not provided or not provided.startswith(self.token_prefix):+ return None+ return provided[len(self.token_prefix) :]++ def verify(self, *, body: bytes, headers: Mapping[str, str]) -> Verification:+ # The header comes before the getters, unlike the HMAC scheme, because a getter that+ # discovers its `jwks_uri` costs an HTTP request a token-less probe must not buy.+ token = self._token(headers)+ if token is None:+ return Verification(outcome=VerificationOutcome.INVALID)++ jwks_uri = self.jwks_uri_getter()+ audience = self.audience_getter()+ issuers = self.issuers_getter()+ # An empty issuer allowlist rejects every token that will ever arrive, so it is an+ # operator problem rather than a caller one, the same as a missing secret.+ if not jwks_uri or not audience or not issuers:+ return Verification(outcome=VerificationOutcome.NOT_CONFIGURED)++ try:+ signing_key = _jwks_client(jwks_uri).get_signing_key_from_jwt(token)+ claims = jwt.decode(+ token,+ signing_key.key,+ algorithms=list(self.algorithms),+ audience=audience,+ issuer=issuers,+ leeway=self.leeway_seconds,+ # Without this, a token that carries no `exp` never expires.+ options={"require": ["exp"]},+ )+ except jwt.PyJWKClientConnectionError as error:+ # The JWKS fetch never completed, so the token was never checked. INVALID here hands a+ # 403 to a provider that retries server errors only, which drops a valid delivery for+ # good over a DNS blip or a JWKS outage.+ logger.warning("ingress_jwt_signing_keys_unreachable", error_type=type(error).__name__)+ return Verification(outcome=VerificationOutcome.UNAVAILABLE)+ except jwt.PyJWKClientError as error:+ # The JWKS was read and holds no key this token can use, which is the token's problem.+ logger.warning("ingress_jwt_signing_key_unavailable", error_type=type(error).__name__)+ return Verification(outcome=VerificationOutcome.INVALID)+ except jwt.InvalidTokenError as error:+ # The error class alone: the token is a credential and its claims are the caller's+ # data, so neither belongs in a log an unauthenticated request drives.+ logger.warning("ingress_jwt_rejected", error_type=type(error).__name__)+ return Verification(outcome=VerificationOutcome.INVALID)++ return Verification(outcome=VerificationOutcome.VERIFIED, facts=claims)diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.pyindex 740f61ec3cd9..356ed6407632 100644--- a/posthog/ingress/verify/schemes.py+++ b/posthog/ingress/verify/schemes.py@@ -1,4 +1,9 @@-"""Signature schemes: the part of a provider incarnation that decides "this is really them"."""+"""Signature schemes: the part of a provider incarnation that decides "this is really them".++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.+"""import reimport hmac@@ -26,6 +31,8 @@ class VerificationOutcome(StrEnum):# The instance holds no secret for this provider app, which is an operator problem# rather than a caller one, so incarnations answer it with their own status code.NOT_CONFIGURED = "not_configured"+ # Verification could not run right now, so the sender is asked to retry.+ UNAVAILABLE = "unavailable"@frozendiff --git a/posthog/ingress/views.py b/posthog/ingress/views.pyindex c05d1e744232..9ac575decb95 100644--- a/posthog/ingress/views.py+++ b/posthog/ingress/views.py@@ -82,6 +82,13 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httobserve_delivery(provider=provider.provider, app=provider.app, outcome="not_configured")reason = "Webhook not configured" if provider.explains_rejections else ""return HttpResponse(reason, status=provider.unconfigured_status)+ if verification.outcome is VerificationOutcome.UNAVAILABLE:+ # The check never ran, so nothing here is the caller's fault. 503 asks any sender that+ # retries a server error to send the delivery again, which the invalid-signature status+ # would not: that one reads as a verdict on the signature.+ logger.warning("ingress_verify_unavailable", provider=provider.provider, app=provider.app)+ observe_delivery(provider=provider.provider, app=provider.app, outcome="verify_unavailable")+ return HttpResponse("Verification unavailable", status=503)if verification.outcome is not VerificationOutcome.VERIFIED:observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_signature")reason = "Invalid signature" if provider.explains_rejections else ""