Skip to content

: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.

fix(oauth): show the consent screen the scope set /authorize resolved (#101269)

Rafael Audibert5df421967b6e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index af55c1182cb4..a69ad25f8b59 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9785,9 +9785,9 @@ snapshots:
scenes-app-oauth-authorize--all-scopes-required--light:
hash: v1.k794b7964.e0efa4768af4e4c1ac0f741d9c62bde840d3a205fa98742ef1b53771a957cfbb.G3POhS2LJF7fk8IJh0zmM17bx9mR4IS2PjieRGrhRmU
scenes-app-oauth-authorize--default-scopes--dark:
- hash: v1.k794b7964.986767f854575bc076567098bc9284bebe23bb9d6cb98e9ce5f1615d7df0c1c8.kbh-ZWkN26OjfOLfAvKWancysKB5gLTFVfm-WayZRWY
+ hash: v1.k794b7964.21a1602ada47b6704da18634c4c1386ba17b890500a833c52bd029cc98f69114.HOL3_R7J0JLMO_znhYmoxsZLaj0iqkemCyEIsK-HkA4
scenes-app-oauth-authorize--default-scopes--light:
- hash: v1.k794b7964.247a8dd0c0990f5be55cd872c28380228cebbab4aaf3fc7278452d920da1b723.fuVL1CbsVt1WsMMm7c5dBlEzWjr1phCEyV9cWtQL54Q
+ hash: v1.k794b7964.2c212df3cd88973bea95657e48b357c70a20772ecbe8ef37f57031a78186d32d.QOqtPFDfX_91zkoeXO487oseTb6yQpwPehH8tO4Dg78
scenes-app-oauth-authorize--every-scope-requested--dark:
hash: v1.k794b7964.5b544e241fa57ad7971a6872fce18c2d3e9dbbcfd5c6b4e2a861cc60683a7eda.SymJ-itmx0Mon5EALqTxh99r_VbtywIv8gFXju-9wRs
scenes-app-oauth-authorize--every-scope-requested--light:
@@ -9796,6 +9796,10 @@ snapshots:
hash: v1.k794b7964.5b544e241fa57ad7971a6872fce18c2d3e9dbbcfd5c6b4e2a861cc60683a7eda.gLSvVEeKbmA7YUlD7Jw056daksT3C2VpGN86wBKJkMU
scenes-app-oauth-authorize--every-scope-requested-scrolled-to-end--light:
hash: v1.k794b7964.44941f1c545b5bbfd22ead5b060e347364df80978d620f78ad4ca95676aa5312.e3Uvl_ZP1tnSSMFZU-GzcBepe2Nz90xOVFtxOe0Q3SA
+ scenes-app-oauth-authorize--identity-only-scopes--dark:
+ hash: v1.k794b7964.6e3f3f52d27e324920f358daaeadb32da366ff50210050c19f8de58d130fc1c1.sDKTyirwbr3u9MmHkz6rng_Hs_eKZHs-SBz0PbCtgTk
+ scenes-app-oauth-authorize--identity-only-scopes--light:
+ hash: v1.k794b7964.247a8dd0c0990f5be55cd872c28380228cebbab4aaf3fc7278452d920da1b723.-v0kuh_uR_IXDf7TZJ-zp-BBuwH1MC84DjGhsgkta0w
scenes-app-oauth-authorize--many-optional-scopes--dark:
hash: v1.k794b7964.ed7236b791f1885a80c8e308825334ea9c1fb33c67cbae1aa98c6fae12ff8c6d.wjzy_8MW69AdymaJU2hQR00ZPRM87GUk2hGbQuI-sE8
scenes-app-oauth-authorize--many-optional-scopes--light:
@@ -9809,9 +9813,9 @@ snapshots:
scenes-app-oauth-authorize--wildcard-scope--light:
hash: v1.k794b7964.95034a6e25daf17b6feda53516e2bb3f681e7d036c1fcfb04ddd887f32515e8f.6mGoqUajhralYp32CniS-HRo0Or5AIEpNSXOC44xX7o
scenes-app-oauth-authorize--with-application-logo--dark:
- hash: v1.k794b7964.945c0d75c83bfac039e99f66e8524ab3bd82a3cd4ede7da12b1ef831e77194b3.NrzqHM_SIujBzqtARGo8QxTVR5EHYWrFyDANxfIDIcc
+ hash: v1.k794b7964.fbbcc2ee9993cdf147788b606adf87bfff6934094aca3e5f33c2ea3e075ce206.b4b_Yi9bKZ56dDhVz6Sf3IY0r13zh4U5ovkfpCEmCrE
scenes-app-oauth-authorize--with-application-logo--light:
- hash: v1.k794b7964.1dcbf92f3d266d21bdbc6e437917f2d314ed940e742b19a730dae94409bb6c5c.HnZj5vfmED1h9E0sTIptiYW4oLndfqQwGgW2NiG25oo
+ hash: v1.k794b7964.4afab937271d0d86e106e8df0b2053bc06585b969ed7a8508030ceebc25596cb.iz6G4K_W0R9ymOOcXfrSEdzRu9WxjvPSJSIlW10oAmk
scenes-app-oauth-authorize--with-required-scopes--dark:
hash: v1.k794b7964.f078f02667fddd8216ec0782c45f1fb95d8bbe6cae9887643e00f284216027cd.Zm5Vw89T37jz_UtxgdvbtIYH3Xo6X-pVxNK28AxFNiE
scenes-app-oauth-authorize--with-required-scopes--light:
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx
index d68a764274fd..f851cc0f745d 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx
@@ -10,26 +10,40 @@ import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
-// Override the server-injected oauth_application context for a story. Set synchronously before
-// the story (and its consent logic) mounts, and restored on unmount so story order can't leak.
+// Every story shares one server-injected app context, so a key a story writes outlives it.
+// Snapshot the listed keys synchronously before the story (and its consent logic) mounts, apply
+// any override, and put the previous values back on unmount so story order can't leak.
+function useAppContextOverride(keys: readonly string[], apply?: (appContext: any) => void): void {
+ const appContext = (window as any).POSTHOG_APP_CONTEXT
+ const original = useRef<Record<string, unknown>>()
+ if (!original.current) {
+ original.current = Object.fromEntries(keys.map((key) => [key, appContext[key]]))
+ apply?.(appContext)
+ }
+ useEffect(
+ () => () => {
+ Object.assign(appContext, original.current)
+ },
+ [appContext]
+ )
+}
+
function withOAuthApplication(overrides: Record<string, unknown>): Decorator {
return function OAuthApplicationDecorator(Story): JSX.Element {
- const appContext = (window as any).POSTHOG_APP_CONTEXT
- const original = useRef<{ value: unknown }>()
- if (!original.current) {
- original.current = { value: appContext.oauth_application }
+ useAppContextOverride(['oauth_application'], (appContext) => {
appContext.oauth_application = { ...appContext.oauth_application, ...overrides }
- }
- useEffect(
- () => () => {
- appContext.oauth_application = original.current?.value
- },
- [appContext]
- )
+ })
return <Story />
}
}
+// `pushAuthorize` writes the resolution the server would have sent, and it runs after the story
+// mounts, so it has nowhere to register a cleanup. This decorator owns that key's restore.
+const withScopeResolution: Decorator = function ScopeResolutionDecorator(Story): JSX.Element {
+ useAppContextOverride(['oauth_scope_resolution'])
+ return <Story />
+}
+
// The visual-regression runner lets a fullscreen scene grow to its full content height, which
// would leave the scrolling permission column and the pinned action row out of the snapshot.
// Pin the app shell to a window-sized box so the snapshot shows what a person actually sees.
@@ -42,7 +56,12 @@ const withPinnedSceneHeight: Decorator = function PinnedSceneHeightDecorator(Sto
)
}
-const pushAuthorize = (scope?: string): void => {
+const pushAuthorize = (scope?: string, resolvedScopes?: string[]): void => {
+ const appContext = (window as any).POSTHOG_APP_CONTEXT
+ appContext.oauth_scope_resolution = {
+ scopes: resolvedScopes ?? (scope ? scope.split(' ') : []),
+ was_defaulted: !scope,
+ }
const params = new URLSearchParams({
client_id: 'test-client-id',
redirect_uri: 'https://app.example.com/oauth/callback',
@@ -64,6 +83,7 @@ const meta: Meta = {
},
},
decorators: [
+ withScopeResolution,
mswDecorator({
get: {
// The logic loads projects per organization for users that have organizations
@@ -112,11 +132,33 @@ export default meta
type Story = StoryObj<{}>
-// Identity-only request (openid/email/profile): permissions render as a plain checkmark list
-// with no access selectors and no bulk actions.
+// A client that sends no `scope` at all: the server defaults the request to the app's ceiling,
+// so every row arrives selected at its highest level with the bulk actions available.
export const DefaultScopes: Story = {
+ decorators: [withOAuthApplication({ required_scopes: [] })],
render: () => {
- useDelayedOnMountEffect(() => pushAuthorize())
+ useDelayedOnMountEffect(() =>
+ pushAuthorize(undefined, [
+ 'openid',
+ 'email',
+ 'profile',
+ 'feature_flag:write',
+ 'insight:write',
+ 'dashboard:write',
+ 'query:read',
+ ])
+ )
+ return <App />
+ },
+}
+
+// Identity-only grant: the client asked for scopes outside the app's ceiling, so the server
+// resolved the request down to the OIDC scopes. Permissions render as a plain checkmark list
+// with no access selectors and no bulk actions.
+export const IdentityOnlyScopes: Story = {
+ decorators: [withOAuthApplication({ required_scopes: [] })],
+ render: () => {
+ useDelayedOnMountEffect(() => pushAuthorize('openid email profile'))
return <App />
},
}
@@ -206,21 +248,11 @@ export const ManyOptionalScopes: Story = {
}
// Sets the server flag that says one of the user's organizations has access-control rules.
-// The story below shows the notice this flag adds under the permission list. The decorator
-// restores the original flag on unmount so it cannot leak into other stories.
+// The story below shows the notice this flag adds under the permission list.
const withAccessControls: Decorator = function AccessControlsDecorator(Story): JSX.Element {
- const appContext = (window as any).POSTHOG_APP_CONTEXT
- const original = useRef<{ value: unknown } | null>(null)
- if (!original.current) {
- original.current = { value: appContext.oauth_consent_access_controls_apply }
+ useAppContextOverride(['oauth_consent_access_controls_apply'], (appContext) => {
appContext.oauth_consent_access_controls_apply = true
- }
- useEffect(
- () => () => {
- appContext.oauth_consent_access_controls_apply = original.current?.value
- },
- [appContext]
- )
+ })
return <Story />
}
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
index 50f0db8785f7..54929a50f574 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
@@ -311,10 +311,12 @@ export const OAuthAuthorize = (): JSX.Element => {
</div>
)}
- {scopesWereDefaulted && isMcpResource && (
+ {scopesWereDefaulted && (
<LemonBanner type="info">
- <strong>No permissions requested.</strong> This application didn't request specific
- permissions. Showing all permissions the PostHog MCP server supports.
+ <strong>No permissions requested.</strong>{' '}
+ {isMcpResource
+ ? "This application didn't request specific permissions. Showing all permissions the PostHog MCP server supports."
+ : "This application didn't request specific permissions, so everything it can access is selected below. Change anything you don't want to grant."}
</LemonBanner>
)}
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
index 1442550848d3..1c9da9cde678 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
@@ -1,7 +1,8 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
-import { decodeParams } from 'kea-router'
+import { decodeParams, router } from 'kea-router'
+import { DEFAULT_OAUTH_SCOPES } from 'lib/scopes'
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
@@ -27,6 +28,7 @@ describe('oauthAuthorizeLogic', () => {
afterEach(() => {
logic.unmount()
+ delete (window as any).POSTHOG_APP_CONTEXT
})
const effectiveScopesCases: { name: string; scopes: string[]; apply?: () => void; expected: string[] }[] = [
@@ -135,6 +137,59 @@ describe('oauthAuthorizeLogic', () => {
expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'insight:read'])
})
+ const scopeSourceCases: {
+ name: string
+ urlScope?: string
+ resolution?: { scopes: string[]; was_defaulted: boolean }
+ mcpConsent?: { is_mcp_resource: boolean; scopes: string[] }
+ expected: string[]
+ }[] = [
+ {
+ name: 'prefers the resolved set over the URL',
+ urlScope: 'insight:read',
+ resolution: { scopes: ['openid', 'insight:read', 'dashboard:write'], was_defaulted: false },
+ expected: ['openid', 'insight:read', 'dashboard:write'],
+ },
+ {
+ name: 'uses the resolved set when the client sent no scope',
+ resolution: { scopes: ['openid', 'insight:write', 'query:read'], was_defaulted: true },
+ expected: ['openid', 'insight:write', 'query:read'],
+ },
+ {
+ name: 'narrows a defaulted request to the MCP set on an MCP resource',
+ resolution: { scopes: ['openid', 'insight:write', 'query:read'], was_defaulted: true },
+ mcpConsent: { is_mcp_resource: true, scopes: ['openid', 'query:read'] },
+ expected: ['openid', 'query:read'],
+ },
+ {
+ name: 'falls back to the URL when the server sent no resolution',
+ urlScope: 'insight:read',
+ expected: ['insight:read'],
+ },
+ {
+ name: 'falls back to the identity scopes when neither the server nor the URL names one',
+ expected: DEFAULT_OAUTH_SCOPES,
+ },
+ ]
+
+ it.each(scopeSourceCases)('scope source $name', ({ urlScope, resolution, mcpConsent, expected }) => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ oauth_scope_resolution: resolution,
+ oauth_mcp_consent: mcpConsent,
+ } as AppContext
+ const params = new URLSearchParams({
+ client_id: 'test-client',
+ redirect_uri: 'https://example.com/callback',
+ response_type: 'code',
+ ...(urlScope ? { scope: urlScope } : {}),
+ })
+
+ router.actions.push(`/oauth/authorize?${params.toString()}`)
+
+ expect(logic.values.scopes).toEqual(expected)
+ })
+
const withRequiredScopes = (required_scopes: string[]): void => {
logic.actions.loadOAuthApplicationSuccess({
name: 'Test App',
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index 390b3de9e7a6..d2b0439410da 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -910,8 +910,9 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
const handleAuthorize = (_: Record<string, any>, searchParams: Record<string, any>): void => {
const requestedScopes = searchParams['scope']?.split(' ')?.filter((scope: string) => scope.length) ?? []
const oauthMcpConsent = getAppContext()?.oauth_mcp_consent
+ const scopeResolution = getAppContext()?.oauth_scope_resolution
- const scopesWereDefaulted = requestedScopes.length === 0
+ const scopesWereDefaulted = scopeResolution?.was_defaulted ?? requestedScopes.length === 0
const rawRequiredAccessLevel = searchParams['required_access_level'] as 'organization' | 'project' | null
const requiredAccessLevel = rawRequiredAccessLevel === 'project' ? 'team' : rawRequiredAccessLevel
@@ -928,14 +929,16 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
actions.loadAllTeams()
if (scopesWereDefaulted && oauthMcpConsent?.is_mcp_resource) {
+ // The MCP branch narrows the resolved set to the scopes MCP tools actually
+ // require, so an app with a broad ceiling doesn't consent to more than the
+ // resource server can use.
actions.setIsMcpResource(true)
actions.setScopes(oauthMcpConsent.scopes ?? DEFAULT_OAUTH_SCOPES)
- } else if (scopesWereDefaulted) {
- actions.setIsMcpResource(false)
- actions.setScopes(DEFAULT_OAUTH_SCOPES)
} else {
actions.setIsMcpResource(false)
- actions.setScopes(requestedScopes)
+ actions.setScopes(
+ scopeResolution?.scopes ?? (requestedScopes.length ? requestedScopes : DEFAULT_OAUTH_SCOPES)
+ )
}
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index bff6195bdd15..8ed215875628 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5238,6 +5238,8 @@ export interface AppContext {
oauth_mcp_consent?: OAuthMcpConsentContext
/** One of the user's organizations has the access-control feature and at least one rule, so a granted scope can reach less. */
oauth_consent_access_controls_apply?: boolean
+ /** The scope set `/authorize` resolved for this request; the consent screen must render this, not the URL's `scope`. */
+ oauth_scope_resolution?: OAuthScopeResolution
/** The user's configured homepage for the current team, bootstrapped so navigation can honor it on first paint. */
homepage?: SceneTab | null
}
@@ -7929,6 +7931,13 @@ export type OAuthMcpConsentContext = {
scopes?: string[]
}
+export type OAuthScopeResolution = {
+ /** What `/authorize` resolved the request to: clamped to the app ceiling, and defaulted to it when the client sent no usable scope. */
+ scopes: string[]
+ /** Whether the client sent no usable `scope` (omitted, or cut off mid-token), so the server picked the set. */
+ was_defaulted: boolean
+}
+
export type OAuthApplicationPublicMetadata = {
name: string
client_id: string
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 81839f66e9d3..a91a27343bee 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -49,12 +49,16 @@ from posthog.models.oauth import (
)
from posthog.models.organization import Organization
from posthog.models.team.team import Team
-from posthog.scopes import get_oauth_scopes_supported
+from posthog.scopes import ALL_SCOPES, ALWAYS_ALLOWED_SCOPES, MIN_SCOPES_BEFORE_TRUNCATION, get_oauth_scopes_supported
from posthog.settings.utils import generate_rsa_private_key_pem
from posthog.utils import absolute_uri
from products.access_control.backend.models.access_control import AccessControl
+# A cut-off `scope` parameter only reads as truncated once enough real scopes come through
+# before the fragment, so a fixture standing in for one has to be that long.
+TRUNCATED_SCOPE_REQUEST = " ".join([*sorted(ALL_SCOPES)[:MIN_SCOPES_BEFORE_TRUNCATION], "can"])
+
def jwks_entry_to_public_key(key_data: dict):
# Rebuild an RSA public key from a JWKS entry's modulus (n) and exponent (e).
@@ -272,6 +276,49 @@ class TestOAuthAPI(APIBaseTest):
},
)
+ @parameterized.expand(
+ [
+ ("truncated", TRUNCATED_SCOPE_REQUEST, ["canvas:read", "insight:read", "notebook:read"], True),
+ ("complete", "insight:read canvas:read", ["canvas:read", "insight:read"], False),
+ ("short_request_with_a_fragment_tail", "insight:read can", ["insight:read"], False),
+ ]
+ )
+ @patch("posthog.api.oauth.views.render_template")
+ def test_authorize_resolves_scopes_for_the_consent_screen(
+ self, _name, requested_scope, expected_resource_scopes, expected_was_defaulted, mock_render
+ ):
+ mock_render.return_value = HttpResponse(status=status.HTTP_200_OK)
+ self.confidential_application.scopes = ["insight:read", "canvas:read", "notebook:read"]
+ self.confidential_application.save()
+
+ response = self.client.get(f"{self.base_authorization_url}&scope={quote(requested_scope)}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ template_context = mock_render.call_args.kwargs["context"]
+ self.assertEqual(
+ template_context["oauth_scope_resolution"],
+ {
+ "scopes": sorted(set(expected_resource_scopes) | ALWAYS_ALLOWED_SCOPES)
+ if expected_was_defaulted
+ else expected_resource_scopes,
+ "was_defaulted": expected_was_defaulted,
+ },
+ )
+
+ def test_authorize_bootstraps_the_resolved_scopes_into_the_app_context(self):
+ self.confidential_application.scopes = ["insight:read", "canvas:read"]
+ self.confidential_application.save()
+
+ response = self.client.get(f"{self.base_authorization_url}&scope={quote(TRUNCATED_SCOPE_REQUEST)}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # The serialized bootstrap, not the view's own template context: `_build_template_context`
+ # forwards only an allowlist of caller-provided keys, and a key it omits never reaches the
+ # frontend.
+ resolution = json.loads(response.context["posthog_app_context"])["oauth_scope_resolution"]
+ self.assertEqual(resolution["scopes"], sorted({"insight:read", "canvas:read"} | ALWAYS_ALLOWED_SCOPES))
+ self.assertTrue(resolution["was_defaulted"])
+
@patch("posthog.api.oauth.views.render_template")
def test_authorize_omits_mcp_consent_for_untrusted_resource(self, mock_render):
mock_render.return_value = HttpResponse(status=status.HTTP_200_OK)
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index b4cee6137e23..e8e857270cd8 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -92,6 +92,7 @@ from posthog.scopes import (
downgrade_scopes_to_read_only,
effective_ceiling,
grantable_ceiling,
+ is_truncated_scope_request,
narrow_scopes_to_ceiling,
resolve_ceiling,
scopes_outside_ceiling,
@@ -735,9 +736,14 @@ class OAuthValidator(OAuth2Validator):
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:
+ response. Three `/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 cut off mid-token, which `is_truncated_scope_request` separates
+ from an ordinary stale scope. Clamping a cut-off list would drop the
+ fragment and stay silent about every scope the cut took with it, so the
+ request resolves as if no scope had been sent rather than granting an
+ arbitrary prefix of what the client asked for.
- a `*` request against a *seeded* (non-empty) ceiling, which resolves to
the ceiling rather than staying a wildcard.
@@ -751,8 +757,9 @@ class OAuthValidator(OAuth2Validator):
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:
+ ordered = list(scopes or [])
+ requested = set(ordered)
+ if not requested or is_truncated_scope_request(ordered):
request.scopes = sorted(effective_ceiling(app_scopes) | ALWAYS_ALLOWED_SCOPES)
return True
request.scopes = clamp_scopes_to_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)
@@ -1477,12 +1484,21 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
status=status.HTTP_400_BAD_REQUEST,
)
+ requested_scope_tokens = (request.query_params.get("scope") or "").split()
+ scope_was_truncated = is_truncated_scope_request(requested_scope_tokens)
+ scopes_were_defaulted = not requested_scope_tokens or scope_was_truncated
+
# Track OAuth authorization attempts with the authenticated user
registration_type = self._registration_type(application)
posthoganalytics.capture(
distinct_id=str(request.user.distinct_id),
event="oauth_authorization_requested",
- properties=_oauth_app_event_properties(application),
+ properties={
+ **_oauth_app_event_properties(application),
+ "requested_scope_count": len(requested_scope_tokens),
+ "has_resource": bool(request.query_params.get("resource")),
+ "scope_was_truncated": scope_was_truncated,
+ },
)
# `validate_scopes` narrows a `*` request to the app's ceiling instead of rejecting it
@@ -1582,7 +1598,15 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# 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)),
- }
+ },
+ # What `validate_scopes` resolved this request to, which is the set the grant
+ # will carry. The consent screen renders this rather than re-parsing `scope`
+ # from the URL, so a request the server defaulted or repaired cannot show the
+ # user a narrower list than the token gets.
+ "oauth_scope_resolution": {
+ "scopes": scope_str.split(),
+ "was_defaulted": scopes_were_defaulted,
+ },
}
# Scopes cap what the token may do; access rules cap what the user may do. The grant can
@@ -1592,8 +1616,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
user_id=request.user.id
)
- requested_scope = (request.query_params.get("scope") or "").strip()
- if not requested_scope:
+ if scopes_were_defaulted:
oauth_mcp_consent = build_oauth_mcp_consent_context(request.query_params.get("resource"))
if oauth_mcp_consent is not None:
template_context["oauth_mcp_consent"] = oauth_mcp_consent
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 893ec2f3d5ea..388d4490a471 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -1,4 +1,4 @@
-from collections.abc import Iterable
+from collections.abc import Iterable, Sequence
from typing import Literal, get_args
## API Scopes
@@ -522,6 +522,45 @@ def clamp_scopes_to_ceiling(
return sorted(granted | always_allowed)
+# How many real scopes a request has to carry before its trailing fragment reads as a cut
+# URL rather than as a junk token. A false positive costs the app's whole ceiling, while a
+# missed one only costs a short consent list, so the bar sits well above the length any
+# deliberate request reaches by accident.
+MIN_SCOPES_BEFORE_TRUNCATION = 20
+
+
+def is_truncated_scope_request(requested: Sequence[str]) -> bool:
+ """Whether a `scope` list looks cut off mid-token rather than merely stale.
+
+ A client pinning a retired or renamed scope is routine, and `clamp_scopes_to_ceiling`
+ drops those one at a time. A cut-off request is a different failure: something in the
+ path truncated the authorization URL, so the last token is a fragment and every scope
+ after it is gone, with no way to tell how many. Dropping the fragment the same way
+ hands the user a short consent list and a half-working client, with no error anywhere.
+
+ The signal is a final token that is a strict prefix of a real scope, with every token
+ before it a real scope. A fragment can only ever be last, because the cut takes the
+ rest of the string with it, and requiring a clean head keeps a client with one stale
+ scope from reading as truncated. `requested` must preserve request order.
+
+ The head also has to be long: `MIN_SCOPES_BEFORE_TRUNCATION` real scopes have to come
+ through before a trailing fragment counts. Scope names are short common words, so a
+ two-token request like `openid insight` prefixes a real scope by coincidence, and
+ reading that as truncation hands the caller the app's whole ceiling. A URL that was
+ actually cut carries most of the list before the cut, so the length is what separates
+ the two.
+ """
+ if len(requested) <= MIN_SCOPES_BEFORE_TRUNCATION:
+ return False
+
+ *head, tail = requested
+ known = ALL_SCOPES | ALWAYS_ALLOWED_SCOPES | {"*"}
+ if not tail or tail in known or not all(scope in known for scope in head):
+ return False
+
+ return any(scope.startswith(tail) for scope in known)
+
+
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).
diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.py
index 0e28a8b0a9dc..cd7a7149c117 100644
--- a/posthog/test/test_scopes.py
+++ b/posthog/test/test_scopes.py
@@ -12,6 +12,7 @@ from posthog.scopes import (
API_SCOPE_ACTIONS,
API_SCOPE_OBJECTS,
INTERNAL_API_SCOPE_OBJECTS,
+ MIN_SCOPES_BEFORE_TRUNCATION,
OAUTH_HIDDEN_SCOPE_OBJECTS,
OAUTH_SCOPES_HIDDEN,
PRIVILEGED_SCOPES,
@@ -24,6 +25,7 @@ from posthog.scopes import (
get_oauth_scopes_supported,
get_scope_descriptions,
grantable_ceiling,
+ is_truncated_scope_request,
narrow_scopes_to_ceiling,
resolve_ceiling,
scopes_outside_ceiling,
@@ -455,6 +457,34 @@ class TestClampScopesToCeiling(SimpleTestCase):
assert scopes_within_ceiling(clamped, app_scopes, allow_wildcard_under_empty_ceiling=True)
+def _real_scopes(count: int) -> list[str]:
+ return sorted(ALL_SCOPES)[:count]
+
+
+LONG_HEAD = _real_scopes(MIN_SCOPES_BEFORE_TRUNCATION)
+
+
+class TestIsTruncatedScopeRequest(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("cut_mid_token", [*LONG_HEAD, "can"], True),
+ ("cut_after_the_colon", [*LONG_HEAD, "feature_flag:"], True),
+ ("complete_request", [*LONG_HEAD, "canvas:read"], False),
+ ("stale_scope", [*LONG_HEAD, "legacy_object:read"], False),
+ ("junk_tail_that_prefixes_nothing", [*LONG_HEAD, "zzz"], False),
+ ("fragment_in_the_middle", [*LONG_HEAD, "can", "canvas:read"], False),
+ ("stale_scope_before_the_fragment", ["legacy_object:read", *LONG_HEAD, "can"], False),
+ ("short_request_with_a_prefix_tail", ["openid", "insight"], False),
+ ("short_request_with_a_single_letter_tail", ["openid", "a"], False),
+ ("one_scope_short_of_the_bar", [*_real_scopes(MIN_SCOPES_BEFORE_TRUNCATION - 1), "can"], False),
+ ("fragment_alone", ["can"], False),
+ ("empty", [], False),
+ ]
+ )
+ def test_resolution(self, _name: str, requested: list[str], expected: bool) -> None:
+ assert is_truncated_scope_request(requested) is expected
+
+
class TestFilterToUnprivilegedScopes(SimpleTestCase):
@parameterized.expand(
[
diff --git a/posthog/utils.py b/posthog/utils.py
index 8c5cc0665807..3240ee847ea9 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -689,13 +689,17 @@ def _build_template_context(
home_settings = UserHomeSettings.objects.filter(team=user.team, user=user).first()
posthog_app_context["homepage"] = (home_settings.homepage or None) if home_settings else None
- # Merge caller-provided keys into posthog_app_context (e.g. oauth_application from the authorize view)
- if "oauth_application" in context:
- posthog_app_context["oauth_application"] = context.pop("oauth_application")
- if "oauth_mcp_consent" in context:
- posthog_app_context["oauth_mcp_consent"] = context.pop("oauth_mcp_consent")
- if "oauth_consent_access_controls_apply" in context:
- posthog_app_context["oauth_consent_access_controls_apply"] = context.pop("oauth_consent_access_controls_apply")
+ # Merge caller-provided keys into posthog_app_context (e.g. oauth_application from the authorize view).
+ # A key absent from this list never reaches `window.POSTHOG_APP_CONTEXT`, so the scene that reads it
+ # silently falls back.
+ for caller_key in (
+ "oauth_application",
+ "oauth_mcp_consent",
+ "oauth_consent_access_controls_apply",
+ "oauth_scope_resolution",
+ ):
+ if caller_key in context:
+ posthog_app_context[caller_key] = context.pop(caller_key)
# JSON dumps here since there may be objects like Queries
# that are not serializable by Django's JSON serializer