: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): restrict and revoke tokens minted during impersonation sessions (#59128)
Rafael Audibertc064dea30db0
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsxindex 8fbed1c2dfa4..7d5ff59b2a56 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx@@ -15,6 +15,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner'import { organizationLogic } from 'scenes/organizationLogic'import ScopeAccessSelector from 'scenes/settings/user/scopes/ScopeAccessSelector'+import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'import { AvailableFeature } from '~/types'import { SceneExport } from '../sceneTypes'@@ -152,6 +153,7 @@ export const OAuthAuthorize = (): JSX.Element => {setOauthAuthorizationValue,} = useActions(oauthAuthorizeLogic)+ const { isReadOnly: isImpersonationReadOnly, isImpersonated } = useValues(impersonationNoticeLogic)const { guardAvailableFeature } = useValues(upgradeModalLogic)const { currentOrganization, projectCreationForbiddenReason } = useValues(organizationLogic)@@ -254,6 +256,17 @@ export const OAuthAuthorize = (): JSX.Element => {</p></div>+ {isImpersonated && (+ <div className="flex items-center gap-2 p-3 mb-4 bg-danger-highlight border border-danger rounded text-sm">+ <IconWarning className="text-warning shrink-0" />+ <span>+ <strong>You are impersonating someone.</strong> Any OAuth tokens authorized in this session+ are short-lived and will be revoked when impersonation ends+ {isImpersonationReadOnly ? ', and write scopes will be downgraded to read-only' : ''}.+ </span>+ </div>+ )}+{!oauthApplication.is_verified && (<div className="flex items-center gap-2 p-3 mb-4 bg-warning-highlight border border-warning rounded text-sm"><IconWarning className="text-warning shrink-0" />diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 1597116fbea9..7959577efacb 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -43,9 +43,11 @@ from posthog.api.oauth.cimd import (get_or_create_cimd_application,is_cimd_client_id,)+from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session+from posthog.middleware import is_read_only_impersonationfrom posthog.models import OAuthAccessToken, OAuthApplication, Team, Userfrom posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken-from posthog.scopes import get_oauth_scopes_supported+from posthog.scopes import downgrade_scopes_to_read_only, get_oauth_scopes_supportedfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import render_templatefrom posthog.views import login_required@@ -64,6 +66,10 @@ CLIENT_IDS_WITHOUT_REFRESH_TOKEN: frozenset[str] = frozenset(})+# Sentinel for the per-request impersonator_id cache so None (no impersonator) is+# distinguishable from "not resolved yet".+_IMPERSONATOR_CACHE_UNSET: object = object()+def get_region_info() -> dict | None:"""Return region metadata if running on PostHog Cloud US/EU, else None."""@@ -74,6 +80,19 @@ def get_region_info() -> dict | None:return None+def _impersonator_id_for_request(request) -> int | None:+ """Return the staff user id that should tag any OAuth token minted on behalf of this request.++ Returns the original (staff) user's id when the Django session is an active impersonation+ session, otherwise None. Threaded through oauthlib via the `credentials` dict so the+ validator can stamp `impersonated_by` on the grant / access token / refresh token.+ """+ if not is_impersonated_session(request):+ return None+ original_user = get_original_user_from_session(request)+ return original_user.pk if original_user else None++class OAuthAuthorizationContext(TypedDict):user: User@@ -156,12 +175,17 @@ class OAuthValidator(OAuth2Validator):return Falsedef _should_skip_refresh_token(self, request) -> bool:- if not hasattr(request, "client") or not request.client:- return False+ # No refresh tokens for impersonation-minted tokens.+ if self._get_impersonator_id(request) is not None:+ return True+# CIMD clients expose their canonical id via cimd_metadata_url (the model's# client_id is an auto-generated UUID for those). Gate on is_cimd_client so# a stray cimd_metadata_url on a non-CIMD app can't flip the behavior.- if getattr(request.client, "is_cimd_client", False):+ client_key: str | None = None+ if not hasattr(request, "client") or not request.client:+ client_key = None+ elif getattr(request.client, "is_cimd_client", False):client_key = getattr(request.client, "cimd_metadata_url", None)else:client_key = getattr(request.client, "client_id", None)@@ -272,8 +296,11 @@ class OAuthValidator(OAuth2Validator):"""Returns access token expiry in seconds.Dynamically registered (DCR/CIMD) clients get extended TTL since they- don't reliably refresh.+ don't reliably refresh. Impersonation-minted tokens are capped to the+ impersonation idle timeout so they can't outlive the admin's session."""+ if self._get_impersonator_id(request) is not None:+ return settings.IMPERSONATION_IDLE_TIMEOUT_SECONDSif self._is_dynamic_client(request):return 60 * 60 * 24 * 7 # 7 daysreturn oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS@@ -286,6 +313,8 @@ class OAuthValidator(OAuth2Validator):"""expires_in = self._get_token_expires_in(request)token["expires_in"] = expires_in+ # Impersonation-minted tokens are short-lived and refresh-less so they can't+ # outlive the admin's impersonation session; clients re-auth instead.skip_refresh = self._should_skip_refresh_token(request)if skip_refresh:# Dropping the key short-circuits DOT's refresh-token branch so no@@ -330,6 +359,7 @@ class OAuthValidator(OAuth2Validator):source_refresh_token=source_refresh_token,scoped_teams=scoped_teams,scoped_organizations=scoped_organizations,+ impersonated_by_id=self._get_impersonator_id(request, refresh_token=source_refresh_token),)def _create_authorization_code(self, request, code, expires=None):@@ -352,6 +382,7 @@ class OAuthValidator(OAuth2Validator):claims=json.dumps(request.claims or {}),scoped_teams=scoped_teams,scoped_organizations=scoped_organizations,+ impersonated_by_id=self._get_impersonator_id(request),)def _create_refresh_token(self, request, refresh_token_code, access_token, previous_refresh_token):@@ -372,8 +403,52 @@ class OAuthValidator(OAuth2Validator):token_family=token_family,scoped_teams=scoped_teams,scoped_organizations=scoped_organizations,+ # access_token already has impersonated_by computed via _create_access_token above —+ # propagate it so the refresh token is revoked alongside its access token.+ impersonated_by_id=access_token.impersonated_by_id if access_token else None,)+ def _get_impersonator_id(self, request, refresh_token: OAuthRefreshToken | None = None):+ """Resolve the impersonator (staff user) that should be tagged on a newly-minted token.++ Priority:+ 1. `impersonated_by_id` attribute set on the oauthlib request — populated from the+ `credentials` dict during `/oauth/authorize` POST and GET auto-approval paths.+ 2. The previous refresh token (token rotation inherits the tag).+ 3. The authorization code grant referenced in the request body (code-exchange flow at+ `/oauth/token`, where there is no impersonated session to read from).++ Returns the staff user's id, or None if not impersonator-issued.+ """+ impersonator_id = getattr(request, "impersonated_by_id", None)+ if impersonator_id:+ return impersonator_id++ if refresh_token and refresh_token.impersonated_by_id:+ return refresh_token.impersonated_by_id++ # Code-exchange path: look up the grant via the `code` body param (same pattern+ # as `_get_scoped_teams_and_organizations`). `save_bearer_token` triggers up to+ # three calls per code exchange (`_get_token_expires_in`,+ # `_should_skip_refresh_token`, `_create_access_token`), so the grant lookup is+ # memoized on the oauthlib request.+ cached = getattr(request, "_posthog_impersonator_id", _IMPERSONATOR_CACHE_UNSET)+ if cached is not _IMPERSONATOR_CACHE_UNSET:+ return cached++ resolved: int | None = None+ if request.decoded_body:+ try:+ code = dict(request.decoded_body).get("code", None)+ if code:+ grant = OAuthGrant.objects.only("impersonated_by_id").get(code=code)+ resolved = grant.impersonated_by_id+ except OAuthGrant.DoesNotExist:+ pass++ request._posthog_impersonator_id = resolved+ return resolved+def _get_scoped_teams_and_organizations(self,request,@@ -500,6 +575,13 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):},)+ impersonator_id = _impersonator_id_for_request(request)+ credentials["impersonated_by_id"] = impersonator_id++ scope_str = " ".join(scopes)+ if is_read_only_impersonation(request):+ scope_str = downgrade_scopes_to_read_only(scope_str)+# First-party apps skip consent screen entirelyif application.is_first_party:try:@@ -514,7 +596,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):credentials["scoped_teams"] = list(team_ids)uri, headers, body, status_code = self.create_authorization_response(- request=request, scopes=" ".join(scopes), credentials=credentials, allow=True+ request=request, scopes=scope_str, credentials=credentials, allow=True)return self.redirect(uri, application)except OAuthToolkitError as error:@@ -527,10 +609,12 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):user=request.user, application=application, expires__gt=timezone.now()).all()+ # `scope_str` already reflects the read-only downgrade applied above (when+ # impersonating), so its split form is the effective set we need to match.for token in tokens:- if token.allow_scopes(scopes):+ if token.allow_scopes(scope_str.split()):uri, headers, body, status_code = self.create_authorization_response(- request=request, scopes=" ".join(scopes), credentials=credentials, allow=True+ request=request, scopes=scope_str, credentials=credentials, allow=True)return self.redirect(uri, application)except OAuthToolkitError as error:@@ -570,6 +654,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):"state": serializer.validated_data.get("state"),"scoped_organizations": serializer.validated_data.get("scoped_organizations"),"scoped_teams": serializer.validated_data.get("scoped_teams"),+ "impersonated_by_id": _impersonator_id_for_request(request),}# Add optional fields if present@@ -577,10 +662,14 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):if serializer.validated_data.get(field):credentials[field] = serializer.validated_data[field]+ scopes = serializer.validated_data.get("scope", "")+ if is_read_only_impersonation(request):+ scopes = downgrade_scopes_to_read_only(scopes)+try:uri, headers, body, status_code = self.create_authorization_response(request=request,- scopes=serializer.validated_data.get("scope", ""),+ scopes=scopes,credentials=credentials,allow=serializer.validated_data["allow"],)diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 9f496ff1b2c4..67029275116b 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -1185,6 +1185,13 @@ READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS: list[str | re.Pattern] = [# Logout is POST in Django 5; the frontend submits to `/logout` (no trailing slash),# while Django's URL config accepts both via opt_slash_path — match both forms.re.compile(r"^/logout/?$"),+ # OAuth consent submission and token exchange. Both run as POST during the OAuth flow.+ # Scopes minted while read-only impersonation is active are filtered through+ # `posthog.scopes.downgrade_scopes_to_read_only` in `OAuthAuthorizationView` so the+ # resulting tokens can't grant write access. Tokens minted here are also tagged with+ # the impersonator and revoked when impersonation ends.+ re.compile(r"^/oauth/authorize/?$"),+ re.compile(r"^/oauth/token/?$"),]diff --git a/posthog/migrations/1166_oauth_impersonated_by.py b/posthog/migrations/1166_oauth_impersonated_by.pynew file mode 100644index 000000000000..954efbe8513e--- /dev/null+++ b/posthog/migrations/1166_oauth_impersonated_by.py@@ -0,0 +1,45 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1165_user_hide_mcp_hints"),+ ]++ operations = [+ migrations.AddField(+ model_name="oauthaccesstoken",+ name="impersonated_by",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ migrations.AddField(+ model_name="oauthrefreshtoken",+ name="impersonated_by",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ migrations.AddField(+ model_name="oauthgrant",+ name="impersonated_by",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 21a7f5c20317..044f05361250 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1165_user_hide_mcp_hints+1166_oauth_impersonated_bydiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex ee9145d45682..807a8620b08d 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -3,12 +3,14 @@ from typing import TYPE_CHECKING, castfrom urllib.parse import urlparsefrom django.conf import settings+from django.contrib.auth.signals import user_logged_outfrom django.contrib.postgres.fields import ArrayFieldfrom django.core.exceptions import ValidationErrorfrom django.db import modelsfrom django.dispatch import receiverfrom django.utils import timezone+import structlogfrom oauth2_provider.models import (AbstractAccessToken,AbstractApplication,@@ -294,6 +296,17 @@ class OAuthAccessToken(AbstractAccessToken):scoped_teams: ArrayField = ArrayField(models.IntegerField(), null=True, blank=True)scoped_organizations: ArrayField = ArrayField(models.CharField(max_length=100), null=True, blank=True)+ # When set, this token was minted by a staff user impersonating `user`. Used to revoke+ # tokens at impersonation end. SET_NULL so the customer's tokens survive admin deactivation.+ impersonated_by: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ db_index=True,+ )+class OAuthIDToken(AbstractIDToken):class Meta(AbstractIDToken.Meta):@@ -329,6 +342,16 @@ class OAuthRefreshToken(AbstractRefreshToken):scoped_teams: ArrayField = ArrayField(models.IntegerField(), null=True, blank=True)scoped_organizations: ArrayField = ArrayField(models.CharField(max_length=100), null=True, blank=True)+ # See OAuthAccessToken.impersonated_by — propagated through token rotation.+ impersonated_by: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ db_index=True,+ )+class OAuthGrant(AbstractGrant):class Meta(AbstractGrant.Meta):@@ -355,6 +378,16 @@ class OAuthGrant(AbstractGrant):scoped_teams: ArrayField = ArrayField(models.IntegerField(), null=True, blank=True)scoped_organizations: ArrayField = ArrayField(models.CharField(max_length=100), null=True, blank=True)+ # See OAuthAccessToken.impersonated_by — propagated from grant to access token at code exchange.+ impersonated_by: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ db_index=True,+ )+def find_oauth_access_token(token: str) -> OAuthAccessToken | None:"""Find an OAuth access token by its value using the token_checksum index."""@@ -494,6 +527,52 @@ class CIMDBlocklistEntry(models.Model):verbose_name_plural = "CIMD Blocklist Entries"+logger = structlog.get_logger(__name__)+++@receiver(user_logged_out)+def _revoke_impersonation_oauth_tokens(sender, request, user, **kwargs):+ """Revoke OAuth tokens minted during an impersonation session when it ends.++ Fires on every logout, but only acts on impersonation logouts — when the loginas+ session flag is still set and we can recover the original (staff) user. Tokens+ are matched by `(user=<impersonated>, impersonated_by=<staff>)`, so only tokens+ this admin minted during this kind of impersonation are revoked; the customer's+ own pre-existing tokens (impersonated_by IS NULL) are untouched.++ Lives in the model module so the receiver is registered as soon as Django+ imports `OAuthAccessToken` — no explicit `apps.py` wiring required.+ """+ if request is None or user is None:+ return++ from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session++ if not is_impersonated_session(request):+ return++ impersonator = get_original_user_from_session(request)+ if impersonator is None:+ return++ now = timezone.now()+ access_deleted, _ = OAuthAccessToken.objects.filter(user=user, impersonated_by=impersonator).delete()+ refresh_revoked = OAuthRefreshToken.objects.filter(+ user=user, impersonated_by=impersonator, revoked__isnull=True+ ).update(revoked=now)+ grants_deleted, _ = OAuthGrant.objects.filter(user=user, impersonated_by=impersonator).delete()++ if access_deleted or refresh_revoked or grants_deleted:+ logger.info(+ "impersonation_oauth_tokens_revoked",+ impersonated_user_id=user.pk,+ impersonator_user_id=impersonator.pk,+ access_tokens_deleted=access_deleted,+ refresh_tokens_revoked=refresh_revoked,+ grants_deleted=grants_deleted,+ )++@receiver(models.signals.post_delete, sender=OAuthApplication)def _block_cimd_url_on_application_delete(sender, instance: OAuthApplication, **kwargs):# Auto-blocklist a CIMD URL when its app is deleted, so a metadata refreshdiff --git a/posthog/scopes.py b/posthog/scopes.pyindex 151f9036bbe1..524a10b147ed 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -139,6 +139,41 @@ def get_scope_descriptions() -> dict[str, str]:}+def downgrade_scopes_to_read_only(scope_str: str) -> str:+ """Strip write access from a space-separated OAuth scope string.++ - `<object>:write` becomes `<object>:read`.+ - `*` is the full-access wildcard (see `posthog/permissions.py` — `if "*" in key_scopes`+ short-circuits the scope check, granting read+write). Pass-through would defeat the+ downgrade, so `*` is expanded to every public `*:read` scope.+ - Existing `<object>:read` scopes and OIDC scopes (`openid`, `profile`, `email`) pass through.++ Returns a deduped, space-separated string preserving first-seen order.+ """+ if not scope_str:+ return scope_str+ all_public_read_scopes = [+ f"{obj}:read"+ for obj in API_SCOPE_OBJECTS+ if obj not in INTERNAL_API_SCOPE_OBJECTS and obj not in OAUTH_HIDDEN_SCOPE_OBJECTS+ ]+ expanded: list[str] = []+ for raw in scope_str.split():+ if raw == "*":+ expanded.extend(all_public_read_scopes)+ elif raw.endswith(":write"):+ expanded.append(raw[: -len(":write")] + ":read")+ else:+ expanded.append(raw)+ seen: set[str] = set()+ deduped: list[str] = []+ for s in expanded:+ if s not in seen:+ seen.add(s)+ deduped.append(s)+ return " ".join(deduped)++# OIDC scopes published in OAuth server metadata alongside the resource scopes.# These match what django-oauth-toolkit's OIDC layer accepts at the /authorize# endpoint. Duplicating the list as plain tuple (rather than importing fromdiff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.pynew file mode 100644index 000000000000..f6fd16f23a9f--- /dev/null+++ b/posthog/test/test_oauth_impersonation.py@@ -0,0 +1,208 @@+import base64+import hashlib+from datetime import timedelta+from urllib.parse import urlencode++from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import patch++from django.conf import settings+from django.contrib.auth import logout+from django.contrib.sessions.backends.db import SessionStore+from django.core.signing import TimestampSigner+from django.test import RequestFactory+from django.utils import timezone++from loginas import settings as la_settings+from parameterized import parameterized++from posthog.api.oauth.views import _impersonator_id_for_request+from posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEY+from posthog.models import OAuthApplication, User+from posthog.models.oauth import OAuthAccessToken, OAuthGrant, OAuthRefreshToken+++class TestImpersonationOAuthRevocation(BaseTest):+ def test_user_logged_out_revokes_only_impersonated_tokens(self) -> None:+ admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")+ admin.is_staff = True+ admin.save()+ target = User.objects.create_user(email="[email protected]", password="x", first_name="C")++ app = OAuthApplication.objects.create(+ client_id="test-client-id",+ redirect_uris="http://localhost/cb",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ organization=self.organization,+ )++ impersonated_access = OAuthAccessToken.objects.create(+ user=target,+ application=app,+ token="imp-access",+ scope="feature_flag:read",+ expires="2099-01-01T00:00:00Z",+ scoped_teams=[],+ scoped_organizations=[],+ impersonated_by=admin,+ )+ impersonated_refresh = OAuthRefreshToken.objects.create(+ user=target,+ application=app,+ token="imp-refresh",+ access_token=impersonated_access,+ scoped_teams=[],+ scoped_organizations=[],+ impersonated_by=admin,+ )+ impersonated_grant = OAuthGrant.objects.create(+ user=target,+ application=app,+ code="imp-code",+ expires="2099-01-01T00:00:00Z",+ redirect_uri="http://localhost/cb",+ scope="feature_flag:read",+ code_challenge="x" * 43,+ code_challenge_method="S256",+ scoped_teams=[],+ scoped_organizations=[],+ impersonated_by=admin,+ )++ customer_owned = OAuthAccessToken.objects.create(+ user=target,+ application=app,+ token="customer-access",+ scope="feature_flag:write",+ expires="2099-01-01T00:00:00Z",+ scoped_teams=[],+ scoped_organizations=[],+ impersonated_by=None,+ )++ request = RequestFactory().get("/")+ request.session = SessionStore()+ request.session[la_settings.USER_SESSION_FLAG] = TimestampSigner().sign(str(admin.pk))+ request.user = target++ with patch("posthog.helpers.impersonation.is_impersonated_session", return_value=True):+ logout(request)++ self.assertFalse(OAuthAccessToken.objects.filter(pk=impersonated_access.pk).exists())+ revived_refresh = OAuthRefreshToken.objects.get(pk=impersonated_refresh.pk)+ self.assertIsNotNone(revived_refresh.revoked)+ self.assertFalse(OAuthGrant.objects.filter(pk=impersonated_grant.pk).exists())++ self.assertTrue(OAuthAccessToken.objects.filter(pk=customer_owned.pk).exists())+++class TestImpersonationOAuthTokenIssuance(APIBaseTest):+ """Code-exchange flow: tokens minted from an impersonation-tagged grant must be+ short-lived and refresh-less, so they expire at the impersonation idle timeout+ even when the staff user never explicitly logs out. The 30min cap + refresh+ suppression key off the grant's `impersonated_by_id` alone, which is set during+ `/oauth/authorize` for both read-only and read-write impersonation — so this+ test implicitly covers both modes."""++ def test_code_exchange_caps_expiry_and_suppresses_refresh_for_impersonation_grants(self) -> None:+ admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")+ admin.is_staff = True+ admin.save()++ app = OAuthApplication.objects.create(+ name="App",+ client_id="impersonation-test-client",+ client_secret="impersonation-test-secret",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ user=self.user,+ hash_client_secret=True,+ algorithm="RS256",+ )++ # PKCE bits — `S256` over a fixed verifier. The validator only checks the+ # challenge round-trips; the exact values don't matter.+ verifier = "impersonation-test-verifier"+ challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("utf-8")).digest()).decode("utf-8").replace("=", "")+ )++ grant = OAuthGrant.objects.create(+ application=app,+ user=self.user,+ code="impersonation-grant-code",+ code_challenge=challenge,+ code_challenge_method="S256",+ expires=timezone.now() + timedelta(minutes=10),+ redirect_uri="https://example.com/callback",+ scope="feature_flag:read",+ scoped_organizations=[str(self.organization.id)],+ scoped_teams=[],+ impersonated_by=admin,+ )++ response = self.client.post(+ "/oauth/token/",+ data=urlencode(+ {+ "grant_type": "authorization_code",+ "client_id": app.client_id,+ "client_secret": "impersonation-test-secret",+ "redirect_uri": "https://example.com/callback",+ "code_verifier": verifier,+ "code": grant.code,+ }+ ),+ content_type="application/x-www-form-urlencoded",+ )++ self.assertEqual(response.status_code, 200, response.content)+ body = response.json()++ self.assertIn("access_token", body)+ self.assertNotIn("refresh_token", body)+ self.assertEqual(body["expires_in"], settings.IMPERSONATION_IDLE_TIMEOUT_SECONDS)++ access_token = OAuthAccessToken.objects.get(token=body["access_token"])+ self.assertEqual(access_token.impersonated_by_id, admin.pk)+ self.assertFalse(OAuthRefreshToken.objects.filter(application=app, user=self.user).exists())+++class TestImpersonatorIdResolution(BaseTest):+ """The 30min cap, refresh suppression, and revocation-on-logout protections key off+ the impersonator stamp set by `_impersonator_id_for_request` during `/oauth/authorize`.+ That stamp must be set for *any* impersonation session — read-only or read-write —+ so write-mode impersonation gets the same gating as read-only (only the scope+ downgrade is read-only-specific)."""++ @parameterized.expand(+ [+ ("read_only", True),+ ("read_write", False),+ ]+ )+ def test_impersonator_id_set_for_both_impersonation_modes(self, _name: str, read_only: bool) -> None:+ admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")+ admin.is_staff = True+ admin.save()+ target = User.objects.create_user(email="[email protected]", password="x", first_name="C")++ request = RequestFactory().get("/")+ request.session = SessionStore()+ request.session[la_settings.USER_SESSION_FLAG] = TimestampSigner().sign(str(admin.pk))+ if read_only:+ request.session[IMPERSONATION_READ_ONLY_SESSION_KEY] = True+ request.user = target++ self.assertEqual(_impersonator_id_for_request(request), admin.pk)++ def test_impersonator_id_none_when_not_impersonating(self) -> None:+ target = User.objects.create_user(email="[email protected]", password="x", first_name="C")+ request = RequestFactory().get("/")+ request.session = SessionStore()+ request.user = target++ self.assertIsNone(_impersonator_id_for_request(request))diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pynew file mode 100644index 000000000000..e7ab5ffcaf1a--- /dev/null+++ b/posthog/test/test_scopes.py@@ -0,0 +1,60 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.scopes import (+ API_SCOPE_OBJECTS,+ INTERNAL_API_SCOPE_OBJECTS,+ OAUTH_HIDDEN_SCOPE_OBJECTS,+ downgrade_scopes_to_read_only,+)+++class TestDowngradeScopesToReadOnly(BaseTest):+ @parameterized.expand(+ [+ ("empty_string", "", ""),+ ("single_read_passthrough", "feature_flag:read", "feature_flag:read"),+ ("single_write_downgraded", "feature_flag:write", "feature_flag:read"),+ ("oidc_passthrough", "openid profile email", "openid profile email"),+ (+ "mixed_read_write_dedupe",+ "feature_flag:read feature_flag:write organization:write",+ "feature_flag:read organization:read",+ ),+ (+ "order_preserved_first_seen",+ "organization:write feature_flag:write",+ "organization:read feature_flag:read",+ ),+ ]+ )+ def test_basic_cases(self, _name: str, given: str, expected: str) -> None:+ self.assertEqual(downgrade_scopes_to_read_only(given), expected)++ def test_wildcard_expands_to_all_public_read_scopes(self) -> None:+ result = downgrade_scopes_to_read_only("*").split()+ expected = [+ f"{obj}:read"+ for obj in API_SCOPE_OBJECTS+ if obj not in INTERNAL_API_SCOPE_OBJECTS and obj not in OAUTH_HIDDEN_SCOPE_OBJECTS+ ]+ self.assertEqual(result, expected)+ # Sanity: no write scope, no internal scope, no hidden scope leaked through.+ for scope in result:+ self.assertFalse(scope.endswith(":write"), f"{scope} should have been read-only")+ for internal in INTERNAL_API_SCOPE_OBJECTS:+ self.assertNotIn(f"{internal}:read", result)+ for hidden in OAUTH_HIDDEN_SCOPE_OBJECTS:+ self.assertNotIn(f"{hidden}:read", result)++ def test_wildcard_combined_with_other_scopes_dedupes(self) -> None:+ # `*` already covers feature_flag:read — passing both must not duplicate the entry.+ result = downgrade_scopes_to_read_only("feature_flag:write * openid").split()+ self.assertEqual(result.count("feature_flag:read"), 1)+ self.assertIn("openid", result)++ def test_wildcard_only_token(self) -> None:+ # Bare `*` alone is the OAuth full-access shorthand and must NOT pass through.+ self.assertNotIn(":write", downgrade_scopes_to_read_only("*"))+ self.assertNotEqual(downgrade_scopes_to_read_only("*"), "*")