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(devex): let products mount their own root routes, starting with webhooks (#101445)

Julian Bezc9875d7885d5
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.md
index cd53b12be703..e53ea63f03de 100644
--- a/.agents/skills/adding-inbound-webhooks/SKILL.md
+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md
@@ -67,7 +67,7 @@ Copy `github/` for the full shape, or `vapi/` for a small one.
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.
+2. Wire the URL with `build_webhook_view()` where the App registration lives. The owner of the third-party App owns the route: a product that registered the App declares `urlpatterns` in its own `products/<product>/backend/routes.py`, for example `opt_slash_path("webhooks/<product>/<provider>", build_webhook_view(build_<provider>_provider()))`. The path must start with `webhooks/<product>/` or `api/<product>/`, or the URL conf fails to load. Only an App several products consume stays in `posthog/urls.py`, which today is the customer-facing GitHub App alone. See [docs/internal/url-routing.md](../../../docs/internal/url-routing.md).
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.
diff --git a/docs/internal/url-routing.md b/docs/internal/url-routing.md
index 1330c5c8f762..99515e824e39 100644
--- a/docs/internal/url-routing.md
+++ b/docs/internal/url-routing.md
@@ -21,5 +21,22 @@ Event deletion is available only with `TEST`.
The Temporal codec endpoint is registered once when either setting is enabled.
These conditions control registration, not only view behavior.
-Product DRF routes continue to register through `products/<product>/backend/routes.py`.
-Root-level product routes remain explicit in `posthog/urls.py`.
+## Product root routes
+
+A product declares its root paths in `products/<product>/backend/routes.py`, as a `urlpatterns` list beside `register_routes`.
+`posthog/product_urls.py` collects every product's list, and `posthog/urls.py` splices it into one slot: after all core routes, and before the `^api.+` fallback and the frontend catch-all.
+Precedence stays one list to read, and a product that adds a path does not touch core.
+
+Each pattern must start with `api/<product>/` or `webhooks/<product>/`, where `<product>` is the product directory name.
+A pattern outside those prefixes raises `ProductRouteError` when the URL conf loads.
+The check is fail-closed because a product path in core's namespace can shadow a core route, and the winner would then depend on app iteration order.
+
+`register_routes(routers)` stays the way to add DRF routes.
+Use `urlpatterns` only for a plain Django path that no router can carry, such as an inbound webhook endpoint.
+
+### Who owns a webhook route
+
+The owner of the third-party App registration owns the route.
+The customer-facing GitHub App is shared: one endpoint fans out to several products, so core mounts it.
+An App a single product registers, such as Stamphog's GitHub App, is mounted by that product.
+The SES topic behind `webhooks/workflows/ses-events` is the exception for now: its view still lives in `backend/api/`, so it waits for the change that moves it onto the ingress builders.
diff --git a/posthog/api/test/test_product_urls.py b/posthog/api/test/test_product_urls.py
new file mode 100644
index 000000000000..ef61387f4f7e
--- /dev/null
+++ b/posthog/api/test/test_product_urls.py
@@ -0,0 +1,93 @@
+from types import ModuleType
+
+from django.http import HttpRequest, HttpResponse
+from django.test import SimpleTestCase
+from django.urls import path, re_path, resolve, reverse
+
+from parameterized import parameterized
+
+import posthog.urls
+from posthog.api import api_not_found
+from posthog.product_urls import ProductRootRoutes, ProductRouteError
+from posthog.utils import opt_slash_path
+
+
+def _view(request: HttpRequest) -> HttpResponse:
+ return HttpResponse()
+
+
+def _routes_module(product: str, *routes: str) -> ModuleType:
+ module = ModuleType(f"products.{product}.backend.routes")
+ module.urlpatterns = [path(route, _view) for route in routes] # type: ignore[attr-defined]
+ return module
+
+
+class TestProductRootRoutes(SimpleTestCase):
+ def test_collects_the_patterns_a_product_declares(self) -> None:
+ module = _routes_module("stamphog", "webhooks/stamphog/github", "api/stamphog/thing")
+
+ collected = ProductRootRoutes.from_module(module)
+
+ assert [str(pattern.pattern) for pattern in collected] == [
+ "webhooks/stamphog/github",
+ "api/stamphog/thing",
+ ]
+
+ def test_a_module_without_urlpatterns_contributes_nothing(self) -> None:
+ assert ProductRootRoutes.from_module(ModuleType("products.stamphog.backend.routes")) == []
+
+ @parameterized.expand(
+ [
+ ("core namespace", "webhooks/github"),
+ ("another product", "api/legal_documents/pandadoc"),
+ ("prefix without the separator", "webhooks/stamphogus/github"),
+ ("unreserved namespace", "internal/stamphog/thing"),
+ ]
+ )
+ def test_rejects_a_route_outside_the_products_own_prefixes(self, _name: str, route: str) -> None:
+ module = _routes_module("stamphog", route)
+
+ with self.assertRaises(ProductRouteError) as caught:
+ ProductRootRoutes.from_module(module)
+
+ assert str(caught.exception) == (
+ f"Product 'stamphog' declares root URL pattern {route!r}, which must start with "
+ "'api/stamphog/' or 'webhooks/stamphog/'"
+ )
+
+ @parameterized.expand(
+ [
+ ("bare regex", "webhooks/stamphog/github"),
+ ("regex ending in a group", "webhooks/stamphog/github/?"),
+ ]
+ )
+ def test_rejects_an_unanchored_regex_route(self, _name: str, regex: str) -> None:
+ module = ModuleType("products.stamphog.backend.routes")
+ module.urlpatterns = [re_path(regex, _view)] # type: ignore[attr-defined]
+
+ with self.assertRaises(ProductRouteError) as caught:
+ ProductRootRoutes.from_module(module)
+
+ assert str(caught.exception) == (
+ f"Product 'stamphog' declares root URL pattern {regex!r} as an unanchored regex, "
+ "which matches anywhere in the path. Start it with '^'"
+ )
+
+ def test_accepts_the_anchored_regex_opt_slash_path_builds(self) -> None:
+ module = ModuleType("products.stamphog.backend.routes")
+ module.urlpatterns = [opt_slash_path("webhooks/stamphog/github", _view)] # type: ignore[attr-defined]
+
+ assert len(ProductRootRoutes.from_module(module)) == 1
+
+
+class TestProductRootRouteSlot(SimpleTestCase):
+ def test_product_routes_sit_after_core_routes_and_before_the_api_fallback(self) -> None:
+ names = [getattr(pattern, "name", None) for pattern in posthog.urls.urlpatterns]
+ routes = [str(pattern.pattern) for pattern in posthog.urls.urlpatterns]
+
+ assert names.index("schema") < names.index("user_interviews_vapi_webhook")
+ assert names.index("user_interviews_vapi_webhook") < routes.index("^api.+")
+
+ def test_the_api_fallback_does_not_shadow_a_moved_product_route(self) -> None:
+ assert reverse("user_interviews_vapi_webhook") == "/api/user_interviews/vapi_webhook/"
+ assert resolve("/api/user_interviews/vapi_webhook/").func is not api_not_found
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 836e0375a071..7f90653c5615 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -53,8 +53,10 @@ An HMAC over raw bytes proves only the signature, so its `facts` are empty and `
| `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.
+The owner of the third-party App registration owns the route.
+The customer-facing GitHub App is shared across products, so its two endpoints are declared in `posthog/urls.py`.
+Every other endpoint is declared by the product that registered the App, in its own `routes.py`.
+The SES endpoint is the exception for now, because its view still lives in `backend/api/` rather than behind the ingress builders.
The Vapi endpoint sits behind a per-IP throttle the product owns, from before ingress had a throttle lane.
It moves onto `throttle_class` next.
@@ -176,12 +178,20 @@ Add a `<provider>/` subpackage with a `provider.py` holding three things (see `g
- 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:
+
+Then mount the URL where the App registration lives.
+A product that registered the App declares the path in its own `products/<product>/backend/routes.py`, under a `webhooks/<product>/` prefix:
```python
-path("webhooks/github/", build_webhook_view(build_github_provider("posthog")))
+urlpatterns: list[URLPattern] = [
+ opt_slash_path("webhooks/stamphog/github", build_webhook_view(build_github_provider("stamphog"))),
+]
```
+An App several products consume has no single owner, so it stays in `posthog/urls.py`.
+The customer-facing GitHub App is the only one today.
+[docs/internal/url-routing.md](../../docs/internal/url-routing.md) has the slot and the prefix rule.
+
Secrets and verifiers that belong to a product are **passed into the builder**.
Nothing under `posthog/ingress/` imports a product.
diff --git a/posthog/product_urls.py b/posthog/product_urls.py
new file mode 100644
index 000000000000..2a6806fc5071
--- /dev/null
+++ b/posthog/product_urls.py
@@ -0,0 +1,85 @@
+"""Collection of the root URL patterns that products declare for themselves.
+
+`register_routes(routers)` in `products/<product>/backend/routes.py` covers DRF routers only.
+A plain Django path has no router to register onto, so a product declares one in the same module
+as a `urlpatterns` list, and `posthog/urls.py` mounts every product's list in one slot.
+"""
+
+from collections.abc import Iterable
+from types import ModuleType
+
+from django.urls import URLPattern, URLResolver
+from django.urls.resolvers import RegexPattern
+
+from posthog.products import load_product_modules
+
+
+class ProductRouteError(Exception):
+ """A product root URL pattern outside the prefixes reserved for that product."""
+
+
+class ProductRootRoutes:
+ """The root patterns products declare, and the prefix rule they must satisfy."""
+
+ # A product route in core's namespace can shadow a core route, and which one wins would then
+ # depend on app iteration order. Reserving a prefix per product removes both.
+ PREFIX_TEMPLATES: tuple[str, ...] = ("api/{product}/", "webhooks/{product}/")
+
+ @staticmethod
+ def _product_name(routes_module_name: str) -> str:
+ """`products.stamphog.backend.routes` -> `stamphog`."""
+ return routes_module_name.split(".")[1]
+
+ @staticmethod
+ def _route_of(pattern: URLPattern | URLResolver) -> str:
+ """The declared route of a pattern, without the regex anchor.
+
+ `path()` carries the route string. `re_path()`, which `opt_slash_path()` builds on,
+ carries the regex, and that regex starts with `^` whenever it is anchored.
+ """
+ return str(pattern.pattern).removeprefix("^")
+
+ @staticmethod
+ def _is_unanchored_regex(pattern: URLPattern | URLResolver) -> bool:
+ """Whether Django will look for this pattern anywhere in the path.
+
+ A `RegexPattern` that does not end in `$` is matched with `re.search`, so a regex without
+ a leading `^` also matches a path that merely contains it. Its text would still start
+ with the product's prefix, which is why the prefix check alone cannot catch this.
+ `path()` builds a `RoutePattern`, which Django anchors itself.
+ """
+ return isinstance(pattern.pattern, RegexPattern) and not str(pattern.pattern).startswith("^")
+
+ @classmethod
+ def from_module(cls, routes_module: ModuleType) -> list[URLPattern | URLResolver]:
+ """The root patterns one product's routes module declares, checked against the rule.
+
+ The check raises at URL conf load rather than logging, so a bad prefix fails every
+ process start and every test instead of silently shadowing a core route in production.
+ """
+ declared: Iterable[URLPattern | URLResolver] = getattr(routes_module, "urlpatterns", ())
+ patterns = list(declared)
+ product = cls._product_name(routes_module.__name__)
+ allowed = tuple(template.format(product=product) for template in cls.PREFIX_TEMPLATES)
+
+ for pattern in patterns:
+ if cls._is_unanchored_regex(pattern):
+ raise ProductRouteError(
+ f"Product {product!r} declares root URL pattern {str(pattern.pattern)!r} as an "
+ f"unanchored regex, which matches anywhere in the path. Start it with '^'"
+ )
+ route = cls._route_of(pattern)
+ if not route.startswith(allowed):
+ allowed_list = " or ".join(repr(prefix) for prefix in allowed)
+ raise ProductRouteError(
+ f"Product {product!r} declares root URL pattern {route!r}, which must start with {allowed_list}"
+ )
+ return patterns
+
+ @classmethod
+ def collect(cls) -> list[URLPattern | URLResolver]:
+ """Every product's root patterns, in one list for `posthog/urls.py` to splice in."""
+ collected: list[URLPattern | URLResolver] = []
+ for routes_module in load_product_modules("routes"):
+ collected.extend(cls.from_module(routes_module))
+ return collected
diff --git a/posthog/urls.py b/posthog/urls.py
index 37d0e4594681..5db14ce9becc 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -37,6 +37,7 @@ from posthog.frontend_views import home, home_with_region_redirect
from posthog.ingress.github.provider import build_github_provider
from posthog.ingress.views import build_webhook_view
from posthog.oauth2_urls import urlpatterns as oauth2_urls
+from posthog.product_urls import ProductRootRoutes
from posthog.temporal.codec_server import decode_payloads
from posthog.web_bot_auth import http_message_signatures_directory
@@ -50,7 +51,6 @@ from products.customer_analytics.backend.presentation.views.internal import (
)
from products.demo.backend.facade.api import demo_route
from products.early_access_features.backend.api import early_access_features
-from products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook
from products.messaging.backend.api.customerio_webhook import CustomerIOWebhookView
from products.messaging.backend.api.push_subscriptions import push_subscriptions
from products.notebooks.backend.facade.sql_v2 import (
@@ -74,10 +74,7 @@ from products.slack_app.backend.views import (
from products.streamlit_apps.backend.presentation.bridge_views import StreamlitBridgeView
from products.surveys.backend.api.survey import public_survey_page
from products.tasks.backend.facade.agent_proxy import agent_proxy_callback
-from products.user_interviews.backend.presentation.webhooks import (
- start_call as user_interviews_start_call,
- vapi_webhook,
-)
+from products.user_interviews.backend.presentation.webhooks import start_call as user_interviews_start_call
from products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSet
from products.workflows.backend.api import hog_flow, hog_flow_template
from products.workflows.backend.api.ses_events_webhook import ses_tenant_events_webhook
@@ -101,10 +98,6 @@ from .views import (
# One view for both paths, so the provider is built once per process rather than once per route.
github_app_webhook = build_webhook_view(build_github_provider("posthog"))
-# Stamphog runs on its own GitHub App, with its own signing secret and its own consumers, so it
-# gets its own view rather than sharing the customer-facing App's endpoint.
-stamphog_github_webhook = build_webhook_view(build_github_provider("stamphog"))
-
urlpatterns = [
# EU spend must precede both the API router and the API fallback.
*(
@@ -148,22 +141,12 @@ urlpatterns = [
path("api/unsubscribe", unsubscribe.unsubscribe),
path("api/alerts/github", github.SecretAlert.as_view()),
opt_slash_path("api/revoke_leaked_key", leaked_key.PublicLeakedKeyReport.as_view()),
- path(
- "api/legal_documents/pandadoc",
- legal_document_pandadoc_webhook,
- name="legal_document_pandadoc_webhook",
- ),
path(
"api/users/<str:user_id>/signal_autonomy/",
signals_user_autonomy_view.as_view(),
name="user_signal_autonomy",
),
path("api/projects/<int:team_id>/messaging/customerio/webhook/", csrf_exempt(CustomerIOWebhookView.as_view())),
- path(
- "api/user_interviews/vapi_webhook/",
- csrf_exempt(vapi_webhook),
- name="user_interviews_vapi_webhook",
- ),
path(
"api/user_interviews/share/<str:access_token>/start_call/",
csrf_exempt(user_interviews_start_call),
@@ -310,6 +293,9 @@ urlpatterns = [
HogliClientMetadataView.as_view(),
name="hogli-client-metadata",
),
+ # The one slot for root routes products declare themselves, after every core route and before
+ # the API fallback and the frontend catch-all. See docs/internal/url-routing.md.
+ *ProductRootRoutes.collect(),
re_path(r"^api.+", api_not_found),
path("authorize_and_redirect/", login_required(authorize_and_redirect)),
path("integrations/connect/<str:kind>/", login_required(integration_connect_redirect)),
@@ -365,11 +351,10 @@ urlpatterns = [
opt_slash_path("slack/event-callback", posthog_code_event_handler),
opt_slash_path("slack/command-callback", slack_app_command_handler),
opt_slash_path("slack/workspace/claims", slack_workspace_claims_view),
- # GitHub App webhook — ingress fans it out to the tasks, conversations and workflows consumers
+ # GitHub App webhook — ingress fans it out to the tasks, conversations and workflows consumers.
+ # It stays in core because the App is shared: no single product owns its registration.
opt_slash_path("webhooks/github/pr", github_app_webhook),
opt_slash_path("webhooks/github", github_app_webhook),
- # Stamphog runs as its own GitHub App with a dedicated inbound endpoint (not the fan-out above)
- opt_slash_path("webhooks/stamphog/github", stamphog_github_webhook),
# AWS SES tenant reputation events (EventBridge -> SNS HTTPS subscription)
opt_slash_path("webhooks/workflows/ses-events", ses_tenant_events_webhook),
# Message preferences
diff --git a/products/README.md b/products/README.md
index 8d992d4e6879..bb794d02f1c6 100644
--- a/products/README.md
+++ b/products/README.md
@@ -24,7 +24,7 @@ products/
apps.py
models.py
logic.py # business logic
- routes.py # API routes: register_routes(routers), auto-discovered from INSTALLED_APPS
+ routes.py # API routes: register_routes(routers) + urlpatterns, auto-discovered from INSTALLED_APPS
migrations/
facade/ # cross-product Python interface
__init__.py
@@ -199,6 +199,7 @@ bin/hogli product:lint --regenerate-baseline
- Modify `posthog/settings/web.py` and add your new product under `PRODUCTS_APPS`.
- Modify `tach.toml` and add a new block for your product. We use `tach` to track cross-dependencies between python apps.
- Add your API routes in `backend/routes.py` with a `register_routes(routers)` function (e.g. `routers.projects.register(r"my_thing", MyThingViewSet, "project_my_thing", ["team_id"])`). It is auto-discovered — once the product is in `PRODUCTS_APPS`, `posthog/api/__init__.py` finds and calls `register_routes(routers)` with no edit to core. See `posthog/api/routing.py:RouterRegistry` for the available router handles (`projects`/`environments`/`organizations`/`root`).
+ - For a plain Django path no router can carry, such as an inbound webhook endpoint, add a `urlpatterns` list to the same `routes.py`. Core mounts every product's list in one slot in `posthog/urls.py`. Each pattern must start with `api/<product>/` or `webhooks/<product>/`, or the URL conf fails to load. See [docs/internal/url-routing.md](../docs/internal/url-routing.md).
- NOTE: we will automate some of these steps in the future, but for now, please do them manually.
## Adding or moving backend models and migrations
diff --git a/products/legal_documents/backend/routes.py b/products/legal_documents/backend/routes.py
index b65bcad39c75..e78bc50dbfb6 100644
--- a/products/legal_documents/backend/routes.py
+++ b/products/legal_documents/backend/routes.py
@@ -1,6 +1,17 @@
+from django.urls import URLPattern, path
+
from posthog.api.routing import RouterRegistry
from products.legal_documents.backend.presentation.views import LegalDocumentViewSet
+from products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook
+
+urlpatterns: list[URLPattern] = [
+ path(
+ "api/legal_documents/pandadoc",
+ legal_document_pandadoc_webhook,
+ name="legal_document_pandadoc_webhook",
+ ),
+]
def register_routes(routers: RouterRegistry) -> None:
diff --git a/products/stamphog/backend/routes.py b/products/stamphog/backend/routes.py
index 2e4345a042a5..4ff44dda994f 100644
--- a/products/stamphog/backend/routes.py
+++ b/products/stamphog/backend/routes.py
@@ -1,9 +1,20 @@
"""Route registration for stamphog. Auto-discovered by posthog/api/__init__.py."""
+from django.urls import URLPattern
+
from posthog.api.routing import RouterRegistry
+from posthog.ingress.github.provider import build_github_provider
+from posthog.ingress.views import build_webhook_view
+from posthog.utils import opt_slash_path
from .presentation.views import DigestRunViewSet, PullRequestViewSet, ReviewRunViewSet, StamphogRepoConfigViewSet
+# Stamphog runs on its own GitHub App, with its own signing secret and its own consumers, so it
+# gets its own view rather than sharing the customer-facing App's endpoint.
+urlpatterns: list[URLPattern] = [
+ opt_slash_path("webhooks/stamphog/github", build_webhook_view(build_github_provider("stamphog"))),
+]
+
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
diff --git a/products/user_interviews/backend/routes.py b/products/user_interviews/backend/routes.py
index e6f75b9f369b..b6c32fe58e94 100644
--- a/products/user_interviews/backend/routes.py
+++ b/products/user_interviews/backend/routes.py
@@ -1,3 +1,6 @@
+from django.urls import URLPattern, path
+from django.views.decorators.csrf import csrf_exempt
+
from posthog.api.routing import RouterRegistry
from products.user_interviews.backend.presentation.views import (
@@ -5,6 +8,15 @@ from products.user_interviews.backend.presentation.views import (
UserInterviewTopicViewSet,
UserInterviewViewSet,
)
+from products.user_interviews.backend.presentation.webhooks import vapi_webhook
+
+urlpatterns: list[URLPattern] = [
+ path(
+ "api/user_interviews/vapi_webhook/",
+ csrf_exempt(vapi_webhook),
+ name="user_interviews_vapi_webhook",
+ ),
+]
def register_routes(routers: RouterRegistry) -> None: