: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
fix(auth): enforce scoped JWT team on nested routes (#84070)
Ben Whited79eb6e9a530
diff --git a/posthog/auth.py b/posthog/auth.pyindex c792ef633310..be5f1d6a09e3 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -1245,19 +1245,25 @@ class ScopedServiceJWTAuthentication(authentication.BaseAuthentication):return "Bearer"+# Routes register the /api/projects/:id/ segment under either a team or a project kwarg+# depending on the viewset (routing treats the URL project id as the team id). Missing any+# spelling here means a token for one team authenticates on that route for another team.+_TEAM_ID_URL_KWARGS = ("parent_lookup_team_id", "team_id", "parent_lookup_project_id", "project_id")++def _team_id_from_request_path(request: Request) -> Optional[str]:parser_context = getattr(request, "parser_context", None)if isinstance(parser_context, dict):kwargs = parser_context.get("kwargs")if isinstance(kwargs, dict):- for lookup in ("parent_lookup_team_id", "team_id"):+ for lookup in _TEAM_ID_URL_KWARGS:if kwargs.get(lookup) is not None:return str(kwargs[lookup])django_request = getattr(request, "_request", request)resolver_match = getattr(django_request, "resolver_match", None)if resolver_match and getattr(resolver_match, "kwargs", None):- for lookup in ("parent_lookup_team_id", "team_id"):+ for lookup in _TEAM_ID_URL_KWARGS:team_id = resolver_match.kwargs.get(lookup)if team_id is not None:return str(team_id)diff --git a/posthog/test/test_scoped_service_jwt.py b/posthog/test/test_scoped_service_jwt.pyindex 7805d5df9bf3..e2dcb650c3c7 100644--- a/posthog/test/test_scoped_service_jwt.py+++ b/posthog/test/test_scoped_service_jwt.py@@ -1,13 +1,13 @@import jsonimport base64from datetime import UTC, datetime, timedelta-from types import SimpleNamespace-from typing import Any, cast+from typing import Anyimport pytestfrom posthog.test.base import APIBaseTestfrom django.test import RequestFactory, override_settings+from django.urls import resolveimport jwt as pyjwtfrom parameterized import parameterized@@ -113,14 +113,17 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):super().setUp()self.factory = RequestFactory()self.authentication = TeamScopedAuthentication()+ # A real second team, so a cross-team test fails on the team check and not on a missing row.+ self.other_team = self.create_team_with_organization(self.organization)- def _request(self, token: str | None, url_team_id: int | str | None = None) -> Request:+ def _request(self, token: str | None, url_team_id: int | str | None = None, endpoint: str = "query") -> Request:+ path = f"/api/projects/{url_team_id}/{endpoint}/" if url_team_id is not None else "/internal/endpoint"if token is not None:- django_request = self.factory.get("/internal/endpoint", HTTP_AUTHORIZATION=f"Bearer {token}")+ django_request = self.factory.get(path, HTTP_AUTHORIZATION=f"Bearer {token}")else:- django_request = self.factory.get("/internal/endpoint")+ django_request = self.factory.get(path)if url_team_id is not None:- django_request.resolver_match = cast(Any, SimpleNamespace(kwargs={"team_id": str(url_team_id)}))+ django_request.resolver_match = resolve(path)return Request(django_request) # ty: ignore[invalid-return-type]def _authenticate(self, authentication: ScopedServiceJWTAuthentication, request: Request) -> tuple[Any, Any]:@@ -138,10 +141,19 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):assert user.current_team_id == self.team.idassert user.current_organization_id == self.team.organization_id- def test_token_for_another_team_cannot_reach_the_url_team(self):- token = TEST_PURPOSE.mint({"team_id": self.team.id + 1})+ @parameterized.expand(+ [+ # /query/ resolves to parent_lookup_team_id; /feature_flags/ resolves to+ # parent_lookup_project_id. A lookup missing from either family lets a token+ # minted for one team authenticate on that route for another team.+ ("team_id_route", "query"),+ ("project_id_route", "feature_flags"),+ ]+ )+ def test_token_for_another_team_cannot_reach_the_url_team(self, _name, endpoint):+ token = TEST_PURPOSE.mint({"team_id": self.other_team.id})with pytest.raises(AuthenticationFailed):- self.authentication.authenticate(self._request(token, url_team_id=self.team.id))+ self.authentication.authenticate(self._request(token, url_team_id=self.team.id, endpoint=endpoint))@parameterized.expand([@@ -188,3 +200,9 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):user, _auth = self._authenticate(FleetScopedAuthentication(), self._request(token))assert user.current_team_id == self.team.id++ def test_fleet_scoped_purpose_with_team_claim_rejects_another_url_team(self):+ token = TEST_PURPOSE.mint({"team_id": self.team.id})++ with pytest.raises(AuthenticationFailed):+ FleetScopedAuthentication().authenticate(self._request(token, url_team_id=self.other_team.id))