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.

feat(oauth): narrow first MCP grants for step-up apps (#127704)

Rafael Audibertfb23eb2dbd8c
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
index 4238f2ac6a32..f73f853f6d78 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
@@ -463,10 +463,16 @@ export const OAuthAuthorize = (): JSX.Element => {
<li key={row.key} className="flex items-center space-x-2">
<IconCheck color="var(--success)" className="shrink-0" />
<span className="font-medium">{row.description}</span>
- {!allScopesRequired && (
- <Tooltip title={`${appName} requires this permission`}>
- <LemonTag>Required</LemonTag>
+ {row.alreadyGranted ? (
+ <Tooltip title={`You granted this to ${appName} before`}>
+ <LemonTag>Already granted</LemonTag>
</Tooltip>
+ ) : (
+ !allScopesRequired && (
+ <Tooltip title={`${appName} requires this permission`}>
+ <LemonTag>Required</LemonTag>
+ </Tooltip>
+ )
)}
</li>
))}
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
index b7c849b8d946..fe099bc6672d 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
@@ -256,6 +256,20 @@ describe('oauthAuthorizeLogic', () => {
expect(logic.values.effectiveScopes).toHaveLength(3)
})
+ it('locks scopes granted before, labels them, and keeps them in the grant under bulk actions', () => {
+ logic.actions.setScopes(['openid', 'insight:write', 'comment:write'])
+ logic.actions.setAlreadyGrantedScopes(['openid', 'insight:write'])
+ logic.actions.setAllScopeAccess('none')
+
+ expect(logic.values.scopeRows.find((r) => r.key === 'insight')).toMatchObject({
+ locked: true,
+ alreadyGranted: true,
+ value: 'write',
+ })
+ expect(logic.values.scopeRows.find((r) => r.key === 'comment')).toMatchObject({ alreadyGranted: false })
+ expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:write'])
+ })
+
it('clamps an optional write above a required read floor to the floor, never below', () => {
logic.actions.setScopes(['openid', 'feature_flag:write'])
withRequiredScopes(['feature_flag:read'])
@@ -332,6 +346,53 @@ describe('oauthAuthorizeLogic', () => {
expect(logic.values.oauthAuthorization.scoped_teams).toEqual(expectedTeams)
})
+ it.each([
+ {
+ name: 'its projects',
+ requiredAccessLevel: null,
+ earlierAccess: { scoped_teams: [11], scoped_organizations: [] },
+ expected: { access_type: 'teams', scoped_teams: [11] },
+ },
+ {
+ name: 'its organizations',
+ requiredAccessLevel: null,
+ earlierAccess: { scoped_teams: [], scoped_organizations: ['org-b'] },
+ expected: { access_type: 'organizations', scoped_organizations: ['org-b'] },
+ },
+ {
+ name: 'its project when the app requires one',
+ requiredAccessLevel: 'project',
+ earlierAccess: { scoped_teams: [22], scoped_organizations: [] },
+ expected: { access_type: 'teams', scoped_teams: [22] },
+ },
+ ])('a step-up pre-selects the earlier grant: $name', ({ requiredAccessLevel, earlierAccess, expected }) => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ oauth_scope_resolution: {
+ scopes: ['comment:write', 'insight:write', 'openid'],
+ was_defaulted: false,
+ already_granted_scopes: ['insight:write', 'openid'],
+ earlier_access: earlierAccess,
+ },
+ } as AppContext
+ const params = new URLSearchParams({
+ client_id: 'test-client',
+ redirect_uri: 'https://example.com/callback',
+ response_type: 'code',
+ scope: 'comment:write',
+ ...(requiredAccessLevel ? { required_access_level: requiredAccessLevel } : {}),
+ })
+
+ router.actions.push(`/oauth/authorize?${params.toString()}`)
+ logic.actions.loadAllTeamsSuccess(HINT_TEAMS as any)
+
+ expect(logic.values.oauthAuthorization).toMatchObject(expected)
+ expect(logic.values.scopeRows.find((r) => r.key === 'insight')).toMatchObject({
+ alreadyGranted: true,
+ locked: true,
+ })
+ })
+
// Before teams load, a pending hint suppresses the eager current-org selection
// (so a fast CTA click can't authorize the wrong project), while the no-hint
// path keeps pre-selecting the current org/team.
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index 057b43d90efa..c53c1ca0a56e 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -25,7 +25,7 @@ import { userLogic } from 'scenes/userLogic'
import type { OAuthApplicationPublicMetadata, OrganizationBasicType, TeamBasicType, UserType } from '~/types'
export type OAuthAuthorizationFormValues = {
- scoped_organizations: number[]
+ scoped_organizations: string[]
scoped_teams: number[]
access_type: 'all' | 'organizations' | 'teams'
}
@@ -43,6 +43,8 @@ export type OAuthScopeRow = ScopePickerRow & {
maxLevel: Exclude<ScopeAccessLevel, 'none'>
/** True when minLevel === maxLevel: nothing to choose, rendered as a locked checkmark row. */
locked: boolean
+ /** True when the floor comes from an earlier grant to this app rather than the app's required scopes. */
+ alreadyGranted: boolean
}
export type OAuthScopeGroup = ScopePickerGroup<OAuthScopeRow>
@@ -53,10 +55,23 @@ export type OAuthScopeGroup = ScopePickerGroup<OAuthScopeRow>
const oauthDisabledReasons = (
minLevel: ScopeAccessLevel,
maxLevel: ScopeAccessLevel,
- appName: string
+ appName: string,
+ alreadyGranted: boolean
): Partial<Record<ScopeAccessLevel, string>> => ({
- ...(minLevel !== 'none' ? { none: `${appName} requires at least ${minLevel} access` } : {}),
- ...(minLevel === 'write' ? { read: `${appName} requires write access` } : {}),
+ ...(minLevel !== 'none'
+ ? {
+ none: alreadyGranted
+ ? `Already granted to ${appName}`
+ : `${appName} requires at least ${minLevel} access`,
+ }
+ : {}),
+ ...(minLevel === 'write'
+ ? {
+ read: alreadyGranted
+ ? `Write access is already granted to ${appName}`
+ : `${appName} requires write access`,
+ }
+ : {}),
...(maxLevel !== 'write' ? { write: `Not requested by ${appName}` } : {}),
})
@@ -199,6 +214,8 @@ export interface oauthAuthorizeLogicValues {
allScopesRequired: boolean
allTeams: TeamBasicType[] | null
allTeamsLoading: boolean
+ alreadyGrantedScopeLevels: Map<string, RequiredLevel>
+ alreadyGrantedScopes: string[]
appName: string
authorizationComplete: boolean
consentResourceScopes: string[]
@@ -286,6 +303,9 @@ export interface oauthAuthorizeLogicActions {
setAllScopeAccess: (level: ScopeAccessLevel) => {
level: ScopeAccessLevel
}
+ setAlreadyGrantedScopes: (alreadyGrantedScopes: string[]) => {
+ alreadyGrantedScopes: string[]
+ }
setAuthorizationComplete: (complete: boolean) => {
complete: boolean
}
@@ -387,7 +407,12 @@ export interface oauthAuthorizeLogicMeta {
) => TeamBasicType[] | null
identityScopeDescriptions: (scopes: string[]) => string[]
requiredScopeLevels: (oauthApplication: OAuthApplicationPublicMetadata | null) => Map<string, RequiredLevel>
- consentResourceScopes: (scopes: string[], oauthApplication: OAuthApplicationPublicMetadata | null) => string[]
+ alreadyGrantedScopeLevels: (alreadyGrantedScopes: string[]) => Map<string, RequiredLevel>
+ consentResourceScopes: (
+ scopes: string[],
+ oauthApplication: OAuthApplicationPublicMetadata | null,
+ alreadyGrantedScopes: string[]
+ ) => string[]
scopeRows: (
consentResourceScopes: string[],
scopeAccessSelections: {
@@ -395,6 +420,7 @@ export interface oauthAuthorizeLogicMeta {
overrides: Record<string, ScopeAccessLevel>
},
requiredScopeLevels: Map<string, RequiredLevel>,
+ alreadyGrantedScopeLevels: Map<string, RequiredLevel>,
appName: string
) => OAuthScopeRow[]
requiredScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
@@ -406,7 +432,8 @@ export interface oauthAuthorizeLogicMeta {
effectiveScopes: (
scopes: string[],
scopeRows: OAuthScopeRow[],
- oauthApplication: OAuthApplicationPublicMetadata | null
+ oauthApplication: OAuthApplicationPublicMetadata | null,
+ alreadyGrantedScopes: string[]
) => string[]
redirectDomain: (oauthApplication: OAuthApplicationPublicMetadata | null) => string
}
@@ -426,6 +453,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
})),
actions({
setScopes: (scopes: string[]) => ({ scopes }),
+ setAlreadyGrantedScopes: (alreadyGrantedScopes: string[]) => ({ alreadyGrantedScopes }),
setScopeAccess: (scopeObject: string, level: ScopeAccessLevel) => ({ scopeObject, level }),
setScopeGroupAccess: (scopeObjects: string[], level: ScopeAccessLevel) => ({ scopeObjects, level }),
setAllScopeAccess: (level: ScopeAccessLevel) => ({ level }),
@@ -529,6 +557,12 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
setScopes: (_, { scopes }) => scopes,
},
],
+ alreadyGrantedScopes: [
+ [] as string[],
+ {
+ setAlreadyGrantedScopes: (_, { alreadyGrantedScopes }) => alreadyGrantedScopes,
+ },
+ ],
// The user's picks. `bulk` is the last bulk action (Select all / Read-only / Deselect
// all); `overrides` are per-object picks made after it. Absent entries default to the
// requested ceiling, and every pick is clamped to [required floor, requested ceiling]
@@ -801,6 +835,13 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
(oauthApplication: OAuthApplicationPublicMetadata | null): Map<string, RequiredLevel> =>
requiredLevelsFromScopes(oauthApplication?.required_scopes ?? []),
],
+ // A step-up keeps what the user granted this app before, so those scopes set a floor
+ // like required scopes do, with their own label.
+ alreadyGrantedScopeLevels: [
+ (s) => [s.alreadyGrantedScopes],
+ (alreadyGrantedScopes: string[]): Map<string, RequiredLevel> =>
+ requiredLevelsFromScopes(alreadyGrantedScopes),
+ ],
// Requested plus required resource scopes, collapsed to the highest action per
// 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
@@ -810,14 +851,18 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
// `*` 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[] => {
+ (s) => [s.scopes, s.oauthApplication, s.alreadyGrantedScopes],
+ (
+ scopes: string[],
+ oauthApplication: OAuthApplicationPublicMetadata | null,
+ alreadyGrantedScopes: string[]
+ ): 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))
: scopes
- const required = (oauthApplication?.required_scopes ?? []).filter(
+ const required = [...(oauthApplication?.required_scopes ?? []), ...alreadyGrantedScopes].filter(
(scope) => scope.includes(':') || scope === '*'
)
return getMinimumEquivalentScopes([...requested, ...required]).filter(
@@ -829,18 +874,29 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
// sets the floor, and the user's selection is clamped between the two — so no pick
// (including bulk actions) can grant more than requested or less than required.
scopeRows: [
- (s) => [s.consentResourceScopes, s.scopeAccessSelections, s.requiredScopeLevels, s.appName],
+ (s) => [
+ s.consentResourceScopes,
+ s.scopeAccessSelections,
+ s.requiredScopeLevels,
+ s.alreadyGrantedScopeLevels,
+ s.appName,
+ ],
(
consentResourceScopes: string[],
scopeAccessSelections: { bulk: ScopeAccessLevel | null; overrides: Record<string, ScopeAccessLevel> },
requiredScopeLevels: Map<string, RequiredLevel>,
+ alreadyGrantedScopeLevels: Map<string, RequiredLevel>,
appName: string
): OAuthScopeRow[] => {
const rows = consentResourceScopes.map((scope): OAuthScopeRow => {
const key = scopeObjectKey(scope)
const maxLevel: 'read' | 'write' = scope === '*' || scope.endsWith(':write') ? 'write' : 'read'
- const minLevel: ScopeAccessLevel = requiredScopeLevels.get(key) ?? 'none'
- const disabledReasons = oauthDisabledReasons(minLevel, maxLevel, appName)
+ const requiredLevel = requiredScopeLevels.get(key)
+ const grantedLevel = alreadyGrantedScopeLevels.get(key)
+ const alreadyGranted =
+ grantedLevel !== undefined && (grantedLevel === 'write' || requiredLevel !== 'write')
+ const minLevel: ScopeAccessLevel = (alreadyGranted ? grantedLevel : requiredLevel) ?? 'none'
+ const disabledReasons = oauthDisabledReasons(minLevel, maxLevel, appName, alreadyGranted)
const selected = scopeAccessSelections.overrides[key] ?? scopeAccessSelections.bulk ?? maxLevel
const value = clampScopeLevel({ key, label: key, value: selected, disabledReasons }, selected)
const apiScope = key === '*' ? undefined : API_SCOPES.find((s) => s.key === key)
@@ -857,6 +913,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
maxLevel,
value,
locked: minLevel === maxLevel,
+ alreadyGranted,
}
})
return rows.sort((a, b) => a.label.localeCompare(b.label))
@@ -892,11 +949,12 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
adjustableScopeRows.some((row) => row.maxLevel === 'write'),
],
effectiveScopes: [
- (s) => [s.scopes, s.scopeRows, s.oauthApplication],
+ (s) => [s.scopes, s.scopeRows, s.oauthApplication, s.alreadyGrantedScopes],
(
scopes: string[],
scopeRows: OAuthScopeRow[],
- oauthApplication: OAuthApplicationPublicMetadata | null
+ oauthApplication: OAuthApplicationPublicMetadata | null,
+ alreadyGrantedScopes: string[]
): string[] => {
const identity = scopes.filter((scope) => IDENTITY_SCOPES.includes(scope))
const resources = scopeRows.flatMap((row) => {
@@ -918,7 +976,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
})
// Also grant the required strings verbatim: collapsing read+write pairs above
// could otherwise drop a literal entry the server's set-difference check expects.
- const required = (oauthApplication?.required_scopes ?? []).filter(
+ const required = [...(oauthApplication?.required_scopes ?? []), ...alreadyGrantedScopes].filter(
(scope) => scope.includes(':') || scope === '*'
)
return Array.from(new Set([...identity, ...resources, ...required]))
@@ -966,9 +1024,26 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
const teamIdParam = Number(searchParams['team_id'])
const teamHint = Number.isInteger(teamIdParam) && teamIdParam > 0 ? teamIdParam : null
+ // A step-up keeps the projects the token already applies to, so the screen starts there.
+ // The user can still pick others.
+ const earlierAccess = scopeResolution?.earlier_access
+ const earlierTeam = requiredAccessLevel === 'team' ? (earlierAccess?.scoped_teams[0] ?? null) : null
+
actions.setScopesWereDefaulted(scopesWereDefaulted)
- actions.setTeamHint(teamHint)
+ actions.setAlreadyGrantedScopes(scopeResolution?.already_granted_scopes ?? [])
+ actions.setTeamHint(teamHint ?? earlierTeam)
actions.setRequiredAccessLevel(requiredAccessLevel || null)
+ if (earlierAccess && !requiredAccessLevel) {
+ actions.setOauthAuthorizationValues(
+ earlierAccess.scoped_teams.length
+ ? { access_type: 'teams', scoped_teams: earlierAccess.scoped_teams }
+ : earlierAccess.scoped_organizations.length
+ ? { access_type: 'organizations', scoped_organizations: earlierAccess.scoped_organizations }
+ : { access_type: 'all' }
+ )
+ } else if (earlierAccess?.scoped_organizations.length && requiredAccessLevel === 'organization') {
+ actions.setOauthAuthorizationValue('scoped_organizations', [earlierAccess.scoped_organizations[0]])
+ }
actions.loadOAuthApplication()
actions.loadAllTeams()
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 5b72274e7760..61d98181739f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7935,6 +7935,10 @@ export type OAuthScopeResolution = {
scopes: string[]
/** Whether the client sent no usable `scope` (omitted, or cut off mid-token), so the server picked the set. */
was_defaulted: boolean
+ /** Scopes of `scopes` the user granted this app before, which a step-up keeps. Shown as granted and not removable. */
+ already_granted_scopes?: string[]
+ /** Where the newest earlier grant applies. A step-up pre-selects it, so the token keeps its projects. Both lists empty means all of them. */
+ earlier_access?: { scoped_teams: number[]; scoped_organizations: string[] }
}
export type OAuthApplicationPublicMetadata = {
diff --git a/posthog/api/oauth/mcp_resource_scopes.py b/posthog/api/oauth/mcp_resource_scopes.py
index 3f2cf7be4e34..8945da736586 100644
--- a/posthog/api/oauth/mcp_resource_scopes.py
+++ b/posthog/api/oauth/mcp_resource_scopes.py
@@ -61,8 +61,13 @@ def mcp_advertised_scopes() -> list[str]:
return [scope for scope in get_oauth_scopes_supported() if ":" not in scope or scope in required]
-def build_oauth_mcp_consent_context(resource_url: str | None) -> OAuthMcpConsentContext | None:
+def build_oauth_mcp_consent_context(
+ resource_url: str | None, scopes: list[str] | None = None
+) -> OAuthMcpConsentContext | None:
+ """`scopes` replaces the advertised set when the server already resolved what the screen lists."""
if not resource_url or not is_trusted_posthog_mcp_resource(resource_url):
return None
- return OAuthMcpConsentContext(is_mcp_resource=True, scopes=mcp_advertised_scopes())
+ return OAuthMcpConsentContext(
+ is_mcp_resource=True, scopes=scopes if scopes is not None else mcp_advertised_scopes()
+ )
diff --git a/posthog/api/oauth/step_up.py b/posthog/api/oauth/step_up.py
new file mode 100644
index 000000000000..5c33010df726
--- /dev/null
+++ b/posthog/api/oauth/step_up.py
@@ -0,0 +1,185 @@
+from collections.abc import Iterable
+
+from django.db.models import Q, QuerySet
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.scopes import clamp_scopes_to_ceiling, scopes_not_covered
+
+# What a step-up app gets on its first connection to the MCP resource. The list comes from MCP
+# tool usage: a scope is in when the tools that need it are among the ones most OAuth users call,
+# so most sessions never need a step-up. Organization and user stay read-only. `project:write` is
+# in because routine project setup (replay sampling, test account filters, cookieless mode) would
+# otherwise send many users to a step-up. `endpoint:write` is in for pushing endpoints from the
+# CLI. A write scope covers its read, so no object appears twice. Anything else arrives through
+# step-up when a tool first needs it.
+STEP_UP_DEFAULT_RESOURCE_SCOPES: frozenset[str] = frozenset(
+ [
+ *(
+ f"{scope_object}:write"
+ for scope_object in (
+ "action",
+ "alert",
+ "annotation",
+ "cohort",
+ "dashboard",
+ "data_catalog",
+ "endpoint",
+ "error_tracking",
+ "event_definition",
+ "experiment",
+ "external_data_source",
+ "feature_flag",
+ "heatmap",
+ "hog_flow",
+ "hog_function",
+ "insight",
+ "insight_variable",
+ "llm_skill",
+ "marketing_analytics",
+ "notebook",
+ "person",
+ "product_enablement",
+ "project",
+ "property_definition",
+ "replay_scanner",
+ "session_recording_playlist",
+ "signal_scout",
+ "subscription",
+ "survey",
+ "task",
+ "warehouse_view",
+ )
+ ),
+ *(
+ f"{scope_object}:read"
+ for scope_object in (
+ "activity_log",
+ "batch_export",
+ "billing",
+ "business_knowledge",
+ "dashboard_template",
+ "early_access_feature",
+ "evaluation",
+ "experiment_saved_metric",
+ "group",
+ "health_issue",
+ "integration",
+ "llm_prompt",
+ "logs",
+ "mcp_analytics",
+ "organization",
+ "organization_member",
+ "query",
+ "session_recording",
+ "ticket",
+ "tracing",
+ "user",
+ "warehouse_table",
+ "web_analytics",
+ )
+ ),
+ ]
+)
+
+
+@frozen
+class GrantAccess:
+ scoped_teams: list[int]
+ scoped_organizations: list[str]
+ """Both lists empty means the grant reaches everything the user can reach."""
+
+
+@frozen
+class StepUpGrant:
+ scopes: list[str]
+ """What the grant carries, which the consent screen lists in full."""
+ already_granted_scopes: list[str]
+ """Scopes of the grant this user granted the app before, which the screen shows as granted."""
+ earlier_access: GrantAccess | None
+ """Where the newest earlier grant applies. The consent screen pre-selects it, so a step-up keeps the token's projects."""
+
+
+def resolve_step_up_grant(
+ *, requested: Iterable[str], application: OAuthApplication, user_id: int, required: Iterable[str]
+) -> StepUpGrant:
+ """Scopes for an MCP authorization by an app that supports step-up.
+
+ A first connection gets the request narrowed to the default set. A step-up keeps every scope
+ this user already granted this app and adds the request, with no cap: some clients
+ re-authorize with only the challenged scopes, and they must not lose what they had.
+ """
+ requested = list(requested)
+ granted = live_granted_scopes(application=application, user_id=user_id)
+ if granted is None:
+ narrowed = narrow_to_step_up_default(requested)
+ # A request with nothing in the default set is already narrow. Narrowing it to identity
+ # scopes alone would only force a second consent for the scope it asked for.
+ if not any(":" in scope for scope in narrowed):
+ narrowed = requested
+ return StepUpGrant(scopes=sorted(_union(narrowed, required)), already_granted_scopes=[], earlier_access=None)
+
+ # The ceiling may have shrunk since an older grant. Clamp as `validate_scopes` does, so the
+ # screen never promises a scope the new grant cannot carry.
+ granted = set(clamp_scopes_to_ceiling(granted, application.ceiling_scopes, allow_wildcard_under_empty_ceiling=True))
+ scopes = sorted(_union(granted, requested, required))
+ already_granted = [scope for scope in scopes if not scopes_not_covered(granted, [scope])]
+ return StepUpGrant(
+ scopes=scopes,
+ already_granted_scopes=already_granted,
+ earlier_access=newest_live_grant_access(application=application, user_id=user_id),
+ )
+
+
+def narrow_to_step_up_default(requested: Iterable[str]) -> list[str]:
+ narrowed: list[str] = []
+ for scope in requested:
+ if scope == "*":
+ narrowed.extend(sorted(STEP_UP_DEFAULT_RESOURCE_SCOPES))
+ elif ":" not in scope or not scopes_not_covered(STEP_UP_DEFAULT_RESOURCE_SCOPES, [scope]):
+ narrowed.append(scope)
+ elif scope.endswith(":write"):
+ read_scope = f"{scope.removesuffix(':write')}:read"
+ if not scopes_not_covered(STEP_UP_DEFAULT_RESOURCE_SCOPES, [read_scope]):
+ narrowed.append(read_scope)
+ return _union(narrowed)
+
+
+def live_granted_scopes(*, application: OAuthApplication, user_id: int) -> set[str] | None:
+ """Every scope this user granted this app on a grant that still works, or None when there is none.
+
+ A grant works while its access token is unexpired or its refresh token is unrevoked. The refresh
+ token outlives the access token, so a client whose access token expired still counts as
+ connected and keeps its scopes. Tokens minted during staff impersonation are left out, because
+ the user did not grant those.
+ """
+ granted: set[str] | None = None
+ for scope_string in _live_access_tokens(application, user_id).values_list("scope", flat=True):
+ granted = (granted or set()) | set((scope_string or "").split())
+ return granted
+
+
+def newest_live_grant_access(*, application: OAuthApplication, user_id: int) -> GrantAccess | None:
+ newest = (
+ _live_access_tokens(application, user_id)
+ .order_by("-created")
+ .values("scoped_teams", "scoped_organizations")
+ .first()
+ )
+ if newest is None:
+ return None
+ return GrantAccess(
+ scoped_teams=list(newest["scoped_teams"] or []),
+ scoped_organizations=[str(org) for org in newest["scoped_organizations"] or []],
+ )
+
+
+def _live_access_tokens(application: OAuthApplication, user_id: int) -> QuerySet[OAuthAccessToken]:
+ return OAuthAccessToken.objects.filter(
+ application=application, user_id=user_id, impersonated_by__isnull=True
+ ).filter(Q(expires__gt=timezone.now()) | Q(refresh_token__isnull=False, refresh_token__revoked__isnull=True))
+
+
+def _union(*scope_lists: Iterable[str]) -> list[str]:
+ return list(dict.fromkeys(scope for scopes in scope_lists for scope in scopes))
diff --git a/posthog/api/oauth/test_step_up.py b/posthog/api/oauth/test_step_up.py
new file mode 100644
index 000000000000..29ff7e113b65
--- /dev/null
+++ b/posthog/api/oauth/test_step_up.py
@@ -0,0 +1,9 @@
+from django.test import SimpleTestCase
+
+from posthog.api.oauth.step_up import STEP_UP_DEFAULT_RESOURCE_SCOPES
+from posthog.scopes import get_oauth_scopes_supported
+
+
+class TestStepUpDefaultScopes(SimpleTestCase):
+ def test_every_default_scope_is_grantable_over_oauth(self):
+ self.assertEqual(STEP_UP_DEFAULT_RESOURCE_SCOPES - set(get_oauth_scopes_supported()), set())
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 0a581340baca..0fc11e2eb6ae 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -82,6 +82,9 @@ def private_pem_to_public_pem(private_key_pem: str) -> str:
return public_pem(private_key.public_key())
+MCP_RESOURCE_PARAM = "&resource=https%3A%2F%2Fmcp.posthog.com%2Fmcp"
+
+
class TestOAuthAPI(APIBaseTest):
def setUp(self):
super().setUp()
@@ -330,6 +333,113 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(resolution["scopes"], sorted({"insight:read", "canvas:read"} | ALWAYS_ALLOWED_SCOPES))
self.assertTrue(resolution["was_defaulted"])
+ @parameterized.expand(
+ [
+ (
+ "step_up_first_connection",
+ True,
+ "openid insight:write batch_export:write comment:write",
+ ["batch_export:read", "insight:write", "openid"],
+ ),
+ (
+ "no_step_up",
+ False,
+ "openid insight:write batch_export:write comment:write",
+ ["batch_export:write", "comment:write", "insight:write", "openid"],
+ ),
+ ("step_up_nothing_in_default_set", True, "openid comment:write", ["comment:write", "openid"]),
+ ]
+ )
+ def test_mcp_authorize_narrows_the_first_connection_of_a_step_up_app(
+ self, _name, supports_step_up, requested, expected
+ ):
+ self.confidential_application.supports_step_up = supports_step_up
+ self.confidential_application.save()
+
+ response = self.client.get(
+ f"{self.base_authorization_url}&scope={quote(requested)}&resource=https%3A%2F%2Fmcp.posthog.com%2Fmcp"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ resolution = response.context["posthog_app_context"]["oauth_scope_resolution"]
+ self.assertEqual(sorted(resolution["scopes"]), expected)
+
+ @parameterized.expand(
+ [
+ (
+ "step_up",
+ True,
+ MCP_RESOURCE_PARAM,
+ "comment:write insight:write openid",
+ ["comment:write", "insight:write", "openid"],
+ ["insight:write", "openid"],
+ {"openid", "insight:write", "comment:write"},
+ ),
+ ("no_step_up", False, MCP_RESOURCE_PARAM, "comment:write", ["comment:write"], None, {"comment:write"}),
+ ("step_up_outside_mcp", True, "", "comment:write", ["comment:write"], None, {"comment:write"}),
+ # A tampered form still gets nothing outside the app's ceiling.
+ (
+ "step_up_tampered_form",
+ True,
+ MCP_RESOURCE_PARAM,
+ "comment:write insight:write openid llm_gateway:read",
+ ["comment:write", "insight:write", "openid"],
+ ["insight:write", "openid"],
+ {"openid", "insight:write", "comment:write"},
+ ),
+ ]
+ )
+ @time_machine.travel("2026-03-01 12:00:00", tick=False)
+ def test_mcp_reauthorize_keeps_prior_scopes_and_preselects_the_prior_projects_for_a_step_up_app(
+ self,
+ _name,
+ supports_step_up,
+ resource_param,
+ submitted_scope,
+ expected_consent,
+ expected_already_granted,
+ expected_token_scopes,
+ ):
+ self.confidential_application.supports_step_up = supports_step_up
+ self.confidential_application.save()
+ expired_access_token = OAuthAccessToken.objects.create(
+ application=self.confidential_application,
+ user=self.user,
+ token="pha_prior_grant",
+ expires=timezone.now() - timedelta(hours=1),
+ # `llm_gateway:read` sits outside the app's ceiling, as after the ceiling shrank.
+ scope="openid insight:write llm_gateway:read",
+ scoped_teams=[self.team.id],
+ )
+ OAuthRefreshToken.objects.create(
+ application=self.confidential_application,
+ user=self.user,
+ token="prior_refresh_token",
+ access_token=expired_access_token,
+ )
+
+ consent = self.client.get(f"{self.base_authorization_url}&scope={quote('comment:write')}{resource_param}")
+ authorize = self.client.post(
+ "/oauth/authorize/",
+ {
+ **self.base_authorization_post_body,
+ "scope": submitted_scope,
+ "access_level": OAuthApplicationAccessLevel.TEAM.value,
+ "scoped_teams": [self.team.id],
+ },
+ )
+ code = authorize.json()["redirect_to"].split("code=")[1].split("&")[0]
+ token = self.post("/oauth/token/", {**self.base_token_body, "code": code}).json()
+
+ resolution = consent.context["posthog_app_context"]["oauth_scope_resolution"]
+ self.assertEqual(resolution["scopes"], expected_consent)
+ self.assertEqual(resolution.get("already_granted_scopes"), expected_already_granted)
+ self.assertEqual(
+ resolution.get("earlier_access"),
+ {"scoped_teams": [self.team.id], "scoped_organizations": []} if expected_already_granted else None,
+ )
+ self.assertEqual(set(token["scope"].split()), expected_token_scopes)
+
@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 14fae2b3b64d..77dfe10e09e9 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -62,7 +62,7 @@ from posthog.api.oauth.client_assertion import (
verify_client_assertion,
)
from posthog.api.oauth.client_auth import verify_client_secret
-from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context
+from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context, is_trusted_posthog_mcp_resource
from posthog.api.oauth.metadata import (
Document,
authorization_server_metadata,
@@ -70,6 +70,7 @@ from posthog.api.oauth.metadata import (
openid_provider_metadata,
protected_resource_metadata,
)
+from posthog.api.oauth.step_up import resolve_step_up_grant
from posthog.auth import IDJagAccessTokenAuthentication, SessionAuthentication
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
from posthog.helpers.oauth_pending_connection import (
@@ -1682,6 +1683,18 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
impersonator_id = _impersonator_id_for_request(request)
credentials["impersonated_by_id"] = impersonator_id
+ required_resource_scopes = {scope for scope in application.required_scopes if ":" in scope}
+ resource = request.query_params.get("resource")
+ step_up_grant = None
+ if application.supports_step_up and resource and is_trusted_posthog_mcp_resource(resource):
+ step_up_grant = resolve_step_up_grant(
+ requested=scopes,
+ application=application,
+ user_id=request.user.id,
+ required=required_resource_scopes,
+ )
+ scopes = step_up_grant.scopes
+
scope_str = " ".join(scopes)
if is_read_only_impersonation(request):
scope_str = downgrade_scopes_to_read_only(scope_str)
@@ -1709,7 +1722,6 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# Check for auto-approval. Skipped when the request omits a required scope:
# auto-approving would mint a grant below the app's required floor, so fall
# through to the consent screen, which displays and grants the full required set.
- required_resource_scopes = {scope for scope in application.required_scopes if ":" in scope}
if request.query_params.get(
"approval_prompt", oauth2_settings.REQUEST_APPROVAL_PROMPT
) == "auto" and required_resource_scopes <= set(scope_str.split()):
@@ -1744,6 +1756,11 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
except OAuthToolkitError as error:
return self.error_response(error, application, state=request.query_params.get("state"))
+ # The consent screen shows these as granted and not removable, and submits them with the rest.
+ already_granted_scopes = step_up_grant.already_granted_scopes if step_up_grant else []
+ if already_granted_scopes and is_read_only_impersonation(request):
+ already_granted_scopes = downgrade_scopes_to_read_only(" ".join(already_granted_scopes)).split()
+
template_context: dict[str, object] = {
"oauth_application": {
"name": application.name,
@@ -1768,6 +1785,17 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
"oauth_scope_resolution": {
"scopes": scope_str.split(),
"was_defaulted": scopes_were_defaulted,
+ **({"already_granted_scopes": already_granted_scopes} if already_granted_scopes else {}),
+ **(
+ {
+ "earlier_access": {
+ "scoped_teams": step_up_grant.earlier_access.scoped_teams,
+ "scoped_organizations": step_up_grant.earlier_access.scoped_organizations,
+ }
+ }
+ if step_up_grant and step_up_grant.earlier_access
+ else {}
+ ),
},
}
@@ -1779,7 +1807,9 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
)
if scopes_were_defaulted:
- oauth_mcp_consent = build_oauth_mcp_consent_context(request.query_params.get("resource"))
+ oauth_mcp_consent = build_oauth_mcp_consent_context(
+ request.query_params.get("resource"), scopes=scope_str.split() if step_up_grant else None
+ )
if oauth_mcp_consent is not None:
template_context["oauth_mcp_consent"] = oauth_mcp_consent