: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(api): keep scoped tokens inside their projects and organizations (#83205)
Yasen989e88e0027c
diff --git a/posthog/api/data_management.py b/posthog/api/data_management.pyindex dfcc2274ec18..a2bef023cf76 100644--- a/posthog/api/data_management.py+++ b/posthog/api/data_management.py@@ -16,7 +16,7 @@ class DataManagementViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):activity_page = load_all_activity(scope_list=["EventDefinition", "PropertyDefinition"],- team_id=request.user.team.id, # type: ignore+ team_id=self.team.id,limit=limit,page=page,)diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 114b57382d63..6e5ad72066fa 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -48,7 +48,7 @@ from posthog.api.team import (validate_team_attrs,)from posthog.api.utils import validate_authorized_url_wildcards-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.auth import SessionAuthenticationfrom posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import AvailableFeaturefrom posthog.decorators import disallow_if_impersonated@@ -91,6 +91,7 @@ from posthog.permissions import (TeamMemberLightManagementPermission,TeamMemberStrictManagementPermission,UserCanCreateProjectPermission,+ get_authenticator_scoped_organization_ids,get_organization_from_view,)from posthog.rbac.user_access_control import (@@ -1327,13 +1328,9 @@ class ProjectViewSet(# IMPORTANT: This is actually what ensures that a user cannot read/update a project for which they don't have permissionvisible_teams_ids = UserPermissions(cast(User, self.request.user)).team_ids_visible_for_userqueryset = queryset.filter(id__in=visible_teams_ids)- if isinstance(self.request.successful_authenticator, PersonalAPIKeyAuthentication):- if scoped_organizations := self.request.successful_authenticator.personal_api_key.scoped_organizations:- queryset = queryset.filter(organization_id__in=scoped_organizations)- if isinstance(self.request.successful_authenticator, OAuthAccessTokenAuthentication):- if scoped_organizations := self.request.successful_authenticator.access_token.scoped_organizations:- queryset = queryset.filter(organization_id__in=scoped_organizations)- return queryset.filter(id__in=visible_teams_ids)+ if scoped_organizations := get_authenticator_scoped_organization_ids(self.request.successful_authenticator):+ queryset = queryset.filter(organization_id__in=scoped_organizations)+ return querysetdef get_serializer_class(self) -> type[serializers.BaseSerializer]:if self.action == "list":@@ -1436,6 +1433,12 @@ class ProjectViewSet(team = getattr(self.request.user, "team", None)if team is None:raise exceptions.NotFound()+ # This branch answers from the user's own state instead of the scoped queryset. A project+ # that moved between organizations leaves that state naming a project the token's+ # organizations no longer cover, so apply the same restriction the queryset would have.+ scoped_organizations = get_authenticator_scoped_organization_ids(self.request.successful_authenticator)+ if scoped_organizations and str(team.organization_id) not in scoped_organizations:+ raise exceptions.NotFound()return team.projectfilter_kwargs = {self.lookup_field: lookup_value}@@ -1864,6 +1867,8 @@ class ProjectViewSet(team.organization_id = target_organization_idteam.save()+ self._reconcile_current_project_of_affected_users(teams, target_organization)+report_user_action(user,"project moved to another organization",@@ -1883,6 +1888,24 @@ class ProjectViewSet(ProjectBackwardCompatSerializer(project, context=self.get_serializer_context()).data, status=200)+ @staticmethod+ def _reconcile_current_project_of_affected_users(teams: list[Team], target_organization: Organization) -> None:+ """Keep `current_team` and `current_organization` in step after a project changes hands.++ Left alone, both fields keep naming the state from before the move. Every check that reads+ the pair then answers for an organization that no longer holds the project.+ """+ affected_users = User.objects.filter(current_team__in=teams)+ member_user_ids = set(+ OrganizationMembership.objects.filter(+ organization=target_organization, user__in=affected_users+ ).values_list("user_id", flat=True)+ )+ # Members follow the project into its new organization; everyone else loses a pointer they+ # can no longer act on, and falls back to an organization they do belong to on next use+ affected_users.filter(id__in=member_user_ids).update(current_organization=target_organization)+ affected_users.exclude(id__in=member_user_ids).update(current_team=None, current_organization=None)+@cached_propertydef user_permissions(self):project = self.get_object() if self.action in actions_that_require_current_team else Nonediff --git a/posthog/api/team.py b/posthog/api/team.pyindex 22f59242a304..8fc16c50174f 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -44,7 +44,7 @@ from posthog.schema import (from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import TeamBasicSerializerfrom posthog.api.utils import action, validate_authorized_url_wildcards-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.auth import SessionAuthenticationfrom posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS, AvailableFeaturefrom posthog.decorators import disallow_if_impersonatedfrom posthog.event_usage import report_user_action@@ -86,6 +86,8 @@ from posthog.permissions import (TeamMemberLightManagementPermission,TeamMemberStrictManagementPermission,UserCanCreateProjectPermission,+ get_authenticator_scoped_organization_ids,+ get_authenticator_scoped_team_ids,)from posthog.rbac.access_control_api_mixin import AccessControlSettingsViewSetMixin, AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixin@@ -2138,16 +2140,11 @@ class TeamViewSet(# IMPORTANT: This is actually what ensures that a user cannot read/update a project for which they don't have permissionvisible_teams_ids = UserPermissions(user).team_ids_visible_for_userqueryset = queryset.filter(id__in=visible_teams_ids)- if isinstance(self.request.successful_authenticator, PersonalAPIKeyAuthentication):- if scoped_organizations := self.request.successful_authenticator.personal_api_key.scoped_organizations:- queryset = queryset.filter(project__organization_id__in=scoped_organizations)- if scoped_teams := self.request.successful_authenticator.personal_api_key.scoped_teams:- queryset = queryset.filter(id__in=scoped_teams)- if isinstance(self.request.successful_authenticator, OAuthAccessTokenAuthentication):- if scoped_organizations := self.request.successful_authenticator.access_token.scoped_organizations:- queryset = queryset.filter(project__organization_id__in=scoped_organizations)- if scoped_teams := self.request.successful_authenticator.access_token.scoped_teams:- queryset = queryset.filter(id__in=scoped_teams)+ authenticator = self.request.successful_authenticator+ if scoped_organizations := get_authenticator_scoped_organization_ids(authenticator):+ queryset = queryset.filter(project__organization_id__in=scoped_organizations)+ if scoped_teams := get_authenticator_scoped_team_ids(authenticator):+ queryset = queryset.filter(id__in=scoped_teams)return querysetdef get_serializer_class(self) -> type[serializers.BaseSerializer]:@@ -2224,6 +2221,12 @@ class TeamViewSet(team = getattr(self.request.user, "team", None)if team is None:raise exceptions.NotFound()+ # This branch answers from the user's own state instead of the scoped queryset. A project+ # that moved between organizations leaves that state naming an environment the token's+ # organizations no longer cover, so apply the same restriction the queryset would have.+ scoped_organizations = get_authenticator_scoped_organization_ids(self.request.successful_authenticator)+ if scoped_organizations and str(team.organization_id) not in scoped_organizations:+ raise exceptions.NotFound()return teamfilter_kwargs = {self.lookup_field: lookup_value}diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.pyindex 349f32c16652..e6507502bd43 100644--- a/posthog/api/test/test_id_jag.py+++ b/posthog/api/test/test_id_jag.py@@ -23,6 +23,7 @@ from django.utils import timezoneimport jwtfrom cryptography.hazmat.primitives import serializationfrom oauth2_provider.utils import jwk_from_pem+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.id_jag import (@@ -1018,3 +1019,18 @@ class TestIDJagAccessTokenAuthentication(APIBaseTest):resp = self.client.get(f"/api/projects/@current/", HTTP_AUTHORIZATION=f"Bearer {token}")self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)self.assertEqual(resp.json()["id"], self.team.id)++ @parameterized.expand([("/api/projects/@current/",), ("/api/environments/@current/",)])+ def test_denies_current_lookup_outside_the_tokens_organization(self, url: str) -> None:+ # A project transfer between organizations leaves `current_team` naming the moved project+ # while `current_organization` still names the organization the token was minted for. The+ # `@current` lookup must answer from the token's organization, not from that stale pair.+ _, _, other_team = Organization.objects.bootstrap(self.user)+ self.user.current_team = other_team+ self.user.current_organization = self.organization+ self.user.save()++ token = self._mint_access_token(scope="project:read")+ resp = self.client.get(url, HTTP_AUTHORIZATION=f"Bearer {token}")++ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND, resp.content)diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex 226e1466fd6b..f400b1dca16b 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -17,6 +17,7 @@ from posthog.api.personal_api_key import PersonalAPIKeySerializerfrom posthog.constants import AvailableFeaturefrom posthog.helpers.dev_api_key import get_local_dev_api_key_valuefrom posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import Organizationfrom posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKeyfrom posthog.models.team.team import Team@@ -985,6 +986,19 @@ class TestPersonalAPIKeysWithOrganizationScopeAPIAuthentication(PersonalAPIKeysBresponse = self._do_request(f"/api/projects/{self.team.id}/events/")assert response.status_code == status.HTTP_200_OK, response.json()+ @parameterized.expand([("/api/projects/@current/",), ("/api/environments/@current/",)])+ def test_denies_current_lookup_when_current_project_is_outside_the_scoped_org(self, url: str):+ # A project transfer between organizations leaves `current_team` pointing at the moved+ # project while `current_organization` still names the old one. The `@current` lookup must+ # still scope to the key's organizations, not to that stale pair.+ self.user.current_team = self.other_team+ self.user.current_organization = self.organization+ self.user.save()++ response = self._do_request(url)++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()+class TestPersonalAPIKeysWithTeamScopeAPIAuthentication(PersonalAPIKeysBaseTest):def setUp(self):@@ -1026,6 +1040,33 @@ class TestPersonalAPIKeysWithTeamScopeAPIAuthentication(PersonalAPIKeysBaseTest)response = self._do_request(f"/api/users/@me/")assert response.status_code == status.HTTP_200_OK, response.json()+ def test_data_management_activity_ignores_the_users_current_project(self):+ # The viewset is INTERNAL, so the `*` wildcard does not reach it — the action names its own scope+ self.key.scopes = ["activity_log:read"]+ self.key.save()+ self.user.current_team = self.other_team+ self.user.current_organization = self.other_organization+ self.user.save()+ ActivityLog.objects.create(+ team_id=self.team.id,+ organization_id=self.organization.id,+ scope="EventDefinition",+ activity="created",+ item_id="in-scope",+ )+ ActivityLog.objects.create(+ team_id=self.other_team.id,+ organization_id=self.other_organization.id,+ scope="EventDefinition",+ activity="created",+ item_id="out-of-scope",+ )++ response = self._do_request(f"/api/projects/{self.team.id}/data_management/activity")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [row["item_id"] for row in response.json()["results"]] == ["in-scope"]+class TestPersonalAPIKeyAPIAccess(APIBaseTest):def setUp(self):diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex e3649cb4c7c5..26abac6b2d6d 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -1420,6 +1420,32 @@ def team_api_test_factory():assert self.project.organization == other_orgassert self.team.organization == other_org+ def test_change_organization_reconciles_current_project_of_affected_users(self):+ other_org, _ = self._create_other_org_and_team(OrganizationMembership.Level.ADMIN)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.user.current_team = self.team+ self.user.current_organization = self.organization+ self.user.save()+ # This user stays behind in the source organization+ outsider = User.objects.create_and_join(self.organization, "[email protected]", None)+ outsider.current_team = self.team+ outsider.current_organization = self.organization+ outsider.save()++ res = self.client.post(+ f"/api/projects/{self.team.project.id}/change_organization/", {"organization_id": other_org.id}+ )+ assert res.status_code == status.HTTP_200_OK, res.json()++ # A member of the target organization keeps the project and follows it across+ self.user.refresh_from_db()+ assert self.user.current_team == self.team+ assert self.user.current_organization == other_org+ # Everyone else loses the pointer instead of keeping a project they cannot reach+ outsider.refresh_from_db()+ assert outsider.current_team_id is None and outsider.current_organization_id is None+def _assert_replay_config_is(self, expected: dict[str, Any] | None) -> HttpResponse:return self._assert_config_is("session_replay_config", expected)diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 2cf0774a9473..bbcac70d574c 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -628,6 +628,26 @@ def get_authenticator_scopes(authenticator) -> list[str] | None:return None+def get_authenticator_scoped_organization_ids(authenticator) -> list[str] | None:+ """The organizations a scoped token is confined to, or None when the credential carries no+ organization restriction (session auth, or a token scoped to every organization).++ The organization-level counterpart of `get_authenticator_scoped_team_ids`. Both exist so that a+ check outside `TeamAndOrgViewSetMixin` reads a credential's reach from one place.+ """+ if isinstance(authenticator, PersonalAPIKeyAuthentication):+ return list(authenticator.personal_api_key.scoped_organizations or []) or None+ if isinstance(authenticator, OAuthAccessTokenAuthentication):+ return list(authenticator.access_token.scoped_organizations or []) or None+ if isinstance(authenticator, IDJagAccessTokenAuthentication):+ # An ID-JAG access token is bound to the one PostHog organization whose OrganizationDomain+ # pinned the trusted IdP, carried in the `org_id` claim. Confining it to that organization+ # keeps it away from the other organizations the resolved user happens to belong to+ # (cross-org confused-deputy defense).+ return [authenticator.organization_id]+ return None++def get_authenticator_scoped_team_ids(authenticator) -> list[int] | None:"""The teams a scoped token is confined to, or None when the credential carries no teamrestriction (session auth, or a token scoped to every team in the organization).@@ -759,23 +779,16 @@ class APIScopePermission(ScopeBasePermission):self._check_organization_personal_api_key_restrictions(request, view)- if isinstance(request.successful_authenticator, OAuthAccessTokenAuthentication):- scoped_organizations = request.successful_authenticator.access_token.scoped_organizations- scoped_teams = request.successful_authenticator.access_token.scoped_teams- elif isinstance(request.successful_authenticator, PersonalAPIKeyAuthentication):- scoped_organizations = request.successful_authenticator.personal_api_key.scoped_organizations- scoped_teams = request.successful_authenticator.personal_api_key.scoped_teams- elif isinstance(request.successful_authenticator, IDJagAccessTokenAuthentication):- # ID-JAG access tokens are bound to the specific PostHog Organization- # whose OrganizationDomain pinned the trusted IdP — carried in the- # `org_id` claim. Pin `scoped_organizations` to that single org so- # the token cannot reach other orgs the resolved user happens to- # be a member of (cross-org confused-deputy defense).- scoped_organizations = [request.successful_authenticator.organization_id]- scoped_teams = None- else:+ authenticator = request.successful_authenticator+ if not isinstance(+ authenticator,+ OAuthAccessTokenAuthentication | PersonalAPIKeyAuthentication | IDJagAccessTokenAuthentication,+ ):raise ValueError("Unexpected authentication type")+ scoped_organizations = get_authenticator_scoped_organization_ids(authenticator)+ scoped_teams = get_authenticator_scoped_team_ids(authenticator)+if scoped_teams and not skip_team_and_org:# Views that aren't project-nested but still need to accept# scoped_teams tokens can set `dangerously_skip_scoped_team_enforcement = True`