: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): stop rejecting authorize requests on scope grounds (#77562)
Matt Brookerfd9ee3d07bd3
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.tsindex 876662621f2f..24f7a5f45e45 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts@@ -724,13 +724,22 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([// object. Both the rows and the grant derive from this one set, so the consent// screen always displays exactly what authorizing will grant — required scopes// the client didn't request get a visible (locked) row, never a silent grant.+ // Scopes outside the app's ceiling are dropped first: `/authorize` clamps them+ // away, so rendering them would promise the user access the token won't carry.+ // `*` survives because the server resolves it separately (`wildcard_read_scopes`)+ // rather than matching it against the ceiling.consentResourceScopes: [(s) => [s.scopes, s.oauthApplication],(scopes: string[], oauthApplication: OAuthApplicationPublicMetadata | null): string[] => {+ const grantable = oauthApplication?.grantable_scopes+ const grantableSet = grantable ? new Set(grantable) : null+ const requested = grantableSet+ ? scopes.filter((scope) => scope === '*' || !scope.includes(':') || grantableSet.has(scope))+ : scopesconst required = (oauthApplication?.required_scopes ?? []).filter((scope) => scope.includes(':') || scope === '*')- return getMinimumEquivalentScopes([...scopes, ...required]).filter(+ return getMinimumEquivalentScopes([...requested, ...required]).filter((scope) => scope.includes(':') || scope === '*')},diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 47a3bf5b5db2..21bb0df5b2e4 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7685,6 +7685,11 @@ export type OAuthApplicationPublicMetadata = {required_scopes?: string[]/** Server-computed read-only form of a `*` grant; the consent page must not derive this client-side. */wildcard_read_scopes?: string[]+ /**+ * The app's resolved scope ceiling. `/authorize` clamps the request to this set, so a requested+ * scope missing from it is dropped rather than granted and must not be rendered as a consent row.+ */+ grantable_scopes?: string[]}export interface EmailSenderDomainStatus {status: 'pending' | 'success'diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.pyindex eea576ca7beb..33d731b8dfba 100644--- a/posthog/api/oauth/test_dcr.py+++ b/posthog/api/oauth/test_dcr.py@@ -1,5 +1,6 @@import base64import hashlib+from urllib.parse import parse_qs, urlparsefrom posthog.test.base import APIBaseTest@@ -8,7 +9,7 @@ from rest_framework import statusfrom rest_framework.test import APIClientfrom posthog.api.oauth.client_name import sanitize_client_name-from posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLevel+from posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLevel, OAuthGrantclass TestDynamicClientRegistration(APIBaseTest):@@ -515,24 +516,17 @@ class TestDynamicClientRegistration(APIBaseTest):self.assertNotIn("error=invalid_scope", redirect_to)self.assertIn("code=", redirect_to)- def test_no_scope_dcr_client_rejects_privileged_scope_at_authorize(self):+ def test_no_scope_dcr_client_does_not_obtain_privileged_scope_at_authorize(self):"""The broad default excludes PRIVILEGED_SCOPES, so a no-ceiling DCR- client cannot obtain llm_gateway access at /authorize."""+ client cannot obtain llm_gateway access at /authorize. It is dropped from+ the grant rather than failing the request, so the unprivileged scope+ alongside it still lands."""client_id = self._register_dcr_client()- self.client.force_login(self.user)- response = self.client.get(- "/oauth/authorize/",- {- "client_id": client_id,- "redirect_uri": "https://example.com/callback",- "response_type": "code",- "scope": "llm_gateway:read",- "code_challenge": self.code_challenge,- "code_challenge_method": "S256",- "state": "test123",- },- )- self.assertEqual(response.status_code, status.HTTP_302_FOUND)- location = response.get("Location")- assert location- self.assertIn("error=invalid_scope", location)+ response = self._authorize_consent_post(client_id, "llm_gateway:read experiment:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ redirect_to = response.json()["redirect_to"]+ self.assertNotIn("error=invalid_scope", redirect_to)+ code = parse_qs(urlparse(redirect_to).query)["code"][0]+ granted = set(OAuthGrant.objects.get(code=code).scope.split())+ self.assertNotIn("llm_gateway:read", granted)+ self.assertIn("experiment:read", granted)diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 1d0b2184e8e8..5f920e2a1b1d 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -1358,6 +1358,29 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(self._refresh_and_get_scopes(refresh_token), expected)+ def test_refresh_of_an_empty_grant_succeeds_instead_of_looping(self):+ # A request that clamps to nothing mints a scope-less token. Rejecting its+ # refresh would send the client back to /authorize, which now clamps rather+ # than failing and returns another empty grant, so the client would refresh,+ # be rejected, and re-authorize forever. It refreshes to an empty grant.+ self.confidential_application.scopes = ["experiment:read"]+ self.confidential_application.save()++ refresh_token = self._create_refreshable_token_pair("")++ 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)+ self.assertEqual(response.json().get("scope", ""), "")+def test_refresh_rejected_when_token_scopes_outside_ceiling(self):self.confidential_application.scopes = ["experiment:read"]self.confidential_application.save()@@ -2608,28 +2631,21 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["error"], "invalid_grant")- def test_invalid_scope_validation_with_and_without_trailing_slash(self):- """Test that invalid scope validation works with and without trailing slash."""-- # Test with trailing slash (this should work correctly - scope validation happens)- invalid_scope_url_with_slash = f"/oauth/authorize/?client_id=test_confidential_client_id&redirect_uri=https://example.com/callback&response_type=code&code_challenge={self.code_challenge}&code_challenge_method=S256&scope=invalid_scope_name"-- response = self.client.get(invalid_scope_url_with_slash)- self.assertEqual(response.status_code, status.HTTP_302_FOUND)- location = response.get("Location")- assert location- self.assertIn("error=invalid_scope", location)-- # Test without trailing slash (should now also validate scopes after fix)- invalid_scope_url_without_slash = f"/oauth/authorize?client_id=test_confidential_client_id&redirect_uri=https://example.com/callback&response_type=code&code_challenge={self.code_challenge}&code_challenge_method=S256&scope=invalid_scope_name"+ @parameterized.expand(+ [("with_trailing_slash", "/oauth/authorize/"), ("without_trailing_slash", "/oauth/authorize")]+ )+ @patch("posthog.api.oauth.views.render_template")+ def test_unknown_scope_renders_consent_instead_of_rejecting(self, _name: str, path: str, mock_render):+ # Both paths reach the same validator, and neither errors: an unknown scope is+ # dropped so the user still reaches consent rather than a redirect carrying+ # error=invalid_scope. Regression guard for the retired-scope breakage.+ mock_render.return_value = HttpResponse(status=status.HTTP_200_OK)+ url = f"{path}?client_id=test_confidential_client_id&redirect_uri=https://example.com/callback&response_type=code&code_challenge={self.code_challenge}&code_challenge_method=S256&scope=invalid_scope_name"- response = self.client.get(invalid_scope_url_without_slash)+ response = self.client.get(url)- # After the fix, both should behave the same - redirect with error- self.assertEqual(response.status_code, status.HTTP_302_FOUND)- location = response.get("Location")- assert location- self.assertIn("error=invalid_scope", location)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_render.assert_called_once()# --- Per-application scope ceiling (OAuthApplication.scopes) ---@@ -2641,15 +2657,46 @@ class TestOAuthAPI(APIBaseTest):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.+ def test_authorize_drops_scope_outside_app_ceiling(self):+ # The consent-screen path, which first-party apps skip. Asserts on the minted+ # grant rather than the rendered ceiling: grantable_scopes is derived from the+ # app alone, so asserting on it would pass even if clamping stopped working.+ self._set_ceiling("experiment:read", "dashboard:read")+ self.confidential_application.optional_scopes = ["dashboard:read"]+ self.confidential_application.save()++ response = self._authorize_post("experiment:read dashboard:read insight:write")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ code = parse_qs(urlparse(response.json()["redirect_to"]).query)["code"][0]+ granted = set(OAuthGrant.objects.get(code=code).scope.split())+ self.assertNotIn("insight:write", granted)+ self.assertEqual(granted, {"experiment:read", "dashboard:read"})++ def test_token_response_reports_the_clamped_scope(self):+ # RFC 6749 section 3.3: when the granted scope differs from the request the token+ # response MUST report what was actually granted. Silent clamping is only safe+ # because a client can read the real set back here.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)++ response = self._authorize_post("experiment:read insight:write")+ code = parse_qs(urlparse(response.json()["redirect_to"]).query)["code"][0]++ token_response = self.post(+ "/oauth/token/",+ {+ "grant_type": "authorization_code",+ "code": code,+ "client_id": "test_confidential_client_id",+ "client_secret": "test_confidential_client_secret",+ "redirect_uri": "https://example.com/callback",+ "code_verifier": self.code_verifier,+ },+ )++ self.assertEqual(token_response.status_code, status.HTTP_200_OK)+ self.assertNotIn("insight:write", token_response.json()["scope"].split())+ self.assertIn("experiment:read", token_response.json()["scope"].split())def test_authorize_accepts_full_grant_of_app_ceiling(self):# Without optional_scopes every ceiling scope is required, so a grant that@@ -2733,6 +2780,79 @@ class TestOAuthAPI(APIBaseTest):self.assertNotIn("*", granted)self.assertEqual(granted, {"experiment:read"})+ @parameterized.expand(+ [+ # A scope retired from APIScopeObject stops being grantable under every ceiling+ # at once. Failing the whole request locked out clients that still send the old+ # list, which have no way to discover the narrower per-app set before asking.+ ("retired_scope_under_empty_ceiling", [], "experiment:read agents:read", {"experiment:read"}),+ (+ "scope_outside_seeded_ceiling",+ ["experiment:read", "dashboard:read"],+ "experiment:read insight:write",+ {"experiment:read"},+ ),+ ("hidden_scope_under_empty_ceiling", [], "experiment:read wizard_session:read", {"experiment:read"}),+ ]+ )+ def test_authorize_clamps_ungrantable_scopes(self, _name, ceiling, requested, expected):+ app = self._create_first_party_app_with_ceiling(*ceiling)+ grant = self._first_party_authorize_grant(app, requested)+ self.assertEqual(set(grant.scope.split()), expected)++ def test_authorize_clamping_captures_event_on_the_consent_grant(self):+ # The event fires where the grant is minted, so the consent path is covered.+ # Capturing on the GET instead would both miss a direct POST and count+ # authorizations the user went on to abandon.+ self._set_ceiling("experiment:read")+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self._authorize_post("experiment:read insight:write")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ clamped = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_scopes_clamped"]+ self.assertEqual(len(clamped), 1)+ props = clamped[0].kwargs["properties"]+ self.assertEqual(props["dropped_scopes"], ["insight:write"])+ self.assertEqual(props["granted_scope_count"], 1)+ self.assertEqual(props["app_id"], str(self.confidential_application.pk))+ self.assertEqual(props["client_name"], self.confidential_application.name)+ self.assertEqual(props["registration_type"], "manual")+ self.assertEqual(props["is_verified"], self.confidential_application.is_verified)+ self.assertEqual(props["is_first_party"], self.confidential_application.is_first_party)++ def test_authorize_rendering_consent_captures_no_clamping_event(self):+ # Rendering the consent screen grants nothing, so an authorization the user+ # never completes must not inflate the clamping numbers.+ self._set_ceiling("experiment:read")+ with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")):+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self.client.get(f"{self.base_authorization_url}&scope=experiment:read insight:write")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ clamped = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_scopes_clamped"]+ self.assertEqual(clamped, [])++ def test_authorize_within_ceiling_captures_no_clamping_event(self):+ self._set_ceiling("experiment:read")+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:+ response = self._authorize_post("experiment:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ clamped = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_scopes_clamped"]+ self.assertEqual(clamped, [])++ def test_read_only_consent_under_a_write_ceiling_grants_read(self):+ # The consent screen's read-only toggle downgrades `insight:write` to+ # `insight:read`. A ceiling naming only the write half must still admit it,+ # or the user is told they granted read access and the token carries nothing.+ # `insight:write` is optional here because a required scope cannot be+ # deselected at consent, so the toggle is only reachable for optional ones.+ self._set_ceiling("experiment:read")+ self.confidential_application.optional_scopes = ["insight:write"]+ self.confidential_application.save()++ response = self._authorize_post("experiment:read insight:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ code = parse_qs(urlparse(response.json()["redirect_to"]).query)["code"][0]+ self.assertEqual(set(OAuthGrant.objects.get(code=code).scope.split()), {"experiment:read", "insight:read"})+def test_authorize_wildcard_narrowing_captures_event(self):self._set_ceiling("experiment:read")with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")):@@ -2853,50 +2973,14 @@ class TestOAuthAPI(APIBaseTest):refresh_token = self._create_refreshable_token_pair("experiment:read dashboard:read")self.assertEqual(self._refresh_and_get_scopes(refresh_token), {"experiment:read", "dashboard:read"})- @parameterized.expand(- [- (- "ceiling_excludes_requested",- ["experiment:read"],- "experiment:write",- "experiment:write",- ["experiment:write"],- ),- ("empty_ceiling_rejects_privileged", [], "llm_gateway:read", "llm_gateway:read", ["llm_gateway:read"]),- # mixed grantable + out-of-ceiling scope: requested records the full set, rejected pins to just the offender- (- "mixed_scope_isolates_offender",- ["experiment:read"],- "experiment:read%20experiment:write",- "experiment:read experiment:write",- ["experiment:write"],- ),- ]- )- def test_authorize_rejection_captures_invalid_scope_event(- self, _name, ceiling, requested_scope, expected_requested_scopes, expected_rejected_scopes- ):- self._set_ceiling(*ceiling)- with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:- response = self.client.get(f"{self.base_authorization_url}&scope={requested_scope}")- self.assertEqual(response.status_code, status.HTTP_302_FOUND)- self.assertIn("error=invalid_scope", response.get("Location") or "")- rejected = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_authorization_rejected"]- self.assertEqual(len(rejected), 1)- props = rejected[0].kwargs["properties"]- self.assertEqual(props["reason"], "invalid_scope")- self.assertEqual(props["app_id"], str(self.confidential_application.pk))- self.assertEqual(props["client_name"], self.confidential_application.name)- self.assertEqual(props["registration_type"], "manual")- self.assertEqual(props["is_verified"], self.confidential_application.is_verified)- self.assertEqual(props["is_first_party"], self.confidential_application.is_first_party)- self.assertEqual(props["requested_scopes"], expected_requested_scopes)- self.assertEqual(props["rejected_scopes"], expected_rejected_scopes)-- def test_authorize_success_does_not_capture_invalid_scope_event(self):+ def test_authorize_never_rejects_on_scope_grounds(self):+ # `/authorize` no longer emits invalid_scope: the out-of-ceiling scope is dropped+ # and the grant proceeds with what survived, instead of failing the whole request.self._set_ceiling("experiment:read")with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:- self._authorize_post("experiment:read")+ response = self._authorize_post("experiment:read insight:write")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertNotIn("error=invalid_scope", response.json()["redirect_to"])rejected = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_authorization_rejected"]self.assertEqual(rejected, [])@@ -3767,14 +3851,15 @@ class TestOAuthAPI(APIBaseTest):algorithm="RS256",)- # Request with an invalid scope to trigger an error redirect+ # An unsupported response_type triggers the error redirect. Scope is no longer+ # usable as the trigger: /authorize drops ungrantable scopes instead of failing.url = (f"/oauth/authorize/?client_id={custom_scheme_app.client_id}"f"&redirect_uri={scheme}://posthog/callback"- f"&response_type=code"+ f"&response_type=unsupported"f"&code_challenge={self.code_challenge}"f"&code_challenge_method=S256"- f"&scope=nonexistent_scope"+ f"&scope=query:read")response = self.client.get(url)@@ -3782,7 +3867,7 @@ class TestOAuthAPI(APIBaseTest):# Should redirect back to the client with the error, not 500self.assertEqual(response.status_code, status.HTTP_302_FOUND)self.assertTrue(response["Location"].startswith(f"{scheme}://posthog/callback"))- self.assertIn("error=invalid_scope", response["Location"])+ self.assertIn("error=unsupported_response_type", response["Location"])@freeze_time("2025-01-01 00:00:00")@override_settings(CLOUD_DEPLOYMENT="US", SITE_URL="https://us.posthog.com")diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 214c47725b15..b500e0efc32b 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -61,14 +61,15 @@ from posthog.models.oauth import ()from posthog.scopes import (ALWAYS_ALLOWED_SCOPES,+ clamp_scopes_to_ceiling,downgrade_scopes_to_read_only,effective_ceiling,get_oauth_scopes_supported,get_scope_descriptions,+ grantable_ceiling,narrow_scopes_to_ceiling,resolve_ceiling,scopes_outside_ceiling,- scopes_within_ceiling,)from posthog.security.url_validation import has_authority_bypass_charsfrom posthog.user_permissions import UserPermissions@@ -449,36 +450,41 @@ class OAuthValidator(OAuth2Validator):return Falsedef validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):- """Enforce the per-application scope ceiling from the app's grantable set.+ """Clamp the requested scopes to the per-application ceiling.The ceiling is `scopes` plus `optional_scopes` (`ceiling_scopes`), so an appusing the required/optional split can request its optional scopes too.- Delegates the ceiling resolution to `scopes_within_ceiling` so `/authorize`- and the hand-rolled provisioning mint paths share one implementation. Two- `/authorize`-specific mutations of `request.scopes` live here:+ Resolution lives in `clamp_scopes_to_ceiling`. The agentic-provisioning mint+ paths still reject out-of-ceiling scopes via `scopes_within_ceiling`: they mint+ for a partner against scopes that partner declared, so a mismatch there is a+ misconfiguration worth failing on, not a client with a stale pinned list.++ A request naming scopes outside the ceiling is granted the part that is+ inside rather than rejected outright, so one ungrantable scope no longer+ costs the user the whole authorization. The clamped set is written back to+ `request.scopes`, which is what oauthlib grants and reports in the token+ response. Two `/authorize`-specific cases resolve here as well:- the client omitting `scope=`, so oauthlib doesn't fall back to just`["openid"]` from `DEFAULT_SCOPES`.- - a `*` request against a *seeded* (non-empty) ceiling, narrowed down to the- resolved ceiling rather than rejected. This keeps legacy first-party- clients still sending `*` signing in once a ceiling is seeded, granting- strictly less than the empty-ceiling `*` grandfathering below. The token- response carries the actual (narrowed) `scope`, so this stays spec-valid.+ - a `*` request against a *seeded* (non-empty) ceiling, which resolves to+ the ceiling rather than staying a wildcard.`*` is still accepted verbatim under an empty ceiling here (legacy PostHogDesktop CLI) but never on the provisioning paths — see the flag.++ This never returns `False`. `/authorize` does not reject on scope grounds:+ scopes are retired and renamed routinely, and a client pinning a hardcoded+ list cannot see that coming, so an ungrantable scope must not cost the user+ their sign-in. A request with nothing grantable yields an identity-only+ token whose resource calls 403; `oauth_scopes_clamped` is what surfaces it."""app_scopes = getattr(client, "ceiling_scopes", None) or []requested = set(scopes or [])if not requested:request.scopes = sorted(effective_ceiling(app_scopes) | ALWAYS_ALLOWED_SCOPES)return True- ceiling = resolve_ceiling(app_scopes)- if ceiling is not None and "*" in requested:- # `*` is never grantable under an explicit ceiling, even if the ceiling itself- # lists it — mirrors the guard in `scopes_within_ceiling`/`scopes_outside_ceiling`.- request.scopes = sorted((ceiling - {"*"}) | (requested & ALWAYS_ALLOWED_SCOPES))- return True- return scopes_within_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)+ request.scopes = clamp_scopes_to_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)+ return Truedef get_original_scopes(self, refresh_token, request, *args, **kwargs):"""Cap refreshed scopes at the application's current ceiling.@@ -497,6 +503,9 @@ class OAuthValidator(OAuth2Validator):without emptying it, so we reject the refresh (`invalid_grant`) — the clientre-authorizes and gets a token within the current ceiling, rather thansilently keeping out-of-ceiling access.+ - a token that never held any scope refreshes as an empty grant instead.+ Rejecting that one would loop, since re-authorizing returns the same empty+ grant; its 403s by scope are where the client should find out.An empty `ceiling_scopes` (no ceiling) is a no-op. Refresh never enforces therequired floor — a token consented below a later-declared required set keeps@@ -926,6 +935,48 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):return "cimd"return "dcr" if application.is_dcr_client else "manual"+ def _capture_scopes_clamped(self, request, application: OAuthApplication, submitted_scope: str) -> None:+ """Report scopes `validate_scopes` dropped from an issued grant.++ Called at each point a grant is actually minted rather than when the request+ arrives, so an abandoned or denied authorization is not counted. Since+ `/authorize` no longer fails on scope grounds, this is the only signal that a+ client is asking for scopes it cannot have. `*` is excluded because+ `oauth_wildcard_scopes_narrowed` already owns that case.++ Both counts derive from `submitted_scope`, the set the grant was minted from,+ so `granted_scope_count` is what the token carries rather than what was asked+ for.+ """+ submitted = submitted_scope.split()+ dropped_scopes = [+ scope+ for scope in scopes_outside_ceiling(+ submitted, application.ceiling_scopes, allow_wildcard_under_empty_ceiling=True+ )+ if scope != "*"+ ]+ if not dropped_scopes:+ return++ granted = clamp_scopes_to_ceiling(+ submitted, application.ceiling_scopes, allow_wildcard_under_empty_ceiling=True+ )+ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="oauth_scopes_clamped",+ properties={+ "client_name": application.name,+ "app_id": str(application.pk),+ "registration_type": self._registration_type(application),+ "is_verified": application.is_verified,+ "is_first_party": application.is_first_party,+ "dropped_scopes": dropped_scopes,+ "granted_scope_count": len(granted),+ **(get_region_info() or {}),+ },+ )+@method_decorator(login_required)def get(self, request, *args, **kwargs):# Rate-limit new CIMD application creation by IP.@@ -1023,6 +1074,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):uri, headers, body, status_code = self.create_authorization_response(request=request, scopes=scope_str, credentials=credentials, allow=True)+ self._capture_scopes_clamped(request, application, scope_str)return self.redirect(uri, application)except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))@@ -1053,6 +1105,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):uri, headers, body, status_code = self.create_authorization_response(request=request, scopes=scope_str, credentials=credentials, allow=True)+ self._capture_scopes_clamped(request, application, scope_str)return self.redirect(uri, application)except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))@@ -1068,8 +1121,11 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):# resolution `validate_scopes` enforces — the frontend's scope list# drifts from the server's (both over- and under-granting otherwise)."wildcard_read_scopes": sorted(- scope for scope in effective_ceiling(application.ceiling_scopes) if scope.endswith(":read")+ scope for scope in grantable_ceiling(application.ceiling_scopes) if scope.endswith(":read")),+ # The same resolution `validate_scopes` clamps against, so the consent screen+ # can drop requested scopes the grant will not include instead of promising them.+ "grantable_scopes": sorted(grantable_ceiling(application.ceiling_scopes)),}}@@ -1166,6 +1222,9 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):logger.debug("Success url for the request: %s", uri)+ if serializer.validated_data["allow"]:+ self._capture_scopes_clamped(request, application, scopes)+redirect = self.redirect(uri, application)return Response(@@ -1193,33 +1252,6 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):"""redirect, error_response = super().error_response(error, **kwargs)- # Surface scope-ceiling rejections so on-call can alert on /authorize failing with invalid_scope.- if getattr(error_response["error"], "error", None) == "invalid_scope" and application is not None:- distinct_id = getattr(getattr(self.request, "user", None), "distinct_id", None) or application.client_id- # invalid_scope only reaches error_response from the GET authorize request, where- # oauthlib raises it pre-consent (the consent POST returns it as a redirect, not a- # raise), so the requested scope is always in the query string here.- requested_scope = self.request.query_params.get("scope") or ""- rejected_scopes = scopes_outside_ceiling(- requested_scope.split(),- application.ceiling_scopes,- allow_wildcard_under_empty_ceiling=True,- )- posthoganalytics.capture(- distinct_id=str(distinct_id),- event="oauth_authorization_rejected",- properties={- "reason": "invalid_scope",- "client_name": application.name,- "app_id": str(application.pk),- "registration_type": self._registration_type(application),- "is_verified": application.is_verified,- "is_first_party": application.is_first_party,- "requested_scopes": requested_scope,- "rejected_scopes": rejected_scopes,- },- )-if redirect:if no_redirect:return Response(diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 0d5676f03e12..01f8f3c958d6 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -341,7 +341,12 @@ def resolve_ceiling(app_scopes: Iterable[str]) -> frozenset[str] | None:which falls back to the `UNPRIVILEGED_SCOPES` default). A `@default` sentinelexpands to `UNPRIVILEGED_SCOPES` unioned with the other listed scopes; without it,a non-empty ceiling stays an exhaustive allow-list. Entries are stripped so a- fat-fingered `" @default"` still resolves (real scopes never have whitespace)."""+ fat-fingered `" @default"` still resolves (real scopes never have whitespace).++ This is the literal ceiling, which is also what a token carries on the paths that+ mint the whole thing (`create_wizard_oauth_access_token_for_user`, provisioning+ account requests). Read halves are added by `grantable_ceiling` at admission time+ instead, so testing a request against the ceiling can't quietly widen those."""app = {s.strip() for s in (app_scopes or [])}app.discard("")if not app:@@ -358,6 +363,24 @@ def effective_ceiling(app_scopes: Iterable[str]) -> frozenset[str]:return ceiling if ceiling is not None else UNPRIVILEGED_SCOPES+def grantable_ceiling(app_scopes: Iterable[str]) -> frozenset[str]:+ """The scopes a request may name: `effective_ceiling` plus the read half of every+ `<object>:write` entry.++ `APIScopePermission` already accepts a `:write` token wherever `:read` is required,+ so refusing a request for the narrower half denies access the token would have+ carried anyway. That is what the consent screen's read-only toggle asks for.++ Distinct from `effective_ceiling` because the read halves must not reach the paths+ that mint the whole ceiling as a token: widening those would hand partners and the+ wizard scope strings they never asked for, for no extra capability."""+ return _with_read_halves(effective_ceiling(app_scopes))+++def _with_read_halves(scopes: frozenset[str]) -> frozenset[str]:+ return frozenset(scopes | {scope.replace(":write", ":read") for scope in scopes if scope.endswith(":write")})++def scopes_within_ceiling(requested: Iterable[str],app_scopes: Iterable[str],@@ -366,9 +389,10 @@ def scopes_within_ceiling() -> bool:"""Whether every requested scope is grantable under an app's scope ceiling.- The single source of truth for ceiling resolution: `/authorize`- (`OAuthValidator.validate_scopes`) and the hand-rolled agentic-provisioning- mint paths both call this so they enforce identical rules.+ The ceiling-resolution rule for callers that reject rather than clamp: the+ hand-rolled agentic-provisioning mint paths. `/authorize` resolves the same+ ceiling through `clamp_scopes_to_ceiling` instead, dropping ungrantable scopes+ rather than failing the request.- OIDC + introspection (`ALWAYS_ALLOWED_SCOPES`) are always granted.- An explicit `app_scopes` ceiling is an exhaustive allow-list: anything@@ -388,7 +412,7 @@ def scopes_within_ceiling(if not to_check:return Trueif ceiling is not None:- return "*" not in to_check and to_check.issubset(ceiling)+ return "*" not in to_check and to_check.issubset(_with_read_halves(ceiling))allowed = UNPRIVILEGED_SCOPES | {"*"} if allow_wildcard_under_empty_ceiling else UNPRIVILEGED_SCOPESreturn to_check.issubset(allowed)@@ -412,11 +436,60 @@ def scopes_outside_ceiling(return []if ceiling is not None:# `*` is never grantable under an explicit ceiling, even if listed.- return sorted(s for s in to_check if s == "*" or s not in ceiling)+ admissible = _with_read_halves(ceiling)+ return sorted(s for s in to_check if s == "*" or s not in admissible)allowed = UNPRIVILEGED_SCOPES | {"*"} if allow_wildcard_under_empty_ceiling else UNPRIVILEGED_SCOPESreturn sorted(to_check - allowed)+def clamp_scopes_to_ceiling(+ requested: Iterable[str],+ app_scopes: Iterable[str],+ *,+ allow_wildcard_under_empty_ceiling: bool = False,+) -> list[str]:+ """The grantable subset of a `/authorize` scope request.++ Where `scopes_within_ceiling` answers whether the whole request is grantable,+ this resolves it to what the token should actually carry. An ungrantable scope+ is dropped, never fatal: `/authorize` does not reject on scope grounds at all.+ Scopes are retired and renamed as a matter of routine, and a client pinning a+ hardcoded list has no way to see that coming. The resource metadata's+ `scopes_supported` is resource-wide, so a client cannot discover a narrower+ per-app ceiling before it asks either. RFC 6749 section 3.3 lets the server+ fully or partially ignore the requested scope as long as the token response+ reports what was granted, which oauthlib does whenever it differs.++ An empty return is a real outcome, not an error: the client asked for nothing+ grantable and gets an identity-only token. That client will 403 on every+ resource call, so `oauth_scopes_clamped` is the signal that matters here.++ Clamping can only ever grant less than the ceiling already allowed, so the+ ceiling stays the sole authority on what a token may hold. Resolution mirrors+ `scopes_within_ceiling` exactly:++ - `ALWAYS_ALLOWED_SCOPES` (OIDC + introspection) pass through untouched.+ - Under an explicit ceiling, `*` resolves to the whole ceiling rather than+ staying a wildcard, which is strictly less than the bypass `*` grants in+ `posthog/permissions.py`.+ - Under an empty ceiling, `*` is kept verbatim when the caller grandfathers it,+ because narrowing it there would strip the legacy client's full access.+ """+ always_allowed = set(requested) & ALWAYS_ALLOWED_SCOPES+ resource_requested = set(requested) - ALWAYS_ALLOWED_SCOPES+ if not resource_requested:+ return sorted(always_allowed)++ ceiling = resolve_ceiling(app_scopes)+ if ceiling is not None:+ granted = (ceiling - {"*"}) if "*" in resource_requested else (resource_requested & _with_read_halves(ceiling))+ else:+ allowed = UNPRIVILEGED_SCOPES | {"*"} if allow_wildcard_under_empty_ceiling else UNPRIVILEGED_SCOPES+ granted = resource_requested & allowed++ return sorted(granted | always_allowed)++def narrow_scopes_to_ceiling(original: Iterable[str], app_scopes: Iterable[str]) -> list[str] | None:"""Cap previously-granted scopes at an app's current ceiling (refresh-time).@@ -428,8 +501,15 @@ def narrow_scopes_to_ceiling(original: Iterable[str], app_scopes: Iterable[str])- A `*` token is left untouched (narrowing it would strip all resourceaccess; `*` retirement is handled separately).- Otherwise returns the sorted intersection with the ceiling plus any- always-allowed scopes, or `None` when that intersection is empty (the- caller should reject with `invalid_grant` and force re-authorization).+ always-allowed scopes, or `None` when a non-empty scope set narrows to+ nothing (the caller should reject with `invalid_grant` and force+ re-authorization, which can then grant whatever is inside the ceiling).++ A token that never held any scope is not that case, and rejecting it would+ loop: `/authorize` clamps rather than rejecting, so the re-authorization the+ rejection forces returns the same empty grant, which refreshes and is+ rejected again. It narrows to the empty list instead, leaving one stable+ token whose resource calls 403 by scope."""original_list = list(original)ceiling = resolve_ceiling(app_scopes)@@ -441,7 +521,7 @@ def narrow_scopes_to_ceiling(original: Iterable[str], app_scopes: Iterable[str])return original_listnarrowed = (original_set & ceiling) | (original_set & ALWAYS_ALLOWED_SCOPES)- if not narrowed:+ if not narrowed and original_set:return Nonereturn sorted(narrowed)diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex 1b44b9cd2bc3..837d88cd8753 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -17,12 +17,15 @@ from posthog.scopes import (OIDC_SCOPES,PRIVILEGED_SCOPES,UNPRIVILEGED_SCOPES,+ clamp_scopes_to_ceiling,downgrade_scopes_to_read_only,effective_ceiling,filter_to_unprivileged_scopes,get_oauth_scopes_supported,get_scope_descriptions,+ grantable_ceiling,narrow_scopes_to_ceiling,+ resolve_ceiling,scopes_outside_ceiling,scopes_within_ceiling,)@@ -233,6 +236,47 @@ class TestScopesWithinCeiling(SimpleTestCase):) -> None:assert scopes_within_ceiling(requested, app_scopes) is True+ @parameterized.expand(+ [+ ("write_entry_admits_its_read_half", ["insight:write"], ["insight:read"], ["insight:read"]),+ ("read_entry_does_not_admit_write", ["insight:read"], ["insight:write"], []),+ (+ "read_only_downgrade_of_a_whole_write_ceiling",+ ["insight:write", "experiment:write"],+ ["insight:read", "experiment:read"],+ ["experiment:read", "insight:read"],+ ),+ ]+ )+ def test_write_ceiling_entry_admits_read(+ self, _name: str, app_scopes: list[str], requested: list[str], expected: list[str]+ ) -> None:+ assert clamp_scopes_to_ceiling(requested, app_scopes) == expected++ def test_read_halves_do_not_reach_the_literal_ceiling(self) -> None:+ # `create_wizard_oauth_access_token_for_user` and the provisioning account-request+ # path mint `resolve_ceiling`/`effective_ceiling` verbatim as a token. Adding read+ # halves there would hand out scope strings nobody asked for, so the expansion+ # lives in `grantable_ceiling`, which only decides what a request may name.+ assert resolve_ceiling(["insight:write"]) == frozenset({"insight:write"})+ assert effective_ceiling(["insight:write"]) == frozenset({"insight:write"})+ assert grantable_ceiling(["insight:write"]) == frozenset({"insight:write", "insight:read"})++ @parameterized.expand(+ [+ # A token that HELD scopes now outside the ceiling: rejecting is right,+ # because re-authorizing can still grant whatever is inside it.+ ("held_scopes_now_outside_ceiling_rejects", ["experiment:write"], None),+ # A token that never held any: rejecting would loop, since /authorize+ # clamps and hands the same empty grant back on re-authorization.+ ("never_held_any_scope_narrows_to_empty", [], []),+ ]+ )+ def test_nothing_surviving_narrowing_depends_on_whether_there_was_anything(+ self, _name: str, original: list[str], expected: list[str] | None+ ) -> None:+ assert narrow_scopes_to_ceiling(original, ["dashboard:read"]) == expected+def test_wildcard_under_empty_ceiling_gated_by_flag(self) -> None:# The one resolution difference between callers: /authorize grandfathers `*`# under an empty ceiling, provisioning (default) does not.@@ -323,12 +367,75 @@ class TestNarrowScopesToCeiling(SimpleTestCase):),])- def test_resolution(- self, _name: str, requested: list[str], app_scopes: list[str], expected: list[str] | None- ) -> None:+ def test_resolution(self, _name: str, requested: list[str], app_scopes: list[str], expected: list[str]) -> None:assert narrow_scopes_to_ceiling(requested, app_scopes) == expected+class TestClampScopesToCeiling(SimpleTestCase):+ @parameterized.expand(+ [+ ("subset_of_ceiling_passes_through", ["query:read"], ["query:read", "insight:read"], ["query:read"]),+ # The regression this exists for: one ungrantable scope used to fail the whole+ # authorization, so a client asking for a retired or hidden scope alongside valid+ # ones could not connect at all.+ (+ "ungrantable_scope_dropped_not_rejected",+ ["query:read", "insight:write"],+ ["query:read"],+ ["query:read"],+ ),+ ("retired_scope_dropped_under_empty_ceiling", ["query:read", "agents:read"], [], ["query:read"]),+ ("hidden_scope_dropped_under_empty_ceiling", ["query:read", "wizard_session:read"], [], ["query:read"]),+ ("privileged_scope_dropped_under_empty_ceiling", ["query:read", "llm_gateway:read"], [], ["query:read"]),+ # An identity-only grant is a real outcome, not a rejection: /authorize never+ # fails on scope grounds, so the client signs in and 403s on resource calls.+ ("all_resource_scopes_ungrantable_grants_nothing", ["insight:write"], ["query:read"], []),+ ("unknown_scope_alone_grants_nothing", ["agents:read"], [], []),+ ("identity_only_request_is_not_a_rejection", ["openid", "email"], ["query:read"], ["email", "openid"]),+ (+ "always_allowed_survive_alongside_dropped_scopes",+ ["openid", "query:read", "insight:write"],+ ["query:read"],+ ["openid", "query:read"],+ ),+ (+ "wildcard_resolves_to_explicit_ceiling",+ ["*"],+ ["query:read", "insight:read"],+ ["insight:read", "query:read"],+ ),+ (+ "default_sentinel_keeps_unprivileged_and_listed_extra",+ ["query:read", "llm_gateway:read", "llm_gateway:write"],+ ["@default", "llm_gateway:read"],+ ["llm_gateway:read", "query:read"],+ ),+ ]+ )+ def test_resolution(self, _name: str, requested: list[str], app_scopes: list[str], expected: list[str]) -> None:+ assert clamp_scopes_to_ceiling(requested, app_scopes) == expected++ def test_wildcard_under_empty_ceiling_gated_by_flag(self) -> None:+ # Narrowing `*` under an empty ceiling would strip the legacy client's full access,+ # so it is kept verbatim where the caller grandfathers it and dropped where it doesn't.+ assert clamp_scopes_to_ceiling(["*"], [], allow_wildcard_under_empty_ceiling=True) == ["*"]+ assert clamp_scopes_to_ceiling(["*"], [], allow_wildcard_under_empty_ceiling=False) == []++ def test_never_grants_outside_the_ceiling(self) -> None:+ # The ceiling stays the sole authority on what a token may hold: clamping may only+ # ever shrink a request, so any result is a subset of what the old all-or-nothing+ # check would have allowed through.+ cases = [+ (["query:read", "insight:write", "llm_gateway:read"], ["query:read", "insight:read"]),+ (["*"], ["query:read"]),+ (["query:read", "agents:read"], []),+ (["query:read", "llm_gateway:write"], ["@default", "llm_gateway:read"]),+ ]+ for requested, app_scopes in cases:+ clamped = clamp_scopes_to_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)+ assert scopes_within_ceiling(clamped, app_scopes, allow_wildcard_under_empty_ceiling=True)++class TestFilterToUnprivilegedScopes(SimpleTestCase):@parameterized.expand([