: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(api): env-prefix rewrite metric + customerio webhook twin (#68649)
Yasen5a5ccc55ea49
diff --git a/posthog/api/test/test_environments_rewrite.py b/posthog/api/test/test_environments_rewrite.pyindex bdce871b2f07..157830c716d1 100644--- a/posthog/api/test/test_environments_rewrite.py+++ b/posthog/api/test/test_environments_rewrite.py@@ -10,6 +10,7 @@ from django.urls import get_resolverfrom django.urls.resolvers import URLPattern, URLResolverfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom rest_framework import statusfrom posthog.middleware import EnvironmentsRewriteMiddleware@@ -27,10 +28,9 @@ PROJECTS_PREFIX = "api/projects"# yet. The middleware skips these (it only rewrites paths that resolve project-side), so# they keep working via the legacy route. Shrink this set by registering projects-side# counterparts; do NOT grow it — new team-scoped endpoints must register under /api/projects.-# Only a few sub-paths still lack a counterpart: messaging/customerio/webhook, a bare-# progress endpoint, and query/<uuid>/progress — everything else is dual-registered.+# The only paths still lacking a counterpart are the defunct query-progress stubs: a bare+# progress endpoint and query/<uuid>/progress.KNOWN_ENVIRONMENT_ONLY_RESOURCES = {- "messaging","progress","query",}@@ -113,11 +113,15 @@ class TestFlagDistinctId(SimpleTestCase):class TestRewriteMechanism(SimpleTestCase):- # The rewrite mutating the request path to /api/projects is the one signal that would go- # silent if it regressed: because both prefixes are dual-registered, an end-to-end request- # would still return 200 via the legacy route even if the rewrite did nothing. This asserts- # the path the downstream handler actually resolves.- def _resolved_path(self, path: str, enabled: bool) -> str:+ # Two signals that would go silent if they regressed: (1) the rewrite mutating the request+ # path to /api/projects — because both prefixes are dual-registered, an end-to-end request+ # returns 200 via the legacy route even if the rewrite did nothing; (2) the `outcome` label+ # on the observability counter, which is the rollout signal — a mis-wired label would+ # silently corrupt the "not routed to projects" metric the rollout is steered by.+ _METRIC = "posthog_environments_prefix_requests_total"+ _OUTCOMES = ("rewritten", "passthrough", "env_only")++ def _run(self, path: str, enabled: bool, expected_outcome: str | None) -> tuple[str, str | None]:captured: dict[str, str] = {}def get_response(request: HttpRequest) -> HttpResponse:@@ -125,32 +129,40 @@ class TestRewriteMechanism(SimpleTestCase):captured["path_info"] = request.path_inforeturn HttpResponse()+ before = {o: REGISTRY.get_sample_value(self._METRIC, {"outcome": o}) or 0.0 for o in self._OUTCOMES}request = RequestFactory().get(path)with patch.object(EnvironmentsRewriteMiddleware, "_rewrite_enabled", return_value=enabled):EnvironmentsRewriteMiddleware(get_response)(request)self.assertEqual(captured["path"], captured["path_info"])- return captured["path"]+ incremented = [+ o+ for o in self._OUTCOMES+ if (REGISTRY.get_sample_value(self._METRIC, {"outcome": o}) or 0.0) - before[o] == 1.0+ ]+ expected_count = 1 if expected_outcome is not None else 0+ self.assertEqual(len(incremented), expected_count, f"unexpected outcome increments: {incremented}")+ return captured["path"], (incremented[0] if incremented else None)@parameterized.expand([- ("dual route + enabled → projects", "/api/environments/2/dashboards/", True, "/api/projects/2/dashboards/"),+ ("dual + enabled", "/api/environments/2/dashboards/", True, "/api/projects/2/dashboards/", "rewritten"),(- "dual route + disabled → unchanged",+ "dual + disabled","/api/environments/2/dashboards/",False,"/api/environments/2/dashboards/",+ "passthrough",),- (- "env-only route + enabled → unchanged",- "/api/environments/2/progress/",- True,- "/api/environments/2/progress/",- ),- ("non-environments path → unchanged", "/api/projects/2/dashboards/", True, "/api/projects/2/dashboards/"),+ ("env-only + enabled", "/api/environments/2/progress/", True, "/api/environments/2/progress/", "env_only"),+ ("non-environments path", "/api/projects/2/dashboards/", True, "/api/projects/2/dashboards/", None),])- def test_downstream_resolves_expected_path(self, _name: str, path: str, enabled: bool, expected: str) -> None:- self.assertEqual(self._resolved_path(path, enabled), expected)+ def test_resolved_path_and_outcome_metric(+ self, _name: str, path: str, enabled: bool, expected_path: str, expected_outcome: str | None+ ) -> None:+ resolved, outcome = self._run(path, enabled, expected_outcome)+ self.assertEqual(resolved, expected_path)+ self.assertEqual(outcome, expected_outcome)class TestEnvironmentsRewrite(APIBaseTest):diff --git a/posthog/api/test/test_team_project_parity.py b/posthog/api/test/test_team_project_parity.pyindex a23f11a92608..169b5779f591 100644--- a/posthog/api/test/test_team_project_parity.py+++ b/posthog/api/test/test_team_project_parity.py@@ -33,13 +33,11 @@ PROJECT_ONLY_SERIALIZER_FIELDS = {"product_description", "is_pending_deletion"}# Actions that legitimately exist only on the project surface (operate on the Project, not the Team).PROJECT_ONLY_ACTIONS = {"change_organization"}-# Routes (normalized suffix after `/api/<prefix>/<id>/`, path params -> `{id}`) that legitimately resolve-# ONLY under /api/environments/ and must NOT be mirrored onto projects:-# - the customerio webhook is posted to a fixed env URL by a third party; redirecting it would break it,-# - the async-query progress endpoints are internal, keyed by the team that ran the query.+# Routes (normalized suffix after `/api/<prefix>/<id>/`, path params -> `{id}`) that resolve ONLY+# under /api/environments/. The async-query progress endpoints are defunct stubs (real progress+# polling goes through the dual-routed query/{id}?show_progress=true) pending removal.# Anything else env-only is drift — mirror it onto /api/projects/ (dual-route the viewset) instead.KNOWN_ENVIRONMENT_ONLY_ROUTES: set[str] = {- "messaging/customerio/webhook","progress","query/{id}/progress",}diff --git a/posthog/middleware.py b/posthog/middleware.pyindex c885c656e14c..dee1c345344d 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -33,7 +33,7 @@ import posthoganalyticsfrom django_prometheus.middleware import Metricsfrom loginas.utils import is_impersonated_session, restore_original_loginfrom opentelemetry import trace-from prometheus_client import Histogram+from prometheus_client import Counter, Histogramfrom social_core.exceptions import AuthCanceled, AuthException, AuthFailedfrom statshog.defaults.django import statsd@@ -591,6 +591,16 @@ class ShortCircuitMiddleware:return response+ENVIRONMENTS_PREFIX_REQUESTS = Counter(+ "posthog_environments_prefix_requests",+ "Requests to the legacy /api/environments/* prefix, by how the middleware served them: "+ "`rewritten` to /api/projects, `passthrough` (a projects route exists but the flag is off "+ "for the team), or `env_only` (no projects counterpart). Any outcome other than `rewritten` "+ "was NOT routed to /api/projects.",+ ["outcome"],+)++class EnvironmentsRewriteMiddleware:"""Serves /api/environments/* through the canonical /api/projects/* viewsets.@@ -633,6 +643,8 @@ class EnvironmentsRewriteMiddleware:target_path = self.PROJECTS_PREFIX + path[len(self.ENVIRONMENTS_PREFIX) :]if not self._projects_route_exists(target_path):+ # No /api/projects counterpart — served on the legacy route, never routed to projects.+ ENVIRONMENTS_PREFIX_REQUESTS.labels(outcome="env_only").inc()return self.get_response(request)query_string = request.META.get("QUERY_STRING", "")@@ -644,6 +656,11 @@ class EnvironmentsRewriteMiddleware:request.path = target_pathrequest.path_info = target_pathrequest.META["PATH_INFO"] = target_path+ ENVIRONMENTS_PREFIX_REQUESTS.labels(outcome="rewritten").inc()+ else:+ # Rewritable, but the flag is off for this team — still served on the legacy+ # route rather than routed to projects.+ ENVIRONMENTS_PREFIX_REQUESTS.labels(outcome="passthrough").inc()response = self.get_response(request)diff --git a/posthog/urls.py b/posthog/urls.pyindex 44911ad28fc2..80fca91bd970 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -366,7 +366,10 @@ urlpatterns = [signals_user_autonomy_view.as_view(),name="user_signal_autonomy",),+ # Dual-served on both prefixes while the Customer.io dispatcher is repointed from the+ # legacy /api/environments/ URL to the canonical /api/projects/ one.path("api/environments/<int:team_id>/messaging/customerio/webhook/", csrf_exempt(CustomerIOWebhookView.as_view())),+ path("api/projects/<int:team_id>/messaging/customerio/webhook/", csrf_exempt(CustomerIOWebhookView.as_view())),path("api/user_interviews/vapi_webhook/",csrf_exempt(vapi_webhook),