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.

feat(ingress): provider-owned parsing, a throttle lane and verification facts (#101439)

Julian Bezdb4026ea8491
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.md
index f725cb90ccc6..cd53b12be703 100644
--- a/.agents/skills/adding-inbound-webhooks/SKILL.md
+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md
@@ -58,7 +58,10 @@ Copy `github/` for the full shape, or `vapi/` for a small one.
`provider.py` holds three things:
- `SPECS`, one `ProviderSpec` per app, naming the event types that app is subscribed to. The registry validates consumers against these.
-- A `WebhookProvider` subclass with `scheme()` (from `posthog/ingress/verify/`), `deliveries()` (how to read the event type, delivery id and context off the verified request), and any status codes the provider's protocol fixes. Defaults are 403 on a bad signature, 500 when unconfigured, 202 on success.
+- A `WebhookProvider` subclass with `scheme()` (from `posthog/ingress/verify/`), `deliveries(request, payload, facts)` (how to read the event type, delivery id and context off the verified request), and any status codes the provider's protocol fixes. Defaults are 403 on a bad signature, 500 when unconfigured, 202 on success.
+ - `verify(request)` answers a `Verification`: the outcome, plus `facts`, whatever the scheme proved on the way. A scheme that validates a signed token puts its verified claims there and `deliveries` cross-checks the body against them; an HMAC scheme leaves it empty and `deliveries` ignores it.
+ - `parse(request)` decodes the body, and defaults to JSON. Override it for a provider that posts a form, and raise `InvalidPayload` for a body it cannot read. Verification runs first and must, because reading `request.POST` consumes the request stream under ASGI.
+ - `throttle_class` names a DRF throttle from `posthog.rate_limit`, run in front of verification. Set one when the endpoint is public and its verification is expensive, such as a JWT signing-key lookup.
- 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.
Then:
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 2c2e6b19f20e..836e0375a071 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -18,6 +18,29 @@ All four lanes are **provider-generic**; each third party is an incarnation unde
Each provider has a `README.md` in its folder, which holds its headers, its scheme, its apps and secrets, its quirks and its consumers.
Adding a provider is another `<provider>/` folder, not a change to the mechanisms.
+## The lanes one request runs through
+
+`build_webhook_view()` runs the same lanes for every provider, in this order:
+
+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.
+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.
+
+Parse belongs to the provider because not every third party posts JSON: Slack's interactivity payloads and Mailgun's events are form-encoded.
+It stays **after** verification, and must: a `parse` that reads `request.POST` consumes the request stream under ASGI, which leaves the signature check without the raw bytes it signs over.
+
+The throttle sits **in front of** verification, because on a provider that signs with a JWT the verification is the expensive half.
+An unsigned request buys a signing-key lookup, so the cap has to be reached first or it caps nothing worth capping.
+`throttle_class` takes a DRF throttle from `posthog.rate_limit`, which is where every other rate belongs.
+A provider whose verification is a local HMAC leaves it at `None`.
+
+A `Verification` carries the outcome and `facts`, a mapping of what the check proved on the way.
+A 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.
+
## Endpoints
| Provider | Path | App | Consumers | Product code |
@@ -33,7 +56,8 @@ Adding a provider is another `<provider>/` folder, not a change to the mechanism
The GitHub endpoints and the SES one are declared in `posthog/urls.py`.
The others are declared by the product that owns them.
-The Vapi endpoint sits behind a per-IP throttle the product owns, because ingress has no throttle lane and the endpoint is public.
+The Vapi endpoint sits behind a per-IP throttle the product owns, from before ingress had a throttle lane.
+It moves onto `throttle_class` next.
## Non-goals
@@ -148,7 +172,7 @@ That is the transport deciding the response, not a consumer.
Add 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. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well.
+- 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. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well. Two more hooks are optional: `parse()`, which decodes the body, and `throttle_class`, which caps request volume. See [The lanes one request runs through](#the-lanes-one-request-runs-through).
- A `build_<provider>_provider(...)` function returning that provider, which the URLconf hands to `build_webhook_view()`.
Add the module to `_INCARNATION_MODULES` in `posthog/ingress/providers.py`, so the registry finds its specs and any core consumers.
@@ -184,7 +208,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`, `not_configured`, `invalid_signature`, `invalid_payload`, `forward_failed`. A consumer failure is not here, because a failing consumer still gets a 2xx receipt.
+- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `throttled`, `not_configured`, `invalid_signature`, `invalid_payload`, `forward_failed`. A consumer failure is not here, because a failing consumer still gets a 2xx receipt.
- **`posthog_ingress_consumer_runs_total{provider,consumer,outcome}`** — `succeeded`, `failed`, `deduped`, `budget_exceeded`.
- **`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/github/provider.py b/posthog/ingress/github/provider.py
index 8ab1b6764262..3066a30eb41b 100644
--- a/posthog/ingress/github/provider.py
+++ b/posthog/ingress/github/provider.py
@@ -85,7 +85,7 @@ class GitHubProvider(WebhookProvider):
def scheme(self) -> SignatureScheme:
return self._scheme
- def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
if not isinstance(payload, Mapping):
return ()
return (
diff --git a/posthog/ingress/observability/metrics.py b/posthog/ingress/observability/metrics.py
index 08c4cedcbff5..964aded29cdb 100644
--- a/posthog/ingress/observability/metrics.py
+++ b/posthog/ingress/observability/metrics.py
@@ -10,6 +10,7 @@ from prometheus_client import Counter, Histogram
DeliveryOutcome = Literal[
"accepted",
"method_not_allowed",
+ "throttled",
"not_configured",
"invalid_signature",
"invalid_payload",
diff --git a/posthog/ingress/pandadoc/provider.py b/posthog/ingress/pandadoc/provider.py
index 78e40ebc530f..68eb9d4501af 100644
--- a/posthog/ingress/pandadoc/provider.py
+++ b/posthog/ingress/pandadoc/provider.py
@@ -15,7 +15,7 @@ from django.utils import timezone
from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
from posthog.ingress.providers import WebhookProvider
-from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme, VerificationOutcome, header_value
+from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme, Verification, VerificationOutcome, header_value
PANDADOC_EVENT_TYPES = frozenset({"document_state_changed"})
PANDADOC_SIGNATURE_HEADER = "X-PandaDoc-Signature"
@@ -47,11 +47,11 @@ class PandaDocProvider(WebhookProvider):
def scheme(self) -> SignatureScheme:
return self._scheme
- def verify(self, request: HttpRequest) -> VerificationOutcome:
+ def verify(self, request: HttpRequest) -> Verification:
# A deployment that does not run the integration answers 404 before it reads anything off
# the request, so the route stays indistinguishable from one that was never registered.
if self._enabled is not None and not self._enabled():
- return VerificationOutcome.INVALID
+ return Verification(outcome=VerificationOutcome.INVALID)
# Read through the scheme's own case-insensitive lookup, because Django normalizes a
# header name to title case and an exact-case match would never find this one.
# Presence decides, not truthiness: an empty header is a signature that fails, never a
@@ -64,7 +64,7 @@ class PandaDocProvider(WebhookProvider):
headers={PANDADOC_SIGNATURE_HEADER: request.GET.get("signature", "")},
)
- def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
events = payload if isinstance(payload, list) else [payload]
received_at = timezone.now()
deliveries: list[WebhookDelivery] = []
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index be72e81c62f0..e5716814bf5a 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -6,15 +6,18 @@ not import a product, and it must stay cheap to import, because the registry imp
one of these on the first delivery.
"""
+import json
import importlib
from abc import ABC, abstractmethod
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from typing import Any
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, VerificationOutcome
+from posthog.ingress.verify.schemes import SignatureScheme, Verification
# Every incarnation module, imported lazily. An incarnation exposes `SPECS` (what it accepts)
# and may expose `CORE_CONSUMERS` (consumers core owns rather than a product).
@@ -27,6 +30,14 @@ _INCARNATION_MODULES = (
)
+class InvalidPayload(Exception):
+ """A body the provider could not decode.
+
+ Carries the decoder's own message, which the view logs and never answers with: what the
+ parser tripped over is a hint to an unauthenticated caller about how PostHog reads a body.
+ """
+
+
class WebhookProvider(ABC):
"""One provider app: how a delivery is verified, and how it is read.
@@ -40,6 +51,12 @@ class WebhookProvider(ABC):
invalid_signature_status: int = 403
unconfigured_status: int = 500
success_status: int = 202
+ # A DRF throttle the view runs in front of verification, for a public endpoint whose
+ # verification is expensive: Teams signs with a JWT, so the first thing an unsigned request
+ # costs is a signing-key lookup. `None` runs no throttle, which is right for an endpoint
+ # whose verification is a local HMAC. It must be a fixed-rate throttle: `build_webhook_view`
+ # refuses a `ScopedRateThrottle`, whose scope lives on a view this one does not have.
+ throttle_class: type[BaseThrottle] | None = None
# Answered instead of the receipt when the forward to the owning region fails, so a provider
# that redelivers on a non-2xx tries again (Slack does, GitHub does not). `None` keeps the
# receipt. This is the one documented exception to "consumers never decide the response": the
@@ -54,12 +71,29 @@ class WebhookProvider(ABC):
"""The signature scheme for this app's secret."""
@abstractmethod
- def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
- """Read zero or more deliveries out of one verified, parsed request."""
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ """Read zero or more deliveries out of one verified, parsed request.
- def verify(self, request: HttpRequest) -> VerificationOutcome:
+ `facts` is what the signature scheme proved on the way, such as a signed token's
+ verified claims. It is empty for a scheme that only checks an HMAC.
+ """
+
+ def verify(self, request: HttpRequest) -> Verification:
return self.scheme().verify(body=request.body, headers=request.headers)
+ def parse(self, request: HttpRequest) -> Any:
+ """Decode the verified body into the value `deliveries` reads.
+
+ JSON is the default because every provider here posts JSON. A provider that posts a
+ form instead (Slack interactivity, Mailgun) overrides this and reads `request.POST`.
+ Raise `InvalidPayload` for a body this provider cannot read, and the view answers 400.
+ """
+ try:
+ # RecursionError: deeply nested JSON must answer 400, not 500.
+ return json.loads(request.body)
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError) as error:
+ raise InvalidPayload(str(error)) from error
+
def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:
"""A handshake the protocol demands, answered before any consumer runs.
diff --git a/posthog/ingress/slack/provider.py b/posthog/ingress/slack/provider.py
index c366df004def..9f0bb0b20c3b 100644
--- a/posthog/ingress/slack/provider.py
+++ b/posthog/ingress/slack/provider.py
@@ -53,7 +53,7 @@ class SlackProvider(WebhookProvider):
return JsonResponse({"challenge": str(payload.get("challenge", ""))})
return None
- def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
if not isinstance(payload, Mapping) or payload.get("type") != "event_callback":
return ()
event = payload.get("event")
diff --git a/posthog/ingress/sns/provider.py b/posthog/ingress/sns/provider.py
index 7decbb411b63..354b631cfd6d 100644
--- a/posthog/ingress/sns/provider.py
+++ b/posthog/ingress/sns/provider.py
@@ -36,7 +36,7 @@ class SnsProvider(WebhookProvider):
def scheme(self) -> SignatureScheme:
return self._scheme
- def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
if not isinstance(payload, Mapping):
return ()
message_id = payload.get("MessageId")
diff --git a/posthog/ingress/test/test_github.py b/posthog/ingress/test/test_github.py
index 4578ed611e53..d8356b4c8b24 100644
--- a/posthog/ingress/test/test_github.py
+++ b/posthog/ingress/test/test_github.py
@@ -33,11 +33,11 @@ class TestGitHubProvider(SimpleTestCase):
scheme = build_github_provider(app).scheme()
self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(own_secret)}),
+ scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(own_secret)}).outcome,
VerificationOutcome.VERIFIED,
)
self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(other_secret)}),
+ scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(other_secret)}).outcome,
VerificationOutcome.INVALID,
)
diff --git a/posthog/ingress/test/test_pandadoc.py b/posthog/ingress/test/test_pandadoc.py
index d14e245f2024..21c1898cd93b 100644
--- a/posthog/ingress/test/test_pandadoc.py
+++ b/posthog/ingress/test/test_pandadoc.py
@@ -39,7 +39,7 @@ class TestPandaDocProvider(SimpleTestCase):
headers={} if header is None else {"X-PandaDoc-Signature": header},
)
- self.assertEqual(build_pandadoc_provider().verify(request), expected)
+ self.assertEqual(build_pandadoc_provider().verify(request).outcome, expected)
def test_a_disabled_deployment_rejects_a_correctly_signed_body(self) -> None:
request = RequestFactory().post(
@@ -51,10 +51,10 @@ class TestPandaDocProvider(SimpleTestCase):
provider = build_pandadoc_provider(enabled=lambda: False)
- self.assertEqual(provider.verify(request), VerificationOutcome.INVALID)
+ self.assertEqual(provider.verify(request).outcome, VerificationOutcome.INVALID)
def test_a_missing_secret_is_not_configured_rather_than_a_bad_signature(self) -> None:
request = RequestFactory().post("/webhooks/pandadoc/", data=BODY, content_type="application/json")
with override_settings(PANDADOC_WEBHOOK_SECRET=""):
- self.assertEqual(build_pandadoc_provider().verify(request), VerificationOutcome.NOT_CONFIGURED)
+ self.assertEqual(build_pandadoc_provider().verify(request).outcome, VerificationOutcome.NOT_CONFIGURED)
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index 90579c29dc9f..28919c6ff311 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -37,19 +37,20 @@ class TestHmacSha256(SimpleTestCase):
encoding=encoding, # type: ignore[arg-type]
)
+ verification = scheme.verify(body=BODY, headers={"X-Signature": prefix + encoded})
+ self.assertEqual(verification.outcome, VerificationOutcome.VERIFIED)
+ # An HMAC over the raw body proves the sender holds the secret and nothing else, so it
+ # hands `deliveries` nothing to cross-check the body against.
+ self.assertEqual(verification.facts, {})
self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Signature": prefix + encoded}),
- VerificationOutcome.VERIFIED,
- )
- self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Signature": encoded}),
+ scheme.verify(body=BODY, headers={"X-Signature": encoded}).outcome,
VerificationOutcome.VERIFIED if prefix == "" else VerificationOutcome.INVALID,
)
def test_header_lookup_is_case_insensitive(self) -> None:
scheme = HmacSha256(secret_getter=lambda: SECRET, signature_header="X-Hub-Signature-256", prefix="sha256=")
self.assertEqual(
- scheme.verify(body=BODY, headers={"x-hub-signature-256": "sha256=" + _digest().hex()}),
+ scheme.verify(body=BODY, headers={"x-hub-signature-256": "sha256=" + _digest().hex()}).outcome,
VerificationOutcome.VERIFIED,
)
@@ -65,12 +66,12 @@ class TestHmacSha256(SimpleTestCase):
self, _name: str, headers: dict[str, str], expected: VerificationOutcome
) -> None:
scheme = HmacSha256(secret_getter=lambda: SECRET, signature_header="X-Signature", prefix="sha256=")
- self.assertEqual(scheme.verify(body=BODY, headers=headers), expected)
+ self.assertEqual(scheme.verify(body=BODY, headers=headers).outcome, expected)
def test_missing_secret_is_not_configured_rather_than_invalid(self) -> None:
scheme = HmacSha256(secret_getter=lambda: None, signature_header="X-Signature")
self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Signature": _digest().hex()}),
+ scheme.verify(body=BODY, headers={"X-Signature": _digest().hex()}).outcome,
VerificationOutcome.NOT_CONFIGURED,
)
@@ -89,10 +90,10 @@ class TestHmacSha256(SimpleTestCase):
"X-Slack-Request-Timestamp": timestamp,
}
- self.assertEqual(scheme.verify(body=BODY, headers=headers), VerificationOutcome.VERIFIED)
+ self.assertEqual(scheme.verify(body=BODY, headers=headers).outcome, VerificationOutcome.VERIFIED)
# The same signature over the body alone must not pass, or the replay window is decorative.
self.assertEqual(
- scheme.verify(body=BODY, headers={**headers, "X-Slack-Signature": "v0=" + _digest().hex()}),
+ scheme.verify(body=BODY, headers={**headers, "X-Slack-Signature": "v0=" + _digest().hex()}).outcome,
VerificationOutcome.INVALID,
)
@@ -116,7 +117,7 @@ class TestHmacSha256(SimpleTestCase):
signed = b"v0:" + timestamp.encode() + b":" + BODY
headers = {"X-Signature": _digest(signed).hex(), "X-Timestamp": timestamp}
- self.assertEqual(scheme.verify(body=BODY, headers=headers), VerificationOutcome.INVALID)
+ self.assertEqual(scheme.verify(body=BODY, headers=headers).outcome, VerificationOutcome.INVALID)
def test_signature_pattern_rejects_before_the_digest_runs(self) -> None:
scheme = HmacSha256(
@@ -126,7 +127,7 @@ class TestHmacSha256(SimpleTestCase):
)
with patch("hmac.digest") as digest:
self.assertEqual(
- scheme.verify(body=BODY, headers={"X-Vapi-Signature": "NOT-A-HEX-DIGEST"}),
+ scheme.verify(body=BODY, headers={"X-Vapi-Signature": "NOT-A-HEX-DIGEST"}).outcome,
VerificationOutcome.INVALID,
)
digest.assert_not_called()
@@ -159,14 +160,16 @@ 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={}), VerificationOutcome(expected))
+ self.assertEqual(
+ self._scheme(verified=verified).verify(body=body, headers={}).outcome, 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={}),
+ self._scheme(allowed=frozenset()).verify(body=body, headers={}).outcome,
VerificationOutcome.NOT_CONFIGURED,
)
def test_unparseable_body_is_invalid_rather_than_raising(self) -> None:
- self.assertEqual(self._scheme().verify(body=b"not json", headers={}), VerificationOutcome.INVALID)
+ self.assertEqual(self._scheme().verify(body=b"not json", headers={}).outcome, VerificationOutcome.INVALID)
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 077505835381..f327580891a0 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -1,15 +1,21 @@
import hmac
import json
-from typing import cast
+from collections.abc import Mapping, Sequence
+from dataclasses import replace
+from typing import Any, cast
+from urllib.parse import urlencode
from unittest.mock import Mock, patch
from django.core.cache import cache
+from django.http import HttpRequest
from django.test import RequestFactory, SimpleTestCase, override_settings
import structlog.testing
from parameterized import parameterized
from requests import RequestException
+from rest_framework.request import Request as DRFRequest
+from rest_framework.throttling import BaseThrottle, ScopedRateThrottle
from posthog.ingress.contracts import DeliveryOwnership, ProviderSpec, WebhookConsumer, WebhookDelivery
from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
@@ -19,6 +25,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.verify.schemes import Verification, VerificationOutcome
from posthog.ingress.views import build_webhook_view
from posthog.regions import SECONDARY_REGION_DOMAIN
@@ -45,6 +52,44 @@ class _RedeliveringGitHubProvider(GitHubProvider):
forward_failure_status = 502
+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.
+ def verify(self, request: HttpRequest) -> Verification:
+ return Verification(outcome=VerificationOutcome.VERIFIED, facts={"tenant_id": "t-1"})
+
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ return [replace(delivery, context=dict(facts)) for delivery in super().deliveries(request, payload, facts)]
+
+
+class _StubThrottle(BaseThrottle):
+ allowed = False
+ wait_seconds: float | None = None
+
+ def allow_request(self, request: DRFRequest, view: object) -> bool:
+ return self.allowed
+
+ def wait(self) -> float | None:
+ return self.wait_seconds
+
+
+class _ThrottledGitHubProvider(GitHubProvider):
+ # Stands in for a provider whose verification is expensive enough to cap in front of, the way
+ # a JWT signing-key lookup is.
+ throttle_class = _StubThrottle
+
+
+class _ScopedThrottleGitHubProvider(GitHubProvider):
+ throttle_class = ScopedRateThrottle
+
+
+class _FormBodyGitHubProvider(GitHubProvider):
+ # Stands in for a provider that posts a form rather than JSON, the way Slack's interactivity
+ # payloads and Mailgun's events do.
+ def parse(self, request: HttpRequest) -> Any:
+ return json.loads(request.POST["payload"])
+
+
class TestWebhookView(SimpleTestCase):
def setUp(self) -> None:
self.factory = RequestFactory()
@@ -74,6 +119,54 @@ class TestWebhookView(SimpleTestCase):
secret.assert_not_called()
self.dispatcher.dispatch.assert_not_called()
+ @parameterized.expand(
+ [
+ ("a_throttle_that_says_how_long", 30.4, "31"),
+ ("a_throttle_that_does_not", None, None),
+ ]
+ )
+ def test_a_throttled_request_is_429_before_any_signature_is_checked(
+ self, _name: str, wait_seconds: float | None, retry_after: str | None
+ ) -> 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.github.provider.get_instance_setting", return_value=SECRET) as secret,
+ patch.object(_StubThrottle, "wait_seconds", wait_seconds),
+ patch("posthog.ingress.views.observe_delivery") as observe,
+ ):
+ response = build_webhook_view(_ThrottledGitHubProvider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 429)
+ self.assertEqual(response.headers.get("Retry-After"), retry_after)
+ self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], ["throttled"])
+ # The cap is worth having only if it lands before the signing key is read.
+ secret.assert_not_called()
+ self.dispatcher.dispatch.assert_not_called()
+
+ def test_a_scoped_throttle_is_refused_when_the_view_is_built(self) -> None:
+ with self.assertRaises(TypeError) as raised:
+ build_webhook_view(_ScopedThrottleGitHubProvider("posthog"))
+
+ # A scoped throttle finds no scope here and permits everything, so the endpoint would
+ # look capped and answer 202 to every request.
+ self.assertIn("github/posthog", str(raised.exception))
+ self.assertIn("ScopedRateThrottle", str(raised.exception))
+
+ def test_a_throttle_that_allows_the_request_changes_nothing(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.github.provider.get_instance_setting", return_value=SECRET),
+ patch.object(_StubThrottle, "allowed", True),
+ ):
+ response = build_webhook_view(_ThrottledGitHubProvider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 202)
+ self.dispatcher.dispatch.assert_called_once()
+
def test_a_bad_signature_is_403_and_never_reaches_a_consumer(self) -> None:
body = json.dumps({"action": "opened"}).encode()
request = self._post(body, {"X-Hub-Signature-256": "sha256=" + "0" * 64, "X-GitHub-Event": "pull_request"})
@@ -121,6 +214,15 @@ class TestWebhookView(SimpleTestCase):
self.assertEqual(delivery.delivery_id, "delivery-1")
self.assertEqual(delivery.context, {"installation_id": "42"})
+ def test_what_the_signature_check_proved_reaches_deliveries(self) -> None:
+ body = json.dumps({"action": "opened"}).encode()
+ request = self._post(body, {"X-GitHub-Event": "issues"})
+
+ response = build_webhook_view(_ClaimsGitHubProvider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 202)
+ self.assertEqual(self.dispatcher.dispatch.call_args.args[0].context, {"tenant_id": "t-1"})
+
def test_a_batched_body_becomes_several_deliveries_that_share_one_budget(self) -> None:
body = json.dumps([{"event": "document_state_changed"}, {"event": "document_state_changed"}]).encode()
request = self.factory.post(
@@ -170,6 +272,23 @@ class TestWebhookView(SimpleTestCase):
self.assertEqual(response.content, b"")
self.dispatcher.dispatch.assert_not_called()
+ def test_a_parse_override_reads_a_form_body_and_still_reaches_deliveries(self) -> None:
+ body = urlencode({"payload": json.dumps({"action": "opened", "installation": {"id": 42}})}).encode()
+ request = self.factory.post(
+ "/webhooks/github/",
+ data=body,
+ content_type="application/x-www-form-urlencoded",
+ headers={"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "pull_request"},
+ )
+
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ response = build_webhook_view(_FormBodyGitHubProvider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 202)
+ delivery = self.dispatcher.dispatch.call_args.args[0]
+ self.assertEqual(delivery.payload, {"action": "opened", "installation": {"id": 42}})
+ self.assertEqual(delivery.context, {"installation_id": "42"})
+
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/vapi/provider.py b/posthog/ingress/vapi/provider.py
index 36025572994c..f307f251ff57 100644
--- a/posthog/ingress/vapi/provider.py
+++ b/posthog/ingress/vapi/provider.py
@@ -45,7 +45,7 @@ class VapiProvider(WebhookProvider):
def scheme(self) -> SignatureScheme:
return self._scheme
- def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
if not isinstance(payload, Mapping):
return ()
message = payload.get("message")
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index 5bfc20cded34..740f61ec3cd9 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -6,6 +6,7 @@ import json
import time
import base64
from collections.abc import Callable, Mapping
+from dataclasses import field
from enum import StrEnum
from typing import Any, Literal, Protocol
@@ -27,6 +28,21 @@ class VerificationOutcome(StrEnum):
NOT_CONFIGURED = "not_configured"
+@frozen
+class Verification:
+ """What a signature check concluded, and what it proved on the way.
+
+ A scheme that checks a signed token learns more than "this is really them": the claims it
+ validated name the sender and the audience. `facts` carries those to `deliveries`, so an
+ incarnation can cross-check the body against what was actually signed, rather than trusting
+ a field of the body that says the same thing. An HMAC over raw bytes proves nothing beyond
+ the signature and leaves `facts` empty.
+ """
+
+ outcome: VerificationOutcome
+ facts: Mapping[str, Any] = field(default_factory=dict)
+
+
def header_value(headers: Mapping[str, str], name: str) -> str | None:
"""Read a header from either Django's case-insensitive mapping or a plain dict."""
value = headers.get(name)
@@ -59,7 +75,7 @@ def signatures_match(expected: str, provided: str) -> bool:
class SignatureScheme(Protocol):
- def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome: ...
+ def verify(self, *, body: bytes, headers: Mapping[str, str]) -> Verification: ...
@frozen
@@ -98,7 +114,7 @@ class HmacSha256:
def _expected_signature(self, secret: str, signed: bytes) -> str:
return hmac_sha256_signature(secret, signed, encoding=self.encoding, prefix=self.prefix)
- def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
+ def _outcome(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
secret = self.secret_getter()
if not secret:
return VerificationOutcome.NOT_CONFIGURED
@@ -120,6 +136,11 @@ class HmacSha256:
return VerificationOutcome.VERIFIED
return VerificationOutcome.INVALID
+ def verify(self, *, body: bytes, headers: Mapping[str, str]) -> Verification:
+ # No facts: an HMAC over the raw body proves the sender holds the secret and says
+ # nothing else about the delivery.
+ return Verification(outcome=self._outcome(body=body, headers=headers))
+
@frozen
class SnsSignature:
@@ -133,7 +154,7 @@ class SnsSignature:
verify_message: Callable[[Mapping[str, Any]], bool]
allowed_topic_arns: Callable[[], frozenset[str]]
- def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
+ def _outcome(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
allowed = self.allowed_topic_arns()
if not allowed:
return VerificationOutcome.NOT_CONFIGURED
@@ -151,3 +172,8 @@ class SnsSignature:
logger.warning("ingress_sns_invalid_signature", message_id=message.get("MessageId"))
return VerificationOutcome.INVALID
return VerificationOutcome.VERIFIED
+
+ def verify(self, *, body: bytes, headers: Mapping[str, str]) -> Verification:
+ # No facts: the allowlist and the RSA check both read the body the incarnation parses
+ # again, so there is nothing here that `deliveries` cannot see for itself.
+ return Verification(outcome=self._outcome(body=body, headers=headers))
diff --git a/posthog/ingress/views.py b/posthog/ingress/views.py
index 5757c77dc8c7..3ef0a48040a0 100644
--- a/posthog/ingress/views.py
+++ b/posthog/ingress/views.py
@@ -1,31 +1,65 @@
-"""The one inbound webhook view: verify, parse, dispatch, answer a fixed receipt."""
+"""The one inbound webhook view: throttle, verify, parse, dispatch, answer a fixed receipt."""
-import json
+import math
from collections.abc import Callable
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import structlog
+from rest_framework.request import Request as DRFRequest
+from rest_framework.throttling import ScopedRateThrottle
from posthog.ingress.contracts import DeliveryOwnership
from posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds
from posthog.ingress.dispatch.forward import forward_to_secondary_region
from posthog.ingress.dispatch.loading import get_dispatcher
from posthog.ingress.observability.metrics import observe_delivery
-from posthog.ingress.providers import WebhookProvider
+from posthog.ingress.providers import InvalidPayload, WebhookProvider
from posthog.ingress.verify.schemes import VerificationOutcome
from posthog.regions import is_primary_region
logger = structlog.get_logger(__name__)
+def _throttle_refusal(provider: WebhookProvider, request: HttpRequest) -> HttpResponse | None:
+ """The 429 this provider's throttle asks for, or `None` when the request may continue."""
+ throttle_class = provider.throttle_class
+ if throttle_class is None:
+ return None
+
+ throttle = throttle_class()
+ # DRF throttles read a DRF request and this is a plain Django view, so the request is
+ # wrapped rather than the throttle reimplemented: the rates live in `posthog.rate_limit`
+ # with every other throttle, and a wrapped request carries the headers they key on.
+ if throttle.allow_request(DRFRequest(request), view=None): # type: ignore[arg-type]
+ return None
+
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="throttled")
+ response = HttpResponse(status=429)
+ wait = throttle.wait()
+ if wait is not None:
+ # Rounded up, so a caller that obeys the header comes back after the window rather
+ # than inside it and spends its next attempt on another 429.
+ response["Retry-After"] = str(math.ceil(wait))
+ return response
+
+
def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], HttpResponse]:
"""A Django view for one provider app.
- The response is a transport receipt. Verification, method and payload decide the status;
- consumers never do, and their return values are ignored.
+ The response is a transport receipt. The method, the throttle, verification and the payload
+ decide the status; consumers never do, and their return values are ignored.
"""
+ # Refused at build rather than per request, because the failure is silent at request time:
+ # a ScopedRateThrottle reads its rate from the view's `throttle_scope`, finds none here, and
+ # permits every request. An endpoint that looks capped and is not is worse than no cap.
+ if provider.throttle_class is not None and issubclass(provider.throttle_class, ScopedRateThrottle):
+ raise TypeError(
+ f"Provider {provider.provider}/{provider.app} sets a ScopedRateThrottle. "
+ "A scoped throttle reads its scope off a view, and this webhook view has none, "
+ "so it would permit every request. Use a fixed-rate throttle from posthog.rate_limit."
+ )
@csrf_exempt
def webhook_view(request: HttpRequest) -> HttpResponse:
@@ -33,25 +67,37 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
observe_delivery(provider=provider.provider, app=provider.app, outcome="method_not_allowed")
return HttpResponse(status=405)
- outcome = provider.verify(request)
- if outcome is VerificationOutcome.NOT_CONFIGURED:
+ # The throttle runs in front of verification, because on a provider that signs with a
+ # JWT the verification is the expensive half: an unsigned request would otherwise buy
+ # a signing-key lookup before anything caps how many of them arrive.
+ throttled = _throttle_refusal(provider, request)
+ if throttled is not None:
+ return throttled
+
+ verification = provider.verify(request)
+ if verification.outcome is VerificationOutcome.NOT_CONFIGURED:
logger.error("ingress_webhook_not_configured", provider=provider.provider, app=provider.app)
observe_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 outcome is not VerificationOutcome.VERIFIED:
+ 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 ""
return HttpResponse(reason, status=provider.invalid_signature_status)
+ # Parse after verification, and keep that order: a provider that reads a form body
+ # overrides `parse` and reads `request.POST`, and under ASGI that read consumes the
+ # stream, so `request.body` is no longer available to the signature check afterwards.
try:
- # RecursionError: deeply nested JSON must answer 400, not 500.
- payload = json.loads(request.body)
- except (json.JSONDecodeError, UnicodeDecodeError, RecursionError) as exc:
+ payload = provider.parse(request)
+ except InvalidPayload as error:
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_payload")
logger.warning(
- "ingress_delivery_invalid_payload", provider=provider.provider, app=provider.app, error=str(exc)
+ "ingress_delivery_invalid_payload",
+ provider=provider.provider,
+ app=provider.app,
+ error=str(error),
)
- observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_payload")
return HttpResponse("Invalid JSON", status=400)
handshake = provider.pre_dispatch_response(request, payload)
@@ -60,7 +106,7 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
return handshake
dispatcher = get_dispatcher()
- deliveries = provider.deliveries(request, payload)
+ deliveries = provider.deliveries(request, payload, verification.facts)
# One budget for the whole request, not one per delivery: PandaDoc turns a batched body
# into many deliveries, and a budget each would hold the request open for the sum. It
# starts before the ownership lookups, which read the database and forward on the same