: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): redirect /api/environments to /api/projects behind kill-switch (#62965)
Yasenb9b1bb53e9c6
diff --git a/posthog/api/test/test_environments_redirect.py b/posthog/api/test/test_environments_redirect.pynew file mode 100644index 000000000000..31e11a341241--- /dev/null+++ b/posthog/api/test/test_environments_redirect.py@@ -0,0 +1,283 @@+import re+import json+from collections.abc import Iterable+from typing import cast++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.http import HttpResponse+from django.test import (+ Client as DjangoTestClient,+ override_settings,+)+from django.urls import get_resolver+from django.urls.resolvers import URLPattern, URLResolver++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIClient++from posthog.middleware import EnvironmentsRedirectMiddleware++# Tests for EnvironmentsRedirectMiddleware: /api/environments/* must 307-redirect to the+# equivalent /api/projects/* path (same id — Project ↔ primary Team are 1:1 and share it),+# preserving method, body, and query string. 307 (not 301/302) is load-bearing: a plain+# redirect lets clients downgrade writes to GET and drop the body. The redirect is gated+# by the `api-environments-redirect` feature flag, so tests patch the flag evaluation.+#+# Test clients follow the env→projects 307 like real HTTP clients and return the end+# response (see _follow_environments_redirect in posthog/test/base.py) — the classes+# asserting raw 307 semantics opt out via `client.follow_environments_redirect = False`.++ENVIRONMENTS_PREFIX = "api/environments"+PROJECTS_PREFIX = "api/projects"++# Resources with at least one /api/environments route that has no /api/projects counterpart+# yet. The middleware skips these (it only redirects paths that resolve project-side), so+# they keep working unredirected. Shrink this set by registering projects-side counterparts;+# do NOT grow it — new team-scoped endpoints must register under /api/projects.+# For `query` and `subscriptions` only specific sub-paths lack counterparts+# (query/<uuid>/progress and subscriptions/<id>/deliveries) — the rest of those+# resources is dual-registered and does redirect.+KNOWN_ENVIRONMENT_ONLY_RESOURCES = {+ "conversations",+ "core_memory",+ "max_hands_free",+ "max_tools",+ "mcp_analytics",+ "messaging",+ "progress",+ "property_access_controls",+ "query",+ "session_summaries",+ "subscriptions",+}+++def _normalize_route(route: str) -> str:+ # Neutralize named-group names (parent_lookup_team_id vs parent_lookup_project_id)+ # and the `[^/.]+` lookup class BEFORE stripping anchors — a bare `^` strip would+ # corrupt the character class — so structurally identical routes compare equal.+ route = re.sub(r"\(\?P<[^>]+>", "(", route)+ route = route.replace("[^/.]+", "[param]")+ return route.replace("^", "").replace("$", "")+++def _collect_routes_under(prefix: str) -> set[str]:+ collected: set[str] = set()++ def walk(patterns: Iterable, base: str) -> None:+ for entry in patterns:+ pattern = base + str(entry.pattern)+ if isinstance(entry, URLResolver):+ walk(entry.url_patterns, pattern)+ elif isinstance(entry, URLPattern):+ collected.add(_normalize_route(pattern))++ walk(get_resolver().url_patterns, "")+ return {route for route in collected if route.startswith(prefix)}+++def _resource_of(route_suffix: str) -> str:+ # Route suffixes look like "/([/.]+)/dashboards/..." or "/<int:team_id>/progress/" —+ # the resource is the first literal segment after the team id parameter.+ segments = route_suffix.lstrip("/").split("/")+ if len(segments) < 2:+ return ""+ match = re.match(r"\w+", segments[1])+ return match.group(0) if match else segments[1]+++class TestEveryEnvironmentsRouteHasAProjectsCounterpart(APIBaseTest):+ def test_environment_only_routes_are_known(self):+ # The middleware only redirects paths whose rewritten /api/projects form resolves,+ # so an unknown env-only route can't 404 — but it also silently won't redirect.+ # This pins the gap so it shrinks deliberately instead of growing unnoticed.+ env_routes = {r.removeprefix(ENVIRONMENTS_PREFIX) for r in _collect_routes_under(ENVIRONMENTS_PREFIX)}+ project_routes = {r.removeprefix(PROJECTS_PREFIX) for r in _collect_routes_under(PROJECTS_PREFIX)}+ unknown = {_resource_of(r) for r in env_routes - project_routes} - KNOWN_ENVIRONMENT_ONLY_RESOURCES+ self.assertEqual(+ unknown,+ set(),+ "new /api/environments routes without a /api/projects counterpart — register them "+ f"under /api/projects (see posthog/api/rest_router.py) instead of env-only: {sorted(unknown)}",+ )+++class TestEnvironmentsRedirect(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.client.follow_environments_redirect = False # type: ignore[attr-defined] # raw 307 assertions+ flag_patcher = patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=True)+ flag_patcher.start()+ self.addCleanup(flag_patcher.stop)++ def assert_redirected(self, path: str, expected_location: str, method: str = "GET") -> HttpResponse:+ # cast: the DRF stubs type APIClient.generic via the request-factory side, but at+ # runtime the client returns the response.+ response = cast(HttpResponse, self.client.generic(method, path))+ self.assertEqual(+ response.status_code,+ status.HTTP_307_TEMPORARY_REDIRECT,+ f"{method} {path} should 307-redirect, got {response.status_code}",+ )+ self.assertEqual(response["Location"], expected_location)+ self.assertEqual(response["Deprecation"], "true")+ self.assertIn(f"<{expected_location}>", response["Link"])+ self.assertIn('rel="successor-version"', response["Link"])+ return response++ @parameterized.expand(["GET", "POST", "PATCH", "PUT", "DELETE"])+ def test_detail_redirects_preserving_method(self, method: str):+ self.assert_redirected(f"/api/environments/{self.team.id}/", f"/api/projects/{self.team.id}/", method)++ @parameterized.expand(["GET", "POST"])+ def test_root_list_redirects_preserving_method(self, method: str):+ self.assert_redirected("/api/environments/", "/api/projects/", method)++ def test_current_alias_redirects(self):+ self.assert_redirected("/api/environments/@current/", "/api/projects/@current/")++ def test_nested_resource_redirects(self):+ self.assert_redirected(+ f"/api/environments/{self.team.id}/dashboards/", f"/api/projects/{self.team.id}/dashboards/", "POST"+ )++ def test_action_redirects_with_query_string(self):+ self.assert_redirected(+ f"/api/environments/{self.team.id}/settings_as_of/?at=2026-01-01T00:00:00Z",+ f"/api/projects/{self.team.id}/settings_as_of/?at=2026-01-01T00:00:00Z",+ )++ def test_query_string_is_preserved(self):+ self.assert_redirected(+ "/api/environments/@current/?limit=10&offset=5&search=a%20b",+ "/api/projects/@current/?limit=10&offset=5&search=a%20b",+ )++ def test_followed_patch_reaches_projects_endpoint_with_body_intact(self):+ # The Django test client preserves method and body across 307, like real clients do —+ # this proves a write round-trips through the redirect end to end.+ response = self.client.patch(+ "/api/environments/@current/",+ data=json.dumps({"name": "Renamed via redirect"}),+ content_type="application/json",+ follow=True,+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.redirect_chain, [("/api/projects/@current/", status.HTTP_307_TEMPORARY_REDIRECT)])+ self.assertEqual(response.json()["name"], "Renamed via redirect")+ self.project.refresh_from_db()+ self.assertEqual(self.project.name, "Renamed via redirect")++ def test_projects_paths_are_not_redirected(self):+ response = self.client.get(f"/api/projects/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertNotIn("Deprecation", response.headers)++ def test_nested_projects_environments_path_is_not_redirected(self):+ # The deprecated nested route /api/projects/:id/environments/ must not loop.+ response = self.client.get(f"/api/projects/{self.team.id}/environments/")+ self.assertNotEqual(response.status_code, status.HTTP_307_TEMPORARY_REDIRECT)+ self.assertNotIn("Location", response.headers)+ self.assertNotIn("Deprecation", response.headers)++ def test_environment_only_route_passes_through_unredirected(self):+ # /api/environments/:id/progress/ has no /api/projects counterpart yet — it must+ # keep working and must not advertise a successor path that would 404.+ response = self.client.get(f"/api/environments/{self.team.id}/progress/")+ self.assertNotEqual(response.status_code, status.HTTP_307_TEMPORARY_REDIRECT)+ self.assertNotIn("Location", response.headers)+ self.assertNotIn("Deprecation", response.headers)++ def test_similarly_prefixed_paths_are_not_redirected(self):+ response = self.client.get("/api/environments_lookalike/")+ self.assertNotEqual(response.status_code, status.HTTP_307_TEMPORARY_REDIRECT)+ self.assertNotIn("Deprecation", response.headers)+++class TestDefaultTestClientFollowsRedirect(APIBaseTest):+ # Uses the default (following) client: when the redirect is on, tests across the+ # repo must receive the end response, not the 307.++ def test_read_through_redirect_returns_end_response(self):+ with patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=True):+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["id"], self.team.id)++ def test_write_through_redirect_preserves_method_and_body(self):+ with patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=True):+ response = self.client.patch(f"/api/environments/{self.team.id}/", {"name": "Followed end to end"})+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.json()["name"], "Followed end to end")++ def test_unrelated_feature_flag_mocks_still_get_end_responses(self):+ # Many tests blanket-mock feature_enabled for their own flags, which turns the+ # redirect on as a side effect — they must keep getting end codes, not 307s+ # (this broke product test suites in CI).+ with patch("posthoganalytics.feature_enabled", return_value=True):+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_hand_built_clients_also_follow(self):+ # Product suites instantiate APIClient()/Client() directly instead of using+ # APIBaseTest's client — the follow behavior is patched onto the classes, so+ # those clients must follow too.+ drf_client = APIClient()+ drf_client.force_login(self.user)+ django_client = DjangoTestClient()+ django_client.force_login(self.user)+ with patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=True):+ for client in (drf_client, django_client):+ response = client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+++class TestEnvironmentsRedirectKillSwitch(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.client.follow_environments_redirect = False # type: ignore[attr-defined] # raw 307 assertions++ def test_redirect_is_off_by_default_but_deprecation_headers_are_present(self):+ # No patch: the analytics SDK is disabled under TEST, so the flag evaluates to+ # None — the redirect must fail closed while deprecation headers still ship.+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response["Deprecation"], "true")+ self.assertIn(f"</api/projects/{self.team.id}/>", response["Link"])+ self.assertIn("Sunset", response.headers)++ def test_flag_toggles_redirect_without_restart(self):+ with patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=True):+ self.assert_redirect_enabled()+ with patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=False):+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ with patch.object(EnvironmentsRedirectMiddleware, "_redirect_enabled", return_value=True):+ self.assert_redirect_enabled()++ def test_flag_is_evaluated_locally_without_emitting_events(self):+ with override_settings(TEST=False), patch("posthoganalytics.feature_enabled", return_value=True) as flag_eval:+ self.assertTrue(EnvironmentsRedirectMiddleware._redirect_enabled())+ flag_eval.assert_called_once_with(+ "api-environments-redirect",+ "environments_api_redirect",+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )++ def assert_redirect_enabled(self) -> None:+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response.status_code, status.HTTP_307_TEMPORARY_REDIRECT)++ @override_settings(API_ENVIRONMENTS_SUNSET_DATE="2026-07-31")+ def test_sunset_header_is_http_date(self):+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertEqual(response["Sunset"], "Fri, 31 Jul 2026 00:00:00 GMT")++ @override_settings(API_ENVIRONMENTS_SUNSET_DATE="")+ def test_sunset_header_is_omitted_when_unset(self):+ response = self.client.get(f"/api/environments/{self.team.id}/")+ self.assertNotIn("Sunset", response.headers)diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 5d48977eb017..e1dd4d77b969 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -5,7 +5,7 @@ import uuidimport posixpathfrom collections.abc import Callablefrom contextlib import suppress-from datetime import datetime, timedelta+from datetime import UTC, datetime, timedeltafrom ipaddress import ip_address, ip_networkfrom typing import Optional, castfrom urllib.parse import urlencode@@ -17,13 +17,16 @@ from django.core.exceptions import MiddlewareNotUsedfrom django.db import connectionfrom django.db.models import QuerySetfrom django.http import HttpRequest, HttpResponse, JsonResponse+from django.http.response import HttpResponseRedirectBasefrom django.middleware.csrf import CsrfViewMiddlewarefrom django.shortcuts import redirect-from django.urls import resolve+from django.urls import Resolver404, resolvefrom django.utils.cache import add_never_cache_headersfrom django.utils.deprecation import MiddlewareMixin+from django.utils.http import http_dateimport structlog+import posthoganalyticsfrom django_prometheus.middleware import Metricsfrom loginas.utils import is_impersonated_session, restore_original_loginfrom opentelemetry import trace@@ -549,6 +552,101 @@ class ShortCircuitMiddleware:return response+class HttpResponseTemporaryRedirectPreserveMethod(HttpResponseRedirectBase):+ status_code = 307+++class EnvironmentsRedirectMiddleware:+ """Redirects /api/environments/* to the equivalent /api/projects/* path.++ /api/projects/ is a backwards-compatible superset of /api/environments/ (a Project+ and its primary Team share the same numeric id, so the id segment — including+ @current — carries over unchanged). Uses 307 so clients re-send the original method+ and body; a 301/302 would let clients downgrade writes to GET and drop the body.++ Only paths whose rewritten /api/projects/* form resolves to a registered route are+ redirected — the few environment-only routes with no projects counterpart yet (see+ test_environments_redirect.KNOWN_ENVIRONMENT_ONLY_RESOURCES) pass through untouched,+ so a redirect can never land on a 404.++ Gated by the `api-environments-redirect` feature flag, evaluated locally per request+ (no network call, no flag events) — turning the flag off disables the redirect+ instantly without a deploy or restart. If the flag can't be evaluated (missing,+ local evaluation unavailable, SDK disabled) the redirect stays OFF. Whether or not+ the redirect is enabled, redirectable /api/environments/* responses carry+ `Deprecation`, `Sunset`, and `Link` headers announcing the successor path to+ integrators.+ """++ ENVIRONMENTS_PREFIX = "/api/environments"+ PROJECTS_PREFIX = "/api/projects"+ FEATURE_FLAG_KEY = "api-environments-redirect"+ FEATURE_FLAG_DISTINCT_ID = "environments_api_redirect"++ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:+ self.get_response = get_response++ def __call__(self, request: HttpRequest) -> HttpResponse:+ path = request.path+ if path != self.ENVIRONMENTS_PREFIX and not path.startswith(self.ENVIRONMENTS_PREFIX + "/"):+ return self.get_response(request)++ target_path = self.PROJECTS_PREFIX + path[len(self.ENVIRONMENTS_PREFIX) :]+ if not self._projects_route_exists(target_path):+ return self.get_response(request)++ query_string = request.META.get("QUERY_STRING", "")+ location = f"{target_path}?{query_string}" if query_string else target_path++ response: HttpResponse+ if self._redirect_enabled():+ response = HttpResponseTemporaryRedirectPreserveMethod(location)+ else:+ response = self.get_response(request)++ response["Deprecation"] = "true"+ response["Link"] = f'<{location}>; rel="successor-version"'+ sunset = self._sunset_http_date()+ if sunset:+ response["Sunset"] = sunset+ return response++ @classmethod+ def _redirect_enabled(cls) -> bool:+ # only_evaluate_locally keeps this off the network on every request; a constant+ # distinct id makes the flag an instance-wide on/off switch (roll out 0% or 100%).+ return bool(+ posthoganalytics.feature_enabled(+ cls.FEATURE_FLAG_KEY,+ cls.FEATURE_FLAG_DISTINCT_ID,+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )++ @staticmethod+ def _projects_route_exists(target_path: str) -> bool:+ # urls.py ends with catch-all routes (api_not_found, SPA fallback), so resolve()+ # matches any path — require the match to be an actual /api/projects route.+ try:+ match = resolve(target_path)+ except Resolver404:+ return False+ return match.route.replace("^", "").startswith("api/projects")++ @staticmethod+ def _sunset_http_date() -> Optional[str]:+ if not settings.API_ENVIRONMENTS_SUNSET_DATE:+ return None+ try:+ sunset_at = datetime.fromisoformat(settings.API_ENVIRONMENTS_SUNSET_DATE)+ except ValueError:+ return None+ if sunset_at.tzinfo is None:+ sunset_at = sunset_at.replace(tzinfo=UTC)+ return http_date(sunset_at.timestamp())++def per_request_logging_context_middleware(get_response: Callable[[HttpRequest], HttpResponse],) -> Callable[[HttpRequest], HttpResponse]:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e07079602587..b1f09340c50b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -149,6 +149,9 @@ MIDDLEWARE = ["corsheaders.middleware.CorsMiddleware","posthog.middleware.CSPMiddleware","django.middleware.common.CommonMiddleware",+ # Below CorsMiddleware so redirects get CORS headers; above auth/CSRF since a+ # redirect needs neither — clients re-send credentials to the rewritten path.+ "posthog.middleware.EnvironmentsRedirectMiddleware","posthog.middleware.CsrfOrKeyViewMiddleware","posthog.middleware.QueryTimeCountingMiddleware","django.contrib.auth.middleware.AuthenticationMiddleware",@@ -699,6 +702,16 @@ KAFKA_PRODUCE_ACK_TIMEOUT_SECONDS = int(os.getenv("KAFKA_PRODUCE_ACK_TIMEOUT_SEC# if `true` we highly increase the rate limit on /query endpoint and limit the number of concurrent queriesAPI_QUERIES_ENABLED = get_from_env("API_QUERIES_ENABLED", False, type_cast=str_to_bool)+####+# /api/environments deprecation++# Requests to /api/environments/* get a method-preserving 307 redirect to the equivalent+# /api/projects/* path, gated by the `api-environments-redirect` feature flag — see+# posthog.middleware.EnvironmentsRedirectMiddleware.+# ISO date announced to integrators via the `Sunset` response header (RFC 8594) on+# /api/environments/* responses. Empty string omits the header.+API_ENVIRONMENTS_SUNSET_DATE = get_from_env("API_ENVIRONMENTS_SUNSET_DATE", "2026-07-31")+# Query service SLO sampling rate. Each QueryRunner.run() call emits two events# (slo_operation_started + slo_operation_completed); unsampled, that's many millions of# events per day. The chosen rate is stamped on each event as `properties.sample_rate`diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 8988981240a3..d67ec7f1361d 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -5,6 +5,7 @@ import uuidimport inspectimport datetime as dtimport resource+import functoolsfrom collections.abc import Callable, Generator, Iteratorfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom contextlib import ExitStack, contextmanager@@ -22,7 +23,13 @@ from django.core.cache import cachefrom django.core.management import call_commandfrom django.db import connection, connectionsfrom django.db.migrations.executor import MigrationExecutor-from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings+from django.test import (+ Client as DjangoTestClient,+ SimpleTestCase,+ TestCase,+ TransactionTestCase,+ override_settings,+)from django.test.utils import CaptureQueriesContext# we have to import pendulum for the side effect of importing it@@ -30,7 +37,10 @@ from django.test.utils import CaptureQueriesContextimport pendulum # noqa F401import sqlparsefrom clickhouse_pool.pool import TooManyConnections-from rest_framework.test import APITestCase as DRFTestCase+from rest_framework.test import (+ APIClient,+ APITestCase as DRFTestCase,+)from syrupy.extensions.amber import AmberSnapshotExtensionfrom posthog.hogql import (@@ -945,6 +955,43 @@ class NonAtomicBaseTestKeepIdentities(PostHogTestCase, ErrorResponsesMixin, Trancursor.execute(f"TRUNCATE TABLE {', '.join(tables)} CASCADE")+def _follow_environments_redirect(original_generic):+ """Make a test client's `generic` follow the /api/environments → /api/projects 307.++ EnvironmentsRedirectMiddleware 307-redirects /api/environments/* requests when the+ `api-environments-redirect` flag evaluates true — which in tests happens whenever a+ test mocks posthoganalytics.feature_enabled for its own flag. Real clients re-send+ the same method and body to the projects path, so test clients do too: tests receive+ the end response, not the redirect hop. Set `client.follow_environments_redirect =+ False` to observe the raw 307 (see posthog/api/test/test_environments_redirect.py).+ """++ @functools.wraps(original_generic)+ def generic(self, method, path, data="", content_type="application/octet-stream", secure=False, **extra):+ response = original_generic(self, method, path, data, content_type, secure, **extra)+ if (+ getattr(self, "follow_environments_redirect", True)+ # RequestFactory shares this method but returns requests, not responses+ and getattr(response, "status_code", None) in (307, 308)+ and isinstance(path, str)+ and path.startswith("/api/environments")+ and response.headers.get("Location", "").startswith("/api/projects")+ ):+ response = original_generic(self, method, response.headers["Location"], data, content_type, secure, **extra)+ return response++ generic._follows_environments_redirect = True # type: ignore[attr-defined]+ return generic+++# Cover every test client, including ones instantiated by hand in product suites —+# Django's Client inherits `generic` from RequestFactory, so shadow it on the class.+if not getattr(APIClient.generic, "_follows_environments_redirect", False):+ APIClient.generic = _follow_environments_redirect(APIClient.generic) # type: ignore[method-assign]+if not getattr(DjangoTestClient.generic, "_follows_environments_redirect", False):+ DjangoTestClient.generic = _follow_environments_redirect(DjangoTestClient.generic) # type: ignore[method-assign]++class APIBaseTest(PostHogTestCase, ErrorResponsesMixin, DRFTestCase):"""Functional API tests using Django REST Framework test suite.