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): reject a bad signature header before reading the body (#102801)

Julian Bez7b28736c24ce
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 6cde6d1067aa..55be3a3e6699 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -25,6 +25,7 @@ Adding a provider is another `<provider>/` folder, not a change to the mechanism
1. **Method** — anything but `POST` is 405, before any secret is read.
2. **Throttle** — `provider.throttle_class`, when the provider sets one. A refusal is 429 with a `Retry-After`.
3. **Verify** — `provider.verify(request)` over the raw body, answering a `Verification`. A bad signature never reaches a consumer.
+ It asks `scheme.rejects_headers(request.headers)` first, so a signature header that is missing or the wrong shape is refused before `request.body` is read.
4. **Parse** — `provider.parse(request)`, which decodes the verified body. The default is JSON; an `InvalidPayload` is 400.
5. **Handshake** — `provider.pre_dispatch_response(request, payload)`, for a challenge the protocol demands.
6. **Dispatch** — `provider.deliveries(request, payload, facts)`, then ownership, the forward and the consumers, all inside one wall-clock budget.
@@ -46,6 +47,8 @@ An HMAC over raw bytes proves only the signature, so its `facts` are empty and `
`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.
+A scheme also answers `rejects_headers(headers)`, the part of the check that needs no body: `HmacSha256` refuses a missing or malformed signature header and a missing, malformed or stale timestamp header there, and `BearerJwt` refuses a request that carries no bearer token. The answer is the same INVALID the full check would reach, with the same status, log line and metric outcome, so an unauthenticated caller cannot make an endpoint read a body of up to the request limit for it. A scheme that cannot decide from headers alone answers `False`, which is what `SnsSignature` does, and so does an HMAC scheme whose secret is unset, so an unconfigured endpoint still answers NOT_CONFIGURED.
+
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.
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index 5d2a243265fb..1e2b14e178ec 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -17,7 +17,7 @@ from django.http import HttpRequest, HttpResponse
from rest_framework.throttling import BaseThrottle
from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
-from posthog.ingress.verify.schemes import SignatureScheme, Verification
+from posthog.ingress.verify.schemes import SignatureScheme, Verification, VerificationOutcome
# Every incarnation module, imported lazily. An incarnation exposes `SPECS` (what it accepts)
# and may expose `CORE_CONSUMERS` (consumers core owns rather than a product).
@@ -98,7 +98,12 @@ class WebhookProvider(ABC):
"""
def verify(self, request: HttpRequest) -> Verification:
- return self.scheme().verify(body=request.body, headers=request.headers)
+ scheme = self.scheme()
+ # Asked before `request.body`, so an unsigned probe cannot make every endpoint here
+ # read a body of up to the request limit before the signature header is even looked at.
+ if scheme.rejects_headers(request.headers):
+ return Verification(outcome=VerificationOutcome.INVALID)
+ return scheme.verify(body=request.body, headers=request.headers)
def parse(self, request: HttpRequest) -> Any:
"""Decode the verified body into the value `deliveries` reads.
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index fc3b6b8c4ebd..4f014bc7f241 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -72,6 +72,39 @@ class TestHmacSha256(SimpleTestCase):
scheme = HmacSha256(secret_getter=lambda: SECRET, signature_header="X-Signature", prefix="sha256=")
self.assertEqual(scheme.verify(body=BODY, headers=headers).outcome, expected)
+ @parameterized.expand(
+ [
+ ("missing_header", {}, True),
+ ("empty_header", {"X-Signature": ""}, True),
+ ("malformed_header", {"X-Signature": "not-a-digest"}, True),
+ ("missing_timestamp", {"X-Signature": "0" * 64}, True),
+ ("malformed_timestamp", {"X-Signature": "0" * 64, "X-Timestamp": "yesterday"}, True),
+ ("stale_timestamp", {"X-Signature": "0" * 64, "X-Timestamp": "1700000000"}, True),
+ ("well_formed", {"X-Signature": "0" * 64, "X-Timestamp": "now"}, False),
+ ("missing_header_but_no_secret", {}, False),
+ ]
+ )
+ def test_headers_alone_decide_whether_the_body_is_worth_reading(
+ self, _name: str, headers: dict[str, str], expected: bool
+ ) -> None:
+ # An unconfigured endpoint keeps its NOT_CONFIGURED answer, so the operator signal survives.
+ secret = "" if _name == "missing_header_but_no_secret" else SECRET
+ headers = {k: str(int(time.time())) if v == "now" else v for k, v in headers.items()}
+ scheme = HmacSha256(
+ secret_getter=lambda: secret,
+ signature_header="X-Signature",
+ signature_pattern=re.compile(r"^[0-9a-f]{64}$"),
+ signed_input="v0_timestamp_body",
+ timestamp_header="X-Timestamp",
+ )
+ self.assertEqual(scheme.rejects_headers(headers), expected)
+ # Every refusal here is the same verdict the full check would reach on those headers.
+ if expected:
+ self.assertEqual(
+ scheme.verify(body=BODY, headers=headers).outcome,
+ VerificationOutcome.INVALID,
+ )
+
def test_missing_secret_is_not_configured_rather_than_invalid(self) -> None:
scheme = HmacSha256(secret_getter=lambda: None, signature_header="X-Signature")
self.assertEqual(
@@ -243,6 +276,8 @@ class TestBearerJwt(SimpleTestCase):
headers = {} if template is None else {"Authorization": template.format(token=self._token())}
self.assertEqual(self._verify(self._scheme(), headers).outcome, VerificationOutcome.INVALID)
+ # The same verdict from the headers alone, so the body is never read for it.
+ self.assertTrue(self._scheme().rejects_headers(headers))
@parameterized.expand(
[
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 0df068e9af62..beb8fefdd5bd 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -5,7 +5,7 @@ from dataclasses import replace
from typing import Any, cast
from urllib.parse import urlencode
-from unittest.mock import Mock, patch
+from unittest.mock import Mock, PropertyMock, patch
from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -33,6 +33,7 @@ from posthog.ingress.github.provider import GitHubProvider, build_github_provide
from posthog.ingress.pandadoc.provider import build_pandadoc_provider
from posthog.ingress.providers import WebhookProvider
from posthog.ingress.slack.provider import build_slack_provider
+from posthog.ingress.vapi.provider import VapiProvider
from posthog.ingress.verify.schemes import Verification, VerificationOutcome
from posthog.ingress.views import build_webhook_view
from posthog.regions import SECONDARY_REGION_DOMAIN
@@ -198,6 +199,34 @@ class TestWebhookView(SimpleTestCase):
self.assertEqual(response.content, b"Invalid signature")
self.dispatcher.dispatch.assert_not_called()
+ @parameterized.expand(
+ [
+ ("missing_header", {}, False),
+ ("empty_header", {"X-Vapi-Signature": ""}, False),
+ ("malformed_header", {"X-Vapi-Signature": "not-a-digest"}, False),
+ ("well_formed_but_wrong_digest", {"X-Vapi-Signature": "0" * 64}, True),
+ ]
+ )
+ @override_settings(VAPI_WEBHOOK_SECRET=SECRET)
+ def test_a_signature_header_that_cannot_pass_is_refused_before_the_body_is_read(
+ self, _name: str, headers: dict[str, str], reads_body: bool
+ ) -> None:
+ request = self.factory.post(
+ "/webhooks/vapi/",
+ data=json.dumps({"message": {"type": "status-update"}}).encode(),
+ content_type="application/json",
+ headers=headers,
+ )
+
+ with patch.object(HttpRequest, "body", new_callable=PropertyMock, return_value=b"{}") as body:
+ response = build_webhook_view(VapiProvider())(request)
+
+ # Same answer either way, so only the body read separates the two paths.
+ self.assertEqual(response.status_code, 401)
+ self.assertEqual(response.content, b"Invalid signature")
+ self.assertEqual(body.called, reads_body)
+ self.dispatcher.dispatch.assert_not_called()
+
def test_an_unparseable_body_is_400_and_logs_the_parser_error(self) -> None:
body = b"{not json"
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
diff --git a/posthog/ingress/verify/jwt.py b/posthog/ingress/verify/jwt.py
index 489575eee242..f1babcb08d14 100644
--- a/posthog/ingress/verify/jwt.py
+++ b/posthog/ingress/verify/jwt.py
@@ -54,7 +54,12 @@ class BearerJwt:
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) :]
+ # A prefix with nothing behind it is no credential, so it is refused from the header
+ # alone rather than sent to the JWKS fetch to fail there.
+ return provided[len(self.token_prefix) :].strip() or None
+
+ def rejects_headers(self, headers: Mapping[str, str]) -> bool:
+ return self._token(headers) is None
def verify(self, *, body: bytes, headers: Mapping[str, str]) -> Verification:
# The header comes before the getters, unlike the HMAC scheme, because a getter that
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index 356ed6407632..427190b369ad 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -84,6 +84,14 @@ def signatures_match(expected: str, provided: str) -> bool:
class SignatureScheme(Protocol):
def verify(self, *, body: bytes, headers: Mapping[str, str]) -> Verification: ...
+ def rejects_headers(self, headers: Mapping[str, str]) -> bool:
+ """Whether the headers alone already fail the check, so the body need not be read.
+
+ `WebhookProvider.verify` asks this first, and a `True` answers exactly what an INVALID
+ verification answers. A scheme that cannot decide from headers alone answers `False`.
+ """
+ ...
+
@frozen
class HmacSha256:
@@ -121,22 +129,35 @@ class HmacSha256:
def _expected_signature(self, secret: str, signed: bytes) -> str:
return hmac_sha256_signature(secret, signed, encoding=self.encoding, prefix=self.prefix)
+ def _headers_fail(self, headers: Mapping[str, str]) -> bool:
+ provided = header_value(headers, self.signature_header)
+ if not provided:
+ return True
+ if self.signature_pattern is not None and not self.signature_pattern.match(provided):
+ return True
+ if self.timestamp_header is None:
+ return False
+ # Freshness needs only the clock, so a malformed or stale timestamp costs no body read either.
+ timestamp = header_value(headers, self.timestamp_header)
+ return not timestamp or not self._timestamp_is_fresh(timestamp)
+
+ def rejects_headers(self, headers: Mapping[str, str]) -> bool:
+ # An unconfigured endpoint keeps answering NOT_CONFIGURED, whatever the headers carry.
+ if not self.secret_getter():
+ return False
+ return self._headers_fail(headers)
+
def _outcome(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
secret = self.secret_getter()
if not secret:
return VerificationOutcome.NOT_CONFIGURED
-
- provided = header_value(headers, self.signature_header)
- if not provided:
- return VerificationOutcome.INVALID
- if self.signature_pattern is not None and not self.signature_pattern.match(provided):
+ if self._headers_fail(headers):
return VerificationOutcome.INVALID
- timestamp: str | None = None
- if self.timestamp_header is not None:
- timestamp = header_value(headers, self.timestamp_header)
- if not timestamp or not self._timestamp_is_fresh(timestamp):
- return VerificationOutcome.INVALID
+ # Present and well-shaped, because `rejects_headers` just said so.
+ provided = header_value(headers, self.signature_header) or ""
+
+ timestamp = header_value(headers, self.timestamp_header) if self.timestamp_header is not None else None
expected = self._expected_signature(secret, self._signed_bytes(body, timestamp))
if signatures_match(expected, provided):
@@ -161,6 +182,11 @@ class SnsSignature:
verify_message: Callable[[Mapping[str, Any]], bool]
allowed_topic_arns: Callable[[], frozenset[str]]
+ def rejects_headers(self, headers: Mapping[str, str]) -> bool:
+ # SNS signs the JSON envelope and carries nothing in the headers, so there is no
+ # header-only refusal to make here.
+ return False
+
def _outcome(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
allowed = self.allowed_topic_arns()
if not allowed: