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.

chore(devex): enforce inbound webhook verification through ingress (#100416)

Julian Bez37d5040710b2
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.md
new file mode 100644
index 000000000000..60279f877e2e
--- /dev/null
+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md
@@ -0,0 +1,92 @@
+---
+name: adding-inbound-webhooks
+description: >
+ Use when adding a webhook endpoint for a third party that sends to PostHog, adding an inbound webhook consumer for a provider that already has an endpoint, or migrating a hand-rolled hmac verifier that the `inbound-webhooks-go-through-ingress` semgrep rule flags.
+ Covers the two jobs separately: a consumer in `products/<product>/backend/webhook_consumers.py`, and a provider incarnation under `posthog/ingress/<provider>/` wired with `build_webhook_view()`.
+ Carries the rules that are easy to get wrong: a consumer name is a dedup cache key, event types must be declared by the provider app or the registry raises, and the module stays cheap to import.
+ Trigger terms: add a webhook, webhook consumer, inbound webhook, hand-rolled hmac, inbound-webhooks-go-through-ingress.
+---
+
+# Adding an inbound webhook
+
+Every webhook a third party sends to PostHog goes through `posthog/ingress/`.
+Read [posthog/ingress/README.md](../../../posthog/ingress/README.md) for the transport contract and the package reference.
+This skill is the decision tree and the checklists.
+
+Which job are you doing?
+
+- The provider already has an endpoint (see the Endpoints table in `posthog/ingress/README.md`) and you want to react to its events: **add a consumer**.
+- No endpoint exists for this third party, or the semgrep rule flagged a hand-rolled verifier: **add a provider**, then add its consumer.
+- Outbound call to a vendor API, which is the other direction: `/routing-outbound-api-calls`.
+
+## Add a consumer
+
+A product declares its consumers in `products/<product>/backend/webhook_consumers.py`, in a `WEBHOOK_CONSUMERS` sequence of `WebhookConsumer` values from `posthog.ingress.contracts`.
+`products/stamphog/backend/webhook_consumers.py` is the smallest complete example.
+
+```python
+WEBHOOK_CONSUMERS = (
+ WebhookConsumer(
+ name="stamphog_review",
+ provider="github",
+ app="stamphog",
+ event_types=frozenset({"pull_request"}),
+ handler=_run_review,
+ ),
+)
+```
+
+Rules that decide whether this works:
+
+- `name` is unique per provider and is part of the dedup cache key. **Treat it as fixed once it ships**: renaming one lets a redelivery run the consumer a second time.
+- `provider` and `app` must match a `ProviderSpec` some incarnation declares, and `event_types` must be a subset of what that app declares. Anything else raises `RegistryError` when the registry is built, rather than sitting there looking registered and never running.
+- `handler` takes one `WebhookDelivery` and returns nothing. Its return value is ignored and it never decides the HTTP status.
+- Keep the module cheap to import. The registry imports it on the first delivery through `load_product_modules("webhook_consumers")`, so defer heavy imports into the handler behind `# noqa: PLC0415` with a reason.
+- The handler runs synchronously inside the request. Enqueue a task for real work, the way stamphog and conversations do.
+- A handler that reads the database wraps the read in `bounded_statement_timeout(ms, models=...)` from `posthog.ingress.dispatch.database`, passing only the models the read actually uses. Opening an alias is itself unbounded, so naming one the read never touches can stall the delivery on connection setup.
+- An import-linter contract (`webhook consumers must only import facade`) holds the module to its own product's `facade/`. Reach product internals through the facade.
+
+Tests: extend the product's existing webhook test module rather than starting a parallel one.
+`products/stamphog/backend/tests/test_webhook_consumers.py` is the shape: drive the real view with a signed `RequestFactory` request and assert the enqueue, plus the event type the app does not register, the bad signature, the unparseable body, the non-POST, and the missing secret.
+Reset the process-cached registry and the dedup cache between tests with `reset_consumer_registry()` and `cache.clear()`.
+
+## Add a provider
+
+Create `posthog/ingress/<provider>/` with an `__init__.py` and a `provider.py`.
+Copy `github/` for the full shape, or `vapi/` for a small one.
+`provider.py` holds three things:
+
+- `SPECS`, one `ProviderSpec` per app, naming the event types that app is subscribed to. The registry validates consumers against these.
+- A `WebhookProvider` subclass with `scheme()` (from `posthog/ingress/verify/`), `deliveries()` (how to read the event type, delivery id and context off the verified request), and any status codes the provider's protocol fixes. Defaults are 403 on a bad signature, 500 when unconfigured, 202 on success.
+- A `build_<provider>_provider(...)` function returning it. Secrets and verifiers a product owns are **passed into this builder**, never imported: nothing under `posthog/ingress/` may import a product.
+
+Then:
+
+1. Add the module path to `_INCARNATION_MODULES` in `posthog/ingress/providers.py`, or the registry never sees its specs or core consumers.
+2. Wire the URL with `build_webhook_view()`, for example `opt_slash_path("webhooks/<provider>", build_webhook_view(build_<provider>_provider()))`. GitHub and SES sit in `posthog/urls.py`; the others are declared by the owning product.
+3. Write `posthog/ingress/<provider>/README.md` with the fixed sections, in this order: 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, and on a README with different or reordered headings.
+4. Add the provider's signature header name to the `$HEADER` regex in `.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml`, plus a fixture case in the `.py` beside it. The header names are spelled out rather than matched generically because a generic header pattern makes semgrep time out on a large module, which drops that file from the scan without failing it.
+5. Delete the migrated endpoint's line from `paths.exclude` in the same rule. That list is a ratchet of verifiers that predate ingress, and the migrating PR removes its own entry.
+6. Preserve the endpoint's externally observable behavior. Existing tests are the contract: move or extend them, do not drop assertions.
+
+### The DRF adapter path
+
+An endpoint that genuinely needs DRF team scoping keeps its view and subclasses `posthog.auth.WebhookSignatureAuthentication`, which computes and compares through `posthog/ingress/verify/schemes.py`.
+Customer.io is the reference: team-scoped, secret from that team's integration row, no fan-out, so `customerio/` contributes a scheme only and declares no spec.
+Everything else goes through `build_webhook_view()`.
+
+## Non-goals
+
+Ingress stores no delivery log, runs no queue, retry or dead letter, lets no consumer decide the response, and promises no consumer order.
+Each was a real proposal already; ["Non-goals" in the package README](../../../posthog/ingress/README.md#non-goals) records the reason for each one, so read it before proposing any of them again.
+
+## Verify
+
+```sh
+semgrep --config .semgrep/rules/devex/ . # the ratchet entry is really gone
+semgrep --test .semgrep/ # only if you changed the rule itself
+lint-imports # the webhook_consumers contract
+hogli test products/<product>/backend/tests/test_webhook_consumers.py
+hogli test posthog/ingress/test/
+ruff check --fix <touched files> && ruff format <touched files>
+```
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.py b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.py
new file mode 100644
index 000000000000..7a101a5b8ded
--- /dev/null
+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.py
@@ -0,0 +1,116 @@
+# Test cases for inbound-webhooks-go-through-ingress rule.
+# ruff: noqa: F841, E501
+import hmac
+import hashlib
+
+from collections.abc import Callable
+
+import stripe
+from django.http import HttpRequest, HttpResponse
+
+from posthog.ingress.github import build_github_provider
+from posthog.ingress.views import build_webhook_view
+
+
+def _verify_signature(body: bytes, signature: str | None, secret: str) -> bool:
+ if not signature or not signature.startswith("sha256="):
+ return False
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.compare_digest(expected, signature)
+
+
+def hand_rolled_view(request: HttpRequest) -> HttpResponse:
+ signature = request.headers.get("X-Hub-Signature-256")
+ if not _verify_signature(request.body, signature, "secret"):
+ return HttpResponse(status=403)
+ return HttpResponse(status=202)
+
+
+def verify_vapi_webhook_signature(body: bytes, signature: str, secret: str) -> bool:
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.compare_digest(expected, signature)
+
+
+def signature_ok(body: bytes, signature: str, secret: str) -> bool:
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.compare_digest(expected, signature)
+
+
+async def verify_slack_signature(body: bytes, signature: str, secret: str) -> bool:
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.compare_digest(expected, signature)
+
+
+def _is_valid_signature(body: bytes, signature: str, secret: str) -> bool:
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest()
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.compare_digest(expected, signature)
+
+
+def bracket_header_view(request: HttpRequest) -> HttpResponse:
+ signature = request.headers["X-Slack-Signature"]
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = hmac.new(b"secret", request.body, hashlib.sha256).hexdigest()
+ # ruleid: inbound-webhooks-go-through-ingress
+ if not hmac.compare_digest(expected, signature):
+ return HttpResponse(status=403)
+ return HttpResponse(status=202)
+
+
+def naive_compare_view(request: HttpRequest) -> HttpResponse:
+ signature = request.headers.get("X-Vapi-Signature", "")
+ # ruleid: inbound-webhooks-go-through-ingress
+ if hmac.new(b"secret", request.body, hashlib.sha256).hexdigest() != signature:
+ return HttpResponse(status=403)
+ return HttpResponse(status=202)
+
+
+def verify_pandadoc_signature(body: bytes, signature: str, secret: str) -> bool:
+ # ruleid: inbound-webhooks-go-through-ingress
+ expected = hmac.digest(secret.encode(), body, hashlib.sha256)
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.compare_digest(expected.hex(), signature)
+
+
+def sdk_delegated_view(request: HttpRequest) -> HttpResponse:
+ # ruleid: inbound-webhooks-go-through-ingress
+ stripe.WebhookSignature.verify_header(request.body.decode(), "t=1,v1=abc", "secret", tolerance=300)
+ return HttpResponse(status=202)
+
+
+def ok_through_ingress() -> Callable[[HttpRequest], HttpResponse]:
+ # ok: inbound-webhooks-go-through-ingress
+ return build_webhook_view(build_github_provider("posthog"))
+
+
+# The three signers below carry no validity word in their name, so the verifier-name branch
+# leaves them alone. They still fire, because the header-aware branch reads the whole module
+# and this module reads signature headers above. That is the intended trade: a module that only
+# signs an outbound request reads no inbound signature header and stays out, and the rare module
+# that does both takes a `# nosemgrep` line.
+def outbound_signing(body: bytes, secret: str) -> str:
+ # ruleid: inbound-webhooks-go-through-ingress
+ return hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+
+
+def build_test_signature(body: bytes, secret: str) -> dict[str, str]:
+ # ruleid: inbound-webhooks-go-through-ingress
+ digest = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
+ return {"X-Hub-Signature-256": f"sha256={digest}"}
+
+
+def compute_signature(secret: str, timestamp: int, body: bytes) -> str:
+ # ruleid: inbound-webhooks-go-through-ingress
+ mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)
+ mac.update(f"{timestamp}.".encode())
+ mac.update(body)
+ return mac.digest().hex()
diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
new file mode 100644
index 000000000000..9cebe2dcf9bb
--- /dev/null
+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml
@@ -0,0 +1,128 @@
+rules:
+ - id: inbound-webhooks-go-through-ingress
+ message: |
+ Inbound webhook signature verification goes through `posthog.ingress`, never a
+ hand-rolled `hmac` check in a view or a per-product helper.
+ Add a `<provider>/` incarnation under `posthog/ingress/` carrying the signature
+ scheme and the delivery parsing, hand it to `build_webhook_view()` in the URLconf,
+ and register the handlers in `products/<product>/backend/webhook_consumers.py`.
+ An endpoint that genuinely needs DRF team scoping (Customer.io) keeps its view and
+ subclasses `WebhookSignatureAuthentication`; that class moves onto the ingress schemes
+ in its own PR. `posthog/ingress/README.md` holds the transport contract.
+
+ Why: a hand-rolled verifier repeats the parts that are easy to get wrong, the
+ constant-time compare, the replay window and the exact signed input, and it lands
+ outside the shared dedup, delivery budget, and delivery metrics, so a wedged
+ consumer is invisible and holds the connection open.
+
+ The rule fires on three shapes: an `hmac` digest or compare in a module that also
+ reads one of the known signature headers, `hmac` inside a function named like a
+ signature verifier, and a vendor SDK call that verifies an inbound signature.
+ What it misses follows from those three. The header list is closed, so a provider
+ whose header is not in it is caught only by the other two branches. A verifier with
+ a name outside the regex, in a module that reads no known header, passes. So does a
+ vendor SDK the third branch does not name, and a verifier in another language.
+
+ Suppress a legitimate exception with
+ `# nosemgrep: inbound-webhooks-go-through-ingress -- <reason>`.
+
+ See `posthog/ingress/README.md` and `posthog/ingress/<provider>/README.md`.
+ languages: [python]
+ severity: ERROR
+ patterns:
+ - pattern-either:
+ # A module that reads a signature header and builds or compares a digest
+ # verifies by hand. Every `hmac` entry point counts, not just the compare:
+ # `hmac.new(secret, body, sha256).hexdigest() == header` is the non-constant-time
+ # mistake the rule exists to catch, and it never reaches `compare_digest`.
+ # Signing an outbound request is legitimate, and stays out because a module that
+ # only signs does not read an inbound signature header.
+ - patterns:
+ - pattern-either:
+ - pattern: hmac.compare_digest(...)
+ - pattern: hmac.new(...)
+ - pattern: hmac.digest(...)
+ - pattern: hmac.HMAC(...)
+ # Both header mappings, and both ways of reading one. The attribute
+ # names are spelled out rather than bound to a metavariable, because a
+ # generic `$REQ.$ATTR.get(...)` makes semgrep time out on a large
+ # module, which drops that file from the scan without failing it.
+ - pattern-either:
+ - pattern-inside: |
+ ...
+ $REQ.headers.get($HEADER, ...)
+ ...
+ - pattern-inside: |
+ ...
+ $REQ.headers[$HEADER]
+ ...
+ - pattern-inside: |
+ ...
+ $REQ.META.get($HEADER, ...)
+ ...
+ - pattern-inside: |
+ ...
+ $REQ.META[$HEADER]
+ ...
+ - metavariable-regex:
+ metavariable: $HEADER
+ regex: (?i)^["'](http[_-])?(x[_-](hub[_-]signature[_-]256|slack[_-]signature|pandadoc[_-]signature|cio[_-]signature|vapi[_-]signature|vercel[_-]signature)|stripe[_-]signature)["']$
+ # The verifier often sits in its own module, away from the header read, so
+ # catch it by what it is called. Both name shapes a verifier takes: a verb
+ # first (`verify_signature`), or a predicate (`signature_ok`,
+ # `_is_valid_signature`). A name that only signs (`compute_signature`,
+ # `build_test_signature`) carries no validity word and stays out.
+ # `hmac.digest` is the stdlib one-shot form of `hmac.new(...).digest()`; a
+ # verifier that reaches for it skips `hmac.new` entirely.
+ # Both def forms, because `def` does not match an `async def` verifier.
+ - patterns:
+ - pattern-either:
+ - pattern: hmac.compare_digest(...)
+ - pattern: hmac.new(...)
+ - pattern: hmac.digest(...)
+ - pattern: hmac.HMAC(...)
+ - pattern-either:
+ - pattern-inside: |
+ def $VERIFY(...):
+ ...
+ - pattern-inside: |
+ async def $VERIFY(...):
+ ...
+ - metavariable-regex:
+ metavariable: $VERIFY
+ regex: ^_?((is_|has_)?(verify|valid|check|match)[a-z0-9_]*(signature|webhook|digest)[a-z0-9_]*|(is_|has_)?[a-z0-9_]*(signature|webhook|digest)[a-z0-9_]*_(ok|valid|verified|match)[a-z0-9_]*)$
+ # A vendor SDK can own the compare, so neither branch above sees any `hmac`.
+ # These calls only ever verify an inbound signature; nothing signs with them.
+ - patterns:
+ - pattern-either:
+ - pattern: stripe.WebhookSignature.verify_header(...)
+ - pattern: stripe.Webhook.construct_event(...)
+ paths:
+ include:
+ - /common/**/*.py
+ - /ee/**/*.py
+ - /posthog/**/*.py
+ - /products/**/*.py
+ exclude:
+ # Ingress is the sanctioned implementation.
+ - /posthog/ingress/**
+ # A test builds a signature to send; it does not verify an inbound one.
+ - '**/test/**'
+ - '**/tests/**'
+ - 'test_*.py'
+ - '*_test.py'
+ # Ratchet. Each entry is a verifier that predates ingress, and the PR that
+ # migrates that endpoint removes its line. The paths are the ones on master,
+ # so the rule holds whether or not the migrations land with it.
+ - /ee/api/vercel/vercel_webhooks.py
+ - /ee/partners/stripe/api/provisioning/signature.py
+ - /posthog/api/github_webhooks/signature.py
+ - /posthog/auth.py
+ - /posthog/models/integration/slack.py
+ - /products/conversations/backend/api/github_events.py
+ - /products/conversations/backend/api/slack_events.py
+ - /products/conversations/backend/mailgun.py
+ - /products/conversations/backend/support_slack.py
+ - /products/legal_documents/backend/logic/pandadoc.py
+ - /products/user_interviews/backend/presentation/webhooks.py
+ - /products/workflows/backend/api/ses_events_webhook.py
diff --git a/AGENTS.md b/AGENTS.md
index 9a3606360323..8168ee5ab6d5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -293,6 +293,7 @@ ALWAYS invoke the matching skill **first** — do not skip it, and do not attemp
- `/sending-notifications` — adding notification support
- `/routing-outbound-api-calls` — adding or changing Python code that calls a third-party HTTP API, or changing any domain under `posthog/egress/` (budget, lanes, identity, metrics, headers)
- `/adding-activity-logging` — adding activity logging (the audit trail) to a model, writing or changing a `model_activity_signal` receiver or an activity describer, auditing which write paths of a model are logged, or debugging a change that is missing from the activity log
+- `/adding-inbound-webhooks` — adding a webhook endpoint for a third party that sends to PostHog, adding a consumer for a provider that already has an endpoint, or migrating a verifier the `inbound-webhooks-go-through-ingress` rule flags
- `/writing-skills` — creating or updating skills in `.agents/skills/`
- `/editing-agents-md` — adding, editing or removing a rule in any `AGENTS.md` or `CLAUDE.md`, root or nested
- `/writing-evals` — adding or changing eval suites, cases, scorers, or seeders under `products/posthog_ai/evals/` or `products/*/evals/`, touching the harness in `products/posthog_ai/eval_harness/`, or running those evals
diff --git a/owners.yaml b/owners.yaml
index 13c42fbb70ea..a7e0918f123d 100644
--- a/owners.yaml
+++ b/owners.yaml
@@ -82,6 +82,21 @@ rules:
owners: team-ingestion
- match: '/packages/quill/'
owners: [platform-ux, '@sampennington']
+ # The URL surface and the inbound webhook transport: shared plumbing every product
+ # lands on, so a change here reaches further than the product that prompted it.
+ - match:
+ - '/docs/internal/github-webhooks.md'
+ - '/docs/internal/url-routing.md'
+ - '/posthog/api/__init__.py'
+ - '/posthog/api/github_webhooks/'
+ - '/posthog/api/rest_router.py'
+ - '/posthog/api/routing.py'
+ - '/posthog/ee_urls.py'
+ - '/posthog/frontend_views.py'
+ - '/posthog/github/'
+ - '/posthog/ingress/'
+ - '/posthog/urls.py'
+ owners: team-devex
- match: '/posthog/helpers/email_utils.py'
owners: team-platform-features
- match: '/posthog/test/activity_logging/'
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 110110da433e..d2546ae20bd5 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -211,6 +211,7 @@ def _verify_stripe_install_signature(state: str, user_id: str, account_id: str,
)
try:
# 300s tolerance matches the Stripe provisioning HMAC check at ee/partners/stripe/api/provisioning/signature.py.
+ # nosemgrep: inbound-webhooks-go-through-ingress -- this signs a marketplace install redirect, not a webhook delivery, so there is nothing for the dispatcher to fan out
stripe.WebhookSignature.verify_header(payload, install_signature, settings.STRIPE_SIGNING_SECRET, tolerance=300)
return True
except stripe.SignatureVerificationError:
diff --git a/posthog/ingress/AGENTS.md b/posthog/ingress/AGENTS.md
index 56b726d2c678..63a42a34bf24 100644
--- a/posthog/ingress/AGENTS.md
+++ b/posthog/ingress/AGENTS.md
@@ -1,9 +1,7 @@
# 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`.
+Read a provider's own `README.md` before changing that provider, and invoke `/adding-inbound-webhooks` before adding or changing a provider.
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.
@README.md
diff --git a/products/architecture.md b/products/architecture.md
index d0e3d9a6d7cb..48af88999cd4 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -200,6 +200,12 @@ A behavioral class that fits no approved interface must not cross at all.
Wrap it in a facade function returning contracts, or register a plain function (see the managed-view provider registry in `products/data_modeling/backend/facade/managed_viewset_hooks.py`).
A product whose facade hands out unapproved behavior is not soundly isolated: it loses `backend:contract-check` and pays the full suite until fixed.
+**Inbound webhook consumers are a designated location of the same kind.**
+A product declares its handlers in `backend/webhook_consumers.py`, in a `WEBHOOK_CONSUMERS` sequence.
+`posthog/ingress/` discovers that module through `load_product_modules("webhook_consumers")` on the first delivery, and its registry validates each consumer at build: an unknown provider app, a name already taken for that provider, or an event type the provider does not declare raises.
+No class crosses, because a consumer is a plain function behind a frozen contract, and an import-linter contract holds the module to its own product's `facade/`.
+See [posthog/ingress/README.md](/posthog/ingress/README.md).
+
Why shape rules rather than location rules: publicness-by-location without a constrained API shape rots.
Shopify's Packwerk `app/public` folders became a "catch-all drawer" of models, controllers, and jobs for exactly this reason.
The facade stays honest only if what crosses is a frozen dataclass or an implementation of a core-owned interface — nothing else.
@@ -258,7 +264,7 @@ myproduct/
### Which locations are fixed, and which are yours
-Only the paths the tooling is pointed at have fixed names: `facade/`, `presentation/`, `tasks/`, `routes.py`, and the wiring locations (`hogql_queries/`, `max_tools.py`, `temporal/`) — see [Wiring couplings](#wiring-couplings).
+Only the paths the tooling is pointed at have fixed names: `facade/`, `presentation/`, `tasks/`, `routes.py`, `webhook_consumers.py`, and the wiring locations (`hogql_queries/`, `max_tools.py`, `temporal/`) — see [Wiring couplings](#wiring-couplings).
They are the narrowed `backend:contract-check` inputs, and two import-linter contracts hold the HTTP surface inside them by shape: `routes.py` may only import `presentation/`, and `presentation/` may only import `facade/`.
Core reaches a product's views only through `routes.py`, so the chain core → routes → presentation → facade is three import edges, and a view anywhere else simply cannot be routed.
`hogli product:lint` holds the same two rules by reading the imports directly, because import-linter cannot see a module under a directory without `__init__.py`.
diff --git a/products/stamphog/turbo.json b/products/stamphog/turbo.json
index 71041022421c..908ed09e3c03 100644
--- a/products/stamphog/turbo.json
+++ b/products/stamphog/turbo.json
@@ -6,6 +6,7 @@
"backend/facade/**",
"backend/presentation/**",
"backend/routes.py",
+ "backend/webhook_consumers.py",
"backend/tasks/**",
"backend/temporal/**",
"backend/models.py",
diff --git a/pyproject.toml b/pyproject.toml
index 7f8a9f3517b2..712e6b568412 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -790,6 +790,24 @@ ignore_imports = [
"products.workflows.backend.routes -> products.workflows.backend.api.workflow_tasks",
]
+# webhook_consumers.py is the one module core reads (through posthog.ingress.dispatch.loading)
+# to register a product's inbound webhook consumers. Restricting what it may import gives the
+# chain core -> webhook_consumers -> facade as two import edges, so a handler cannot reach
+# product internals. Unlike the two contracts above it, this one carries no grandfathered list:
+# stamphog's is the only such module in the tree, and the ones arriving with the remaining
+# endpoint migrations already import only their own facade.
+[[tool.importlinter.contracts]]
+name = "webhook consumers must only import facade"
+type = "forbidden"
+source_modules = ["products.*.backend.webhook_consumers"]
+forbidden_modules = [
+ "products.*.backend",
+]
+allow_indirect_imports = true
+ignore_imports = [
+ "products.**.backend.webhook_consumers -> products.**.backend.facade.**",
+]
+
# The facade is the layer below presentation. A facade that imports its product's presentation
# inverts the layering (and drags DRF onto every consumer's import path); a facade that imports
# DRF is presentation in disguise. Only direct imports are checked (allow_indirect_imports is
diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.py
index c6a508dcc11d..42f2aa78b971 100644
--- a/tools/hogli-commands/hogli_commands/product/checks.py
+++ b/tools/hogli-commands/hogli_commands/product/checks.py
@@ -34,6 +34,7 @@ from .isolation import (
names_from_pattern as _names_from_pattern,
pattern_targets_public_surface as _pattern_targets_public_surface,
routes_in_turbo_inputs,
+ webhook_consumers_unwatched,
)
from .paths import TACH_TOML, get_tach_block
@@ -439,12 +440,13 @@ def _contract_check_withheld_note(status: IsolationStatus) -> str | None:
class ImportSurfaceCheck(ProductCheck):
- """Hold the two import-linter contracts by AST, so a namespace package cannot dodge them.
+ """Hold the three import-linter contracts by AST, so a namespace package cannot dodge them.
- The contracts say routes.py imports only presentation/, and presentation/ imports only
- facade/ and itself. import-linter enforces both through grimp, and grimp does not descend
- into a directory without an __init__.py — so `from ...backend.services.views import X`
- with no `services/__init__.py` is invisible to it and the contract passes vacuously.
+ The contracts say routes.py imports only presentation/, presentation/ imports only facade/
+ and itself, and webhook_consumers.py imports only facade/. import-linter enforces them all
+ through grimp, and grimp does not descend into a directory without an __init__.py — so
+ `from ...backend.services.views import X` with no `services/__init__.py` is invisible to it
+ and the contract passes vacuously.
That is a live view outside presentation/ that the narrowed contract-check inputs do not
watch. This check reads the same imports straight from the AST, honors the same
ignore_imports deferrals, and fails on what grimp cannot see.
@@ -457,6 +459,7 @@ class ImportSurfaceCheck(ProductCheck):
SURFACES = (
("routes", ("presentation",)),
("presentation", ("presentation", "facade")),
+ ("webhook_consumers", ("facade",)),
)
def should_run(self, ctx: CheckContext) -> bool:
@@ -480,7 +483,9 @@ class ImportSurfaceCheck(ProductCheck):
for f in files:
importer = self._module_name(ctx, f)
for line, target in module_import_targets(f, ctx.backend_dir, prefix):
- if target.startswith(allowed_prefixes) or f"{importer} -> {target}" in ignored:
+ # Segment boundary on purpose: `facade_legacy` must not pass as `facade`.
+ under_surface = any(target == p or target.startswith(f"{p}.") for p in allowed_prefixes)
+ if under_surface or f"{importer} -> {target}" in ignored:
continue
issues.append(
f"{f.relative_to(ctx.product_dir)}:{line} imports {target} — {source} may only import "
@@ -852,8 +857,9 @@ class IsolationChainCheck(ProductCheck):
"facade/presentation — the skip is inert (every change still re-runs the full Django "
'suite). Add a turbo.json narrowing inputs to ["backend/facade/**", '
'"backend/presentation/**"] plus the model surface (backend/models.py or '
- "backend/models/**, and backend/migrations/**) and any wiring locations the "
- "product has (backend/tasks/**, backend/temporal/**, …) to turn the skip on"
+ "backend/models/**, and backend/migrations/**), backend/webhook_consumers.py if the "
+ "product declares webhook consumers, and any wiring locations the product has "
+ "(backend/tasks/**, backend/temporal/**, …) to turn the skip on"
)
# When needs_turn_on is suppressed purely because of a facade violation (the other four
# conjuncts hold), the facade_violations warning above already explains what blocks narrowing,
@@ -875,6 +881,21 @@ class IsolationChainCheck(ProductCheck):
f'routes-only change would skip the Django suite. Add "{routes_glob}" to the contract-check inputs'
)
+ # Watching the consumer declarations: posthog/ingress/ imports webhook_consumers.py by name
+ # on the first delivery, so a consumer change a narrowing does not watch would skip the
+ # Django suite. Reported on its own condition, not folded into needs_turn_on: an unwatched
+ # consumer module is itself what makes has_narrowed False, so every other turbo-omission
+ # issue goes quiet with it, and needs_turn_on is ANDed with eligibility, sealing and the
+ # facade-violation gate — any one of those would hide the omission that caused the silence.
+ consumers_unwatched = webhook_consumers_unwatched(ctx.product_dir)
+ if consumers_unwatched:
+ result.issues.append(
+ "turbo.json narrows contract-check inputs but omits backend/webhook_consumers.py — "
+ "posthog/ingress imports the module by name on the first delivery, so a consumer "
+ "change (a new handler, a new event type) would skip the Django suite. Add "
+ '"backend/webhook_consumers.py" to the contract-check inputs'
+ )
+
# Watching the permanent-interface exposures: a marked [[interfaces]] block lets core
# depend on these modules outside the import graph (ClickHouse DDL in the schema registry
# and frozen migrations). That coupling can't be sealed, so the skip stays sound only if a
@@ -938,11 +959,11 @@ class IsolationChainCheck(ProductCheck):
# PackageJsonScriptsCheck — the skip can't be enabled until the wave empties them.
if result.issues or result.warnings:
- # needs_turn_on and routes_unwatched both point at turbo.json. needs_turn_on can't
- # co-occur with the facade/turbo mismatch issues above (it requires a real facade, a
- # script, and no narrowing). routes_unwatched can co-occur with them (it only needs
- # has_narrowed + a routes module), but turbo.json is still where the routes omission is
- # fixed, so it wins; the co-firing mismatch issues still print in the lint output.
+ # needs_turn_on, routes_unwatched and consumers_unwatched all point at turbo.json.
+ # needs_turn_on can't co-occur with the facade/turbo mismatch issues above (it requires
+ # a real facade, a script, and no narrowing). routes_unwatched and consumers_unwatched
+ # can co-occur with them, but turbo.json is still where those omissions are fixed, so
+ # they win; the co-firing mismatch issues still print in the lint output.
# An unqualified permanent exposure is a defect in the tach.toml marker itself, so point
# there; it takes precedence because it's the most fundamental of these issues.
turbo_omission = has_narrowed and (
@@ -950,7 +971,7 @@ class IsolationChainCheck(ProductCheck):
)
if status.unqualified_permanent_exposures:
result.file = "tach.toml"
- elif needs_turn_on or routes_unwatched or turbo_omission:
+ elif needs_turn_on or routes_unwatched or consumers_unwatched or turbo_omission:
result.file = f"products/{ctx.name}/turbo.json"
else:
result.file = f"products/{ctx.name}/backend/facade/api.py"
diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.py
index 8a30b0c13c02..dee586ff0518 100644
--- a/tools/hogli-commands/hogli_commands/product/isolation.py
+++ b/tools/hogli-commands/hogli_commands/product/isolation.py
@@ -306,11 +306,14 @@ def contract_check_inputs(product_dir: Path) -> list[str]:
# A contract-check input is "on the public surface" when it targets the facade, the presentation
-# layer, or the routes registration module. Anchored on the path separator so a near-miss like
-# backend/facade_legacy/** can't pass.
+# layer, the routes registration module, or the webhook consumer declarations. Anchored on the path
+# separator so a near-miss like backend/facade_legacy/** can't pass.
_FACADE_PREFIX = "backend/facade/"
_FACADE_PRESENTATION_PREFIXES = (_FACADE_PREFIX, "backend/presentation/")
_ROUTES_PREFIXES = ("backend/routes.py", "backend/routes/")
+# posthog/ingress/ imports this module by name on the first delivery, and an import-linter contract
+# holds it to its own product's facade, so a change to it has to re-run that lane.
+_WEBHOOK_CONSUMERS_PREFIXES = ("backend/webhook_consumers.py",)
# The wiring locations; the identifiers below call them garages. A prefix is either a directory
# (trailing slash) or a single-file module. A class re-exported from one of these is accepted
@@ -355,6 +358,40 @@ def location_input_glob(location: str) -> str:
return f"{location.rstrip('/')}/**" if location.endswith("/") else location
+def _input_covers(input_glob: str, accepted: str) -> bool:
+ """A directory location (trailing slash) is covered by any input inside it; a single-file
+ location by an exact input, or by a wildcard-free `dir/**` input whose directory contains it —
+ backend/models/** watches backend/models/tcac.py, but backend/tasks.py.bak must not count as
+ watching backend/tasks.py (and backend/tasks/** does not watch backend/tasks.py)."""
+ if accepted.endswith("/"):
+ return input_glob.startswith(accepted)
+ if input_glob == accepted:
+ return True
+ base, _, pattern = input_glob.rpartition("/")
+ if pattern == "**":
+ return "*" not in base and accepted.startswith(base + "/")
+ # `dir/**/*.py` and `dir/*.py` are the two glob shapes turbo.json inputs use for a file set.
+ if pattern.startswith("*.") and "*" not in pattern[1:]:
+ if not accepted.endswith(pattern[1:]):
+ return False
+ if base.endswith("/**"):
+ root = base.removesuffix("/**")
+ return "*" not in root and accepted.startswith(root + "/")
+ return "*" not in base and accepted.rpartition("/")[0] == base
+ return False
+
+
+def _webhook_consumers_unwatched(product_dir: Path, inputs: list[str]) -> bool:
+ """True when the product declares webhook consumers and no narrowed input watches the module.
+
+ Presence-based like the routes rule, because core imports the module by name on the first
+ delivery: a product that adds it without listing it would keep the skip while a consumer
+ change — a new handler, a new event type — runs no Django suite."""
+ if not (product_dir / "backend" / "webhook_consumers.py").exists():
+ return False
+ return not any(_input_covers(i.removeprefix("./"), p) for i in inputs for p in _WEBHOOK_CONSUMERS_PREFIXES)
+
+
def has_narrowed_turbo_inputs(
product_dir: Path,
permanent_modules: frozenset[str] = frozenset(),
@@ -370,14 +407,20 @@ def has_narrowed_turbo_inputs(
all count as extended surface: a product may list them without forfeiting the narrowing, since
core depends on each outside the plain facade->contracts channel and they must re-run the suite
on change (see uncovered_permanent_modules, unwatched_garages, and the carve-out/model coverage
- checks)."""
+ checks).
+
+ A webhook_consumers.py module is the one extended surface that is also required once it exists:
+ listing it is optional for a product that has none, mandatory for a product that has one."""
inputs = [i for i in contract_check_inputs(product_dir) if not i.startswith("!")]
if not inputs:
return False
+ if _webhook_consumers_unwatched(product_dir, inputs):
+ return False
permanent_prefixes = tuple(p for m in permanent_modules for p in _module_input_prefixes(m))
accepted = (
_FACADE_PRESENTATION_PREFIXES
+ _ROUTES_PREFIXES
+ + _WEBHOOK_CONSUMERS_PREFIXES
+ GARAGE_PREFIXES
+ permanent_prefixes
+ tuple(carveout_modules)
@@ -388,17 +431,18 @@ def has_narrowed_turbo_inputs(
)
-def _input_covers(input_glob: str, accepted: str) -> bool:
- """A directory location (trailing slash) is covered by any input inside it; a single-file
- location by an exact input, or by a wildcard-free `dir/**` input whose directory contains it —
- backend/models/** watches backend/models/tcac.py, but backend/tasks.py.bak must not count as
- watching backend/tasks.py (and backend/tasks/** does not watch backend/tasks.py)."""
- if accepted.endswith("/"):
- return input_glob.startswith(accepted)
- if input_glob == accepted:
- return True
- directory = input_glob.removesuffix("/**")
- return directory != input_glob and "*" not in directory and accepted.startswith(directory + "/")
+def webhook_consumers_unwatched(product_dir: Path) -> bool:
+ """True when a product that narrows contract-check inputs declares webhook consumers and
+ lists no input that watches the module.
+
+ Reported on its own by the lint rather than only inside the narrowing verdict. An unwatched
+ consumer module is what makes has_narrowed_turbo_inputs() answer False, and every other
+ turbo-omission issue is gated on a narrowed product, so the omission that silenced them would
+ otherwise be the one thing nobody says out loud."""
+ inputs = [i for i in contract_check_inputs(product_dir) if not i.startswith("!")]
+ if not inputs:
+ return False
+ return _webhook_consumers_unwatched(product_dir, inputs)
def _uncovered_locations(product_dir: Path, targets_to_prefixes: dict[str, tuple[str, ...]]) -> set[str]:
diff --git a/tools/hogli-commands/hogli_commands/product_structure.yaml b/tools/hogli-commands/hogli_commands/product_structure.yaml
index a4c1f82ac2e2..7fa9a07038eb 100644
--- a/tools/hogli-commands/hogli_commands/product_structure.yaml
+++ b/tools/hogli-commands/hogli_commands/product_structure.yaml
@@ -69,6 +69,7 @@ root_files:
"inputs": [
"backend/facade/**",
"backend/presentation/**",
+ "backend/webhook_consumers.py",
"backend/tasks/**",
"backend/models.py",
"backend/migrations/**"
diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.py
index c11c368b8bd6..93583e45f5a3 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py
@@ -327,6 +327,22 @@ _NARROWED_TURBO_WITH_ROUTES = {
},
}
+_NARROWED_TURBO_WITH_CONSUMERS = {
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/webhook_consumers.py",
+ "backend/migrations/**",
+ ],
+ "outputs": [],
+ "cache": True,
+ }
+ },
+}
+
chain_check = IsolationChainCheck()
@@ -442,6 +458,41 @@ class TestIsolationChainRoutes:
assert not any("routes.py" in i for i in result.issues)
+class TestIsolationChainWebhookConsumers:
+ @pytest.mark.parametrize(
+ "turbo, reported",
+ [
+ pytest.param(_NARROWED_TURBO, True, id="narrowed_without_the_consumer_input"),
+ pytest.param(_NARROWED_TURBO_WITH_CONSUMERS, False, id="narrowed_with_the_consumer_input"),
+ pytest.param(None, False, id="unnarrowed_still_watches_all_of_backend"),
+ ],
+ )
+ def test_unwatched_consumer_module_is_reported_when_not_eligible(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, turbo: dict | None, reported: bool
+ ) -> None:
+ # No tach interface, so the product is not externally sealed and not eligible for isolated
+ # tests — needs_turn_on stays silent. An unwatched consumer module is also what makes
+ # has_narrowed False, so every other turbo-omission issue is silent too. The consumer
+ # omission must still be reported, or the narrowing that skips the Django suite on a
+ # consumer change goes unmentioned by the whole check.
+ import hogli_commands.product.isolation as isolation_module
+
+ monkeypatch.setattr(isolation_module, "has_tach_interface", lambda *_a, **_k: False)
+ monkeypatch.setattr(isolation_module, "has_legacy_interface_leaks", lambda *_a, **_k: False)
+ monkeypatch.setattr(isolation_module, "presentation_bypass_entries", lambda *_a, **_k: [])
+ ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)
+ (ctx.backend_dir / "webhook_consumers.py").write_text("")
+ if turbo is not None:
+ (ctx.product_dir / "turbo.json").write_text(json.dumps(turbo))
+
+ result = chain_check.run(ctx)
+
+ assert any("webhook_consumers.py" in i for i in result.issues) is reported
+ assert not any("inert" in i for i in result.issues)
+ if reported:
+ assert result.file == "products/my_product/turbo.json"
+
+
class TestNarrowedTurboDetection:
@pytest.mark.parametrize(
"inputs, expected",
@@ -1047,7 +1098,7 @@ def _make_backend(tmp_path: Path, files: list[str]) -> CheckContext:
class TestImportSurfaceCheck:
- """The AST twin of the two import-linter contracts. Its reason to exist is the namespace
+ """The AST twin of the three import-linter contracts. Its reason to exist is the namespace
package: grimp cannot see a module under a directory without __init__.py, so a routed
view there passes the contract vacuously. None of the fixtures below carry a marker."""
@@ -1098,6 +1149,27 @@ class TestImportSurfaceCheck:
0,
id="cross_product_is_tachs_job",
),
+ pytest.param(
+ {"webhook_consumers.py": "from products.p.backend.facade.api import f\n", "facade/api.py": ""},
+ 0,
+ id="webhook_consumers_from_facade",
+ ),
+ pytest.param(
+ {
+ "webhook_consumers.py": "from products.p.backend.services.handlers import h\n",
+ "services/handlers.py": "",
+ },
+ 1,
+ id="webhook_consumers_from_unmarked_package",
+ ),
+ pytest.param(
+ {
+ "webhook_consumers.py": "from products.p.backend.facade_legacy.handlers import h\n",
+ "facade_legacy/handlers.py": "",
+ },
+ 1,
+ id="webhook_consumers_from_facade_lookalike",
+ ),
],
)
def test_surface(
@@ -1917,6 +1989,20 @@ class TestNarrowedTurboWiringSurface:
product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=inputs)
assert has_narrowed_turbo_inputs(product_dir) is expected
+ @pytest.mark.parametrize(
+ "inputs, expected",
+ [
+ (["backend/facade/**", "backend/webhook_consumers.py"], True),
+ # present but unlisted: a consumer change would run no Django suite, so it isn't narrowed
+ (["backend/facade/**"], False),
+ ],
+ )
+ def test_present_webhook_consumers_must_stay_watched(
+ self, tmp_path: Path, inputs: list[str], expected: bool
+ ) -> None:
+ product_dir, _ = _write_facade_product(tmp_path, sources={"webhook_consumers.py": ""}, turbo_inputs=inputs)
+ assert has_narrowed_turbo_inputs(product_dir) is expected
+
def test_carveout_module_is_accepted_surface_only_when_declared(self, tmp_path: Path) -> None:
# a carve-out defining module is an odd input (not facade/garage): it only counts as
# narrowing when the caller passes it as a known carve-out module.
@@ -1929,6 +2015,9 @@ class TestNarrowedTurboWiringSurface:
[
(["backend/facade/**", "backend/models/tcac.py"], set()), # covered
(["backend/facade/**", "backend/models/**"], set()), # a dir glob covers the file inside it
+ (["backend/facade/**", "backend/models/**/*.py"], set()), # the file-set form turbo inputs use
+ (["backend/facade/**", "backend/models/*.py"], set()), # single-level file set
+ (["backend/facade/**", "backend/models/**/*.ts"], {"backend/models/tcac.py"}), # other extension
(["backend/facade/**", "backend/models_extra/**"], {"backend/models/tcac.py"}), # sibling dir doesn't
(["backend/facade/**"], {"backend/models/tcac.py"}), # missing -> uncovered
],