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.

fix(api): serve /api/environments via internal rewrite instead of a 307 (#68511)

Yasen78dfd2871498
diff --git a/posthog/api/test/test_environments_redirect.py b/posthog/api/test/test_environments_redirect.py
deleted file mode 100644
index 513a255bfe6f..000000000000
--- a/posthog/api/test/test_environments_redirect.py
+++ /dev/null
@@ -1,310 +0,0 @@
-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,
- SimpleTestCase,
- 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 TestFlagDistinctId(SimpleTestCase):
- # The distinct id fed to the flag is what makes the rollout incremental: a per-team id
- # buckets by team, the constant id rides the global switch. If id extraction regresses,
- # numeric-team paths silently fall back to the constant and the flag becomes a kill
- # switch again — these cases catch that (and the reverse: @current must NOT get a team id).
- @parameterized.expand(
- [
- (
- "numeric id buckets per team",
- "/api/environments/123/feature_flags/",
- "environments_api_redirect:team:123",
- ),
- ("numeric id no trailing slash", "/api/environments/42", "environments_api_redirect:team:42"),
- (
- "current alias falls back to constant",
- "/api/environments/@current/insights/",
- "environments_api_redirect",
- ),
- ("non-numeric id falls back to constant", "/api/environments/abc/foo/", "environments_api_redirect"),
- ("keyless path falls back to constant", "/api/environments", "environments_api_redirect"),
- ]
- )
- def test_flag_distinct_id(self, _name: str, path: str, expected: str) -> None:
- self.assertEqual(EnvironmentsRedirectMiddleware._flag_distinct_id(path), expected)
-
-
-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/api/test/test_environments_rewrite.py b/posthog/api/test/test_environments_rewrite.py
new file mode 100644
index 000000000000..bdce871b2f07
--- /dev/null
+++ b/posthog/api/test/test_environments_rewrite.py
@@ -0,0 +1,244 @@
+import re
+from collections.abc import Iterable
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.http import HttpRequest, HttpResponse
+from django.test import RequestFactory, SimpleTestCase, 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 posthog.middleware import EnvironmentsRewriteMiddleware
+
+# Tests for EnvironmentsRewriteMiddleware: /api/environments/* is served through the
+# equivalent /api/projects/* viewset (same id — Project ↔ primary Team are 1:1 and share
+# it) via an in-process path rewrite, gated by the `api-environments-redirect` flag. The
+# rewrite is deliberately not a 307/308 — many API clients don't follow redirects — so the
+# client gets a normal 200 on the original URL with method, body, and query string intact.
+
+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 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.
+KNOWN_ENVIRONMENT_ONLY_RESOURCES = {
+ "messaging",
+ "progress",
+ "query",
+}
+
+
+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 rewrites paths whose /api/projects form resolves, so an
+ # unknown env-only route can't 404 — but it also silently won't be rewritten.
+ # 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 TestFlagDistinctId(SimpleTestCase):
+ # The distinct id fed to the flag is what makes the rollout incremental: a per-team id
+ # buckets by team, the constant id rides the global switch. If id extraction regresses,
+ # numeric-team paths silently fall back to the constant and the flag becomes a kill
+ # switch again — these cases catch that (and the reverse: @current must NOT get a team id).
+ @parameterized.expand(
+ [
+ (
+ "numeric id buckets per team",
+ "/api/environments/123/feature_flags/",
+ "environments_api_redirect:team:123",
+ ),
+ ("numeric id no trailing slash", "/api/environments/42", "environments_api_redirect:team:42"),
+ (
+ "current alias falls back to constant",
+ "/api/environments/@current/insights/",
+ "environments_api_redirect",
+ ),
+ ("non-numeric id falls back to constant", "/api/environments/abc/foo/", "environments_api_redirect"),
+ ("keyless path falls back to constant", "/api/environments", "environments_api_redirect"),
+ ]
+ )
+ def test_flag_distinct_id(self, _name: str, path: str, expected: str) -> None:
+ self.assertEqual(EnvironmentsRewriteMiddleware._flag_distinct_id(path), expected)
+
+
+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:
+ captured: dict[str, str] = {}
+
+ def get_response(request: HttpRequest) -> HttpResponse:
+ captured["path"] = request.path
+ captured["path_info"] = request.path_info
+ return HttpResponse()
+
+ 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"]
+
+ @parameterized.expand(
+ [
+ ("dual route + enabled → projects", "/api/environments/2/dashboards/", True, "/api/projects/2/dashboards/"),
+ (
+ "dual route + disabled → unchanged",
+ "/api/environments/2/dashboards/",
+ False,
+ "/api/environments/2/dashboards/",
+ ),
+ (
+ "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/"),
+ ]
+ )
+ def test_downstream_resolves_expected_path(self, _name: str, path: str, enabled: bool, expected: str) -> None:
+ self.assertEqual(self._resolved_path(path, enabled), expected)
+
+
+class TestEnvironmentsRewrite(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ patcher = patch.object(EnvironmentsRewriteMiddleware, "_rewrite_enabled", return_value=True)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_read_is_served_transparently_without_a_redirect(self):
+ response = self.client.get(f"/api/environments/{self.team.id}/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn("Location", response.headers)
+ self.assertEqual(response.json()["id"], self.team.id)
+ self.assertEqual(response["Deprecation"], "true")
+ self.assertIn(f"</api/projects/{self.team.id}/>", response["Link"])
+ self.assertIn('rel="successor-version"', response["Link"])
+
+ def test_write_round_trips_method_and_body_without_a_redirect(self):
+ # The point of the rewrite: a write to /api/environments applies on the same request,
+ # so clients that don't follow 3xx (httpx, Guzzle) keep working.
+ response = self.client.patch("/api/environments/@current/", {"name": "Renamed via rewrite"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertNotIn("Location", response.headers)
+ self.assertEqual(response.json()["name"], "Renamed via rewrite")
+ self.project.refresh_from_db()
+ self.assertEqual(self.project.name, "Renamed via rewrite")
+
+ def test_successor_link_includes_preserved_query_string(self):
+ response = self.client.get(f"/api/environments/{self.team.id}/dashboards/?limit=1")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn(f"</api/projects/{self.team.id}/dashboards/?limit=1>", response["Link"])
+
+ def test_environment_only_route_is_not_rewritten_or_deprecated(self):
+ # /progress/ has no /api/projects counterpart — served by the legacy route, and it
+ # must not advertise a successor path that would 404.
+ response = self.client.get(f"/api/environments/{self.team.id}/progress/")
+ self.assertNotIn("Location", response.headers)
+ self.assertNotIn("Deprecation", response.headers)
+
+ @parameterized.expand(
+ [
+ ("projects path", "/api/projects/{team}/"),
+ ("nested projects environments", "/api/projects/{team}/environments/"),
+ ("similarly prefixed", "/api/environments_lookalike/"),
+ ]
+ )
+ def test_paths_outside_the_environments_prefix_are_untouched(self, _name: str, path_template: str) -> None:
+ response = self.client.get(path_template.format(team=self.team.id))
+ self.assertNotIn("Deprecation", response.headers)
+ self.assertNotIn("Location", response.headers)
+
+
+class TestEnvironmentsRewriteFlag(APIBaseTest):
+ def test_disabled_by_default_still_serves_and_advertises_successor(self):
+ # SDK disabled under TEST → flag None → rewrite OFF, but the request must still
+ # succeed (served by the legacy env route) and carry deprecation headers.
+ response = self.client.get(f"/api/environments/{self.team.id}/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn("Location", response.headers)
+ self.assertEqual(response["Deprecation"], "true")
+ self.assertIn(f"</api/projects/{self.team.id}/>", response["Link"])
+ self.assertIn("Sunset", response.headers)
+
+ def test_blanket_feature_flag_mock_still_gets_a_transparent_response(self):
+ # Product suites often mock feature_enabled=True for their own flags, which turns the
+ # rewrite on as a side effect — they must keep getting a normal 200, never a redirect.
+ 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)
+ self.assertNotIn("Location", response.headers)
+
+ 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(EnvironmentsRewriteMiddleware._rewrite_enabled())
+ flag_eval.assert_called_once_with(
+ "api-environments-redirect",
+ "environments_api_redirect",
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+
+ @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.py
index 5d6cd6621e5e..c885c656e14c 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -21,7 +21,6 @@ from django.db import (
)
from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse, JsonResponse
-from django.http.response import HttpResponseRedirectBase
from django.middleware.csrf import CsrfViewMiddleware
from django.shortcuts import redirect
from django.urls import Resolver404, resolve
@@ -592,30 +591,29 @@ class ShortCircuitMiddleware:
return response
-class HttpResponseTemporaryRedirectPreserveMethod(HttpResponseRedirectBase):
- status_code = 307
-
-
-class EnvironmentsRedirectMiddleware:
- """Redirects /api/environments/* to the equivalent /api/projects/* path.
+class EnvironmentsRewriteMiddleware:
+ """Serves /api/environments/* through the canonical /api/projects/* viewsets.
/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.
+ @current — carries over unchanged). When enabled for a team, the request path is
+ rewritten in place to /api/projects/* and re-routed to the projects viewset, so the
+ client gets a normal 200 on the original URL. This is deliberately NOT a 307/308:
+ many API clients (httpx, Guzzle, …) don't follow redirects by default, so a redirect
+ silently breaks them — an in-process rewrite is transparent to every client and keeps
+ method, body, query string, and auth on the same request.
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.
+ rewritten — the few environment-only routes with no projects counterpart yet (see
+ test_environments_rewrite.KNOWN_ENVIRONMENT_ONLY_RESOURCES) pass through untouched.
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. The flag is bucketed on the team/project id
- from the path (see _flag_distinct_id), so a percentage rollout redirects that
- fraction of teams (0% off, 100% on) rather than flipping the whole instance at once.
- 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
+ (no network call, no flag events) — turning the flag off serves the request via the
+ legacy /api/environments route instead, instantly and without a deploy. The flag is
+ bucketed on the team/project id from the path (see _flag_distinct_id), so a percentage
+ rollout rewrites that fraction of teams (0% off, 100% on) rather than flipping the
+ whole instance at once. If the flag can't be evaluated (missing, local evaluation
+ unavailable, SDK disabled) the rewrite stays OFF. Either way, rewritable
/api/environments/* responses carry `Deprecation`, `Sunset`, and `Link` headers
announcing the successor path to integrators.
"""
@@ -638,16 +636,19 @@ class EnvironmentsRedirectMiddleware:
return self.get_response(request)
query_string = request.META.get("QUERY_STRING", "")
- location = f"{target_path}?{query_string}" if query_string else target_path
+ successor = f"{target_path}?{query_string}" if query_string else target_path
- response: HttpResponse
- if self._redirect_enabled(self._flag_distinct_id(path)):
- response = HttpResponseTemporaryRedirectPreserveMethod(location)
- else:
- response = self.get_response(request)
+ if self._rewrite_enabled(self._flag_distinct_id(path)):
+ # Re-route URL resolution to the projects viewset with no client-visible
+ # redirect; method, body, query string, and auth stay on the same request.
+ request.path = target_path
+ request.path_info = target_path
+ request.META["PATH_INFO"] = target_path
+
+ response = self.get_response(request)
response["Deprecation"] = "true"
- response["Link"] = f'<{location}>; rel="successor-version"'
+ response["Link"] = f'<{successor}>; rel="successor-version"'
sunset = self._sunset_http_date()
if sunset:
response["Sunset"] = sunset
@@ -668,7 +669,7 @@ class EnvironmentsRedirectMiddleware:
return cls.FEATURE_FLAG_DISTINCT_ID
@classmethod
- def _redirect_enabled(cls, distinct_id: Optional[str] = None) -> bool:
+ def _rewrite_enabled(cls, distinct_id: Optional[str] = None) -> bool:
# only_evaluate_locally keeps this off the network on every request; a per-team
# distinct id lets a percentage rollout bucket by team instead of flipping the
# whole instance at once (see _flag_distinct_id).
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 8bcbc8d7e196..df42915c0d9b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -155,9 +155,10 @@ 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",
+ # Below CorsMiddleware so responses get CORS headers; above auth/CSRF and URL
+ # resolution so the /api/environments → /api/projects rewrite is in place before the
+ # request is routed and authenticated.
+ "posthog.middleware.EnvironmentsRewriteMiddleware",
"posthog.middleware.CsrfOrKeyViewMiddleware",
"posthog.middleware.QueryTimeCountingMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
@@ -796,9 +797,9 @@ API_QUERIES_ENABLED = get_from_env("API_QUERIES_ENABLED", False, type_cast=str_t
####
# /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.
+# Requests to /api/environments/* are served through the equivalent /api/projects/*
+# viewset via an in-process path rewrite, gated by the `api-environments-redirect`
+# feature flag — see posthog.middleware.EnvironmentsRewriteMiddleware.
# 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")
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 3d174cbad224..8478be85842f 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -5,7 +5,6 @@ import uuid
import inspect
import datetime as dt
import resource
-import functools
from collections.abc import Callable, Generator, Iterator
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import ExitStack, contextmanager
@@ -23,13 +22,7 @@ from django.core.cache import cache
from django.core.management import call_command
from django.db import connection, connections
from django.db.migrations.executor import MigrationExecutor
-from django.test import (
- Client as DjangoTestClient,
- SimpleTestCase,
- TestCase,
- TransactionTestCase,
- override_settings,
-)
+from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings
from django.test.utils import CaptureQueriesContext
# we have to import pendulum for the side effect of importing it
@@ -37,10 +30,7 @@ from django.test.utils import CaptureQueriesContext
import pendulum # noqa F401
import sqlparse
from clickhouse_pool.pool import TooManyConnections
-from rest_framework.test import (
- APIClient,
- APITestCase as DRFTestCase,
-)
+from rest_framework.test import APITestCase as DRFTestCase
from syrupy.extensions.amber import AmberSnapshotExtension
from posthog.hogql import (
@@ -925,43 +915,6 @@ class NonAtomicBaseTestKeepIdentities(PostHogTestCase, ErrorResponsesMixin, Tran
cursor.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.