: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): block API tokens for deactivated organizations (#96538)
Yasend6054a12ae06
diff --git a/posthog/api/routing.py b/posthog/api/routing.pyindex b63efbd2af30..d30a7d3f1a71 100644--- a/posthog/api/routing.py+++ b/posthog/api/routing.py@@ -33,6 +33,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import (AccessControlPermission,+ ActiveOrganizationPermission,APIScopePermission,MCPAccessPermission,OrganizationMemberPermissions,@@ -257,9 +258,14 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):except NotImplementedError:passelse:- # Domain enforcement and the MCP cap are tenant boundaries, not authorization- # levels. Views that shape their own permission chain cannot remove them.- return [*dangerously_defined, VerifiedDomainEnforcementPermission(), MCPAccessPermission()]+ # These are tenant boundaries, not authorization levels. Views that shape their own+ # permission chain cannot remove them.+ return [+ *dangerously_defined,+ VerifiedDomainEnforcementPermission(),+ MCPAccessPermission(),+ ActiveOrganizationPermission(),+ ]if isinstance(self.request.successful_authenticator, InternalAPIAuthentication):return [IsAuthenticated()]@@ -288,6 +294,7 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):# its message must not disclose another organization's security settings.permission_classes.append(VerifiedDomainEnforcementPermission)permission_classes.append(MCPAccessPermission)+ permission_classes.append(ActiveOrganizationPermission)permission_classes.extend(self.permission_classes)return [permission() for permission in permission_classes]diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.pyindex 8cbab7f9a0e2..fdc682855e61 100644--- a/posthog/api/test/test_routing.py+++ b/posthog/api/test/test_routing.py@@ -22,9 +22,11 @@ from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry, TeamAndOrfrom posthog.auth import ProjectSecretAPIKeyAuthenticationfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organization+from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project import Projectfrom posthog.models.scoping import get_current_team_idfrom posthog.models.team.team import Team+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.permissions import APIScopePermissionfrom posthog.products import product_app_names@@ -219,6 +221,79 @@ class TestTeamAndOrgViewSetMixin(APIBaseTest):)+@override_settings(ROOT_URLCONF=__name__)+class TestDeactivatedOrganizationBlocksTokens(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test key",+ user=self.user,+ secure_value=hash_key_value(self.key_value),+ scopes=["*"],+ )+ Annotation.objects.create(team=self.team, organization=self.organization)++ def _get_with_key(self):+ return self.client.get(+ f"/api/scoped_environments/{self.team.id}/scoped_foos/",+ HTTP_AUTHORIZATION=f"Bearer {self.key_value}",+ )++ def _deactivate(self, reason=None):+ self.organization.is_active = False+ self.organization.is_not_active_reason = reason+ self.organization.save(update_fields=["is_active", "is_not_active_reason"])++ def test_personal_api_key_is_refused_once_the_organization_is_deactivated(self):+ self.assertEqual(self._get_with_key().status_code, 200)++ self._deactivate(reason="Access revoked due to unpaid balance.")++ response = self._get_with_key()+ self.assertEqual(response.status_code, 403)+ self.assertEqual(response.json()["code"], "organization_deactivated")+ self.assertIn("Access revoked due to unpaid balance.", response.json()["detail"])++ def test_session_auth_still_reaches_a_deactivated_organization(self):+ self._deactivate()++ response = self.client.get(f"/api/scoped_environments/{self.team.id}/scoped_foos/")++ self.assertEqual(response.status_code, 200)++ def test_a_key_still_reaches_an_active_organization_of_the_same_user(self):+ self._deactivate()+ _, _, other_team = Organization.objects.bootstrap(user=self.user)+ # bootstrap makes the new organization current, which would let a check that reads+ # current_organization pass for the wrong reason. Put the deactivated one back.+ self.user.current_organization = self.organization+ self.user.save()++ response = self.client.get(+ f"/api/scoped_environments/{other_team.id}/scoped_foos/",+ HTTP_AUTHORIZATION=f"Bearer {self.key_value}",+ )++ self.assertEqual(response.status_code, 200)++ def test_a_root_write_is_refused_for_a_deactivated_current_organization(self):+ # A 400 here would mean the request reached the serializer, which is the bypass this guards.+ self._deactivate()++ response = self.client.post("/api/scoped_projects/", {}, HTTP_AUTHORIZATION=f"Bearer {self.key_value}")++ self.assertEqual(response.status_code, 403)+ self.assertEqual(response.json()["code"], "organization_deactivated")++ def test_a_root_read_still_works_so_a_member_can_switch_organization(self):+ self._deactivate()++ response = self.client.get("/api/scoped_projects/", HTTP_AUTHORIZATION=f"Bearer {self.key_value}")++ self.assertEqual(response.status_code, 200)++@override_settings(ROOT_URLCONF=__name__)class TestOAuthAccessTokenAuthentication(APIBaseTest):"""Test that OAuth access tokens work through the routing layer with proper permissions"""diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 6beb3c5c9861..7b3563eff824 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -253,15 +253,10 @@ class VerifiedDomainEnforcementPermission(BasePermission):if not isinstance(request.user, User):return True- # Root viewsets (organizations, projects, environments) carry no parent URL kwargs, and the- # mixin's `organization` falls back to the user's current organization there, which is not- # the request's target. Gate on the fetched object below instead. Views deriving their- # target from the current team (`param_derived_from_user_current_team`) are the exception:- # for those the current team is the target by construction.- if not view.parent_query_kwargs and not view.param_derived_from_user_current_team:+ if not view_targets_one_organization(view):return True- organization = self._target_organization(view)+ organization = url_target_organization(view)if organization is None:return Truereturn self._admits(request, organization)@@ -294,26 +289,130 @@ class VerifiedDomainEnforcementPermission(BasePermission):return True- def _target_organization(self, view) -> Optional[Organization]:- # Same resolution as `get_organization_from_view`, but the team's FK first: routing loads- # the team with `select_related("organization")` and `TeamMemberAccessPermission` has- # already resolved it, whereas `view.organization` would issue its own PK query on- # team-scoped views.- try:- organization = view.team.organization- if isinstance(organization, Organization):- return organization- except (KeyError, AttributeError, AssertionError, Team.DoesNotExist):- pass- try:- organization = view.organization- if isinstance(organization, Organization):- return organization- except (KeyError, AttributeError, AssertionError):- pass+def url_target_organization(view) -> Optional[Organization]:+ """The organization the request URL points at, or None when the view resolves no target.- return None+ Same resolution as `get_organization_from_view`, but the team's FK first: routing loads the+ team with `select_related("organization")` and `TeamMemberAccessPermission` has already+ resolved it, whereas `view.organization` would issue its own PK query on team-scoped views.+ """+ try:+ organization = view.team.organization+ if isinstance(organization, Organization):+ return organization+ except (KeyError, AttributeError, AssertionError, Team.DoesNotExist):+ pass++ try:+ organization = view.organization+ if isinstance(organization, Organization):+ return organization+ except (KeyError, AttributeError, AssertionError):+ pass++ return None+++def view_targets_one_organization(view) -> bool:+ """Whether the view acts on one organization that the URL identifies.++ Root viewsets (organizations, projects, environments) carry no parent URL kwargs, and the+ mixin's `organization` falls back to the user's current organization there, which is not the+ request's target. Views deriving their target from the current team+ (`param_derived_from_user_current_team`) are the exception: for those the current team is the+ target by construction.+ """+ return bool(view.parent_query_kwargs or view.param_derived_from_user_current_team)+++ORGANIZATION_PENDING_DELETION_ERROR = (+ "This organization is scheduled for deletion. API access is blocked. Contact support if you need it restored."+)+++def organization_deactivated_error(reason: Optional[str]) -> str:+ """The refusal shown to an API caller. `reason` is operator text, already user-facing."""+ detail = f"This organization is deactivated. {reason.strip()}" if reason else "This organization is deactivated."+ return f"{detail} API access stays blocked until it's restored. Contact support if you think this is a mistake."+++class ActiveOrganizationPermission(BasePermission):+ """+ Deny token-authenticated requests that target a deactivated organization.++ `ActiveOrganizationMiddleware` redirects the browser away from a deactivated organization, but+ it skips every `/api` path, so API keys kept full read and write access. Appended to every+ `TeamAndOrgViewSetMixin` view in `get_permissions`, so it holds regardless of a view's own+ `authentication_classes`.++ Session auth passes through. The middleware already covers the browser, and a member of a+ deactivated organization still has to reach the app to see why and to pay an unpaid balance.++ A null `is_active` counts as deactivated. The column is nullable because the field was added+ with `null=True`, and treating an unknown state as deactivated fails closed.++ Checked against the URL-resolved organization, never `user.current_organization`, because the+ current organization is a UI preference the API doesn't validate.+ """++ # Billing stays reachable, so an integration can still read the state that explains the refusal.+ EXEMPT_SCOPE_OBJECTS = frozenset({"billing"})++ def has_permission(self, request: Request, view) -> bool:+ if not self._applies(request, view):+ return True++ organization = self._target_organization(request, view)+ if organization is None:+ return True+ return self._admits(organization)++ def _target_organization(self, request: Request, view) -> Optional[Organization]:+ """The organization this request acts on, or None when it has no single target.++ On a root viewset the mixin falls back to the current organization, which is a UI+ preference rather than the request's target. Reads pass, because listing organizations is+ how a member switches away from a deactivated one. Detail routes pass to+ `has_object_permission`, which judges the organization the URL names; gating them here+ would refuse an active organization whenever a deactivated one happened to be current.+ Creating an organization passes, because the new row lands outside the current one.+ Every other root write does land in the current organization, so it is gated here.+ """+ if view_targets_one_organization(view):+ return url_target_organization(view)+ if request.method in SAFE_METHODS or getattr(view, "detail", False):+ return None+ if getattr(view, "basename", None) == "organizations" and getattr(view, "action", None) == "create":+ return None+ return url_target_organization(view)++ def has_object_permission(self, request: Request, view, object: Model) -> bool:+ if not self._applies(request, view):+ return True+ if isinstance(object, Organization):+ return self._admits(object)+ if isinstance(object, Team | Project):+ return self._admits(object.organization)+ return True++ def _applies(self, request: Request, view) -> bool:+ if getattr(view, "scope_object", None) in self.EXEMPT_SCOPE_OBJECTS:+ return False+ return get_authenticator_scopes(getattr(request, "successful_authenticator", None)) is not None++ def _admits(self, organization: Organization) -> bool:+ if organization.is_pending_deletion:+ raise PermissionDenied(+ detail=ORGANIZATION_PENDING_DELETION_ERROR,+ code="organization_pending_deletion",+ )+ if not organization.is_active:+ raise PermissionDenied(+ detail=organization_deactivated_error(organization.is_not_active_reason),+ code="organization_deactivated",+ )+ return Truedef is_authenticated_via_team_secret_token(request: Request) -> bool:diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex 3f1538b7b304..d99eae38f5b5 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -1,5 +1,6 @@import jsonfrom datetime import timedelta+from typing import castfrom posthog.test.base import BaseTestfrom unittest.mock import Mock, PropertyMock, patch@@ -10,17 +11,28 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import ErrorDetail, PermissionDeniedfrom rest_framework.test import APIRequestFactory-from posthog.auth import PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthentication, TeamSecretTokenAuthentication+from posthog.auth import (+ ExportRendererAuthentication,+ IDJagAccessTokenAuthentication,+ JwtAuthentication,+ OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,+ ProjectSecretAPIKeyAuthentication,+ SessionAuthentication,+ TeamSecretTokenAuthentication,+)from posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Organization, Team, Userfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from posthog.permissions import AccessControlPermission, PostHogFeatureFlagPermission+from posthog.permissions import AccessControlPermission, ActiveOrganizationPermission, PostHogFeatureFlagPermissionfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.access_control.backend.models.access_control import AccessControl@@ -1371,3 +1383,191 @@ class TestPostHogFeatureFlagPermission(BaseTest):self.assertFalse(result)mock_ff.assert_called_once()+++class TestActiveOrganizationPermission(SimpleTestCase):+ # The permission reads three fields off the organization, so unsaved instances are enough.+ def setUp(self):+ self.permission = ActiveOrganizationPermission()+ self.organization = Organization(name="Test org")+ self.team = Team(organization=self.organization)++ def _view(self, scope_object="insight", team=None, basename="project_insights", action="list"):+ view = Mock()+ view.parent_query_kwargs = ["team_id"]+ view.param_derived_from_user_current_team = None+ view.team = team if team is not None else self.team+ view.scope_object = scope_object+ view.basename = basename+ view.action = action+ # A bare Mock would hand back a truthy attribute and skip the check everywhere.+ view.detail = False+ return view++ def _root_view(self, basename="projects", action="create"):+ view = self._view(basename=basename, action=action)+ view.parent_query_kwargs = []+ view.organization = self.organization+ return view++ def _request(self, authenticator, method="GET"):+ request = Mock()+ request.successful_authenticator = authenticator+ request.method = method+ return request++ def _personal_api_key_auth(self):+ auth = PersonalAPIKeyAuthentication()+ auth.personal_api_key = PersonalAPIKey(scopes=["*"])+ return auth++ def _oauth_auth(self):+ auth = OAuthAccessTokenAuthentication()+ auth.access_token = OAuthAccessToken(scope="insight:read")+ return auth++ def _project_secret_key_auth(self):+ auth = ProjectSecretAPIKeyAuthentication()+ auth.project_secret_api_key = ProjectSecretAPIKey(scopes=["feature_flag:read"])+ return auth++ def _id_jag_auth(self):+ auth = IDJagAccessTokenAuthentication()+ auth.scopes = ["insight:read"]+ return auth++ def _export_renderer_auth(self):+ auth = ExportRendererAuthentication()+ auth.scopes = ["insight:read"]+ return auth++ def _deactivate(self, reason=None):+ self.organization.is_active = False+ self.organization.is_not_active_reason = reason++ def _denial_code(self, exception: PermissionDenied) -> str | None:+ return cast(ErrorDetail, exception.detail).code++ @parameterized.expand(+ [+ ("personal_api_key", "_personal_api_key_auth"),+ ("oauth", "_oauth_auth"),+ ("project_secret_api_key", "_project_secret_key_auth"),+ ("id_jag", "_id_jag_auth"),+ ("export_renderer", "_export_renderer_auth"),+ ]+ )+ def test_every_token_credential_is_blocked_for_a_deactivated_organization(self, _name, auth_factory):+ self._deactivate()+ request = self._request(getattr(self, auth_factory)())++ with self.assertRaises(PermissionDenied) as denial:+ self.permission.has_permission(request, self._view())++ self.assertEqual(self._denial_code(denial.exception), "organization_deactivated")++ @parameterized.expand(+ [+ ("session", SessionAuthentication),+ ("jwt", JwtAuthentication),+ ("team_secret_token", TeamSecretTokenAuthentication),+ ("none", None),+ ]+ )+ def test_non_token_credentials_still_reach_a_deactivated_organization(self, _name, authenticator_class):+ self._deactivate()+ authenticator = authenticator_class() if authenticator_class else None++ self.assertTrue(self.permission.has_permission(self._request(authenticator), self._view()))++ def test_null_is_active_is_treated_as_deactivated(self):+ self.organization.is_active = None++ with self.assertRaises(PermissionDenied) as denial:+ self.permission.has_permission(self._request(self._personal_api_key_auth()), self._view())++ self.assertEqual(self._denial_code(denial.exception), "organization_deactivated")++ def test_active_organization_admits_a_token(self):+ self.assertTrue(self.permission.has_permission(self._request(self._personal_api_key_auth()), self._view()))++ def test_pending_deletion_is_blocked_even_while_active(self):+ self.organization.is_pending_deletion = True++ with self.assertRaises(PermissionDenied) as denial:+ self.permission.has_permission(self._request(self._personal_api_key_auth()), self._view())++ self.assertEqual(self._denial_code(denial.exception), "organization_pending_deletion")++ def test_billing_stays_reachable_so_a_customer_can_pay(self):+ self._deactivate(reason="Access revoked due to unpaid balance.")+ view = self._view(scope_object="billing")++ self.assertTrue(self.permission.has_permission(self._request(self._personal_api_key_auth()), view))++ def test_deactivation_reason_is_surfaced_to_the_caller(self):+ self._deactivate(reason="Access revoked due to unpaid balance.")++ with self.assertRaises(PermissionDenied) as denial:+ self.permission.has_permission(self._request(self._personal_api_key_auth()), self._view())++ self.assertIn("Access revoked due to unpaid balance.", str(denial.exception.detail))++ def test_a_second_organization_is_judged_on_its_own_state(self):+ self._deactivate()+ other_team = Team(organization=Organization(name="Still active"))++ view = self._view(team=other_team)++ self.assertTrue(self.permission.has_permission(self._request(self._personal_api_key_auth()), view))++ def test_object_level_check_covers_root_viewsets(self):+ self._deactivate()+ view = self._view()+ view.parent_query_kwargs = []+ request = self._request(self._personal_api_key_auth())++ self.assertTrue(self.permission.has_permission(request, view))+ with self.assertRaises(PermissionDenied):+ self.permission.has_object_permission(request, view, self.organization)+ with self.assertRaises(PermissionDenied):+ self.permission.has_object_permission(request, view, self.team)++ @parameterized.expand([("post", "POST"), ("patch", "PATCH"), ("delete", "DELETE")])+ def test_root_writes_are_blocked_for_the_current_organization(self, _name, method):+ # DRF runs no object check for a root create, so has_permission is the only gate.+ self._deactivate()+ request = self._request(self._personal_api_key_auth(), method=method)++ with self.assertRaises(PermissionDenied) as denial:+ self.permission.has_permission(request, self._root_view())++ self.assertEqual(self._denial_code(denial.exception), "organization_deactivated")++ def test_root_reads_stay_open_so_a_member_can_switch_organization(self):+ # Listing organizations is how a member leaves a deactivated one.+ self._deactivate()+ request = self._request(self._personal_api_key_auth(), method="GET")++ view = self._root_view(basename="organizations", action="list")+ self.assertTrue(self.permission.has_permission(request, view))++ def test_creating_an_organization_is_not_judged_on_the_current_one(self):+ self._deactivate()+ request = self._request(self._personal_api_key_auth(), method="POST")++ view = self._root_view(basename="organizations", action="create")+ self.assertTrue(self.permission.has_permission(request, view))++ @parameterized.expand([("patch", "PATCH", "partial_update"), ("delete", "DELETE", "destroy")])+ def test_a_root_detail_route_is_left_to_the_object_check(self, _name, method, action):+ # The URL names the target, but the mixin resolves no organization from it and falls back+ # to the current one. Gating here would refuse an active organization whenever a+ # deactivated one happened to be current.+ self._deactivate()+ request = self._request(self._personal_api_key_auth(), method=method)++ view = self._root_view(basename="projects", action=action)+ view.detail = True++ self.assertTrue(self.permission.has_permission(request, view))