: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(oauth): block impersonated oauth when org disabled ai processing (#60942)
Rafael Audibert61d9324253c0
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 298600545f82..fa20a8890ef4 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -46,7 +46,7 @@ from posthog.api.oauth.cimd import ()from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_sessionfrom posthog.middleware import is_read_only_impersonation-from posthog.models import OAuthAccessToken, OAuthApplication, Team, User+from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, Userfrom posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshTokenfrom posthog.scopes import downgrade_scopes_to_read_only, get_oauth_scopes_supportedfrom posthog.security.url_validation import has_authority_bypass_chars@@ -112,6 +112,66 @@ def _impersonator_id_for_request(request) -> int | None:return original_user.pk if original_user else None+def _scoped_organization_ids(+ user: User,+ access_level: str | None,+ scoped_organization_ids: list[str] | None,+ scoped_team_ids: list[int] | None,+) -> set[uuid.UUID]:+ """Resolve the set of organizations a grant with this access scope would reach.++ `all` access (or any unscoped grant) reaches every organization the user belongs to;+ `organization` access is the listed organizations; `team` access is the organizations+ owning the listed teams.+ """+ if access_level == OAuthApplicationAccessLevel.ORGANIZATION.value and scoped_organization_ids:+ return {uuid.UUID(str(org_id)) for org_id in scoped_organization_ids}+ if access_level == OAuthApplicationAccessLevel.TEAM.value and scoped_team_ids:+ return set(Team.objects.filter(pk__in=scoped_team_ids).values_list("organization_id", flat=True))+ return set(user.organizations.values_list("id", flat=True))+++def _impersonation_ai_processing_block(+ request,+ *,+ access_level: str | None = None,+ scoped_organization_ids: list[str] | None = None,+ scoped_team_ids: list[int] | None = None,+) -> Response | None:+ """Block OAuth during impersonation when an in-scope organization has disabled AI data processing.++ Some organizations explicitly opt out of AI processing of their data+ (`Organization.is_ai_data_processing_approved`). A staff member impersonating a customer+ must not be able to grant an OAuth client access to that data in that case (the MCP being+ the motivating case). This does not apply to customers authorizing a client themselves —+ they have already consented for their own data.++ Mirrors the fail-closed check used elsewhere for AI features: only an explicit `True`+ counts as approved, so a null/unset value is treated as not approved. Returns a 403+ `Response` to short-circuit with, or `None` to proceed.+ """+ if not is_impersonated_session(request):+ return None++ organization_ids = _scoped_organization_ids(request.user, access_level, scoped_organization_ids, scoped_team_ids)+ if not organization_ids:+ return None++ has_disabled_org = (+ Organization.objects.filter(id__in=organization_ids).exclude(is_ai_data_processing_approved=True).exists()+ )+ if not has_disabled_org:+ return None++ return Response(+ {+ "error": "access_denied",+ "error_description": "This organization has disabled AI data processing, so it cannot be authorized for an OAuth client while impersonating.",+ },+ status=status.HTTP_403_FORBIDDEN,+ )++class OAuthAuthorizationContext(TypedDict):user: User@@ -606,6 +666,8 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):# First-party apps skip consent screen entirelyif application.is_first_party:+ if block := _impersonation_ai_processing_block(request):+ return blocktry:org_ids = request.user.organizations.values_list("id", flat=True)credentials["scoped_organizations"] = [str(org_id) for org_id in org_ids]@@ -629,6 +691,13 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):# impersonating), so its split form is the effective set we need to match.for token in tokens:if token.allow_scopes(scope_str.split()):+ # Conservative fallback: check every org the impersonated user belongs to,+ # not just the existing token's scope. Auto-approval during impersonation+ # is a near-dead path (those tokens are short-lived, refresh-less, and+ # revoked on logout), so the broader check isn't worth threading the+ # matched token's scope through — the precise check lives in the POST path.+ if block := _impersonation_ai_processing_block(request):+ return blockuri, headers, body, status_code = self.create_authorization_response(request=request, scopes=scope_str, credentials=credentials, allow=True)@@ -682,6 +751,15 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):if is_read_only_impersonation(request):scopes = downgrade_scopes_to_read_only(scopes)+ if serializer.validated_data["allow"]:+ if block := _impersonation_ai_processing_block(+ request,+ access_level=serializer.validated_data.get("access_level"),+ scoped_organization_ids=serializer.validated_data.get("scoped_organizations"),+ scoped_team_ids=serializer.validated_data.get("scoped_teams"),+ ):+ return block+try:uri, headers, body, status_code = self.create_authorization_response(request=request,diff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.pyindex 38e8027cab22..82c87fd6b21f 100644--- a/posthog/test/test_oauth_impersonation.py+++ b/posthog/test/test_oauth_impersonation.py@@ -10,6 +10,7 @@ from django.conf import settingsfrom django.contrib.auth import logoutfrom django.contrib.sessions.backends.db import SessionStorefrom django.core.signing import TimestampSigner+from django.http import HttpRequestfrom django.test import RequestFactory, override_settingsfrom django.utils import timezone@@ -17,10 +18,10 @@ from loginas import settings as la_settingsfrom parameterized import parameterizedfrom posthog.api.oauth.test_dcr import generate_rsa_key-from posthog.api.oauth.views import _impersonator_id_for_request+from posthog.api.oauth.views import _impersonation_ai_processing_block, _impersonator_id_for_requestfrom posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEY-from posthog.models import OAuthApplication, User-from posthog.models.oauth import OAuthAccessToken, OAuthGrant, OAuthRefreshToken+from posthog.models import OAuthApplication, Organization, OrganizationMembership, Team, User+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshTokenTEST_OAUTH2_PROVIDER_WITH_RSA = {**settings.OAUTH2_PROVIDER,@@ -214,3 +215,86 @@ class TestImpersonatorIdResolution(BaseTest):request.user = targetself.assertIsNone(_impersonator_id_for_request(request))+++class TestImpersonationAIProcessingBlock(BaseTest):+ """Organizations that opt out of AI data processing must not be authorizable for any OAuth+ client (the MCP being the motivating case) while a staff member is impersonating a customer.+ Customers authorizing a client themselves are unaffected — they have already consented for+ their own data."""++ def _build_request(self, target: User, *, impersonating: bool) -> HttpRequest:+ request = RequestFactory().get("/")+ request.session = SessionStore()+ if impersonating:+ admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")+ admin.is_staff = True+ admin.save()+ request.session[la_settings.USER_SESSION_FLAG] = TimestampSigner().sign(str(admin.pk))+ request.user = target+ return request++ def _member_of(self, organization: Organization) -> User:+ target = User.objects.create_user(email="[email protected]", password="x", first_name="C")+ OrganizationMembership.objects.create(user=target, organization=organization)+ return target++ def test_no_block_when_not_impersonating_even_if_disabled(self) -> None:+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()+ target = self._member_of(self.organization)+ request = self._build_request(target, impersonating=False)++ self.assertIsNone(_impersonation_ai_processing_block(request))++ @parameterized.expand([("explicitly_disabled", False), ("unset", None)])+ def test_blocks_impersonation_when_org_not_approved(self, _name: str, value: bool | None) -> None:+ self.organization.is_ai_data_processing_approved = value+ self.organization.save()+ target = self._member_of(self.organization)+ request = self._build_request(target, impersonating=True)++ response = _impersonation_ai_processing_block(request)+ assert response is not None+ self.assertEqual(response.status_code, 403)+ self.assertEqual(response.data["error"], "access_denied")++ def test_no_block_when_org_approved(self) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ target = self._member_of(self.organization)+ request = self._build_request(target, impersonating=True)++ self.assertIsNone(_impersonation_ai_processing_block(request))++ def test_no_block_when_disabled_org_out_of_scope(self) -> None:+ approved_org = Organization.objects.create(name="approved", is_ai_data_processing_approved=True)+ disabled_org = Organization.objects.create(name="disabled", is_ai_data_processing_approved=False)+ target = User.objects.create_user(email="[email protected]", password="x", first_name="C")+ OrganizationMembership.objects.create(user=target, organization=approved_org)+ OrganizationMembership.objects.create(user=target, organization=disabled_org)+ request = self._build_request(target, impersonating=True)++ # Scoping the grant to the approved org only must not be blocked by the unrelated disabled org.+ self.assertIsNone(+ _impersonation_ai_processing_block(+ request,+ access_level=OAuthApplicationAccessLevel.ORGANIZATION.value,+ scoped_organization_ids=[str(approved_org.id)],+ )+ )++ def test_blocks_when_scoped_team_belongs_to_disabled_org(self) -> None:+ disabled_org = Organization.objects.create(name="disabled", is_ai_data_processing_approved=False)+ team = Team.objects.create(organization=disabled_org, name="t")+ target = User.objects.create_user(email="[email protected]", password="x", first_name="C")+ OrganizationMembership.objects.create(user=target, organization=disabled_org)+ request = self._build_request(target, impersonating=True)++ response = _impersonation_ai_processing_block(+ request,+ access_level=OAuthApplicationAccessLevel.TEAM.value,+ scoped_team_ids=[team.id],+ )+ assert response is not None+ self.assertEqual(response.status_code, 403)