: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(auth): delegate webhook HMAC verification to ingress (#100888)
Julian Bezc31986de635b
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex 89968e9ed395..8183ff61f8eb 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -7,8 +7,8 @@ rules:scheme and the delivery parsing, hand it to `build_webhook_view()` in the URLconf,and register the handlers in `products/<product>/backend/webhook_consumers.py`.An endpoint that genuinely needs DRF team scoping (Customer.io) keeps its view and- subclasses `WebhookSignatureAuthentication`; that class moves onto the ingress schemes- in its own PR. `posthog/ingress/README.md` holds the transport contract.+ subclasses `WebhookSignatureAuthentication`, which itself verifies through the ingress+ schemes. `posthog/ingress/README.md` holds the transport contract.Why: a hand-rolled verifier repeats the parts that are easy to get wrong, theconstant-time compare, the replay window and the exact signed input, and it lands@@ -117,7 +117,6 @@ rules:- /ee/api/vercel/vercel_webhooks.py- /ee/partners/stripe/api/provisioning/signature.py- /posthog/api/github_webhooks/signature.py- - /posthog/auth.py- /posthog/models/integration/slack.py- /products/conversations/backend/api/github_events.py- /products/conversations/backend/api/slack_events.pydiff --git a/posthog/auth.py b/posthog/auth.pyindex 4e47bb3dd0eb..7d4aa9d7c545 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -1,7 +1,6 @@import reimport hmacimport time-import hashlibimport loggingimport functoolsfrom abc import abstractmethod@@ -32,6 +31,7 @@ from posthog.clickhouse.query_tagging import AccessMethod, tag_authenticationfrom posthog.constants import AvailableFeaturefrom posthog.helpers.two_factor_session import enforce_two_factorfrom posthog.helpers.verified_domain_enforcement import enforce_verified_domain+from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_matchfrom posthog.internal_api_secret import usable_internal_api_secretsfrom posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, get_oidc_verification_keysfrom posthog.models.activity_logging.utils import activity_storage@@ -1512,12 +1512,8 @@ class WebhookSignatureAuthentication(authentication.BaseAuthentication):raw_body = django_request.body.decode()hmac_input = self.build_hmac_input(timestamp, raw_body)- expected = hmac.new(- signing_secret.encode(),- hmac_input.encode(),- hashlib.sha256,- ).hexdigest()- if not hmac.compare_digest(signature, expected):+ expected = hmac_sha256_signature(signing_secret, hmac_input.encode())+ if not signatures_match(expected, signature):raise AuthenticationFailed("Invalid webhook signature.")try:diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex d9b56200eade..a602d5da0bc0 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -143,7 +143,9 @@ Last, write `<provider>/README.md` with the fixed sections every provider READMETwo shapes that already exist and are worth copying rather than re-deriving:- **Several apps on one provider.** One incarnation can serve several apps, each with its own secret getter, its own subscribed event types, and its own consumer set. Consumers register against the app name. `github/` is the case.-- **The DRF adapter path.** An endpoint that genuinely needs DRF's team scoping keeps its view, and the incarnation contributes a scheme only, declaring no spec, because nothing dispatches there. `customerio/` is the case. The view verifies through `posthog.auth.WebhookSignatureAuthentication`, which still carries its own HMAC-SHA256 computation rather than the scheme here; moving that class onto the schemes is its own PR.+- **The DRF adapter path.** An endpoint that genuinely needs DRF's team scoping keeps its view, and the incarnation contributes a scheme only, declaring no spec, because nothing dispatches there. `customerio/` is the case. The view verifies through `posthog.auth.WebhookSignatureAuthentication`.+ That base class computes its digest with `hmac_sha256_signature()` and compares with `signatures_match()` from `verify/schemes.py`, so the adapter path and the dispatched path share one implementation of HMAC-SHA256.+ It backs three endpoints rather than Customer.io alone, because the tasks cross-region usage lookup and the AI observability cross-region spend lookup subclass it too, each with its own header names, signed-input format, and secret.## Dedupdiff --git a/posthog/ingress/customerio/README.md b/posthog/ingress/customerio/README.mdindex f99e37a19d24..dbb803173602 100644--- a/posthog/ingress/customerio/README.md+++ b/posthog/ingress/customerio/README.md@@ -28,8 +28,8 @@ The secret is per team: it comes from that team's messaging integration row rathThis is the DRF adapter path.`posthog.auth.WebhookSignatureAuthentication` does the verifying, and the view answers 200 for an event it does not handle.-That class still carries its own HMAC-SHA256 computation rather than the scheme described above, so the scheme here documents the shape without being on the request path yet.-Moving the class onto the ingress schemes is its own PR.+That class delegates the HMAC-SHA256 computation and the constant-time compare to `posthog/ingress/verify/schemes.py`, so the adapter path and the dispatched path share one implementation.+It still assembles the signed input and checks the replay window itself, which is why the scheme here is not yet the object on the request path.Reach for this path only when an endpoint genuinely needs DRF's team scoping.Everything else goes through `build_webhook_view()`.diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.pyindex f0cd2c834f03..5bfc20cded34 100644--- a/posthog/ingress/verify/schemes.py+++ b/posthog/ingress/verify/schemes.py@@ -39,6 +39,25 @@ def header_value(headers: Mapping[str, str], name: str) -> str | None:return None+def hmac_sha256_signature(+ secret: str,+ signed: bytes,+ *,+ encoding: SignatureEncoding = "hex",+ prefix: str = "",+) -> str:+ digest = hmac.digest(secret.encode("utf-8"), signed, "sha256")+ encoded = base64.b64encode(digest).decode("ascii") if encoding == "base64" else digest.hex()+ return prefix + encoded+++def signatures_match(expected: str, provided: str) -> bool:+ # Compared as bytes, because compare_digest raises TypeError on a str that holds a+ # non-ASCII code point, and a header arrives here decoded as latin-1. An unauthenticated+ # caller could otherwise turn a junk header into a 500.+ return hmac.compare_digest(expected.encode("utf-8"), provided.encode("utf-8"))++class SignatureScheme(Protocol):def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome: ...@@ -77,9 +96,7 @@ class HmacSha256:return bodydef _expected_signature(self, secret: str, signed: bytes) -> str:- digest = hmac.digest(secret.encode("utf-8"), signed, "sha256")- encoded = base64.b64encode(digest).decode("ascii") if self.encoding == "base64" else digest.hex()- return self.prefix + encoded+ return hmac_sha256_signature(secret, signed, encoding=self.encoding, prefix=self.prefix)def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:secret = self.secret_getter()@@ -99,10 +116,7 @@ class HmacSha256:return VerificationOutcome.INVALIDexpected = self._expected_signature(secret, self._signed_bytes(body, timestamp))- # Compared as bytes, because compare_digest raises TypeError on a str that holds a- # non-ASCII code point, and a header arrives here decoded as latin-1. An unauthenticated- # caller could otherwise turn a junk header into a 500.- if hmac.compare_digest(expected.encode("utf-8"), provided.encode("utf-8")):+ if signatures_match(expected, provided):return VerificationOutcome.VERIFIEDreturn VerificationOutcome.INVALIDdiff --git a/products/tasks/backend/tests/test_task_usage_api.py b/products/tasks/backend/tests/test_task_usage_api.pyindex 309712801baa..603d7ad49c49 100644--- a/products/tasks/backend/tests/test_task_usage_api.py+++ b/products/tasks/backend/tests/test_task_usage_api.py@@ -1,17 +1,30 @@+import json+import timefrom datetime import UTC, datetimefrom decimal import Decimalfrom uuid import UUID+from posthog.test.base import APIBaseTestfrom unittest.mock import patch-from django.test import SimpleTestCase+from django.test import SimpleTestCase, override_settings+from parameterized import parameterized+from rest_framework import statusfrom rest_framework.parsers import JSONParserfrom rest_framework.request import Requestfrom rest_framework.test import APIRequestFactory+from products.tasks.backend.logic.services.task_usage import (+ TASK_USAGE_INTERNAL_PATH,+ TASK_USAGE_SIGNATURE_HEADER,+ TASK_USAGE_TIMESTAMP_HEADER,+ sign_task_usage_request,+)from products.tasks.backend.presentation.views.task_usage_api import InternalTaskUsageViewSet+CROSS_REGION_SECRET = "test-cross-region-secret"+class TestInternalTaskUsageViewSet(SimpleTestCase):@patch(@@ -41,3 +54,74 @@ class TestInternalTaskUsageViewSet(SimpleTestCase):task_id=UUID("00000000-0000-0000-0000-000000000001"),task_created_at=datetime(2026, 8, 1, tzinfo=UTC),)+++class TestInternalTaskUsageAuthentication(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ overrides = override_settings(PERSONAL_SPEND_CROSS_REGION_SECRET=CROSS_REGION_SECRET)+ overrides.enable()+ self.addCleanup(overrides.disable)+ # No session, so the endpoint stands on the signature alone.+ self.client.logout()+ token_cost = patch(+ "products.tasks.backend.presentation.views.task_usage_api.get_local_task_token_cost",+ return_value=Decimal("1.25"),+ )+ self.get_token_cost = token_cost.start()+ self.addCleanup(token_cost.stop)+ self.body = json.dumps(+ {+ "team_id": self.team.id,+ "task_id": str(UUID("00000000-0000-0000-0000-000000000001")),+ "task_created_at": datetime(2026, 8, 1, tzinfo=UTC).isoformat(),+ }+ ).encode()++ def _post(self, headers: dict[str, str]):+ return self.client.post(+ TASK_USAGE_INTERNAL_PATH,+ data=self.body,+ content_type="application/json",+ headers=headers,+ )++ def _signed_headers(self, *, secret: str = CROSS_REGION_SECRET, timestamp: int | None = None) -> dict[str, str]:+ signed = sign_task_usage_request(self.body, secret, timestamp=timestamp)+ return {+ TASK_USAGE_SIGNATURE_HEADER: signed.signature,+ TASK_USAGE_TIMESTAMP_HEADER: signed.timestamp,+ }++ @parameterized.expand(+ [+ ("wrong_secret", "a-different-secret", 0, None),+ ("stale_timestamp", CROSS_REGION_SECRET, -3600, None),+ # WSGI decodes header bytes as latin-1, so a junk byte reaches the adapter as a+ # str holding a non-ASCII code point. That shape used to raise out of+ # compare_digest and turn an unauthenticated request into a 500.+ ("non_ascii_signature", CROSS_REGION_SECRET, 0, "sha256=\xe9"),+ ]+ )+ def test_rejects_a_request_the_signature_does_not_vouch_for(+ self, _name: str, secret: str, timestamp_offset: int, signature_override: str | None+ ) -> None:+ headers = self._signed_headers(secret=secret, timestamp=int(time.time()) + timestamp_offset)+ if signature_override is not None:+ headers[TASK_USAGE_SIGNATURE_HEADER] = signature_override++ response = self._post(headers)++ assert response.status_code == status.HTTP_401_UNAUTHORIZED+ self.get_token_cost.assert_not_called()++ def test_signed_request_authenticates_and_returns_the_token_cost(self) -> None:+ response = self._post(self._signed_headers())++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json() == {"token_cost_usd": 1.25}+ self.get_token_cost.assert_called_once_with(+ team_id=self.team.id,+ task_id=UUID("00000000-0000-0000-0000-000000000001"),+ task_created_at=datetime(2026, 8, 1, tzinfo=UTC),+ )