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): add inbound webhook transport package (#100292)

Julian Bez3e1d24bcd1a6
diff --git a/posthog/api/github_webhooks/attribution.py b/posthog/api/github_webhooks/attribution.py
index 71c24678999a..30a25a641960 100644
--- a/posthog/api/github_webhooks/attribution.py
+++ b/posthog/api/github_webhooks/attribution.py
@@ -1,14 +1,8 @@
-from collections.abc import Iterator
-from contextlib import ExitStack, contextmanager
-
-from django.conf import settings
-from django.db import OperationalError, connections, router, transaction
-from django.db.backends.base.base import BaseDatabaseWrapper
-
import structlog
from social_django.models import UserSocialAuth
from posthog.api.github_webhooks.metrics import GitHubWebhookAttributionOutcome, observe_github_webhook_attribution
+from posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeout
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
@@ -32,91 +26,6 @@ _ATTRIBUTION_STATEMENT_TIMEOUT_MS = 800
_ATTRIBUTION_MODELS = (Team, User, OrganizationMembership, UserSocialAuth, UserIntegration, Integration)
-def _attribution_db_aliases() -> list[str]:
- """The aliases the org-member lookup actually reads from, deduped, in model order.
-
- Bounding an alias means opening it, and opening is itself unbounded -- ``postgres_config``
- sets no ``connect_timeout`` on these aliases. So take the set from the router rather than
- assuming: reaching for an alias the resolver never uses could stall the webhook on
- connection setup before the cap is installed, which is the failure this exists to prevent.
- That cuts both ways -- a fully replica-opted deployment must not be made to wait on the
- primary either.
- """
- aliases: list[str] = []
- for model in _ATTRIBUTION_MODELS:
- alias = router.db_for_read(model) or "default"
- if alias not in aliases and alias in settings.DATABASES:
- aliases.append(alias)
- return aliases
-
-
-def _read_statement_timeout(connection: BaseDatabaseWrapper) -> str | None:
- with connection.cursor() as cursor:
- cursor.execute("SHOW statement_timeout")
- row = cursor.fetchone()
- return row[0] if row else None
-
-
-def _apply_statement_timeout(connection: BaseDatabaseWrapper, value: str) -> None:
- # set_config(..., is_local=True) is SET LOCAL, but takes the value as a bind parameter,
- # so a restored value ("30s", "0", ...) does not have to be quoted by hand.
- with connection.cursor() as cursor:
- cursor.execute("SELECT set_config('statement_timeout', %s, true)", [value])
-
-
-@contextmanager
-def _statement_timeout(connection: BaseDatabaseWrapper, timeout_ms: int, *, restore: bool) -> Iterator[None]:
- """Cap statements on one connection, optionally putting the previous value back."""
- previous = _read_statement_timeout(connection) if restore else None
- _apply_statement_timeout(connection, f"{timeout_ms}ms")
-
- yield
-
- # Only reached when the block succeeded. If it raised, the enclosing atomic() rolls the
- # (sub)transaction back and PostgreSQL undoes SET LOCAL with it, so there is nothing to
- # restore -- and a statement on an aborted transaction would error anyway.
- if previous:
- _apply_statement_timeout(connection, previous)
-
-
-@contextmanager
-def _bounded_attribution_lookup() -> Iterator[None]:
- """Run a block under a per-statement timeout on each configured DB the lookup may use.
-
- A read routed to an alias joins that alias's open transaction, so ``SET LOCAL
- statement_timeout`` there caps the query regardless of read-replica routing.
- """
- with ExitStack() as stack:
- for alias in _attribution_db_aliases():
- connection = connections[alias]
- # SET LOCAL dies with the transaction it was set in, so the cap only needs
- # restoring when we are joining a transaction somebody else owns -- a future
- # caller wrapping this in its own atomic block, or ATOMIC_REQUESTS (which
- # PostHog does not enable today). Otherwise the commit below ends it for us.
- restore = connection.in_atomic_block
- stack.enter_context(transaction.atomic(using=alias))
- stack.enter_context(_statement_timeout(connection, _ATTRIBUTION_STATEMENT_TIMEOUT_MS, restore=restore))
- yield
-
-
-# PostgreSQL raises query_canceled when statement_timeout fires. Django wraps the driver
-# error in OperationalError, so the SQLSTATE lives on the cause -- psycopg3 spells it
-# `sqlstate`, psycopg2 `pgcode`. The message check is the fallback for anything that loses
-# the cause on the way up.
-_QUERY_CANCELED_SQLSTATE = "57014"
-
-
-def _is_statement_timeout(error: Exception) -> bool:
- if not isinstance(error, OperationalError):
- return False
- cause = error.__cause__
- if getattr(cause, "sqlstate", None) == _QUERY_CANCELED_SQLSTATE:
- return True
- if getattr(cause, "pgcode", None) == _QUERY_CANCELED_SQLSTATE:
- return True
- return "statement timeout" in str(error).lower()
-
-
def _resolve_github_login_distinct_id(login: str | None, team_id: int) -> str | None:
"""Distinct id of the org member matching a GitHub login, or None when unresolvable.
@@ -126,13 +35,13 @@ def _resolve_github_login_distinct_id(login: str | None, team_id: int) -> str |
if not login:
return None
try:
- with _bounded_attribution_lookup():
+ with bounded_statement_timeout(_ATTRIBUTION_STATEMENT_TIMEOUT_MS, models=_ATTRIBUTION_MODELS):
resolved = resolve_github_login_distinct_id(str(login), team_id)
except Exception as e:
# timeout is meant to be the leading indicator for the cap we just installed, so it
# has to mean "statement cancelled", not "any OperationalError" -- connection resets
# and other DB incidents raise the same class and would drown the signal.
- outcome: GitHubWebhookAttributionOutcome = "timeout" if _is_statement_timeout(e) else "error"
+ outcome: GitHubWebhookAttributionOutcome = "timeout" if is_statement_timeout(e) else "error"
observe_github_webhook_attribution(outcome=outcome)
logger.warning(
"github_webhook_login_resolution_failed", login=login, team_id=team_id, outcome=outcome, error=str(e)
diff --git a/posthog/api/test/test_github_webhooks.py b/posthog/api/test/test_github_webhooks.py
index 0b1cb1a1e807..a3e7f2240eec 100644
--- a/posthog/api/test/test_github_webhooks.py
+++ b/posthog/api/test/test_github_webhooks.py
@@ -53,7 +53,7 @@ class TestProductPullRequestAttribution(SimpleTestCase):
patch(
"posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id", return_value="reviewer-id"
),
- patch("posthog.api.github_webhooks.attribution._bounded_attribution_lookup"),
+ patch("posthog.api.github_webhooks.attribution.bounded_statement_timeout"),
patch(
"posthog.api.github_webhooks.pull_requests._resolve_github_login_distinct_id",
return_value="reviewer-id",
diff --git a/posthog/ingress/AGENTS.md b/posthog/ingress/AGENTS.md
new file mode 100644
index 000000000000..56b726d2c678
--- /dev/null
+++ b/posthog/ingress/AGENTS.md
@@ -0,0 +1,9 @@
+# Inbound webhook verification & dispatch
+
+Read the README before adding a provider, changing a scheme, or touching the registry.
+Read a provider's own `README.md` before changing that provider.
+A change to a provider's headers, signature scheme, delivery id, apps and secrets, or consumers updates that provider's `README.md` in the same PR.
+A provider folder without a `README.md` fails `posthog/ingress/test/test_provider_readme_sections.py`.
+Three things are easy to re-derive wrong: the response is a transport receipt (a consumer never decides the status), a consumer's `name` is a dedup cache key (renaming one lets a redelivery run twice), and nothing here may import a product — product-owned secrets and verifiers are passed into the provider builder.
+
diff --git a/posthog/ingress/CLAUDE.md b/posthog/ingress/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/posthog/ingress/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
new file mode 100644
index 000000000000..fa59f6c1168f
--- /dev/null
+++ b/posthog/ingress/README.md
@@ -0,0 +1,163 @@
+# Inbound ingress: verification, dispatch, transport
+
+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.
+- **`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.
+
+Two more modules sit at the package root because every lane and every incarnation speaks them: `contracts.py` holds the three values (`WebhookDelivery`, `WebhookConsumer`, `ProviderSpec`), and `providers.py` holds the `WebhookProvider` base each incarnation subclasses plus the lazy import list that finds the incarnations.
+
+This is _inbound_ ingress — what PostHog receives.
+It is the sibling of `posthog/egress/`, which is what PostHog sends, and unrelated to `posthog.rate_limit`, which throttles inbound DRF requests from PostHog's own clients.
+
+All four lanes are **provider-generic**; each third party is an incarnation under its own subpackage, supplying header names, a scheme, and how to read an event type and a delivery id off the request.
+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.
+
+## Endpoints
+
+| Provider | Path | App | Consumers | Product code |
+| ------------ | ------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
+| `github` | `/webhooks/github`, `/webhooks/github/pr` | `posthog` | `installation_lifecycle`, `installation_repositories` (core), `conversations`, `loops`, `tasks_pr_backstop`, `tasks_pr_review`, `workflows` | `products/{tasks,conversations,workflows}/backend/webhook_consumers.py` |
+| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
+| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
+| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
+| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
+| `sns` | `/webhooks/workflows/ses-events` | `default` | `workflows_ses_events` | `products/workflows/backend/webhook_consumers.py` |
+| `customerio` | `/api/projects/<team_id>/messaging/customerio/webhook/` | none | none, it is the DRF adapter path | `products/messaging/backend/api/customerio_webhook.py` |
+
+The GitHub endpoints and the SES one are declared in `posthog/urls.py`.
+The others are declared by the product that owns them.
+See [`url-routing.md`](../../docs/internal/url-routing.md) for the routing rules those declarations follow, and [`github-webhooks.md`](../../docs/internal/github-webhooks.md) for the GitHub specifics.
+
+The Vapi endpoint sits behind a per-IP throttle the product owns, because ingress has no throttle lane and the endpoint is public.
+
+## Non-goals
+
+This section records what ingress does not do, and why.
+
+**Ingress does not store a delivery log.**
+A delivery record's footprint tracks inbound volume, which is set by the third party rather than by PostHog, so it has no natural ceiling.
+Storing one therefore needs a size budget, an eviction policy, and a store of its own.
+The dedup mark is the opposite: it is O(1) per delivery, expires on its own, and holds no payload.
+A consumer that needs the payload later writes its own receipt, as conversations already does.
+
+**Ingress does not queue, retry, or dead-letter.**
+The provider already retries, and it knows things PostHog does not: how many attempts are left, and when to give up.
+A second retry layer on this side would deliver the same event twice under two different clocks.
+A consumer that wants asynchronous work enqueues its own task and answers immediately, which is what conversations and stamphog do.
+
+**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.
+A consumer that fails must not turn a verified delivery into a 500 the provider will replay against every other consumer too.
+If a provider's protocol needs the response body to say something, the incarnation answers that handshake before dispatch.
+
+**Ingress does not promise an order.**
+Consumers are independent by construction; anything that depends on another consumer's result belongs in one consumer.
+The dispatcher iterates sorted by name so logs and metrics are stable, but that is an implementation detail and not a contract.
+
+## Contracts
+
+```python
+from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+```
+
+`WebhookDelivery` is one verified, parsed delivery: provider, app, delivery id (`None` when the provider sends none), event type, payload, receipt time, and a small string-valued `context` for provider extras such as an installation id or Slack's retry headers.
+One request can become several deliveries, because a provider can batch several events into one body.
+
+`WebhookConsumer` is a handler registered for some of a provider app's event types.
+Its `name` is part of the dedup cache key, so **renaming a consumer lets a redelivery run it twice**.
+Treat the name as fixed once it ships.
+
+## Adding a consumer
+
+A product declares `products/<name>/backend/webhook_consumers.py` with a `WEBHOOK_CONSUMERS` sequence:
+
+```python
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="loops",
+ provider="github",
+ app="posthog",
+ event_types=frozenset({"issues", "issue_comment", "pull_request", "push"}),
+ handler=handle_github_event_for_loops,
+ ),
+)
+```
+
+The registry finds these through `posthog.products.load_product_modules("webhook_consumers")` on the **first delivery**, not at `django.setup()`.
+That is deliberate: eager loading would drag every product's webhook module onto the startup import path, which `posthog/test/repo_invariants/test_startup_import_budget.py` exists to keep clear.
+Keep the module itself cheap to import and defer the heavy work into the handler.
+
+Registration is validated and fail-closed.
+A consumer that names a provider app nobody declares, reuses a name already taken for that provider, or registers for an event type the provider does not declare raises `RegistryError` at build, rather than sitting there looking registered and never running.
+
+A handler takes one `WebhookDelivery` and returns nothing.
+It runs synchronously inside the request, isolated: raising is logged and captured, and it releases its own dedup mark so the provider's redelivery reaches it again.
+
+`dedup=False` turns the mark off for one consumer.
+That is right when the consumer already keys its own recovery on the provider's delivery id, so a redelivery is how work that never finished gets picked up.
+Leave it on everywhere else: without an idempotency key of its own, a consumer that opts out does the work again on every redelivery.
+
+## The delivery budget
+
+Every request gets one wall-clock budget, `INGRESS_DELIVERY_BUDGET_SECONDS` (default 8).
+Consumers draw from it in turn, across every delivery the request carries, because a request that batches several events would otherwise hold the connection open for one budget per event.
+When it is spent, the consumers that have not started are skipped with outcome `budget_exceeded` and a warning that names them, and they are **not** marked in dedup — so the provider's redelivery reaches them.
+
+The budget is a backstop, not a scheduler: it cannot interrupt a consumer that is already running.
+A consumer that touches the database on this path wraps its reads in `bounded_statement_timeout(ms, models=...)`, which installs `SET LOCAL statement_timeout` on each alias those models route to.
+Pass the models rather than capping every configured alias: opening an alias is itself unbounded, so reaching for one the read never uses can stall the delivery on connection setup before the cap is even installed.
+
+Both controls exist because the incidents on the GitHub webhook path came from unbounded query cost against a shared connection pool, not from running consumers inside the request.
+The fixes that worked bounded the queries: [#83852](https://github.com/PostHog/posthog/pull/83852) scoped the run lookup to the installation's teams and put a statement timeout on the attribution lookup, and [#87779](https://github.com/PostHog/posthog/pull/87779) added the indexes it needed.
+Ingress carries both as general controls, so the next endpoint gets them without rediscovering the same failure.
+
+## Adding a provider
+
+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.
+- 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.
+Then register the URL as usual:
+
+```python
+path("webhooks/github/", build_webhook_view(build_github_provider("posthog")))
+```
+
+Secrets and verifiers that belong to a product are **passed into the builder**.
+Nothing under `posthog/ingress/` imports a product.
+
+A consumer no product owns is registered by the incarnation itself, in a `CORE_CONSUMERS` tuple next to `SPECS`.
+
+Last, write `<provider>/README.md` with the fixed sections every provider README carries: headers, signature scheme, delivery id and event type, apps and secrets, quirks, consumers.
+`posthog/ingress/test/test_provider_readme_sections.py` fails on a provider folder without one.
+
+Two 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.
+
+## Dedup
+
+Dedup is per `(provider, consumer, delivery_id)` in the Django cache, for 24 hours.
+The mark is set before the consumer runs and released when it raises, so a failure does not burn the delivery for a day.
+Keying per consumer rather than per delivery matters: one delivery legitimately fans out to several consumers, and a delivery-wide key would starve every consumer but the first.
+A cache error fails **open** — dropping deliveries during a cache outage is worse than running a consumer twice, and consumers carry their own idempotency underneath this.
+
+A provider that sends no delivery id skips dedup entirely, and its own README says why it has none.
+
+## Observability
+
+- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `not_configured`, `invalid_signature`, `invalid_payload`. 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.
+
+A secret in a URL or header is the credential and never becomes a metric label.
diff --git a/posthog/ingress/__init__.py b/posthog/ingress/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/contracts.py b/posthog/ingress/contracts.py
new file mode 100644
index 000000000000..2467c70dc135
--- /dev/null
+++ b/posthog/ingress/contracts.py
@@ -0,0 +1,52 @@
+"""The three values every lane in this package speaks in."""
+
+from collections.abc import Callable, Mapping
+from datetime import datetime
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class WebhookDelivery:
+ """One inbound delivery, already verified and parsed.
+
+ A provider incarnation may turn one HTTP request into several of these (PandaDoc
+ batches events into one body), so this is the unit a consumer sees, not the request.
+ """
+
+ provider: str
+ app: str
+ delivery_id: str | None
+ event_type: str
+ payload: Mapping[str, Any]
+ received_at: datetime
+ context: Mapping[str, str]
+
+
+@frozen
+class WebhookConsumer:
+ """A handler a product registers for some of a provider app's event types.
+
+ ``name`` is part of the dedup cache key, so renaming one lets a redelivery run twice.
+ The handler's return value is ignored: the HTTP response is a transport receipt the
+ provider incarnation decides.
+ """
+
+ name: str
+ provider: str
+ app: str
+ event_types: frozenset[str]
+ handler: Callable[[WebhookDelivery], None]
+ # Off for a consumer that already keys its own recovery on the provider's delivery id: the
+ # 24 h mark would otherwise stop a redelivery from ever reaching that recovery path.
+ dedup: bool = True
+
+
+@frozen
+class ProviderSpec:
+ """What one provider app accepts, as the registry validates consumers against it."""
+
+ provider: str
+ app: str
+ event_types: frozenset[str]
diff --git a/posthog/ingress/customerio/README.md b/posthog/ingress/customerio/README.md
new file mode 100644
index 000000000000..f99e37a19d24
--- /dev/null
+++ b/posthog/ingress/customerio/README.md
@@ -0,0 +1,40 @@
+# Customer.io
+
+The signature scheme for the Customer.io reporting webhook, which stays on the DRF adapter path.
+
+## Headers
+
+- `x-cio-signature` carries the signature.
+- `x-cio-timestamp` carries the timestamp the signature covers.
+
+## Signature scheme
+
+HMAC-SHA256, hex encoded, with no prefix.
+The signed input is `v0:{timestamp}:{body}`.
+The replay window is the default one: 300 seconds old at most, and 300 seconds into the future at most.
+
+## Delivery id and event type
+
+Neither exists here.
+This incarnation contributes a scheme only, so it reads no deliveries off a request, and dedup does not apply.
+The DRF view reads the event out of the body itself.
+
+## Apps and secrets
+
+No app and no `ProviderSpec`, because nothing dispatches here.
+The secret is per team: it comes from that team's messaging integration row rather than from a setting, which is why the endpoint keeps DRF's team scoping.
+
+## Quirks
+
+This 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.
+Reach for this path only when an endpoint genuinely needs DRF's team scoping.
+Everything else goes through `build_webhook_view()`.
+
+## Consumers
+
+None.
+This is the DRF adapter path, with no dispatcher.
+The endpoint is `/api/projects/<team_id>/messaging/customerio/webhook/`, served by `products/messaging/backend/api/customerio_webhook.py`.
diff --git a/posthog/ingress/customerio/__init__.py b/posthog/ingress/customerio/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/customerio/scheme.py b/posthog/ingress/customerio/scheme.py
new file mode 100644
index 000000000000..767ca64ea997
--- /dev/null
+++ b/posthog/ingress/customerio/scheme.py
@@ -0,0 +1,20 @@
+"""Customer.io signature scheme, for the DRF adapter path.
+
+Customer.io is the one endpoint that keeps its DRF view: it is team-scoped, its secret comes
+from that team's integration row, and it needs no fan-out. So this incarnation contributes a
+scheme only -- `posthog.auth.WebhookSignatureAuthentication` does the verifying -- and
+declares no provider spec, because nothing dispatches here.
+"""
+
+from collections.abc import Callable
+
+from posthog.ingress.verify.schemes import HmacSha256
+
+
+def build_customerio_scheme(secret_getter: Callable[[], str | None]) -> HmacSha256:
+ return HmacSha256(
+ secret_getter=secret_getter,
+ signature_header="x-cio-signature",
+ signed_input="v0_timestamp_body",
+ timestamp_header="x-cio-timestamp",
+ )
diff --git a/posthog/ingress/dispatch/__init__.py b/posthog/ingress/dispatch/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/dispatch/budget.py b/posthog/ingress/dispatch/budget.py
new file mode 100644
index 000000000000..520e0c47a4d2
--- /dev/null
+++ b/posthog/ingress/dispatch/budget.py
@@ -0,0 +1,44 @@
+"""The wall-clock budget one delivery's consumers share."""
+
+import math
+import time
+
+from django.conf import settings
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_DELIVERY_BUDGET_SECONDS = 8.0
+
+
+def delivery_budget_seconds() -> float:
+ """Seconds one delivery may spend in consumers, read per delivery so it can be tuned live.
+
+ A value that is not positive and finite falls back to the default rather than being
+ honored: zero or less skips every consumer, and infinity or NaN removes the backstop.
+ """
+ seconds = float(getattr(settings, "INGRESS_DELIVERY_BUDGET_SECONDS", DEFAULT_DELIVERY_BUDGET_SECONDS))
+ if not math.isfinite(seconds) or seconds <= 0:
+ logger.warning(
+ "ingress_delivery_budget_invalid",
+ setting="INGRESS_DELIVERY_BUDGET_SECONDS",
+ configured=seconds,
+ default=DEFAULT_DELIVERY_BUDGET_SECONDS,
+ )
+ return DEFAULT_DELIVERY_BUDGET_SECONDS
+ return seconds
+
+
+class DeliveryBudget:
+ """A deadline for one delivery.
+
+ Monotonic rather than wall clock, so an NTP step mid-delivery cannot make the budget
+ look spent (or endless).
+ """
+
+ def __init__(self, seconds: float) -> None:
+ self._deadline = time.monotonic() + seconds
+
+ def is_spent(self) -> bool:
+ return time.monotonic() >= self._deadline
diff --git a/posthog/ingress/dispatch/database.py b/posthog/ingress/dispatch/database.py
new file mode 100644
index 000000000000..5ef90c64b045
--- /dev/null
+++ b/posthog/ingress/dispatch/database.py
@@ -0,0 +1,103 @@
+"""A statement-timeout cap for consumers that read the database on the request path.
+
+A provider gives a delivery one short window and mostly never retries it, so a slow query
+can cost the whole delivery rather than just the piece of work that issued it. Bounding the
+statement degrades that to a missing lookup.
+"""
+
+from collections.abc import Iterator, Sequence
+from contextlib import ExitStack, contextmanager
+
+from django.conf import settings
+from django.db import OperationalError, connections, router, transaction
+from django.db.backends.base.base import BaseDatabaseWrapper
+from django.db.models import Model
+
+# PostgreSQL raises query_canceled when statement_timeout fires. Django wraps the driver
+# error in OperationalError, so the SQLSTATE lives on the cause -- psycopg3 spells it
+# `sqlstate`, psycopg2 `pgcode`. The message check is the fallback for anything that loses
+# the cause on the way up.
+_QUERY_CANCELED_SQLSTATE = "57014"
+
+
+def is_statement_timeout(error: Exception) -> bool:
+ """Whether an error is the cap firing, rather than any other database failure.
+
+ Callers use this to keep "the cap we installed fired" as a leading indicator: connection
+ resets and other incidents raise the same class and would drown the signal.
+ """
+ if not isinstance(error, OperationalError):
+ return False
+ cause = error.__cause__
+ if getattr(cause, "sqlstate", None) == _QUERY_CANCELED_SQLSTATE:
+ return True
+ if getattr(cause, "pgcode", None) == _QUERY_CANCELED_SQLSTATE:
+ return True
+ return "statement timeout" in str(error).lower()
+
+
+def read_aliases(models: Sequence[type[Model]]) -> list[str]:
+ """The aliases a read of these models actually uses, deduped, in model order.
+
+ Bounding an alias means opening it, and opening is itself unbounded -- `postgres_config`
+ sets no `connect_timeout` on these aliases. So take the set from the router rather than
+ assuming: reaching for an alias the caller never uses could stall the delivery on
+ connection setup before the cap is installed, which is the failure this exists to
+ prevent. That cuts both ways -- a fully replica-opted deployment must not be made to
+ wait on the primary either.
+ """
+ aliases: list[str] = []
+ for model in models:
+ alias = router.db_for_read(model) or "default"
+ if alias not in aliases and alias in settings.DATABASES:
+ aliases.append(alias)
+ return aliases
+
+
+def _read_statement_timeout(connection: BaseDatabaseWrapper) -> str | None:
+ with connection.cursor() as cursor:
+ cursor.execute("SHOW statement_timeout")
+ row = cursor.fetchone()
+ return row[0] if row else None
+
+
+def _apply_statement_timeout(connection: BaseDatabaseWrapper, value: str) -> None:
+ # set_config(..., is_local=True) is SET LOCAL, but takes the value as a bind parameter,
+ # so a restored value ("30s", "0", ...) does not have to be quoted by hand.
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT set_config('statement_timeout', %s, true)", [value])
+
+
+@contextmanager
+def _statement_timeout(connection: BaseDatabaseWrapper, timeout_ms: int, *, restore: bool) -> Iterator[None]:
+ """Cap statements on one connection, optionally putting the previous value back."""
+ previous = _read_statement_timeout(connection) if restore else None
+ _apply_statement_timeout(connection, f"{timeout_ms}ms")
+
+ yield
+
+ # Only reached when the block succeeded. If it raised, the enclosing atomic() rolls the
+ # (sub)transaction back and PostgreSQL undoes SET LOCAL with it, so there is nothing to
+ # restore -- and a statement on an aborted transaction would error anyway.
+ if previous:
+ _apply_statement_timeout(connection, previous)
+
+
+@contextmanager
+def bounded_statement_timeout(timeout_ms: int, *, models: Sequence[type[Model]]) -> Iterator[None]:
+ """Run a block under a per-statement timeout on each alias a read of `models` may use.
+
+ A read routed to an alias joins that alias's open transaction, so `SET LOCAL
+ statement_timeout` there caps the query regardless of read-replica routing.
+ """
+ with ExitStack() as stack:
+ for alias in read_aliases(models):
+ connection = connections[alias]
+ # SET LOCAL dies with the transaction it was set in, so the cap only needs
+ # restoring when we are joining a transaction somebody else owns -- a caller
+ # wrapping this in its own atomic block, or ATOMIC_REQUESTS (which PostHog does
+ # not enable today). Otherwise the commit below ends it for us.
+ restore = connection.in_atomic_block
+ stack.enter_context(transaction.atomic(using=alias))
+ stack.enter_context(_statement_timeout(connection, timeout_ms, restore=restore))
+ yield
diff --git a/posthog/ingress/dispatch/dedup.py b/posthog/ingress/dispatch/dedup.py
new file mode 100644
index 000000000000..8d3f9175c57e
--- /dev/null
+++ b/posthog/ingress/dispatch/dedup.py
@@ -0,0 +1,63 @@
+"""Per-delivery, per-consumer dedup marks in the Django cache."""
+
+from django.core.cache import cache
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+DELIVERY_DEDUP_TTL_SECONDS = 24 * 60 * 60
+
+
+class DeliveryDedup:
+ """Marks a (provider, consumer, delivery id) so a redelivery skips work already done.
+
+ Keyed per consumer, not per delivery: one delivery legitimately fans out to several
+ consumers, so a delivery-wide key would starve every consumer but the first. This sits
+ alongside each consumer's own idempotency rather than replacing it.
+ """
+
+ @staticmethod
+ def key(*, provider: str, consumer: str, delivery_id: str) -> str:
+ return f"webhook_delivery:{provider}:{consumer}:{delivery_id}"
+
+ def claim(self, *, provider: str, consumer: str, delivery_id: str) -> bool:
+ """True when this process may run the consumer for this delivery.
+
+ Fail-open on a cache error: dropping deliveries during a cache outage is worse than
+ running a consumer twice, and consumers carry their own idempotency.
+ """
+ try:
+ return bool(
+ cache.add(
+ self.key(provider=provider, consumer=consumer, delivery_id=delivery_id),
+ True,
+ timeout=DELIVERY_DEDUP_TTL_SECONDS,
+ )
+ )
+ except Exception:
+ logger.warning(
+ "ingress_dedup_cache_failed",
+ provider=provider,
+ consumer=consumer,
+ delivery_id=delivery_id,
+ exc_info=True,
+ )
+ return True
+
+ def release(self, *, provider: str, consumer: str, delivery_id: str) -> None:
+ """Drop the mark after a consumer raised, so the provider's redelivery reaches it.
+
+ The mark is set before the consumer runs, so without this a failure would burn the
+ delivery for the whole TTL.
+ """
+ try:
+ cache.delete(self.key(provider=provider, consumer=consumer, delivery_id=delivery_id))
+ except Exception:
+ logger.warning(
+ "ingress_dedup_release_failed",
+ provider=provider,
+ consumer=consumer,
+ delivery_id=delivery_id,
+ exc_info=True,
+ )
diff --git a/posthog/ingress/dispatch/dispatcher.py b/posthog/ingress/dispatch/dispatcher.py
new file mode 100644
index 000000000000..48e9edd4f5c5
--- /dev/null
+++ b/posthog/ingress/dispatch/dispatcher.py
@@ -0,0 +1,131 @@
+"""Fan one delivery out to its consumers, inside one wall-clock budget."""
+
+import time
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+from posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds
+from posthog.ingress.dispatch.dedup import DeliveryDedup
+from posthog.ingress.dispatch.registry import ConsumerRegistry
+from posthog.ingress.observability.metrics import observe_consumer_duration, observe_consumer_run
+
+logger = structlog.get_logger(__name__)
+
+
+class WebhookDispatcher:
+ """Runs the consumers registered for a delivery, in name order.
+
+ Each consumer is isolated: one raising is logged and captured but never stops another,
+ and never changes the response the provider already earned by signing the request.
+ """
+
+ def __init__(
+ self,
+ registry: ConsumerRegistry,
+ *,
+ dedup: DeliveryDedup | None = None,
+ budget_seconds: float | None = None,
+ ) -> None:
+ self._registry = registry
+ self._dedup = dedup if dedup is not None else DeliveryDedup()
+ self._budget_seconds = budget_seconds
+
+ def _run(self, consumer: WebhookConsumer, delivery: WebhookDelivery) -> None:
+ # A consumer that opted out of dedup claims and releases nothing, so a redelivery always
+ # reaches it. Skipping is not an outcome of its own: it simply runs.
+ delivery_id = delivery.delivery_id if consumer.dedup else None
+ if delivery_id and not self._dedup.claim(
+ provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id
+ ):
+ logger.info(
+ "ingress_consumer_deduped",
+ provider=delivery.provider,
+ consumer=consumer.name,
+ event_type=delivery.event_type,
+ delivery_id=delivery.delivery_id,
+ )
+ observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="deduped")
+ return
+
+ started = time.monotonic()
+ try:
+ consumer.handler(delivery)
+ except Exception as error:
+ logger.exception(
+ "ingress_consumer_failed",
+ provider=delivery.provider,
+ consumer=consumer.name,
+ event_type=delivery.event_type,
+ delivery_id=delivery.delivery_id,
+ )
+ capture_exception(error)
+ if delivery_id:
+ self._dedup.release(provider=delivery.provider, consumer=consumer.name, delivery_id=delivery_id)
+ observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="failed")
+ else:
+ observe_consumer_run(provider=delivery.provider, consumer=consumer.name, outcome="succeeded")
+ finally:
+ observe_consumer_duration(
+ provider=delivery.provider, consumer=consumer.name, seconds=time.monotonic() - started
+ )
+
+ def dispatch(self, delivery: WebhookDelivery, *, budget: DeliveryBudget | None = None) -> None:
+ """Run this delivery's consumers.
+
+ The caller passes a budget when one request carries several deliveries, so the request
+ is bounded rather than each delivery separately.
+ """
+ if not self._registry.declares(provider=delivery.provider, app=delivery.app):
+ # A verified delivery for an app no incarnation declares is a wiring mistake: the
+ # endpoint answers its usual receipt and runs nothing at all.
+ logger.error(
+ "ingress_delivery_undeclared_app",
+ provider=delivery.provider,
+ app=delivery.app,
+ event_type=delivery.event_type,
+ )
+ return
+
+ consumers = self._registry.consumers_for(
+ provider=delivery.provider, app=delivery.app, event_type=delivery.event_type
+ )
+ if not consumers:
+ logger.info(
+ "ingress_delivery_without_consumers",
+ provider=delivery.provider,
+ app=delivery.app,
+ event_type=delivery.event_type,
+ )
+ return
+
+ logger.info(
+ "ingress_delivery_dispatch",
+ provider=delivery.provider,
+ app=delivery.app,
+ event_type=delivery.event_type,
+ delivery_id=delivery.delivery_id,
+ consumers=[consumer.name for consumer in consumers],
+ )
+
+ if budget is None:
+ budget = DeliveryBudget(
+ self._budget_seconds if self._budget_seconds is not None else delivery_budget_seconds()
+ )
+ for index, consumer in enumerate(consumers):
+ if budget.is_spent():
+ skipped = consumers[index:]
+ # No dedup mark for these, so the provider's redelivery reaches them.
+ logger.warning(
+ "ingress_delivery_budget_exceeded",
+ provider=delivery.provider,
+ app=delivery.app,
+ event_type=delivery.event_type,
+ delivery_id=delivery.delivery_id,
+ skipped=[pending.name for pending in skipped],
+ )
+ for pending in skipped:
+ observe_consumer_run(provider=delivery.provider, consumer=pending.name, outcome="budget_exceeded")
+ return
+ self._run(consumer, delivery)
diff --git a/posthog/ingress/dispatch/loading.py b/posthog/ingress/dispatch/loading.py
new file mode 100644
index 000000000000..2ec571842650
--- /dev/null
+++ b/posthog/ingress/dispatch/loading.py
@@ -0,0 +1,44 @@
+"""Builds the registry on the first delivery, then keeps it for the process.
+
+Eager building would drag every product's webhook module onto the `django.setup()` import
+path, which `posthog/test/repo_invariants/test_startup_import_budget.py` exists to keep
+clear -- a shell, a migrate and every Celery worker would pay for it.
+"""
+
+from collections.abc import Sequence
+from functools import lru_cache
+
+from posthog.ingress.contracts import WebhookConsumer
+from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
+from posthog.ingress.dispatch.registry import ConsumerRegistry
+from posthog.ingress.providers import core_consumers, provider_specs
+from posthog.products import load_product_modules
+
+PRODUCT_CONSUMER_MODULE = "webhook_consumers"
+PRODUCT_CONSUMER_ATTRIBUTE = "WEBHOOK_CONSUMERS"
+
+
+def product_consumers() -> list[WebhookConsumer]:
+ """Consumers declared by `products/<x>/backend/webhook_consumers.py`."""
+ consumers: list[WebhookConsumer] = []
+ for module in load_product_modules(PRODUCT_CONSUMER_MODULE):
+ declared: Sequence[WebhookConsumer] = getattr(module, PRODUCT_CONSUMER_ATTRIBUTE, ())
+ consumers.extend(declared)
+ return consumers
+
+
+@lru_cache(maxsize=1)
+def get_consumer_registry() -> ConsumerRegistry:
+ return ConsumerRegistry(
+ providers=provider_specs(),
+ consumers=[*core_consumers(), *product_consumers()],
+ )
+
+
+def reset_consumer_registry() -> None:
+ """Drop the cached registry. For tests that register their own consumers."""
+ get_consumer_registry.cache_clear()
+
+
+def get_dispatcher() -> WebhookDispatcher:
+ return WebhookDispatcher(get_consumer_registry())
diff --git a/posthog/ingress/dispatch/registry.py b/posthog/ingress/dispatch/registry.py
new file mode 100644
index 000000000000..b29f2e3f3655
--- /dev/null
+++ b/posthog/ingress/dispatch/registry.py
@@ -0,0 +1,67 @@
+"""The validated consumer registry.
+
+Registration order is unspecified by contract. The implementation iterates consumers sorted
+by name so logs and metrics read the same way on every delivery, and so a product cannot make
+its consumer run first by registering earlier.
+"""
+
+from collections import defaultdict
+from collections.abc import Sequence
+
+from posthog.ingress.contracts import ProviderSpec, WebhookConsumer
+
+
+class RegistryError(Exception):
+ """A consumer declaration no provider incarnation can serve."""
+
+
+class ConsumerRegistry:
+ """Consumers grouped by (provider, app, event type), validated once at build.
+
+ Validation is fail-closed on purpose: a consumer that names a provider nobody
+ declares, or an event type the provider never sends, would otherwise sit there
+ looking registered and never run.
+ """
+
+ def __init__(self, *, providers: Sequence[ProviderSpec], consumers: Sequence[WebhookConsumer]) -> None:
+ specs = {(spec.provider, spec.app): spec for spec in providers}
+ names_by_provider: dict[str, set[str]] = defaultdict(set)
+ grouped: dict[tuple[str, str, str], list[WebhookConsumer]] = defaultdict(list)
+
+ for consumer in sorted(consumers, key=lambda registered: registered.name):
+ spec = specs.get((consumer.provider, consumer.app))
+ if spec is None:
+ raise RegistryError(
+ f"Consumer {consumer.name!r} registers for unknown provider app "
+ f"{consumer.provider!r}/{consumer.app!r}"
+ )
+ # Scoped per provider rather than per app, because the dedup cache key carries
+ # the provider and the name but not the app.
+ if consumer.name in names_by_provider[consumer.provider]:
+ raise RegistryError(f"Duplicate consumer name {consumer.name!r} for provider {consumer.provider!r}")
+ names_by_provider[consumer.provider].add(consumer.name)
+
+ undeclared = consumer.event_types - spec.event_types
+ if undeclared:
+ raise RegistryError(
+ f"Consumer {consumer.name!r} registers for event types {sorted(undeclared)} that "
+ f"{consumer.provider!r}/{consumer.app!r} does not declare"
+ )
+ for event_type in sorted(consumer.event_types):
+ grouped[(consumer.provider, consumer.app, event_type)].append(consumer)
+
+ self._declared: frozenset[tuple[str, str]] = frozenset(specs)
+ self._grouped: dict[tuple[str, str, str], tuple[WebhookConsumer, ...]] = {
+ key: tuple(matched) for key, matched in grouped.items()
+ }
+
+ def declares(self, *, provider: str, app: str) -> bool:
+ """Whether any incarnation declares this provider app.
+
+ A delivery for an app nobody declares can never match a consumer, so the dispatcher
+ reports it rather than answering a healthy-looking receipt to nothing.
+ """
+ return (provider, app) in self._declared
+
+ def consumers_for(self, *, provider: str, app: str, event_type: str) -> tuple[WebhookConsumer, ...]:
+ return self._grouped.get((provider, app, event_type), ())
diff --git a/posthog/ingress/github/README.md b/posthog/ingress/github/README.md
new file mode 100644
index 000000000000..4c25c8f484c4
--- /dev/null
+++ b/posthog/ingress/github/README.md
@@ -0,0 +1,42 @@
+# GitHub
+
+Deliveries from the GitHub Apps PostHog runs.
+
+## Headers
+
+- `X-Hub-Signature-256` carries the signature.
+- `X-GitHub-Delivery` carries the delivery id.
+- `X-GitHub-Event` carries the event type.
+
+## Signature scheme
+
+HMAC-SHA256 over the raw body, hex encoded, with the prefix `sha256=`.
+GitHub sends no timestamp, so there is no replay window.
+
+## Delivery id and event type
+
+Both come from headers, never from the body.
+A request without `X-GitHub-Delivery` gets no delivery id and skips dedup.
+The payload's `installation.id` goes into the delivery context as `installation_id`.
+
+## Apps and secrets
+
+Two apps share this incarnation, each subscribed to its own event types in GitHub.
+
+- `posthog`, the customer-facing App. Its secret is the instance setting `GITHUB_WEBHOOK_SECRET`, so an operator can rotate it without a deploy.
+- `stamphog`, the review App. Its secret is the Django setting `STAMPHOG_GITHUB_APP_WEBHOOK_SECRET`, because it is instance-wide infrastructure.
+
+A consumer registers against an app name, so the two apps share no consumers.
+
+## Quirks
+
+The status codes are the defaults: 403 on a bad signature, 500 when unconfigured, 202 on success.
+The installation lifecycle is a core consumer rather than a product one, because it keeps PostHog's own integration rows in step with GitHub.
+
+## Consumers
+
+- `posthog/ingress/github/provider.py` registers `installation_lifecycle` and `installation_repositories` on the `posthog` app.
+- `products/stamphog/backend/webhook_consumers.py` registers `stamphog_review` on the `stamphog` app.
+
+The remaining GitHub consumers move to ingress one product at a time.
+The [Endpoints table](../README.md#endpoints) lists them.
diff --git a/posthog/ingress/github/__init__.py b/posthog/ingress/github/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/github/provider.py b/posthog/ingress/github/provider.py
new file mode 100644
index 000000000000..8ab1b6764262
--- /dev/null
+++ b/posthog/ingress/github/provider.py
@@ -0,0 +1,141 @@
+"""GitHub App deliveries, for every App PostHog runs.
+
+Two apps share this incarnation: the customer-facing PostHog App (`posthog`, secret in
+instance settings so an operator can rotate it without a deploy) and the Stamphog review App
+(`stamphog`, secret in env because it is instance-wide infrastructure).
+"""
+
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any
+
+from django.conf import settings
+from django.http import HttpRequest
+from django.utils import timezone
+
+from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
+from posthog.ingress.providers import WebhookProvider
+from posthog.ingress.verify.schemes import HmacSha256, SignatureScheme
+from posthog.models.instance_setting import get_instance_setting
+
+# What each App is subscribed to. A consumer for an event type outside its App's set fails
+# registry validation, which is the point: it would never run. The two Apps are subscribed
+# separately in GitHub, so they get separate sets rather than one shared superset.
+GITHUB_EVENT_TYPES = frozenset(
+ {
+ "issues",
+ "issue_comment",
+ "pull_request",
+ "pull_request_review",
+ "installation",
+ "installation_repositories",
+ "push",
+ }
+)
+
+# The Stamphog App reviews pull requests and keeps its repo-config rows in step with GitHub.
+STAMPHOG_EVENT_TYPES = frozenset({"pull_request", "installation", "installation_repositories"})
+
+
+def _posthog_app_secret() -> str | None:
+ secret = get_instance_setting("GITHUB_WEBHOOK_SECRET")
+ return secret if secret else None
+
+
+def _stamphog_app_secret() -> str | None:
+ return getattr(settings, "STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", "") or None
+
+
+_SECRET_GETTERS: Mapping[str, Callable[[], str | None]] = {
+ "posthog": _posthog_app_secret,
+ "stamphog": _stamphog_app_secret,
+}
+
+_APP_EVENT_TYPES: Mapping[str, frozenset[str]] = {
+ "posthog": GITHUB_EVENT_TYPES,
+ "stamphog": STAMPHOG_EVENT_TYPES,
+}
+
+SPECS = tuple(
+ ProviderSpec(provider="github", app=app, event_types=_APP_EVENT_TYPES[app]) for app in sorted(_SECRET_GETTERS)
+)
+
+
+def _installation_context(payload: Mapping[str, Any]) -> dict[str, str]:
+ installation = payload.get("installation")
+ if not isinstance(installation, Mapping):
+ return {}
+ installation_id = installation.get("id")
+ return {"installation_id": str(installation_id)} if installation_id is not None else {}
+
+
+class GitHubProvider(WebhookProvider):
+ provider = "github"
+
+ def __init__(self, app: str) -> None:
+ secret_getter = _SECRET_GETTERS.get(app)
+ if secret_getter is None:
+ raise ValueError(f"Unknown GitHub app {app!r}, expected one of {sorted(_SECRET_GETTERS)}")
+ self.app = app
+ self._scheme = HmacSha256(
+ secret_getter=secret_getter,
+ signature_header="X-Hub-Signature-256",
+ prefix="sha256=",
+ )
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ delivery_id=request.headers.get("X-GitHub-Delivery") or None,
+ event_type=request.headers.get("X-GitHub-Event", ""),
+ payload=payload,
+ received_at=timezone.now(),
+ context=_installation_context(payload),
+ ),
+ )
+
+
+def build_github_provider(app: str) -> GitHubProvider:
+ return GitHubProvider(app)
+
+
+def _run_installation_lifecycle(delivery: WebhookDelivery) -> None:
+ from posthog.api.github_callback.installation_events import (
+ handle_installation_event, # noqa: PLC0415 - keeps the integration models off the incarnation's import path
+ )
+
+ handle_installation_event(dict(delivery.payload))
+
+
+def _run_installation_repositories(delivery: WebhookDelivery) -> None:
+ from posthog.api.github_callback.installation_events import (
+ handle_installation_repositories_event, # noqa: PLC0415 - keeps the integration models off the incarnation's import path
+ )
+
+ handle_installation_repositories_event(dict(delivery.payload))
+
+
+# Core owns the installation lifecycle: it is what keeps PostHog's own integration rows in
+# step with GitHub, so no product registers it.
+CORE_CONSUMERS = (
+ WebhookConsumer(
+ name="installation_lifecycle",
+ provider="github",
+ app="posthog",
+ event_types=frozenset({"installation"}),
+ handler=_run_installation_lifecycle,
+ ),
+ WebhookConsumer(
+ name="installation_repositories",
+ provider="github",
+ app="posthog",
+ event_types=frozenset({"installation_repositories"}),
+ handler=_run_installation_repositories,
+ ),
+)
diff --git a/posthog/ingress/observability/__init__.py b/posthog/ingress/observability/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/observability/metrics.py b/posthog/ingress/observability/metrics.py
new file mode 100644
index 000000000000..cc3e326cc515
--- /dev/null
+++ b/posthog/ingress/observability/metrics.py
@@ -0,0 +1,50 @@
+"""Prometheus metrics for inbound deliveries and the consumers they fan out to."""
+
+from typing import Literal
+
+from prometheus_client import Counter, Histogram
+
+# outcome: what the transport answered, never what a consumer decided. `accepted` means the
+# delivery was verified, parsed and handed to the dispatcher -- consumer failures are counted
+# on their own metric below, because a failing consumer still gets a 2xx receipt.
+DeliveryOutcome = Literal[
+ "accepted",
+ "method_not_allowed",
+ "not_configured",
+ "invalid_signature",
+ "invalid_payload",
+]
+
+# budget_exceeded means the delivery ran out of wall clock before this consumer started. It is
+# not marked in dedup, so the provider's redelivery reaches it.
+ConsumerOutcome = Literal["succeeded", "failed", "deduped", "budget_exceeded"]
+
+INGRESS_DELIVERIES_TOTAL = Counter(
+ "posthog_ingress_deliveries_total",
+ "Inbound webhook deliveries, labeled by provider app and what the transport answered",
+ labelnames=["provider", "app", "outcome"],
+)
+
+INGRESS_CONSUMER_RUNS_TOTAL = Counter(
+ "posthog_ingress_consumer_runs_total",
+ "Consumer runs for inbound webhook deliveries, labeled by consumer and outcome",
+ labelnames=["provider", "consumer", "outcome"],
+)
+
+INGRESS_CONSUMER_DURATION_SECONDS = Histogram(
+ "posthog_ingress_consumer_duration_seconds",
+ "Wall-clock seconds one consumer spent on one inbound webhook delivery",
+ labelnames=["provider", "consumer"],
+)
+
+
+def observe_delivery(*, provider: str, app: str, outcome: DeliveryOutcome) -> None:
+ INGRESS_DELIVERIES_TOTAL.labels(provider=provider, app=app, outcome=outcome).inc()
+
+
+def observe_consumer_run(*, provider: str, consumer: str, outcome: ConsumerOutcome) -> None:
+ INGRESS_CONSUMER_RUNS_TOTAL.labels(provider=provider, consumer=consumer, outcome=outcome).inc()
+
+
+def observe_consumer_duration(*, provider: str, consumer: str, seconds: float) -> None:
+ INGRESS_CONSUMER_DURATION_SECONDS.labels(provider=provider, consumer=consumer).observe(seconds)
diff --git a/posthog/ingress/pandadoc/README.md b/posthog/ingress/pandadoc/README.md
new file mode 100644
index 000000000000..1c4838e7f07a
--- /dev/null
+++ b/posthog/ingress/pandadoc/README.md
@@ -0,0 +1,37 @@
+# PandaDoc
+
+Deliveries from PandaDoc document events.
+
+## Headers
+
+- `X-PandaDoc-Signature` carries the signature.
+- The `signature` query parameter is the fallback, read only when that header is absent.
+
+Presence decides, not truthiness.
+An empty header is a signature that fails, never a reason to look for a query parameter the caller did not sign with.
+
+## Signature scheme
+
+HMAC-SHA256 over the raw body, hex encoded, with no prefix.
+PandaDoc sends no timestamp, so there is no replay window.
+
+## Delivery id and event type
+
+PandaDoc sends no delivery id, so dedup is skipped and a consumer carries its own idempotency.
+The event type is the `event` field of each event object in the body.
+
+## Apps and secrets
+
+One app, `default`.
+The secret is the Django setting `PANDADOC_WEBHOOK_SECRET`.
+
+## Quirks
+
+PandaDoc batches several events into one body, so one request becomes one delivery per event, and all of them draw from the one request budget.
+A bad signature answers 404 instead of 403, so a prober cannot tell a wrong secret from an unknown route.
+
+## Consumers
+
+No product registers a PandaDoc consumer yet.
+The legal documents endpoint moves to ingress in its own PR.
+See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/pandadoc/__init__.py b/posthog/ingress/pandadoc/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/pandadoc/provider.py b/posthog/ingress/pandadoc/provider.py
new file mode 100644
index 000000000000..28ccad072213
--- /dev/null
+++ b/posthog/ingress/pandadoc/provider.py
@@ -0,0 +1,80 @@
+"""PandaDoc document webhooks.
+
+Two quirks: PandaDoc batches several events into one body, so one request becomes several
+deliveries, and it may carry the signature as a query parameter instead of a header. A bad
+signature answers 404 by design, so an attacker cannot tell a wrong secret from an unknown
+route.
+"""
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from django.conf import settings
+from django.http import HttpRequest
+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
+
+PANDADOC_EVENT_TYPES = frozenset({"document_state_changed"})
+PANDADOC_SIGNATURE_HEADER = "X-PandaDoc-Signature"
+
+SPECS = (ProviderSpec(provider="pandadoc", app="default", event_types=PANDADOC_EVENT_TYPES),)
+
+
+def _pandadoc_secret() -> str | None:
+ return getattr(settings, "PANDADOC_WEBHOOK_SECRET", "") or None
+
+
+class PandaDocProvider(WebhookProvider):
+ provider = "pandadoc"
+ app = "default"
+ invalid_signature_status = 404
+
+ def __init__(self) -> None:
+ self._scheme = HmacSha256(
+ secret_getter=_pandadoc_secret,
+ signature_header=PANDADOC_SIGNATURE_HEADER,
+ )
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def verify(self, request: HttpRequest) -> VerificationOutcome:
+ # 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
+ # reason to go looking for a query parameter the caller did not sign with.
+ if header_value(request.headers, PANDADOC_SIGNATURE_HEADER) is not None:
+ return self._scheme.verify(body=request.body, headers=request.headers)
+ # The query parameter is the fallback only, so a signed header always decides.
+ return self._scheme.verify(
+ body=request.body,
+ headers={PANDADOC_SIGNATURE_HEADER: request.GET.get("signature", "")},
+ )
+
+ def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ events = payload if isinstance(payload, list) else [payload]
+ received_at = timezone.now()
+ deliveries: list[WebhookDelivery] = []
+ for event in events:
+ if not isinstance(event, Mapping):
+ continue
+ deliveries.append(
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ # PandaDoc sends no delivery id, so dedup is the consumer's own job.
+ delivery_id=None,
+ event_type=str(event.get("event", "")),
+ payload=event,
+ received_at=received_at,
+ context={},
+ )
+ )
+ return tuple(deliveries)
+
+
+def build_pandadoc_provider() -> PandaDocProvider:
+ return PandaDocProvider()
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
new file mode 100644
index 000000000000..97a7d4a56d54
--- /dev/null
+++ b/posthog/ingress/providers.py
@@ -0,0 +1,77 @@
+"""The provider incarnation base, and how the package finds every incarnation.
+
+An incarnation is a thin module under `posthog/ingress/<provider>/`: header names, a
+signature scheme, and how to read an event type and a delivery id off the request. It must
+not import a product, and it must stay cheap to import, because the registry imports every
+one of these on the first delivery.
+"""
+
+import importlib
+from abc import ABC, abstractmethod
+from collections.abc import Sequence
+from typing import Any
+
+from django.http import HttpRequest, HttpResponse
+
+from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
+from posthog.ingress.verify.schemes import SignatureScheme, 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).
+_INCARNATION_MODULES = (
+ "posthog.ingress.github.provider",
+ "posthog.ingress.slack.provider",
+ "posthog.ingress.pandadoc.provider",
+ "posthog.ingress.vapi.provider",
+ "posthog.ingress.sns.provider",
+)
+
+
+class WebhookProvider(ABC):
+ """One provider app: how a delivery is verified, and how it is read.
+
+ The status codes are attributes rather than view arguments because they are part of the
+ provider's own protocol: PandaDoc answers 404 on a bad signature by design, and Vapi
+ answers 401. Everything else is a 202 transport receipt.
+ """
+
+ provider: str = ""
+ app: str = ""
+ invalid_signature_status: int = 403
+ unconfigured_status: int = 500
+ success_status: int = 202
+
+ @abstractmethod
+ def scheme(self) -> SignatureScheme:
+ """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 verify(self, request: HttpRequest) -> VerificationOutcome:
+ return self.scheme().verify(body=request.body, headers=request.headers)
+
+ def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:
+ """A response the provider's protocol demands before any consumer runs.
+
+ Only handshakes belong here (Slack's `url_verification` challenge), never anything a
+ consumer's outcome decides.
+ """
+ return None
+
+
+def provider_specs() -> tuple[ProviderSpec, ...]:
+ specs: list[ProviderSpec] = []
+ for module_name in _INCARNATION_MODULES:
+ module = importlib.import_module(module_name)
+ specs.extend(getattr(module, "SPECS", ()))
+ return tuple(specs)
+
+
+def core_consumers() -> tuple[WebhookConsumer, ...]:
+ consumers: list[WebhookConsumer] = []
+ for module_name in _INCARNATION_MODULES:
+ module = importlib.import_module(module_name)
+ consumers.extend(getattr(module, "CORE_CONSUMERS", ()))
+ return tuple(consumers)
diff --git a/posthog/ingress/slack/README.md b/posthog/ingress/slack/README.md
new file mode 100644
index 000000000000..b8e33d6eaac8
--- /dev/null
+++ b/posthog/ingress/slack/README.md
@@ -0,0 +1,40 @@
+# Slack
+
+Deliveries from the Slack Events API.
+
+## Headers
+
+- `X-Slack-Signature` carries the signature.
+- `X-Slack-Request-Timestamp` carries the timestamp the signature covers.
+- `X-Slack-Retry-Num` and `X-Slack-Retry-Reason` go into the delivery context, because they tell a consumer that Slack thinks a delivery failed.
+
+## Signature scheme
+
+HMAC-SHA256, hex encoded, with the prefix `v0=`.
+The signed input is `v0:{timestamp}:{body}`.
+The replay window accepts a timestamp up to 300 seconds old, which is Slack's own guidance, and up to 60 seconds in the future for clock skew.
+
+## Delivery id and event type
+
+The delivery id is the envelope's `event_id`.
+The event type is the inner `event.type`, not the envelope's `type`, so a consumer registers for `message` rather than for `event_callback`.
+An envelope that is not an `event_callback` becomes no delivery at all.
+The context also carries `slack_team_id`.
+
+## Apps and secrets
+
+One app, `supporthog`.
+The signing secret belongs to the product that owns the Slack app, so `build_slack_provider()` takes it as a getter.
+Nothing under `posthog/ingress/` reads it.
+
+## Quirks
+
+Slack's `url_verification` handshake wants the challenge echoed in the response body, which no consumer can do.
+The incarnation answers it in `pre_dispatch_response()`, before dispatch.
+The status codes are the defaults.
+
+## Consumers
+
+No product registers a Slack consumer yet.
+The conversations Slack endpoint moves to ingress in its own PR.
+See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/slack/__init__.py b/posthog/ingress/slack/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/slack/provider.py b/posthog/ingress/slack/provider.py
new file mode 100644
index 000000000000..c366df004def
--- /dev/null
+++ b/posthog/ingress/slack/provider.py
@@ -0,0 +1,84 @@
+"""Slack Events API deliveries.
+
+Slack wraps the interesting event in an envelope, so the event type a consumer registers for
+is the inner `event.type`, not the envelope's. The `url_verification` handshake is answered
+before any consumer runs, because Slack wants the challenge echoed in the body.
+"""
+
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any
+
+from django.http import HttpRequest, HttpResponse, JsonResponse
+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
+
+SLACK_EVENT_TYPES = frozenset(
+ {
+ "app_mention",
+ "message",
+ "reaction_added",
+ "member_joined_channel",
+ "member_left_channel",
+ }
+)
+
+SPECS = (ProviderSpec(provider="slack", app="supporthog", event_types=SLACK_EVENT_TYPES),)
+
+
+class SlackProvider(WebhookProvider):
+ provider = "slack"
+
+ def __init__(self, *, app: str = "supporthog", secret_getter: Callable[[], str | None]) -> None:
+ self.app = app
+ self._scheme = HmacSha256(
+ secret_getter=secret_getter,
+ signature_header="X-Slack-Signature",
+ prefix="v0=",
+ signed_input="v0_timestamp_body",
+ timestamp_header="X-Slack-Request-Timestamp",
+ # Slack's own guidance: drop anything older than five minutes. The tighter future
+ # bound is clock skew only, so a replayed future timestamp buys almost nothing.
+ timestamp_max_age_seconds=300,
+ timestamp_max_future_seconds=60,
+ )
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:
+ if isinstance(payload, Mapping) and payload.get("type") == "url_verification":
+ return JsonResponse({"challenge": str(payload.get("challenge", ""))})
+ return None
+
+ def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping) or payload.get("type") != "event_callback":
+ return ()
+ event = payload.get("event")
+ event = event if isinstance(event, Mapping) else {}
+ event_id = payload.get("event_id")
+ context = {
+ "slack_team_id": str(payload.get("team_id") or ""),
+ # Slack retries a delivery it thinks failed and says so in these headers, which
+ # consumers record on their receipt.
+ "retry_num": request.headers.get("X-Slack-Retry-Num", ""),
+ "retry_reason": request.headers.get("X-Slack-Retry-Reason", ""),
+ }
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ delivery_id=str(event_id) if isinstance(event_id, str) and event_id else None,
+ event_type=str(event.get("type", "")),
+ payload=payload,
+ received_at=timezone.now(),
+ context=context,
+ ),
+ )
+
+
+def build_slack_provider(*, secret_getter: Callable[[], str | None], app: str = "supporthog") -> SlackProvider:
+ """The signing secret lives with the product that owns the Slack app, so it is passed in."""
+ return SlackProvider(app=app, secret_getter=secret_getter)
diff --git a/posthog/ingress/sns/README.md b/posthog/ingress/sns/README.md
new file mode 100644
index 000000000000..cd2bbd1afc19
--- /dev/null
+++ b/posthog/ingress/sns/README.md
@@ -0,0 +1,41 @@
+# SNS
+
+Deliveries from an AWS SNS HTTPS subscription.
+
+## Headers
+
+None.
+SNS signs the message itself, so this incarnation reads no header.
+The envelope fields `Type`, `MessageId` and `TopicArn` all come from the JSON body.
+
+## Signature scheme
+
+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.
+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.
+
+## Delivery id and event type
+
+The delivery id is the body's `MessageId`.
+The event type is the body's `Type`: `SubscriptionConfirmation`, `Notification` or `UnsubscribeConfirmation`.
+The `TopicArn` goes into the delivery context.
+
+## Apps and secrets
+
+One app, `default`, and no secret.
+The verifier and the topic allowlist belong to whoever owns the topic, so `build_sns_provider()` takes both as callables.
+
+## Quirks
+
+The subscription handshake is an event type, not a pre-dispatch response.
+Confirming a subscription means calling AWS back, which is a consumer's business rather than the transport's, so a consumer registers for `SubscriptionConfirmation` separately from `Notification`.
+An unknown topic logs `ingress_sns_unknown_topic` and answers like a bad signature.
+
+## Consumers
+
+No product registers an SNS consumer yet.
+The workflows SES events endpoint moves to ingress in its own PR.
+See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/sns/__init__.py b/posthog/ingress/sns/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/sns/provider.py b/posthog/ingress/sns/provider.py
new file mode 100644
index 000000000000..7decbb411b63
--- /dev/null
+++ b/posthog/ingress/sns/provider.py
@@ -0,0 +1,65 @@
+"""AWS SNS HTTPS subscriptions.
+
+The event type is the SNS envelope's `Type`, so a consumer registers separately for the
+subscription handshake and for notifications: confirming a subscription means calling AWS
+back, which is the consumer's business, not the transport's.
+"""
+
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any
+
+from django.http import HttpRequest
+from django.utils import timezone
+
+from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
+from posthog.ingress.providers import WebhookProvider
+from posthog.ingress.verify.schemes import SignatureScheme, SnsSignature
+
+SNS_EVENT_TYPES = frozenset({"SubscriptionConfirmation", "Notification", "UnsubscribeConfirmation"})
+
+SPECS = (ProviderSpec(provider="sns", app="default", event_types=SNS_EVENT_TYPES),)
+
+
+class SnsProvider(WebhookProvider):
+ provider = "sns"
+
+ def __init__(
+ self,
+ *,
+ app: str = "default",
+ verify_message: Callable[[Mapping[str, Any]], bool],
+ allowed_topic_arns: Callable[[], frozenset[str]],
+ ) -> None:
+ self.app = app
+ self._scheme = SnsSignature(verify_message=verify_message, allowed_topic_arns=allowed_topic_arns)
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+ message_id = payload.get("MessageId")
+ topic_arn = payload.get("TopicArn")
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ delivery_id=str(message_id) if isinstance(message_id, str) and message_id else None,
+ event_type=str(payload.get("Type", "")),
+ payload=payload,
+ received_at=timezone.now(),
+ context={"topic_arn": str(topic_arn)} if isinstance(topic_arn, str) else {},
+ ),
+ )
+
+
+def build_sns_provider(
+ *,
+ verify_message: Callable[[Mapping[str, Any]], bool],
+ allowed_topic_arns: Callable[[], frozenset[str]],
+ app: str = "default",
+) -> SnsProvider:
+ """The RSA verifier and the topic allowlist belong to whoever owns the topic, so both are
+ passed in rather than reached for from here."""
+ return SnsProvider(app=app, verify_message=verify_message, allowed_topic_arns=allowed_topic_arns)
diff --git a/posthog/ingress/test/__init__.py b/posthog/ingress/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/test/test_database.py b/posthog/ingress/test/test_database.py
new file mode 100644
index 000000000000..05f6ae1577c1
--- /dev/null
+++ b/posthog/ingress/test/test_database.py
@@ -0,0 +1,70 @@
+from unittest.mock import patch
+
+from django.conf import settings
+from django.db import OperationalError, connections
+from django.test import SimpleTestCase, TestCase
+
+from parameterized import parameterized
+
+from posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeout, read_aliases
+from posthog.models import Team, User
+
+
+def _current_statement_timeout(alias: str) -> str:
+ with connections[alias].cursor() as cursor:
+ cursor.execute("SHOW statement_timeout")
+ row = cursor.fetchone()
+ return row[0]
+
+
+class TestReadAliases(SimpleTestCase):
+ def test_models_that_route_to_one_alias_are_capped_once(self) -> None:
+ self.assertEqual(read_aliases([Team, User]), read_aliases([Team]))
+
+ @parameterized.expand(
+ [
+ ("a_configured_replica_the_router_never_reads_is_not_dialled", lambda model: "default", ["default"]),
+ ("a_fully_replica_opted_read_does_not_wait_on_the_primary", lambda model: "replica", ["replica"]),
+ (
+ "an_alias_only_some_models_read_from_is_still_capped",
+ lambda model: "replica" if model is User else "default",
+ ["default", "replica"],
+ ),
+ ]
+ )
+ def test_takes_the_alias_set_from_the_router(self, _name, db_for_read, expected) -> None:
+ # Bounding an alias means opening it, and connection setup is itself unbounded (these
+ # aliases carry no connect_timeout), so an alias the read never uses must not be dialled
+ # just to install a cap on it. That cuts both ways, hence the first two cases.
+ with self.settings(DATABASES={**settings.DATABASES, "replica": settings.DATABASES["default"]}):
+ with patch("posthog.ingress.dispatch.database.router.db_for_read", side_effect=db_for_read):
+ self.assertEqual(sorted(read_aliases([Team, User])), expected)
+
+
+class TestIsStatementTimeout(SimpleTestCase):
+ def test_an_unrelated_database_failure_is_not_the_cap_firing(self) -> None:
+ self.assertFalse(is_statement_timeout(OperationalError("server closed the connection unexpectedly")))
+ self.assertFalse(is_statement_timeout(ValueError("not a database error")))
+
+
+class TestBoundedStatementTimeout(TestCase):
+ def test_a_statement_over_the_cap_is_cancelled_and_reported_as_a_timeout(self) -> None:
+ alias = read_aliases([Team])[0]
+
+ with self.assertRaises(OperationalError) as raised:
+ with bounded_statement_timeout(50, models=[Team]):
+ with connections[alias].cursor() as cursor:
+ cursor.execute("SELECT pg_sleep(5)")
+
+ self.assertTrue(is_statement_timeout(raised.exception))
+
+ def test_the_previous_cap_comes_back_when_the_caller_owns_the_transaction(self) -> None:
+ alias = read_aliases([Team])[0]
+ # A Django TestCase wraps every test in a transaction, so this is the joining case:
+ # SET LOCAL outlives the block and has to be put back by hand.
+ before = _current_statement_timeout(alias)
+
+ with bounded_statement_timeout(50, models=[Team]):
+ self.assertEqual(_current_statement_timeout(alias), "50ms")
+
+ self.assertEqual(_current_statement_timeout(alias), before)
diff --git a/posthog/ingress/test/test_dispatcher.py b/posthog/ingress/test/test_dispatcher.py
new file mode 100644
index 000000000000..0ad15a90699f
--- /dev/null
+++ b/posthog/ingress/test/test_dispatcher.py
@@ -0,0 +1,177 @@
+from datetime import UTC, datetime
+
+from unittest.mock import Mock, patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
+from posthog.ingress.dispatch.budget import DEFAULT_DELIVERY_BUDGET_SECONDS, DeliveryBudget, delivery_budget_seconds
+from posthog.ingress.dispatch.dedup import DeliveryDedup
+from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
+from posthog.ingress.dispatch.registry import ConsumerRegistry
+
+SPEC = ProviderSpec(provider="github", app="posthog", event_types=frozenset({"pull_request"}))
+
+
+def _delivery(delivery_id: str | None = "delivery-1") -> WebhookDelivery:
+ return WebhookDelivery(
+ provider="github",
+ app="posthog",
+ delivery_id=delivery_id,
+ event_type="pull_request",
+ payload={},
+ received_at=datetime(2026, 9, 14, tzinfo=UTC),
+ context={},
+ )
+
+
+def _consumer(name: str, handler, *, dedup: bool = True) -> WebhookConsumer:
+ return WebhookConsumer(
+ name=name,
+ provider="github",
+ app="posthog",
+ event_types=frozenset({"pull_request"}),
+ handler=handler,
+ dedup=dedup,
+ )
+
+
+def _dispatcher(consumers: list[WebhookConsumer], *, budget_seconds: float | None = None) -> WebhookDispatcher:
+ return WebhookDispatcher(
+ ConsumerRegistry(providers=[SPEC], consumers=consumers),
+ budget_seconds=budget_seconds,
+ )
+
+
+@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+class TestWebhookDispatcher(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ def test_runs_consumers_in_name_order(self) -> None:
+ ran: list[str] = []
+ consumers = [
+ _consumer("zulu", lambda delivery: ran.append("zulu")),
+ _consumer("alpha", lambda delivery: ran.append("alpha")),
+ ]
+
+ _dispatcher(consumers).dispatch(_delivery())
+
+ self.assertEqual(ran, ["alpha", "zulu"])
+
+ def test_one_failing_consumer_does_not_stop_the_others(self) -> None:
+ failing = Mock(side_effect=RuntimeError("consumer failed"))
+ surviving = Mock()
+
+ with patch("posthog.ingress.dispatch.dispatcher.capture_exception") as capture:
+ _dispatcher([_consumer("alpha", failing), _consumer("zulu", surviving)]).dispatch(_delivery())
+
+ surviving.assert_called_once()
+ capture.assert_called_once()
+
+ def test_dedup_marks_before_the_run_and_releases_when_the_consumer_raises(self) -> None:
+ failing = Mock(side_effect=RuntimeError("consumer failed"))
+ succeeding = Mock()
+ dispatcher = _dispatcher([_consumer("alpha", failing), _consumer("zulu", succeeding)])
+
+ with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):
+ dispatcher.dispatch(_delivery())
+
+ self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1")))
+ self.assertTrue(cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1")))
+
+ with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):
+ dispatcher.dispatch(_delivery())
+
+ self.assertEqual(failing.call_count, 2)
+ self.assertEqual(succeeding.call_count, 1)
+
+ def test_a_provider_without_a_delivery_id_skips_dedup(self) -> None:
+ handler = Mock()
+ dispatcher = _dispatcher([_consumer("alpha", handler)])
+
+ dispatcher.dispatch(_delivery(delivery_id=None))
+ dispatcher.dispatch(_delivery(delivery_id=None))
+
+ self.assertEqual(handler.call_count, 2)
+
+ def test_a_consumer_that_opted_out_of_dedup_runs_on_every_redelivery(self) -> None:
+ opted_out = Mock()
+ sibling = Mock()
+ dispatcher = _dispatcher([_consumer("alpha", opted_out, dedup=False), _consumer("zulu", sibling)])
+
+ dispatcher.dispatch(_delivery())
+ dispatcher.dispatch(_delivery())
+
+ self.assertEqual(opted_out.call_count, 2)
+ self.assertEqual(sibling.call_count, 1)
+ self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="alpha", delivery_id="delivery-1")))
+
+ def test_a_cache_outage_fails_open_rather_than_dropping_the_delivery(self) -> None:
+ handler = Mock()
+ with patch.object(cache, "add", side_effect=RuntimeError("cache down")):
+ _dispatcher([_consumer("alpha", handler)]).dispatch(_delivery())
+
+ handler.assert_called_once()
+
+ def test_a_spent_budget_skips_the_rest_without_marking_them_deduped(self) -> None:
+ elapsed = {"seconds": 0.0}
+
+ def spend_the_budget(delivery: WebhookDelivery) -> None:
+ elapsed["seconds"] += 30.0
+
+ skipped = Mock()
+ dispatcher = _dispatcher([_consumer("alpha", spend_the_budget), _consumer("zulu", skipped)], budget_seconds=8)
+
+ with (
+ patch("time.monotonic", lambda: elapsed["seconds"]),
+ patch("posthog.ingress.dispatch.dispatcher.observe_consumer_run") as observe,
+ ):
+ dispatcher.dispatch(_delivery())
+
+ skipped.assert_not_called()
+ self.assertIn(
+ {"provider": "github", "consumer": "zulu", "outcome": "budget_exceeded"},
+ [call.kwargs for call in observe.call_args_list],
+ )
+ self.assertIsNone(cache.get(DeliveryDedup.key(provider="github", consumer="zulu", delivery_id="delivery-1")))
+
+ dispatcher_with_room = _dispatcher([_consumer("zulu", skipped)], budget_seconds=10)
+ dispatcher_with_room.dispatch(_delivery())
+ skipped.assert_called_once()
+
+ def test_a_budget_passed_in_spans_every_delivery_of_one_request(self) -> None:
+ elapsed = {"seconds": 0.0}
+
+ def spend_the_budget(delivery: WebhookDelivery) -> None:
+ elapsed["seconds"] += 30.0
+
+ second = Mock()
+ dispatcher = _dispatcher([_consumer("alpha", spend_the_budget)])
+
+ with patch("time.monotonic", lambda: elapsed["seconds"]):
+ budget = DeliveryBudget(8)
+ dispatcher.dispatch(_delivery(delivery_id="delivery-1"), budget=budget)
+ _dispatcher([_consumer("alpha", second)]).dispatch(_delivery(delivery_id="delivery-2"), budget=budget)
+
+ second.assert_not_called()
+
+
+class TestDeliveryBudgetSeconds(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("zero_would_skip_every_consumer", 0, DEFAULT_DELIVERY_BUDGET_SECONDS),
+ ("negative_would_skip_every_consumer", -1, DEFAULT_DELIVERY_BUDGET_SECONDS),
+ ("infinity_would_remove_the_backstop", float("inf"), DEFAULT_DELIVERY_BUDGET_SECONDS),
+ ("nan_would_remove_the_backstop", float("nan"), DEFAULT_DELIVERY_BUDGET_SECONDS),
+ ("a_positive_finite_value_is_honored", 2.5, 2.5),
+ ]
+ )
+ def test_a_misconfigured_setting_falls_back_to_the_default(
+ self, _name: str, configured: float, expected: float
+ ) -> None:
+ with override_settings(INGRESS_DELIVERY_BUDGET_SECONDS=configured):
+ self.assertEqual(delivery_budget_seconds(), expected)
diff --git a/posthog/ingress/test/test_github.py b/posthog/ingress/test/test_github.py
new file mode 100644
index 000000000000..4578ed611e53
--- /dev/null
+++ b/posthog/ingress/test/test_github.py
@@ -0,0 +1,55 @@
+import hmac
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.ingress.github.provider import CORE_CONSUMERS, SPECS, build_github_provider
+from posthog.ingress.verify.schemes import VerificationOutcome
+
+BODY = b'{"action":"created"}'
+INSTANCE_SECRET = "posthog-app-secret"
+STAMPHOG_SECRET = "stamphog-app-secret"
+
+
+def _signature(secret: str) -> str:
+ return "sha256=" + hmac.digest(secret.encode(), BODY, "sha256").hex()
+
+
+@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=STAMPHOG_SECRET)
+class TestGitHubProvider(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("posthog_app", "posthog", INSTANCE_SECRET, STAMPHOG_SECRET),
+ ("stamphog_app", "stamphog", STAMPHOG_SECRET, INSTANCE_SECRET),
+ ]
+ )
+ def test_each_app_only_accepts_its_own_secret(
+ self, _name: str, app: str, own_secret: str, other_secret: str
+ ) -> None:
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=INSTANCE_SECRET):
+ scheme = build_github_provider(app).scheme()
+
+ self.assertEqual(
+ scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(own_secret)}),
+ VerificationOutcome.VERIFIED,
+ )
+ self.assertEqual(
+ scheme.verify(body=BODY, headers={"X-Hub-Signature-256": _signature(other_secret)}),
+ VerificationOutcome.INVALID,
+ )
+
+ def test_an_unknown_app_is_refused_at_build(self) -> None:
+ with self.assertRaises(ValueError):
+ build_github_provider("gitlab")
+
+ def test_every_declared_app_has_a_spec_and_the_core_consumers_fit_it(self) -> None:
+ self.assertEqual({spec.app for spec in SPECS}, {"posthog", "stamphog"})
+ declared = {(spec.provider, spec.app): spec.event_types for spec in SPECS}
+ # A shared superset would let a Stamphog consumer register for an event type that App
+ # never receives, which is what the registry validation exists to refuse.
+ self.assertLess(declared[("github", "stamphog")], declared[("github", "posthog")])
+ for consumer in CORE_CONSUMERS:
+ self.assertLessEqual(consumer.event_types, declared[(consumer.provider, consumer.app)])
diff --git a/posthog/ingress/test/test_pandadoc.py b/posthog/ingress/test/test_pandadoc.py
new file mode 100644
index 000000000000..e94fc67e4589
--- /dev/null
+++ b/posthog/ingress/test/test_pandadoc.py
@@ -0,0 +1,48 @@
+import hmac
+
+from django.test import RequestFactory, SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.ingress.pandadoc.provider import build_pandadoc_provider
+from posthog.ingress.verify.schemes import VerificationOutcome
+
+SECRET = "pandadoc-secret"
+BODY = b'[{"event":"document_state_changed"}]'
+
+
+def _signature() -> str:
+ return hmac.digest(SECRET.encode(), BODY, "sha256").hex()
+
+
+@override_settings(PANDADOC_WEBHOOK_SECRET=SECRET)
+class TestPandaDocProvider(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("header_only", _signature(), None, VerificationOutcome.VERIFIED),
+ ("header_plus_an_unrelated_query_parameter", _signature(), "not-a-signature", VerificationOutcome.VERIFIED),
+ ("query_parameter_only", None, _signature(), VerificationOutcome.VERIFIED),
+ ("an_empty_header_does_not_fall_through", "", _signature(), VerificationOutcome.INVALID),
+ ("neither", None, None, VerificationOutcome.INVALID),
+ ]
+ )
+ def test_a_header_signature_is_never_overridden_by_the_query_parameter(
+ self, _name: str, header: str | None, query_signature: str | None, expected: VerificationOutcome
+ ) -> None:
+ url = "/webhooks/pandadoc/"
+ if query_signature is not None:
+ url = f"{url}?signature={query_signature}"
+ request = RequestFactory().post(
+ url,
+ data=BODY,
+ content_type="application/json",
+ headers={} if header is None else {"X-PandaDoc-Signature": header},
+ )
+
+ self.assertEqual(build_pandadoc_provider().verify(request), expected)
+
+ 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)
diff --git a/posthog/ingress/test/test_provider_readme_sections.py b/posthog/ingress/test/test_provider_readme_sections.py
new file mode 100644
index 000000000000..9ae1a36270e2
--- /dev/null
+++ b/posthog/ingress/test/test_provider_readme_sections.py
@@ -0,0 +1,42 @@
+from pathlib import Path
+
+from django.test import SimpleTestCase
+
+INGRESS_ROOT = Path(__file__).resolve().parent.parent
+
+# A provider folder is one with a `provider.py` (it dispatches) or a `scheme.py` (it feeds the
+# DRF adapter path). Both kinds carry a README.
+PROVIDER_MODULES = ("provider.py", "scheme.py")
+
+# The same headings in the same order for every provider, so a reader finds a provider's facts
+# in one place, instead of in paragraphs that collide in the package README.
+REQUIRED_SECTIONS = [
+ "Headers",
+ "Signature scheme",
+ "Delivery id and event type",
+ "Apps and secrets",
+ "Quirks",
+ "Consumers",
+]
+
+
+def provider_directories() -> list[Path]:
+ directories = {path.parent for module in PROVIDER_MODULES for path in INGRESS_ROOT.glob(f"*/{module}")}
+ return sorted(directories)
+
+
+def section_headings(readme: Path) -> list[str]:
+ lines = readme.read_text(encoding="utf-8").splitlines()
+ return [line.removeprefix("## ").strip() for line in lines if line.startswith("## ")]
+
+
+class TestProviderReadmeSections(SimpleTestCase):
+ def test_every_provider_folder_has_a_readme_with_the_fixed_sections(self) -> None:
+ directories = provider_directories()
+ self.assertTrue(directories, "no provider folders found under posthog/ingress/")
+
+ for directory in directories:
+ with self.subTest(provider=directory.name):
+ readme = directory / "README.md"
+ self.assertTrue(readme.is_file(), f"{directory.name}/ has no README.md")
+ self.assertEqual(section_headings(readme), REQUIRED_SECTIONS)
diff --git a/posthog/ingress/test/test_registry.py b/posthog/ingress/test/test_registry.py
new file mode 100644
index 000000000000..296ce6dcb4d7
--- /dev/null
+++ b/posthog/ingress/test/test_registry.py
@@ -0,0 +1,97 @@
+from django.test import SimpleTestCase
+
+from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery
+from posthog.ingress.dispatch.loading import get_consumer_registry, reset_consumer_registry
+from posthog.ingress.dispatch.registry import ConsumerRegistry, RegistryError
+
+GITHUB = ProviderSpec(provider="github", app="posthog", event_types=frozenset({"pull_request", "push"}))
+STAMPHOG = ProviderSpec(provider="github", app="stamphog", event_types=frozenset({"pull_request"}))
+
+
+def _noop(delivery: WebhookDelivery) -> None:
+ return None
+
+
+def _consumer(
+ name: str,
+ *,
+ provider: str = "github",
+ app: str = "posthog",
+ event_types: frozenset[str] = frozenset({"pull_request"}),
+) -> WebhookConsumer:
+ return WebhookConsumer(name=name, provider=provider, app=app, event_types=event_types, handler=_noop)
+
+
+class TestConsumerRegistry(SimpleTestCase):
+ def test_groups_consumers_by_event_type_in_name_order(self) -> None:
+ registry = ConsumerRegistry(
+ providers=[GITHUB],
+ consumers=[
+ _consumer("loops", event_types=frozenset({"pull_request", "push"})),
+ _consumer("tasks_pr_backstop"),
+ _consumer("conversations", event_types=frozenset({"push"})),
+ ],
+ )
+
+ self.assertEqual(
+ [consumer.name for consumer in registry.consumers_for(provider="github", app="posthog", event_type="push")],
+ ["conversations", "loops"],
+ )
+ self.assertEqual(
+ [
+ consumer.name
+ for consumer in registry.consumers_for(provider="github", app="posthog", event_type="pull_request")
+ ],
+ ["loops", "tasks_pr_backstop"],
+ )
+ self.assertEqual(registry.consumers_for(provider="github", app="posthog", event_type="issues"), ())
+
+ def test_duplicate_name_within_a_provider_is_refused(self) -> None:
+ with self.assertRaises(RegistryError) as caught:
+ ConsumerRegistry(
+ providers=[GITHUB, STAMPHOG],
+ consumers=[_consumer("loops"), _consumer("loops", app="stamphog")],
+ )
+ self.assertIn("Duplicate consumer name", str(caught.exception))
+
+ def test_unknown_provider_app_is_refused(self) -> None:
+ with self.assertRaises(RegistryError) as caught:
+ ConsumerRegistry(providers=[GITHUB], consumers=[_consumer("loops", app="gitlab")])
+ self.assertIn("unknown provider app", str(caught.exception))
+
+ def test_event_type_the_provider_does_not_declare_is_refused(self) -> None:
+ with self.assertRaises(RegistryError) as caught:
+ ConsumerRegistry(
+ providers=[GITHUB],
+ consumers=[_consumer("loops", event_types=frozenset({"pull_request", "deployment"}))],
+ )
+ self.assertIn("deployment", str(caught.exception))
+
+ def test_the_real_registry_builds_from_every_incarnation_and_product(self) -> None:
+ reset_consumer_registry()
+ self.addCleanup(reset_consumer_registry)
+
+ registry = get_consumer_registry()
+
+ self.assertEqual(
+ [
+ consumer.name
+ for consumer in registry.consumers_for(provider="github", app="posthog", event_type="installation")
+ ],
+ ["installation_lifecycle"],
+ )
+
+ def test_same_name_on_two_apps_is_kept_apart_when_providers_differ(self) -> None:
+ slack = ProviderSpec(provider="slack", app="supporthog", event_types=frozenset({"message"}))
+ registry = ConsumerRegistry(
+ providers=[GITHUB, slack],
+ consumers=[
+ _consumer("conversations"),
+ _consumer("conversations", provider="slack", app="supporthog", event_types=frozenset({"message"})),
+ ],
+ )
+
+ self.assertEqual(
+ len(registry.consumers_for(provider="slack", app="supporthog", event_type="message")),
+ 1,
+ )
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
new file mode 100644
index 000000000000..90579c29dc9f
--- /dev/null
+++ b/posthog/ingress/test/test_verify.py
@@ -0,0 +1,172 @@
+import re
+import hmac
+import time
+import base64
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.ingress.verify.schemes import HmacSha256, SnsSignature, VerificationOutcome
+
+SECRET = "s3cret"
+BODY = b'{"action":"opened"}'
+
+
+def _digest(body: bytes = BODY, secret: str = SECRET) -> bytes:
+ return hmac.digest(secret.encode(), body, "sha256")
+
+
+class TestHmacSha256(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("github_hex_prefix", "hex", "sha256="),
+ ("bare_hex", "hex", ""),
+ ("base64_prefix", "base64", "v0="),
+ ]
+ )
+ def test_accepts_its_own_encoding_and_prefix(self, _name: str, encoding: str, prefix: str) -> None:
+ digest = _digest()
+ encoded = base64.b64encode(digest).decode() if encoding == "base64" else digest.hex()
+ scheme = HmacSha256(
+ secret_getter=lambda: SECRET,
+ signature_header="X-Signature",
+ prefix=prefix,
+ encoding=encoding, # type: ignore[arg-type]
+ )
+
+ self.assertEqual(
+ scheme.verify(body=BODY, headers={"X-Signature": prefix + encoded}),
+ VerificationOutcome.VERIFIED,
+ )
+ self.assertEqual(
+ scheme.verify(body=BODY, headers={"X-Signature": encoded}),
+ 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()}),
+ VerificationOutcome.VERIFIED,
+ )
+
+ @parameterized.expand(
+ [
+ ("missing_header", {}, VerificationOutcome.INVALID),
+ ("empty_header", {"X-Signature": ""}, VerificationOutcome.INVALID),
+ ("wrong_digest", {"X-Signature": "sha256=" + "0" * 64}, VerificationOutcome.INVALID),
+ ("non_ascii_header", {"X-Signature": "sha256=ÿ" + "0" * 63}, VerificationOutcome.INVALID),
+ ]
+ )
+ def test_rejects_unsigned_and_wrongly_signed_bodies(
+ 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)
+
+ 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()}),
+ VerificationOutcome.NOT_CONFIGURED,
+ )
+
+ def test_v0_timestamp_input_signs_timestamp_with_body(self) -> None:
+ timestamp = str(int(time.time()))
+ scheme = HmacSha256(
+ secret_getter=lambda: SECRET,
+ signature_header="X-Slack-Signature",
+ prefix="v0=",
+ signed_input="v0_timestamp_body",
+ timestamp_header="X-Slack-Request-Timestamp",
+ )
+ signed = b"v0:" + timestamp.encode() + b":" + BODY
+ headers = {
+ "X-Slack-Signature": "v0=" + _digest(signed).hex(),
+ "X-Slack-Request-Timestamp": timestamp,
+ }
+
+ self.assertEqual(scheme.verify(body=BODY, headers=headers), 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()}),
+ VerificationOutcome.INVALID,
+ )
+
+ @parameterized.expand(
+ [
+ ("too_old", -3600),
+ ("too_far_ahead", 3600),
+ ("unparseable", None),
+ ]
+ )
+ def test_rejects_a_replayed_timestamp(self, _name: str, offset_seconds: int | None) -> None:
+ timestamp = "not-a-time" if offset_seconds is None else str(int(time.time()) + offset_seconds)
+ scheme = HmacSha256(
+ secret_getter=lambda: SECRET,
+ signature_header="X-Signature",
+ signed_input="v0_timestamp_body",
+ timestamp_header="X-Timestamp",
+ timestamp_max_age_seconds=300,
+ timestamp_max_future_seconds=60,
+ )
+ 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)
+
+ def test_signature_pattern_rejects_before_the_digest_runs(self) -> None:
+ scheme = HmacSha256(
+ secret_getter=lambda: SECRET,
+ signature_header="X-Vapi-Signature",
+ signature_pattern=re.compile(r"^[0-9a-f]{64}$"),
+ )
+ with patch("hmac.digest") as digest:
+ self.assertEqual(
+ scheme.verify(body=BODY, headers={"X-Vapi-Signature": "NOT-A-HEX-DIGEST"}),
+ VerificationOutcome.INVALID,
+ )
+ digest.assert_not_called()
+
+ def test_compares_in_constant_time(self) -> None:
+ scheme = HmacSha256(secret_getter=lambda: SECRET, signature_header="X-Signature")
+ with patch("hmac.compare_digest", wraps=hmac.compare_digest) as compare:
+ scheme.verify(body=BODY, headers={"X-Signature": _digest().hex()})
+ compare.assert_called_once()
+
+
+class TestSnsSignature(SimpleTestCase):
+ def setUp(self) -> None:
+ self.allowed = frozenset({"arn:aws:sns:eu-west-1:1:ses-events"})
+
+ def _scheme(self, *, verified: bool = True, allowed: frozenset[str] | None = None) -> SnsSignature:
+ return SnsSignature(
+ verify_message=lambda message: verified,
+ allowed_topic_arns=lambda: self.allowed if allowed is None else allowed,
+ )
+
+ @parameterized.expand(
+ [
+ ("allowed_topic_and_valid_signature", "arn:aws:sns:eu-west-1:1:ses-events", True, "verified"),
+ ("foreign_topic", "arn:aws:sns:eu-west-1:2:someone-elses", True, "invalid"),
+ ("allowed_topic_but_bad_signature", "arn:aws:sns:eu-west-1:1:ses-events", False, "invalid"),
+ ]
+ )
+ def test_needs_both_the_allowlist_and_the_signature(
+ 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))
+
+ 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={}),
+ 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)
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
new file mode 100644
index 000000000000..bd40550a86f0
--- /dev/null
+++ b/posthog/ingress/test/test_views.py
@@ -0,0 +1,167 @@
+import hmac
+import json
+
+from unittest.mock import Mock, patch
+
+from django.test import RequestFactory, SimpleTestCase, override_settings
+
+from posthog.ingress.github.provider import build_github_provider
+from posthog.ingress.pandadoc.provider import build_pandadoc_provider
+from posthog.ingress.slack.provider import build_slack_provider
+from posthog.ingress.views import build_webhook_view
+
+SECRET = "s3cret"
+
+
+def _github_signature(body: bytes) -> str:
+ return "sha256=" + hmac.digest(SECRET.encode(), body, "sha256").hex()
+
+
+def _slack_signature(timestamp: str, body: bytes) -> str:
+ return "v0=" + hmac.digest(SECRET.encode(), b"v0:" + timestamp.encode() + b":" + body, "sha256").hex()
+
+
+class TestWebhookView(SimpleTestCase):
+ def setUp(self) -> None:
+ self.factory = RequestFactory()
+ self.dispatcher = Mock()
+ patcher = patch("posthog.ingress.views.get_dispatcher", return_value=self.dispatcher)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _github_view(self):
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ provider = build_github_provider("posthog")
+ return build_webhook_view(provider)
+
+ def _post(self, body: bytes, headers: dict[str, str]):
+ return self.factory.post(
+ "/webhooks/github/",
+ data=body,
+ content_type="application/json",
+ headers=headers,
+ )
+
+ def test_a_non_post_is_refused_before_any_verification(self) -> None:
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET) as secret:
+ response = self._github_view()(self.factory.get("/webhooks/github/"))
+ self.assertEqual(response.status_code, 405)
+ secret.assert_not_called()
+ self.dispatcher.dispatch.assert_not_called()
+
+ 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"})
+
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ response = self._github_view()(request)
+
+ self.assertEqual(response.status_code, 403)
+ self.dispatcher.dispatch.assert_not_called()
+
+ def test_an_unparseable_body_is_400(self) -> None:
+ body = b"{not json"
+ request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
+
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ response = self._github_view()(request)
+
+ self.assertEqual(response.status_code, 400)
+ self.dispatcher.dispatch.assert_not_called()
+
+ def test_a_verified_delivery_is_202_whatever_the_consumers_did(self) -> None:
+ body = json.dumps({"action": "opened", "installation": {"id": 42}}).encode()
+ request = self._post(
+ body,
+ {
+ "X-Hub-Signature-256": _github_signature(body),
+ "X-GitHub-Event": "pull_request",
+ "X-GitHub-Delivery": "delivery-1",
+ },
+ )
+
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET):
+ response = self._github_view()(request)
+
+ self.assertEqual(response.status_code, 202)
+ delivery = self.dispatcher.dispatch.call_args.args[0]
+ self.assertEqual(delivery.event_type, "pull_request")
+ self.assertEqual(delivery.delivery_id, "delivery-1")
+ self.assertEqual(delivery.context, {"installation_id": "42"})
+
+ 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(
+ "/webhooks/pandadoc/",
+ data=body,
+ content_type="application/json",
+ headers={"X-PandaDoc-Signature": hmac.digest(SECRET.encode(), body, "sha256").hex()},
+ )
+
+ with override_settings(PANDADOC_WEBHOOK_SECRET=SECRET):
+ response = build_webhook_view(build_pandadoc_provider())(request)
+
+ self.assertEqual(response.status_code, 202)
+ calls = self.dispatcher.dispatch.call_args_list
+ self.assertEqual(len(calls), 2)
+ self.assertEqual(len({id(call.kwargs["budget"]) for call in calls}), 1)
+
+ def test_an_unconfigured_provider_is_500_rather_than_a_signature_failure(self) -> None:
+ body = json.dumps({"action": "opened"}).encode()
+ request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
+
+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=""):
+ response = build_webhook_view(build_github_provider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 500)
+
+ def test_slack_url_verification_echoes_the_challenge_before_dispatch(self) -> None:
+ body = json.dumps({"type": "url_verification", "challenge": "abc123"}).encode()
+ timestamp = "1789000000"
+ request = self.factory.post(
+ "/slack/events/",
+ data=body,
+ content_type="application/json",
+ headers={
+ "X-Slack-Signature": _slack_signature(timestamp, body),
+ "X-Slack-Request-Timestamp": timestamp,
+ },
+ )
+ view = build_webhook_view(build_slack_provider(secret_getter=lambda: SECRET))
+
+ with patch("posthog.ingress.verify.schemes.time.time", return_value=float(timestamp)):
+ response = view(request)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(json.loads(response.content), {"challenge": "abc123"})
+ self.dispatcher.dispatch.assert_not_called()
+
+ def test_slack_event_callback_dispatches_the_inner_event_type(self) -> None:
+ body = json.dumps(
+ {
+ "type": "event_callback",
+ "event_id": "Ev1",
+ "team_id": "T1",
+ "event": {"type": "app_mention"},
+ }
+ ).encode()
+ timestamp = "1789000000"
+ request = self.factory.post(
+ "/slack/events/",
+ data=body,
+ content_type="application/json",
+ headers={
+ "X-Slack-Signature": _slack_signature(timestamp, body),
+ "X-Slack-Request-Timestamp": timestamp,
+ },
+ )
+ view = build_webhook_view(build_slack_provider(secret_getter=lambda: SECRET))
+
+ with patch("posthog.ingress.verify.schemes.time.time", return_value=float(timestamp)):
+ response = view(request)
+
+ self.assertEqual(response.status_code, 202)
+ delivery = self.dispatcher.dispatch.call_args.args[0]
+ self.assertEqual(delivery.event_type, "app_mention")
+ self.assertEqual(delivery.delivery_id, "Ev1")
+ self.assertEqual(delivery.context["slack_team_id"], "T1")
diff --git a/posthog/ingress/vapi/README.md b/posthog/ingress/vapi/README.md
new file mode 100644
index 000000000000..6ccb02be082a
--- /dev/null
+++ b/posthog/ingress/vapi/README.md
@@ -0,0 +1,39 @@
+# Vapi
+
+Deliveries from the Vapi voice agent.
+
+## Headers
+
+- `X-Vapi-Signature` carries the signature.
+
+Vapi sends no delivery header and no timestamp header.
+
+## Signature scheme
+
+HMAC-SHA256 over the raw body, hex encoded, with no prefix.
+There is no replay window, because there is no timestamp to check.
+A signature that is not 64 lowercase hex characters is rejected before the HMAC runs, which keeps a casual probe off the digest path.
+
+## Delivery id and event type
+
+Vapi sends no delivery id, so dedup is skipped.
+The call id is the only stable id in the payload, and it repeats across the status update and the end-of-call report.
+It therefore cannot key dedup: a mark set by the first message would swallow the second.
+The call id goes into the delivery context as `call_id`, and the consumer stays idempotent on it.
+The event type is `message.type`.
+
+## Apps and secrets
+
+One app, `default`.
+The secret is the Django setting `VAPI_WEBHOOK_SECRET`.
+
+## Quirks
+
+A bad signature answers 401 and an unconfigured instance answers 503.
+The public interview surface already relies on both codes.
+
+## Consumers
+
+No product registers a Vapi consumer yet.
+The user interviews endpoint moves to ingress in its own PR.
+See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/vapi/__init__.py b/posthog/ingress/vapi/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/vapi/provider.py b/posthog/ingress/vapi/provider.py
new file mode 100644
index 000000000000..36025572994c
--- /dev/null
+++ b/posthog/ingress/vapi/provider.py
@@ -0,0 +1,74 @@
+"""Vapi voice-agent webhooks.
+
+An unconfigured instance answers 503 and a bad signature 401, both of which the public
+interview surface already relies on.
+"""
+
+import re
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from django.conf import settings
+from django.http import HttpRequest
+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
+
+VAPI_EVENT_TYPES = frozenset({"status-update", "end-of-call-report"})
+
+# Vapi's HMAC-SHA256 hex digest is exactly 64 lowercase hex chars. Rejecting other shapes
+# before the HMAC keeps casual probes off the digest path and out of the diagnostic logs.
+VAPI_SIGNATURE_PATTERN = re.compile(r"^[0-9a-f]{64}$")
+
+SPECS = (ProviderSpec(provider="vapi", app="default", event_types=VAPI_EVENT_TYPES),)
+
+
+def _vapi_secret() -> str | None:
+ return getattr(settings, "VAPI_WEBHOOK_SECRET", "") or None
+
+
+class VapiProvider(WebhookProvider):
+ provider = "vapi"
+ app = "default"
+ invalid_signature_status = 401
+ unconfigured_status = 503
+
+ def __init__(self) -> None:
+ self._scheme = HmacSha256(
+ secret_getter=_vapi_secret,
+ signature_header="X-Vapi-Signature",
+ signature_pattern=VAPI_SIGNATURE_PATTERN,
+ )
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def deliveries(self, request: HttpRequest, payload: Any) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+ message = payload.get("message")
+ message = message if isinstance(message, Mapping) else {}
+ call = message.get("call")
+ call = call if isinstance(call, Mapping) else {}
+ call_id = call.get("id")
+ context = {"call_id": str(call_id)} if isinstance(call_id, str) and call_id else {}
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ # The call id is the only stable id Vapi sends, and it repeats across the
+ # status update and the end-of-call report, so it cannot key dedup. The
+ # consumer stays idempotent on it instead.
+ delivery_id=None,
+ event_type=str(message.get("type", "")),
+ payload=payload,
+ received_at=timezone.now(),
+ context=context,
+ ),
+ )
+
+
+def build_vapi_provider() -> VapiProvider:
+ return VapiProvider()
diff --git a/posthog/ingress/verify/__init__.py b/posthog/ingress/verify/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
new file mode 100644
index 000000000000..f0cd2c834f03
--- /dev/null
+++ b/posthog/ingress/verify/schemes.py
@@ -0,0 +1,139 @@
+"""Signature schemes: the part of a provider incarnation that decides "this is really them"."""
+
+import re
+import hmac
+import json
+import time
+import base64
+from collections.abc import Callable, Mapping
+from enum import StrEnum
+from typing import Any, Literal, Protocol
+
+import structlog
+
+from posthog.dataclasses import frozen
+
+logger = structlog.get_logger(__name__)
+
+SignedInput = Literal["body", "v0_timestamp_body"]
+SignatureEncoding = Literal["hex", "base64"]
+
+
+class VerificationOutcome(StrEnum):
+ VERIFIED = "verified"
+ INVALID = "invalid"
+ # 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"
+
+
+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)
+ if value is not None:
+ return value
+ lowered = name.lower()
+ for key, candidate in headers.items():
+ if key.lower() == lowered:
+ return candidate
+ return None
+
+
+class SignatureScheme(Protocol):
+ def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome: ...
+
+
+@frozen
+class HmacSha256:
+ """HMAC-SHA256 over the raw body, in the shapes the providers here actually send.
+
+ GitHub sends ``sha256=<hex>``; Slack and Customer.io sign ``v0:{timestamp}:{body}``
+ and pair the signature with a timestamp header they expect to be checked for replay.
+ """
+
+ secret_getter: Callable[[], str | None]
+ signature_header: str
+ prefix: str = ""
+ encoding: SignatureEncoding = "hex"
+ signed_input: SignedInput = "body"
+ timestamp_header: str | None = None
+ timestamp_max_age_seconds: int = 300
+ timestamp_max_future_seconds: int = 300
+ # Cheap shape gate run before the HMAC, so a probe cannot drive digest CPU (Vapi).
+ signature_pattern: re.Pattern[str] | None = None
+
+ def _timestamp_is_fresh(self, timestamp: str) -> bool:
+ try:
+ age_seconds = time.time() - float(timestamp)
+ except ValueError:
+ return False
+ return -self.timestamp_max_future_seconds <= age_seconds <= self.timestamp_max_age_seconds
+
+ def _signed_bytes(self, body: bytes, timestamp: str | None) -> bytes:
+ if self.signed_input == "v0_timestamp_body" and timestamp is not None:
+ # Assembled as bytes rather than through a decoded string, so a body that is
+ # not valid UTF-8 fails the comparison instead of raising.
+ return b"v0:" + timestamp.encode("utf-8") + b":" + body
+ return body
+
+ def _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
+
+ def verify(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):
+ 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
+
+ expected = 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")):
+ return VerificationOutcome.VERIFIED
+ return VerificationOutcome.INVALID
+
+
+@frozen
+class SnsSignature:
+ """AWS SNS message signature plus a topic-ARN allowlist.
+
+ 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.
+ """
+
+ verify_message: Callable[[Mapping[str, Any]], bool]
+ allowed_topic_arns: Callable[[], frozenset[str]]
+
+ def verify(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
+ allowed = self.allowed_topic_arns()
+ if not allowed:
+ return VerificationOutcome.NOT_CONFIGURED
+ try:
+ # RecursionError: deeply nested JSON from an unauthenticated caller must not 500.
+ message = json.loads(body)
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):
+ return VerificationOutcome.INVALID
+ if not isinstance(message, dict):
+ return VerificationOutcome.INVALID
+ 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):
+ logger.warning("ingress_sns_invalid_signature", message_id=message.get("MessageId"))
+ return VerificationOutcome.INVALID
+ return VerificationOutcome.VERIFIED
diff --git a/posthog/ingress/views.py b/posthog/ingress/views.py
new file mode 100644
index 000000000000..3e44fabb7e9d
--- /dev/null
+++ b/posthog/ingress/views.py
@@ -0,0 +1,65 @@
+"""The one inbound webhook view: verify, parse, dispatch, answer a fixed receipt."""
+
+import json
+from collections.abc import Callable
+
+from django.http import HttpRequest, HttpResponse
+from django.views.decorators.csrf import csrf_exempt
+
+import structlog
+
+from posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds
+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.verify.schemes import VerificationOutcome
+
+logger = structlog.get_logger(__name__)
+
+
+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.
+ """
+
+ @csrf_exempt
+ def webhook_view(request: HttpRequest) -> HttpResponse:
+ if request.method != "POST":
+ 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:
+ logger.error("ingress_webhook_not_configured", provider=provider.provider, app=provider.app)
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="not_configured")
+ return HttpResponse("Webhook not configured", status=provider.unconfigured_status)
+ if outcome is not VerificationOutcome.VERIFIED:
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_signature")
+ return HttpResponse("Invalid signature", status=provider.invalid_signature_status)
+
+ try:
+ # RecursionError: deeply nested JSON must answer 400, not 500.
+ payload = json.loads(request.body)
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_payload")
+ return HttpResponse("Invalid JSON", status=400)
+
+ handshake = provider.pre_dispatch_response(request, payload)
+ if handshake is not None:
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="accepted")
+ return handshake
+
+ dispatcher = get_dispatcher()
+ # 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.
+ budget = DeliveryBudget(delivery_budget_seconds())
+ for delivery in provider.deliveries(request, payload):
+ dispatcher.dispatch(delivery, budget=budget)
+
+ observe_delivery(provider=provider.provider, app=provider.app, outcome="accepted")
+ return HttpResponse(status=provider.success_status)
+
+ webhook_view.__name__ = f"{provider.provider}_{provider.app}_webhook"
+ return webhook_view
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index ab0fe4f646f9..d7c8584a4fe9 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1112,6 +1112,13 @@ ERROR_TRACKING_WEEKLY_DIGEST_ALLOWED_EMAILS = get_list(get_from_env("ERROR_TRACK
# webhook secret used initially for ET weekly digest workflow webhook but feel free to adopt it
WORKFLOWS_WEBHOOK_SECRET = get_from_env("WORKFLOWS_WEBHOOK_SECRET", "")
+####
+# Inbound webhook ingress (see posthog/ingress/)
+# Wall-clock seconds one request's consumers share. Providers give a delivery a short window
+# and mostly never retry it, so this sits under the tightest of those (GitHub's ten seconds)
+# and leaves room for verification and the response itself.
+INGRESS_DELIVERY_BUDGET_SECONDS = get_from_env("INGRESS_DELIVERY_BUDGET_SECONDS", 8.0, type_cast=float)
+
####
# OAuth
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 78b79341ebeb..2e21f42f2fd8 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -192,10 +192,8 @@ django.Exists products.dashboards.backend.facade.api.insight_has_listed_tile fac
django.HttpRequest products.demo.backend.facade.api.demo_route facade-accepts(request) 1
django.HttpRequest products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane facade-accepts(request) 1
django.HttpRequest products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane_status facade-accepts(request) 1
-django.HttpRequest products.stamphog.backend.facade.webhooks.stamphog_github_webhook facade-accepts(request) 1
django.HttpResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane facade-returns 1
django.HttpResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane_status facade-returns 1
-django.HttpResponse products.stamphog.backend.facade.webhooks.stamphog_github_webhook facade-returns 1
django.HttpResponse products.tasks.backend.facade.webhooks.handle_pull_request_event facade-returns 1
django.HttpResponse products.tasks.backend.facade.webhooks.handle_pull_request_review_event facade-returns 1
django.HttpResponseBase products.exports.backend.facade.api.get_export_asset_content_response facade-returns 1
diff --git a/products/stamphog/backend/presentation/webhooks.py b/products/stamphog/backend/presentation/webhooks.py
index 2e053da38fee..2c3969e50918 100644
--- a/products/stamphog/backend/presentation/webhooks.py
+++ b/products/stamphog/backend/presentation/webhooks.py
@@ -1,64 +1,13 @@
-"""Inbound webhook for the dedicated Stamphog GitHub App.
+"""The inbound webhook view for the dedicated Stamphog GitHub App.
-This is a standalone endpoint for Stamphog's own GitHub App — it does not share the
-unified ``posthog.urls.github_webhook`` fan-out. The integration layer wires the URL.
+This is a standalone endpoint for Stamphog's own GitHub App. It does not share the
+customer-facing App's endpoint. The integration layer wires the URL at this name.
"""
-import hmac
-import json
-import hashlib
-from typing import Any, cast
+from posthog.ingress.github.provider import build_github_provider
+from posthog.ingress.views import build_webhook_view
-from django.conf import settings
-from django.http import HttpRequest, HttpResponse
-from django.views.decorators.csrf import csrf_exempt
+# Built once per process: the provider only stores the secret getter, it never reads the secret here.
+stamphog_github_webhook = build_webhook_view(build_github_provider("stamphog"))
-import structlog
-
-from products.stamphog.backend.facade.tasks import process_installation_event, process_pull_request_event
-
-logger = structlog.get_logger(__name__)
-
-# Installation lifecycle events keep the repo-config rows in step with GitHub (repos added/removed,
-# app uninstalled) so newly installed repos appear in the toggle list without a manual re-sync.
-_INSTALLATION_EVENTS = frozenset({"installation", "installation_repositories"})
-
-
-def _verify_signature(body: bytes, signature: str | None, secret: str) -> bool:
- """Constant-time check of the ``X-Hub-Signature-256`` header (``sha256=<hex>``)."""
- if not signature or not signature.startswith("sha256="):
- return False
- expected = "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
- return hmac.compare_digest(expected, signature)
-
-
-@csrf_exempt
-def stamphog_github_webhook(request: HttpRequest) -> HttpResponse:
- """Verify, filter, and enqueue an inbound Stamphog GitHub App delivery."""
- if request.method != "POST":
- return HttpResponse(status=405)
-
- secret = getattr(settings, "STAMPHOG_GITHUB_APP_WEBHOOK_SECRET", "")
- if not secret:
- logger.error("stamphog_webhook_not_configured")
- return HttpResponse("Webhook not configured", status=500)
-
- signature = request.headers.get("X-Hub-Signature-256")
- if not _verify_signature(request.body, signature, secret):
- return HttpResponse("Invalid signature", status=403)
-
- # pull_request drives reviews; installation lifecycle events maintain the repo-config rows.
- # Ack everything else so GitHub stops retrying.
- event_type = request.headers.get("X-GitHub-Event", "")
- if event_type != "pull_request" and event_type not in _INSTALLATION_EVENTS:
- return HttpResponse(status=200)
-
- try:
- payload = json.loads(request.body)
- except json.JSONDecodeError:
- return HttpResponse("Invalid JSON", status=400)
-
- delivery_id = request.headers.get("X-GitHub-Delivery", "")
- task = process_installation_event if event_type in _INSTALLATION_EVENTS else process_pull_request_event
- cast(Any, task).delay(payload=payload, delivery_id=delivery_id)
- return HttpResponse(status=202)
+__all__ = ["stamphog_github_webhook"]
diff --git a/products/stamphog/backend/tests/test_presentation.py b/products/stamphog/backend/tests/test_presentation.py
deleted file mode 100644
index 467da3500e40..000000000000
--- a/products/stamphog/backend/tests/test_presentation.py
+++ /dev/null
@@ -1,76 +0,0 @@
-import hmac
-import json
-import hashlib
-from typing import Any
-
-import pytest
-from unittest.mock import patch
-
-from django.test import RequestFactory, override_settings
-
-from products.stamphog.backend.presentation.webhooks import stamphog_github_webhook
-
-WEBHOOK_SECRET = "test-webhook-secret"
-
-
-def _signature(body: bytes, secret: str) -> str:
- return "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
-
-
-def _request(body: bytes, *, event: str = "pull_request", delivery_id: str = "delivery-1", signature: str | None):
- factory = RequestFactory()
- headers: dict[str, Any] = {"HTTP_X_GITHUB_EVENT": event, "HTTP_X_GITHUB_DELIVERY": delivery_id}
- if signature is not None:
- headers["HTTP_X_HUB_SIGNATURE_256"] = signature
- return factory.post("/stamphog/webhook/", data=body, content_type="application/json", **headers)
-
-
-@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
-@patch("products.stamphog.backend.presentation.webhooks.process_pull_request_event.delay")
-def test_valid_pull_request_event_enqueues_and_returns_202(mock_delay):
- body = json.dumps({"action": "opened"}).encode("utf-8")
- request = _request(body, signature=_signature(body, WEBHOOK_SECRET))
-
- response = stamphog_github_webhook(request)
-
- assert response.status_code == 202
- mock_delay.assert_called_once_with(payload={"action": "opened"}, delivery_id="delivery-1")
-
-
-@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
-@patch("products.stamphog.backend.presentation.webhooks.process_pull_request_event.delay")
-def test_non_pull_request_event_is_acked_without_enqueueing(mock_delay):
- body = json.dumps({"action": "created"}).encode("utf-8")
- request = _request(body, event="issue_comment", signature=_signature(body, WEBHOOK_SECRET))
-
- response = stamphog_github_webhook(request)
-
- assert response.status_code == 200
- mock_delay.assert_not_called()
-
-
- "signature",
- [None, "sha256=" + "0" * 64],
- ids=["missing_signature", "wrong_signature"],
-)
-@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
-@patch("products.stamphog.backend.presentation.webhooks.process_pull_request_event.delay")
-def test_invalid_signature_is_rejected(mock_delay, signature):
- body = json.dumps({"action": "opened"}).encode("utf-8")
- request = _request(body, signature=signature)
-
- response = stamphog_github_webhook(request)
-
- assert response.status_code == 403
- mock_delay.assert_not_called()
-
-
-@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET="")
-def test_missing_secret_configuration_returns_500():
- body = json.dumps({"action": "opened"}).encode("utf-8")
- request = _request(body, signature=_signature(body, "irrelevant"))
-
- response = stamphog_github_webhook(request)
-
- assert response.status_code == 500
diff --git a/products/stamphog/backend/tests/test_webhook_consumers.py b/products/stamphog/backend/tests/test_webhook_consumers.py
new file mode 100644
index 000000000000..1eae537c00e2
--- /dev/null
+++ b/products/stamphog/backend/tests/test_webhook_consumers.py
@@ -0,0 +1,140 @@
+import hmac
+import json
+import hashlib
+from typing import Any
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import RequestFactory, SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.ingress.dispatch.loading import reset_consumer_registry
+
+from products.stamphog.backend.facade.webhooks import stamphog_github_webhook
+
+WEBHOOK_SECRET = "test-webhook-secret"
+WEBHOOK_PATH = "/webhooks/stamphog/github"
+
+PULL_REQUEST_DELAY = "products.stamphog.backend.facade.tasks.process_pull_request_event.delay"
+INSTALLATION_DELAY = "products.stamphog.backend.facade.tasks.process_installation_event.delay"
+
+
+def _signature(body: bytes, secret: str) -> str:
+ return "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
+
+
+@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)
+class TestStamphogGitHubWebhook(SimpleTestCase):
+ def setUp(self) -> None:
+ self.factory = RequestFactory()
+ # The registry is cached for the process and the dedup marks sit in the cache; both would
+ # otherwise carry another test's state into this one.
+ reset_consumer_registry()
+ cache.clear()
+ self.addCleanup(reset_consumer_registry)
+ self.addCleanup(cache.clear)
+
+ def _post(
+ self,
+ body: bytes,
+ *,
+ signature: str | None,
+ event: str = "pull_request",
+ delivery_id: str = "delivery-1",
+ ) -> Any:
+ headers: dict[str, str] = {"X-GitHub-Event": event, "X-GitHub-Delivery": delivery_id}
+ if signature is not None:
+ headers["X-Hub-Signature-256"] = signature
+ return self.factory.post(WEBHOOK_PATH, data=body, content_type="application/json", headers=headers)
+
+ @parameterized.expand(
+ [
+ ("pull_request", PULL_REQUEST_DELAY, INSTALLATION_DELAY),
+ ("installation", INSTALLATION_DELAY, PULL_REQUEST_DELAY),
+ ("installation_repositories", INSTALLATION_DELAY, PULL_REQUEST_DELAY),
+ ]
+ )
+ def test_a_verified_delivery_enqueues_the_task_that_event_routes_to(
+ self, event: str, expected_task: str, other_task: str
+ ) -> None:
+ body = json.dumps({"action": "opened"}).encode("utf-8")
+ request = self._post(body, event=event, signature=_signature(body, WEBHOOK_SECRET))
+
+ with patch(expected_task) as expected_delay, patch(other_task) as other_delay:
+ response = stamphog_github_webhook(request)
+
+ assert response.status_code == 202
+ expected_delay.assert_called_once_with(payload={"action": "opened"}, delivery_id="delivery-1")
+ other_delay.assert_not_called()
+
+ @patch(PULL_REQUEST_DELAY)
+ def test_a_redelivery_reaches_the_task_again_because_the_consumer_opts_out_of_dedup(self, mock_delay) -> None:
+ body = json.dumps({"action": "opened"}).encode("utf-8")
+
+ for _ in range(2):
+ request = self._post(body, signature=_signature(body, WEBHOOK_SECRET))
+ assert stamphog_github_webhook(request).status_code == 202
+
+ # The task keys its resume path on the delivery id, so GitHub's redelivery is how a run
+ # that never finished gets picked up. An ingress dedup mark would hold that off for 24 h.
+ assert mock_delay.call_count == 2
+
+ @patch(PULL_REQUEST_DELAY)
+ @patch(INSTALLATION_DELAY)
+ def test_an_event_type_the_app_does_not_register_is_acked_without_enqueueing(
+ self, mock_installation_delay, mock_pull_request_delay
+ ) -> None:
+ body = json.dumps({"action": "created"}).encode("utf-8")
+ request = self._post(body, event="issue_comment", signature=_signature(body, WEBHOOK_SECRET))
+
+ response = stamphog_github_webhook(request)
+
+ assert response.status_code == 202
+ mock_pull_request_delay.assert_not_called()
+ mock_installation_delay.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("missing_signature", None),
+ ("wrong_signature", "sha256=" + "0" * 64),
+ ]
+ )
+ @patch(PULL_REQUEST_DELAY)
+ def test_an_invalid_signature_is_rejected(self, _name: str, signature: str | None, mock_delay) -> None:
+ body = json.dumps({"action": "opened"}).encode("utf-8")
+ request = self._post(body, signature=signature)
+
+ response = stamphog_github_webhook(request)
+
+ assert response.status_code == 403
+ mock_delay.assert_not_called()
+
+ @patch(PULL_REQUEST_DELAY)
+ def test_a_signed_but_unparseable_body_is_rejected(self, mock_delay) -> None:
+ body = b"{not json"
+ request = self._post(body, signature=_signature(body, WEBHOOK_SECRET))
+
+ response = stamphog_github_webhook(request)
+
+ assert response.status_code == 400
+ mock_delay.assert_not_called()
+
+ @patch(PULL_REQUEST_DELAY)
+ def test_a_non_post_is_refused(self, mock_delay) -> None:
+ response = stamphog_github_webhook(self.factory.get(WEBHOOK_PATH))
+
+ assert response.status_code == 405
+ mock_delay.assert_not_called()
+
+ @override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET="")
+ @patch(PULL_REQUEST_DELAY)
+ def test_a_missing_app_secret_is_500_rather_than_a_signature_failure(self, mock_delay) -> None:
+ body = json.dumps({"action": "opened"}).encode("utf-8")
+ request = self._post(body, signature=_signature(body, "irrelevant"))
+
+ response = stamphog_github_webhook(request)
+
+ assert response.status_code == 500
+ mock_delay.assert_not_called()
diff --git a/products/stamphog/backend/webhook_consumers.py b/products/stamphog/backend/webhook_consumers.py
new file mode 100644
index 000000000000..6096f25303f1
--- /dev/null
+++ b/products/stamphog/backend/webhook_consumers.py
@@ -0,0 +1,37 @@
+"""Stamphog's consumer on its own GitHub App endpoint.
+
+The registry imports this module on the first delivery, so it stays cheap: the handler defers
+the task import, which drags the GitHub and Temporal clients in.
+"""
+
+from typing import Any, cast
+
+from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
+
+# Installation lifecycle events keep the repo-config rows in step with GitHub (repos added/removed,
+# app uninstalled) so newly installed repos appear in the toggle list without a manual re-sync.
+_INSTALLATION_EVENTS = frozenset({"installation", "installation_repositories"})
+
+
+def _run_review(delivery: WebhookDelivery) -> None:
+ from products.stamphog.backend.facade.tasks import ( # noqa: PLC0415 - keeps the GitHub and Temporal clients off the registry's import path
+ process_installation_event,
+ process_pull_request_event,
+ )
+
+ task = process_installation_event if delivery.event_type in _INSTALLATION_EVENTS else process_pull_request_event
+ cast(Any, task).delay(payload=dict(delivery.payload), delivery_id=delivery.delivery_id or "")
+
+
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="stamphog_review",
+ provider="github",
+ app="stamphog",
+ event_types=frozenset({"pull_request"}) | _INSTALLATION_EVENTS,
+ handler=_run_review,
+ # The task resumes its own work off `delivery_id`, so a redelivery is how a run that
+ # never finished gets picked up again. An ingress mark would hold that off for 24 h.
+ dedup=False,
+ ),
+)
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 99bbbbf036bd..e01e963d19d8 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -5,9 +5,8 @@ from typing import ClassVar
from unittest.mock import MagicMock, patch
-from django.conf import settings
from django.core.cache import cache
-from django.db import OperationalError, connection
+from django.db import OperationalError
from django.test import TestCase
from parameterized import parameterized
@@ -15,7 +14,6 @@ from prometheus_client import REGISTRY
from rest_framework.test import APIClient
from social_django.models import UserSocialAuth
-from posthog.api.github_webhooks.attribution import _attribution_db_aliases, _bounded_attribution_lookup
from posthog.api.github_webhooks.integrations import _installation_team_ids
from posthog.api.github_webhooks.pull_requests import _PR_BODY_MAX_CHARS, _account_type
from posthog.models.integration import Integration
@@ -2552,53 +2550,3 @@ class TestFindSignalImplementationRun(TestCase):
assert found is not None
assert found.run_id == legitimate.id
-
-
-class TestAttributionDbAliases(TestCase):
- def _with_replica_configured(self):
- return self.settings(DATABASES={**settings.DATABASES, "replica": settings.DATABASES["default"]})
-
- def test_default_only_when_no_replica_is_configured(self):
- self.assertEqual(_attribution_db_aliases(), ["default"])
-
- @patch("posthog.api.github_webhooks.attribution.router.db_for_read", return_value="default")
- def test_skips_a_configured_replica_the_router_would_not_read_from(self, _mock_db_for_read):
- # Bounding an alias means opening it, and connection setup is itself unbounded (these
- # aliases carry no connect_timeout), so a replica the router never reads from must not
- # be dialled just to install a cap on it.
- with self._with_replica_configured():
- self.assertEqual(_attribution_db_aliases(), ["default"])
-
- @patch("posthog.api.github_webhooks.attribution.router.db_for_read", return_value="replica")
- def test_skips_the_primary_when_every_model_reads_from_the_replica(self, _mock_db_for_read):
- # Symmetric to the above: a fully replica-opted deployment must not be made to wait on
- # the primary either, since opening it is just as unbounded.
- with self._with_replica_configured():
- self.assertEqual(_attribution_db_aliases(), ["replica"])
-
- @patch("posthog.api.github_webhooks.attribution.router.db_for_read")
- def test_covers_every_alias_the_models_read_from(self, mock_db_for_read):
- mock_db_for_read.side_effect = lambda model: "replica" if model is User else "default"
- with self._with_replica_configured():
- self.assertEqual(sorted(_attribution_db_aliases()), ["default", "replica"])
-
-
-class TestBoundedAttributionLookup(TestCase):
- def _statement_timeout(self) -> str:
- with connection.cursor() as cursor:
- cursor.execute("SHOW statement_timeout")
- row = cursor.fetchone()
- assert row is not None
- return row[0]
-
- def test_caps_statements_and_restores_the_previous_value(self):
- # Django's TestCase runs each test inside a transaction, which is exactly the case
- # the restore exists for: joining a transaction we did not open (a future caller's
- # atomic block, or ATOMIC_REQUESTS) must not leave the 800 ms cap behind.
- before = self._statement_timeout()
-
- with _bounded_attribution_lookup():
- inside = self._statement_timeout()
-
- self.assertEqual(inside, "800ms")
- self.assertEqual(self._statement_timeout(), before)