: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): server-side scope assignment + /authorize enforcement (#60477)
Matt Brooker9e4a7eb522cf
diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex 89bf170e4e59..9f7b24c7f798 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -136,7 +136,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne(None, {"fields": ("id", "name", "client_id", "client_type", "auth_brand", "logo_uri")}),("Authorization",- {"fields": ("authorization_grant_type", "redirect_uris", "algorithm")},+ {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes")},),("Ownership", {"fields": ("user", "organization")}),("Status", {"fields": ("is_verified", "is_first_party", "is_dcr_client", "is_cimd_client")}),@@ -160,7 +160,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne(None, {"fields": ("name", "client_id", "client_secret", "client_type", "auth_brand", "logo_uri")}),("Authorization",- {"fields": ("authorization_grant_type", "redirect_uris", "algorithm")},+ {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes")},),("Ownership", {"fields": ("user", "organization")}),("Status", {"fields": ("is_verified", "is_first_party")}),diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex b98f3c7366d7..d1ca97a89fb7 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -1135,6 +1135,93 @@ class TestOAuthAPI(APIBaseTest):refresh_token = refresh_response.json()["refresh_token"]+ def _create_refreshable_token_pair(self, scope: str) -> OAuthRefreshToken:+ suffix = scope.replace(" ", "_").replace("*", "star").replace(":", "_")+ access_token = OAuthAccessToken.objects.create(+ application=self.confidential_application,+ user=self.user,+ token=f"at_{suffix}",+ expires=timezone.now() + timedelta(hours=1),+ scope=scope,+ scoped_teams=[self.team.id],+ scoped_organizations=None,+ )+ return OAuthRefreshToken.objects.create(+ application=self.confidential_application,+ user=self.user,+ token=f"rt_{suffix}",+ access_token=access_token,+ scoped_teams=[self.team.id],+ scoped_organizations=None,+ )++ def _refresh_and_get_scopes(self, refresh_token: OAuthRefreshToken) -> set[str]:+ response = self.post(+ "/oauth/token/",+ {+ "grant_type": "refresh_token",+ "refresh_token": refresh_token.token,+ "client_id": self.confidential_application.client_id,+ "client_secret": "test_confidential_client_secret",+ },+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ new_access_token = OAuthAccessToken.objects.get(token=response.json()["access_token"])+ return set((new_access_token.scope or "").split())++ @parameterized.expand(+ [+ (+ "narrow_to_tightened_ceiling",+ ["experiment:read"],+ "openid experiment:read insight:read",+ {"openid", "experiment:read"},+ ),+ (+ "preserve_in_ceiling",+ ["experiment:read", "insight:read"],+ "experiment:read insight:read",+ {"experiment:read", "insight:read"},+ ),+ ("empty_ceiling_is_noop", [], "experiment:read insight:read", {"experiment:read", "insight:read"}),+ ]+ )+ def test_refresh_caps_scopes_at_app_ceiling(self, _name, ceiling, token_scope, expected):+ self.confidential_application.scopes = ceiling+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair(token_scope)++ self.assertEqual(self._refresh_and_get_scopes(refresh_token), expected)++ def test_refresh_rejected_when_token_scopes_outside_ceiling(self):+ self.confidential_application.scopes = ["experiment:read"]+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair("insight:read")++ response = self.post(+ "/oauth/token/",+ {+ "grant_type": "refresh_token",+ "refresh_token": refresh_token.token,+ "client_id": self.confidential_application.client_id,+ "client_secret": "test_confidential_client_secret",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "invalid_grant")++ def test_refresh_leaves_wildcard_token_untouched(self):+ self.confidential_application.scopes = ["experiment:read"]+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair("*")++ # Wildcard narrowing is deferred to #60342; the token must keep working.+ self.assertIn("*", self._refresh_and_get_scopes(refresh_token))+def test_refresh_with_injected_code_does_not_escalate_scopes(self):"""A refresh request that includes a `code` parameter from a broader-scopegrant must NOT override the scopes inherited from the refresh token."""@@ -2180,6 +2267,71 @@ class TestOAuthAPI(APIBaseTest):assert locationself.assertIn("error=invalid_scope", location)+ # --- Per-application scope ceiling (OAuthApplication.scopes) ---++ def _set_ceiling(self, *scopes: str) -> None:+ self.confidential_application.scopes = list(scopes)+ self.confidential_application.save()++ def _authorize_post(self, scope: str):+ body = {**self.base_authorization_post_body, "scope": scope}+ return self.client.post("/oauth/authorize/", body)++ def test_authorize_rejects_scope_outside_app_ceiling(self):+ # GET rejects with a redirect carrying error=invalid_scope; the+ # validator short-circuits before any template render.+ self._set_ceiling("experiment:read")+ response = self.client.get(f"{self.base_authorization_url}&scope=experiment:write")+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ location = response.get("Location")+ assert location+ self.assertIn("error=invalid_scope", location)++ def test_authorize_accepts_scope_within_app_ceiling(self):+ self._set_ceiling("experiment:read", "dashboard:read")+ response = self._authorize_post("experiment:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ redirect_to = response.json()["redirect_to"]+ self.assertNotIn("error=invalid_scope", redirect_to)+ self.assertIn("code=", redirect_to)++ def test_authorize_empty_ceiling_falls_back_to_unprivileged(self):+ # confidential_application.scopes defaults to [] -> broad default+ # (UNPRIVILEGED_SCOPES), so experiment:read passes.+ response = self._authorize_post("experiment:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ redirect_to = response.json()["redirect_to"]+ self.assertNotIn("error=invalid_scope", redirect_to)+ self.assertIn("code=", redirect_to)++ def test_authorize_oidc_and_introspection_bypass_app_ceiling(self):+ # OIDC + introspection are identity / token-management scopes, not+ # resource permissions; they pass regardless of the per-app ceiling.+ self._set_ceiling("experiment:read")+ response = self._authorize_post("openid profile email introspection experiment:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ redirect_to = response.json()["redirect_to"]+ self.assertNotIn("error=invalid_scope", redirect_to)+ self.assertIn("code=", redirect_to)++ def test_authorize_wildcard_rejected_when_app_ceiling_set(self):+ self._set_ceiling("experiment:read")+ response = self.client.get(f"{self.base_authorization_url}&scope=*")+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ location = response.get("Location")+ assert location+ self.assertIn("error=invalid_scope", location)++ def test_authorize_wildcard_accepted_when_app_ceiling_empty(self):+ # Existing clients (the PostHog Code CLI today) still send scope=*+ # against apps that have no explicit ceiling. Until wildcard retirement+ # (#60342) lands, those broad-default apps keep accepting it.+ response = self._authorize_post("*")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ redirect_to = response.json()["redirect_to"]+ self.assertNotIn("error=invalid_scope", redirect_to)+ self.assertIn("code=", redirect_to)+@freeze_time("2025-01-01 00:00:00")def test_token_endpoint_with_json_payload(self):grant = OAuthGrant.objects.create(diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex fa20a8890ef4..984099b769e8 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -30,6 +30,7 @@ from oauth2_provider.views import (UserInfoView,)from oauth2_provider.views.mixins import OAuthLibMixin+from oauthlib.oauth2 import InvalidGrantErrorfrom rest_framework import serializers, statusfrom rest_framework.authentication import SessionAuthenticationfrom rest_framework.permissions import IsAuthenticated@@ -48,7 +49,7 @@ from posthog.helpers.impersonation import get_original_user_from_session, is_impfrom posthog.middleware import is_read_only_impersonationfrom posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, Userfrom posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken-from posthog.scopes import downgrade_scopes_to_read_only, get_oauth_scopes_supported+from posthog.scopes import OIDC_SCOPES, UNPRIVILEGED_SCOPES, downgrade_scopes_to_read_only, get_oauth_scopes_supportedfrom posthog.security.url_validation import has_authority_bypass_charsfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import render_template@@ -358,6 +359,93 @@ class OAuthValidator(OAuth2Validator):return False+ # OIDC + introspection are accepted independently of the per-app ceiling.+ # They are identity / token-management scopes, not resource permissions.+ _ALWAYS_ALLOWED_SCOPES: frozenset[str] = frozenset(OIDC_SCOPES) | {"introspection"}++ def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):+ """Enforce the per-application scope ceiling from `OAuthApplication.scopes`.++ Resolution:+ - empty / omitted `scope=` -> grant the effective ceiling (mutate+ `request.scopes` so oauthlib's default-resolution doesn't fall back+ to just ["openid"] from DEFAULT_SCOPES).+ - any subset of `effective_scopes` plus the always-allowed (OIDC,+ introspection) -> grant as requested.+ - any value outside that union (including `*` when the app has an+ explicit ceiling) -> reject. oauthlib turns the False return into+ `InvalidScopeError` / RFC 6749 `error=invalid_scope`.++ Empty `application.scopes` resolves to UNPRIVILEGED_SCOPES (the broad+ default), and `*` is accepted in that mode so existing clients (the+ PostHog Code CLI today) keep working until wildcard retirement.+ """+ app_scopes = getattr(client, "scopes", None) or []+ has_ceiling = bool(app_scopes)+ effective = frozenset(app_scopes) if has_ceiling else UNPRIVILEGED_SCOPES++ requested = set(scopes or [])+ if not requested:+ request.scopes = sorted(effective | self._ALWAYS_ALLOWED_SCOPES)+ return True++ to_check = requested - self._ALWAYS_ALLOWED_SCOPES+ if not to_check:+ return True++ if has_ceiling:+ return "*" not in to_check and to_check.issubset(effective)+ return to_check.issubset(UNPRIVILEGED_SCOPES | {"*"})++ def get_original_scopes(self, refresh_token, request, *args, **kwargs):+ """Cap refreshed scopes at the application's current ceiling.++ DOT's refresh grant copies the prior access token's scopes verbatim and never+ re-runs `validate_scopes`, so a token minted before a ceiling was tightened would+ keep refreshing into the old, broader set. Intersecting with `application.scopes`+ means a narrowed app drops the removed scopes on the next refresh.++ Always-allowed scopes (OIDC, introspection) pass through, mirroring+ `validate_scopes`. Resolution when the app has a ceiling:+ - a `*` token is left untouched: narrowing it would strip all resource access+ on refresh, and `*` is still issued to legacy clients. Its retirement is+ handled separately in #60330 (coupled to #60342).+ - a token whose scopes have no overlap with the ceiling can't be narrowed+ without emptying it, so we reject the refresh (`invalid_grant`) — the client+ re-authorizes and gets a token within the current ceiling, rather than+ silently keeping out-of-ceiling access.++ An empty `application.scopes` (no ceiling) is a no-op.+ """+ original = super().get_original_scopes(refresh_token, request, *args, **kwargs)+ # DOT's base returns the stored scope as a space-delimited string; oauthlib+ # `scope_to_list`s whatever we return, so a list back is fine.+ original_list = original.split() if isinstance(original, str) else list(original)+ # `request.client` is not always populated when oauthlib calls this during the+ # refresh grant, so fall back to resolving the application from the token row.+ application = getattr(request, "client", None)+ if application is None:+ rt = OAuthRefreshToken.objects.filter(token=refresh_token).select_related("application").first()+ application = rt.application if rt else None++ app_scopes = set(getattr(application, "scopes", None) or [])+ if not app_scopes:+ return original_list++ original_set = set(original_list)+ if "*" in original_set:+ return original_list++ narrowed = (original_set & app_scopes) | (original_set & self._ALWAYS_ALLOWED_SCOPES)+ if not narrowed:+ # Raised inside oauthlib's validate_token_request, which create_token_response+ # wraps and turns into an RFC 6749 `invalid_grant` 400 — not a 500.+ raise InvalidGrantError(+ description="Token scopes are no longer within the application's allowed scopes; re-authorize.",+ request=request,+ )+ return sorted(narrowed)+def rotate_refresh_token(self, request) -> bool:"""Don't rotate refresh tokens for dynamically registered (DCR/CIMD) clients.diff --git a/posthog/migrations/1193_oauthaccesstoken_label_oauthapplication_scopes.py b/posthog/migrations/1193_oauthaccesstoken_label_oauthapplication_scopes.pynew file mode 100644index 000000000000..6f7b2fb3aae8--- /dev/null+++ b/posthog/migrations/1193_oauthaccesstoken_label_oauthapplication_scopes.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.14 on 2026-05-28 18:46++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1192_id_jag_organization_domain_fields")]++ operations = [+ migrations.AddField(+ model_name="oauthaccesstoken",+ name="label",+ field=models.CharField(+ blank=True,+ db_default="",+ default="",+ help_text="Optional user-facing label so a user can identify a token (per-device, per-IP, or by purpose).",+ max_length=40,+ ),+ ),+ migrations.AddField(+ model_name="oauthapplication",+ name="scopes",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=100),+ blank=True,+ db_default=[],+ default=list,+ help_text="Scope ceiling — strings tokens issued for this app may carry. Empty list means no per-app cap.",+ size=None,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 2d525e19cf70..91f3a6288c33 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1192_id_jag_organization_domain_fields+1193_oauthaccesstoken_label_oauthapplication_scopesdiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 807a8620b08d..bd9baa279d04 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -96,6 +96,19 @@ class OAuthApplication(AbstractApplication):help_text="Branding to use on authentication pages",)+ # Server-stored scope ceiling for tokens issued for this app.+ # CharField max_length matches PersonalAPIKey.scopes (`max_length=100`)+ # so the same `obj:action` strings fit identically across both+ # PAT and OAuth surfaces.+ scopes: ArrayField = ArrayField(+ models.CharField(max_length=100),+ default=list,+ db_default=[],+ blank=True,+ null=False,+ help_text=("Scope ceiling — strings tokens issued for this app may carry. Empty list means no per-app cap."),+ )+# CIMD (Client ID Metadata Document) fields — draft-ietf-oauth-client-id-metadata-document-00is_cimd_client: models.BooleanField = models.BooleanField(default=False,@@ -307,6 +320,16 @@ class OAuthAccessToken(AbstractAccessToken):db_index=True,)+ # Optional user-facing label set at mint time. Carried across refreshes so+ # it persists for the life of the connection, not just one rotated token.+ label: models.CharField = models.CharField(+ max_length=40,+ blank=True,+ default="",+ db_default="",+ help_text="Optional user-facing label so a user can identify a token (per-device, per-IP, or by purpose).",+ )+class OAuthIDToken(AbstractIDToken):class Meta(AbstractIDToken.Meta):diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.pyindex 1bcfc3db7300..44a016f592cb 100644--- a/posthog/models/test/test_oauth.py+++ b/posthog/models/test/test_oauth.py@@ -48,6 +48,58 @@ class TestOAuthModels(TestCase):self.assertEqual(app.client_id, "test_client_id")self.assertEqual(app.algorithm, "RS256")+ def _make_app(self, name: str, client_id: str, **overrides) -> OAuthApplication:+ return OAuthApplication.objects.create(+ name=name,+ client_id=client_id,+ client_secret=f"{client_id}_secret",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ algorithm="RS256",+ **overrides,+ )++ def test_oauth_application_scopes_defaults_to_empty_list(self):+ app = self._make_app("Scopes Default", "scopes_default_client")+ self.assertEqual(app.scopes, [])+ app.refresh_from_db()+ self.assertEqual(app.scopes, [])++ def test_oauth_application_scopes_persists_explicit_list(self):+ app = self._make_app(+ "Scopes Explicit",+ "scopes_explicit_client",+ scopes=["insight:read", "llm_gateway:read"],+ )+ app.refresh_from_db()+ self.assertEqual(app.scopes, ["insight:read", "llm_gateway:read"])++ def test_oauth_access_token_label_defaults_to_empty_string(self):+ app = self._make_app("Token Label Default", "token_label_default_client")+ token = OAuthAccessToken.objects.create(+ application=app,+ user=self.user,+ token="default_label_token",+ expires=timezone.now() + timedelta(minutes=5),+ )+ self.assertEqual(token.label, "")+ token.refresh_from_db()+ self.assertEqual(token.label, "")++ def test_oauth_access_token_label_persists_explicit_value(self):+ app = self._make_app("Token Label Explicit", "token_label_explicit_client")+ token = OAuthAccessToken.objects.create(+ application=app,+ user=self.user,+ token="labeled_token",+ expires=timezone.now() + timedelta(minutes=5),+ label="laptop-2026",+ )+ token.refresh_from_db()+ self.assertEqual(token.label, "laptop-2026")+@freeze_time("2024-01-01 00:00:00")def test_create_oauth_application_with_skip_authorization_fails(self):# Test that creating an application with skip_authorization=True raises an errordiff --git a/posthog/scopes.py b/posthog/scopes.pyindex b8c411cbc0fc..db684f0a3692 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -144,6 +144,48 @@ OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"metrics", "wPROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [("endpoint", "read")]+# Server-side scope assignment string-set constants (see RFC: server-side scope+# assignment for OAuthApplications).+#+# Naming convention in this module: `*_SCOPE_OBJECTS` (frozenset[APIScopeObject])+# and `*_SCOPE_ACTIONS` hold scope-OBJECT sets; bare `*_SCOPES` (frozenset[str])+# hold scope-STRING (`obj:action`) sets. The object sets above+# (INTERNAL_API_SCOPE_OBJECTS, OAUTH_HIDDEN_SCOPE_OBJECTS) remain canonical for+# object-level checks; the string sets below are the surface used by+# `OAuthApplication.scopes` and `UNPRIVILEGED_SCOPES` set arithmetic.++# Every public `obj:action` scope string. Matches `get_scope_descriptions()`+# keys; excludes INTERNAL scopes (programmatic-only, never user-facing).+ALL_SCOPES: frozenset[str] = frozenset(+ f"{obj}:{action}"+ for obj in API_SCOPE_OBJECTS+ if obj not in INTERNAL_API_SCOPE_OBJECTS+ for action in API_SCOPE_ACTIONS+)++# Privileged scopes only land on `OAuthApplication.scopes` via an admin-driven+# path (Django admin, the Stripe HMAC seed list, first-party data migrations).+# Filtered out of partner-facing self-serve registration (CIMD, DCR per+# RFC 7591), so a partner cannot programmatically grant themselves+# `llm_gateway:read`.+PRIVILEGED_SCOPES: frozenset[str] = frozenset({"llm_gateway:read", "llm_gateway:write"})++# String form of `OAUTH_HIDDEN_SCOPE_OBJECTS`. PAT-grantable but never+# advertised via OAuth metadata; excluded from `UNPRIVILEGED_SCOPES` so an+# alpha scope never reaches the broad default. Intersected with `ALL_SCOPES`+# so a future hidden object whose action set narrows doesn't carry a phantom+# string into the set.+OAUTH_HIDDEN_SCOPES: frozenset[str] = (+ frozenset(f"{obj}:{action}" for obj in OAUTH_HIDDEN_SCOPE_OBJECTS for action in API_SCOPE_ACTIONS) & ALL_SCOPES+)++# Everything safe to grant a generic OAuth client. The broad default for an+# `OAuthApplication` with empty `scopes`: empty resolves to this set at+# `/authorize` time. OIDC scopes (openid/profile/email) are NOT in this set —+# they live in `OIDC_SCOPES` below and are accepted at `/authorize`+# independently of `application.scopes`.+UNPRIVILEGED_SCOPES: frozenset[str] = ALL_SCOPES - PRIVILEGED_SCOPES - OAUTH_HIDDEN_SCOPES+def get_scope_descriptions() -> dict[str, str]:return {@@ -205,10 +247,13 @@ def get_oauth_scopes_supported() -> list[str]:(the latter generated at build time via `bin/build-mcp-oauth-scopes.py` sothe protected resource cannot drift out of subset of the AS).- Strict-excludes both `INTERNAL_API_SCOPE_OBJECTS` (server-mint-only scopes- like `signal_scout_internal` — never advertised, never user-grantable) and- `OAUTH_HIDDEN_SCOPE_OBJECTS` (PAK-only alpha scopes). PAT validation uses- `get_scope_descriptions()` directly and is unaffected.+ Built from `UNPRIVILEGED_SCOPES`, so it excludes all three non-advertised+ classes: `INTERNAL_API_SCOPE_OBJECTS` (server-mint-only, e.g.+ `signal_scout_internal` — never user-grantable), `OAUTH_HIDDEN_SCOPES`+ (alpha / PAT-only), and `PRIVILEGED_SCOPES` (`llm_gateway:*`, admin-granted+ only). Discovery metadata shouldn't advertise scopes an OAuth client can't+ obtain self-serve. PAT validation uses `get_scope_descriptions()` directly+ and is unaffected.The Signals scout harness sandbox token carries `signal_scout_internal:write`,but it is minted by directly inserting an `OAuthAccessToken` row (see@@ -218,10 +263,8 @@ def get_oauth_scopes_supported() -> list[str]:via user consent — a durable prompt-injection vector (scratchpad rows are readverbatim into every subsequent run's prompt)."""- visible = (- f"{obj}:{action}"- for obj in API_SCOPE_OBJECTS- if obj not in INTERNAL_API_SCOPE_OBJECTS and obj not in OAUTH_HIDDEN_SCOPE_OBJECTS- for action in API_SCOPE_ACTIONS- )- return list(OIDC_SCOPES) + list(visible)+ visible = UNPRIVILEGED_SCOPES+ ordered = [+ f"{obj}:{action}" for obj in API_SCOPE_OBJECTS for action in API_SCOPE_ACTIONS if f"{obj}:{action}" in visible+ ]+ return list(OIDC_SCOPES) + ordereddiff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex a980514e1e14..34da4a68b633 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -1,3 +1,6 @@+import runpy+from pathlib import Path+from posthog.test.base import BaseTestfrom django.test import SimpleTestCase@@ -5,9 +8,15 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthog.scopes import (+ ALL_SCOPES,+ API_SCOPE_ACTIONS,API_SCOPE_OBJECTS,INTERNAL_API_SCOPE_OBJECTS,OAUTH_HIDDEN_SCOPE_OBJECTS,+ OAUTH_HIDDEN_SCOPES,+ OIDC_SCOPES,+ PRIVILEGED_SCOPES,+ UNPRIVILEGED_SCOPES,downgrade_scopes_to_read_only,get_oauth_scopes_supported,get_scope_descriptions,@@ -64,6 +73,97 @@ class TestDowngradeScopesToReadOnly(BaseTest):self.assertNotEqual(downgrade_scopes_to_read_only("*"), "*")+class TestScopeSets(BaseTest):+ def test_all_scopes_matches_scope_descriptions_keys(self) -> None:+ self.assertEqual(ALL_SCOPES, frozenset(get_scope_descriptions().keys()))++ @parameterized.expand(+ [+ ("insight:read",),+ ("insight:write",),+ ("llm_gateway:read",),+ ("llm_gateway:write",),+ ]+ )+ def test_all_scopes_contains_known_string(self, scope: str) -> None:+ self.assertIn(scope, ALL_SCOPES)++ @parameterized.expand([(f"{obj}:{action}",) for obj in INTERNAL_API_SCOPE_OBJECTS for action in API_SCOPE_ACTIONS])+ def test_all_scopes_excludes_internal_scope(self, scope: str) -> None:+ self.assertNotIn(scope, ALL_SCOPES)++ def test_privileged_scopes_subset_of_all_scopes(self) -> None:+ self.assertTrue(PRIVILEGED_SCOPES.issubset(ALL_SCOPES))+ self.assertIn("llm_gateway:read", PRIVILEGED_SCOPES)++ def test_oauth_hidden_scopes_expands_oauth_hidden_objects_to_strings(self) -> None:+ # OAUTH_HIDDEN_SCOPES is the `obj:action` STRING form of+ # OAUTH_HIDDEN_SCOPE_OBJECTS, intersected with ALL_SCOPES so phantom+ # combinations can't leak in.+ expected = (+ frozenset(f"{obj}:{action}" for obj in OAUTH_HIDDEN_SCOPE_OBJECTS for action in API_SCOPE_ACTIONS)+ & ALL_SCOPES+ )+ self.assertEqual(OAUTH_HIDDEN_SCOPES, expected)++ def test_unprivileged_scopes_excludes_privileged_and_hidden(self) -> None:+ self.assertTrue(UNPRIVILEGED_SCOPES.isdisjoint(PRIVILEGED_SCOPES))+ self.assertTrue(UNPRIVILEGED_SCOPES.isdisjoint(OAUTH_HIDDEN_SCOPES))++ def test_unprivileged_scopes_subset_of_all_scopes(self) -> None:+ self.assertTrue(UNPRIVILEGED_SCOPES.issubset(ALL_SCOPES))++ @parameterized.expand([("openid",), ("profile",), ("email",)])+ def test_unprivileged_scopes_excludes_oidc(self, oidc: str) -> None:+ # OIDC scopes are accepted at /authorize independently of application.scopes;+ # they are not part of the UNPRIVILEGED broad-default set.+ self.assertNotIn(oidc, UNPRIVILEGED_SCOPES)++ @parameterized.expand([(f"{obj}:{action}",) for obj in INTERNAL_API_SCOPE_OBJECTS for action in API_SCOPE_ACTIONS])+ def test_unprivileged_scopes_excludes_internal_scope(self, scope: str) -> None:+ self.assertNotIn(scope, UNPRIVILEGED_SCOPES)++ @parameterized.expand([("insight:read",), ("dashboard:write",), ("query:read",)])+ def test_unprivileged_scopes_covers_known_public_scope(self, scope: str) -> None:+ # Spot-check: a generic OAuth client should be able to request these.+ self.assertIn(scope, UNPRIVILEGED_SCOPES)++ def test_scopes_module_loadable_via_runpy_like_mcp_codegen(self) -> None:+ # MCP scope codegen at bin/build-mcp-oauth-scopes.py loads this module via+ # runpy.run_path (bypassing posthog/__init__.py which pulls in Django).+ # Mirror that mechanism here so the test actually catches a regression+ # where someone adds a Django-requiring import to posthog/scopes.py.+ # `import posthog.scopes` would not catch it — that runs __init__.py too.+ scopes_path = Path(__file__).resolve().parent.parent / "scopes.py"+ loaded = runpy.run_path(str(scopes_path))+ self.assertIn("UNPRIVILEGED_SCOPES", loaded)+ self.assertTrue(loaded["UNPRIVILEGED_SCOPES"])+ self.assertIn("llm_gateway:read", loaded["PRIVILEGED_SCOPES"])++ def test_oauth_scopes_supported_excludes_privileged_and_hidden(self) -> None:+ # Discovery metadata (/.well-known/oauth-authorization-server) must not+ # advertise privileged scopes (llm_gateway:*, admin-granted only) or+ # OAUTH_HIDDEN scopes — an OAuth client can't obtain them self-serve.+ supported = set(get_oauth_scopes_supported())+ self.assertTrue(supported.isdisjoint(PRIVILEGED_SCOPES))+ self.assertTrue(supported.isdisjoint(OAUTH_HIDDEN_SCOPES))+ self.assertNotIn("llm_gateway:read", supported)+ self.assertNotIn("llm_gateway:write", supported)++ def test_oauth_scopes_supported_includes_oidc_and_unprivileged(self) -> None:+ supported = set(get_oauth_scopes_supported())+ for oidc in OIDC_SCOPES:+ self.assertIn(oidc, supported)+ self.assertEqual(supported - set(OIDC_SCOPES), UNPRIVILEGED_SCOPES)++ def test_all_scope_objects_fit_in_oauthapplication_scopes_charfield(self) -> None:+ # OAuthApplication.scopes is ArrayField(CharField(max_length=100)), matching+ # PersonalAPIKey.scopes. Verify every `obj:action` string fits so admin-set+ # ceilings don't truncate.+ for scope in ALL_SCOPES:+ self.assertLessEqual(len(scope), 100, f"{scope} exceeds OAuthApplication.scopes CharField max_length=100")++class TestScopeBucketInvariants(SimpleTestCase):def test_signal_scout_internal_is_internal(self) -> None:# The scout internal scope must stay in INTERNAL_API_SCOPE_OBJECTS so it isdiff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 9088e81aec20..fd957a24ede3 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -107,8 +107,6 @@ export const OAUTH_SCOPES_SUPPORTED = ['live_debugger:write','llm_analytics:read','llm_analytics:write',- 'llm_gateway:read',- 'llm_gateway:write','llm_prompt:read','llm_prompt:write','llm_provider_key:read',