: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): let people choose scopes when approving a device login (#128859)
Rafael Audibert58fd2f7051c2
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 89fa3e1f2f97..eedf13c1c01a 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -39,6 +39,8 @@ export interface DeviceApprovalApi {user_code: string/** The project the token is scoped to. */project_id: number+ /** The requested scopes the person kept. Leave it out to grant every requested scope. It must include every scope in `required_scopes`, and nothing outside the requested scopes. */+ scopes?: string[]}/**@@ -99,6 +101,8 @@ export interface DeviceGrantDetailsApi {is_verified: boolean/** The scopes the token will carry if the person approves. */scopes: string[]+ /** The requested scopes the person can't leave out: the client's required scopes and identity scopes such as `openid`. */+ required_scopes: string[]/** The scopes the person already gave this client, per project. A step-up in a project asks for these plus new ones, and the page lists only the new ones. */granted_scopes: GrantedScopesApi[]/** When the code expires. */diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex fd117b485ea4..50af787c08bf 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -196,7 +196,7 @@ export const getOauthDeviceApproveCreateUrl = () => {}/**- * Approve a device grant for one project. The token gets the scopes `lookup` showed.+ * Approve a device grant for one project. The token gets the requested scopes the person kept.*/export const oauthDeviceApproveCreate = async (deviceApprovalApi: DeviceApprovalApi,diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 53c1499da095..85a5f8b525ed 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -10,7 +10,7 @@import * as zod from 'zod'/**- * Approve a device grant for one project. The token gets the scopes `lookup` showed.+ * Approve a device grant for one project. The token gets the requested scopes the person kept.*/export const oauthDeviceApproveCreateBodyUserCodeMax = 20@@ -20,6 +20,12 @@ export const OauthDeviceApproveCreateBody = /* @__PURE__ */ zod.object({.max(oauthDeviceApproveCreateBodyUserCodeMax).describe("The code the device shows, as the person typed it. Case and dashes don't matter."),project_id: zod.number().describe('The project the token is scoped to.'),+ scopes: zod+ .array(zod.string())+ .optional()+ .describe(+ 'The requested scopes the person kept. Leave it out to grant every requested scope. It must include every scope in `required_scopes`, and nothing outside the requested scopes.'+ ),})/**diff --git a/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsx b/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsxnew file mode 100644index 000000000000..144819958d3d--- /dev/null+++ b/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsx@@ -0,0 +1,89 @@+import { IconCheck } from '@posthog/icons'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import type { OAuthScopeGroup, OAuthScopeRow } from 'lib/oauthScopeRows'+import type { ScopeAccessLevel } from 'lib/scopes'++import { ScopeAccessGroup } from './ScopeAccessGroup'+import { ScopeAccessRow } from './ScopeAccessRow'++interface OAuthScopeListProps {+ appName: string+ identityScopeDescriptions: string[]+ /** Rows with nothing to choose, shown as a checkmark list. */+ requiredScopeRows: OAuthScopeRow[]+ adjustableScopeRows: OAuthScopeRow[]+ /** The adjustable rows in groups, or null to list them flat. */+ scopeGroups: OAuthScopeGroup[] | null+ /** Hides the "Required" tag when every row is required, because it then tells the person nothing. */+ allScopesRequired: boolean+ onChangeRow: (scopeObject: string, level: ScopeAccessLevel) => void+ onChangeGroup: (scopeObjects: string[], level: ScopeAccessLevel) => void+ dataAttrPrefix: string+}++/** The permissions an OAuth client asks for: fixed ones as checkmarks, the rest with an access control. */+export function OAuthScopeList({+ appName,+ identityScopeDescriptions,+ requiredScopeRows,+ adjustableScopeRows,+ scopeGroups,+ allScopesRequired,+ onChangeRow,+ onChangeGroup,+ dataAttrPrefix,+}: OAuthScopeListProps): JSX.Element {+ return (+ <>+ {(identityScopeDescriptions.length > 0 || requiredScopeRows.length > 0) && (+ <ul className="space-y-2">+ {identityScopeDescriptions.map((description) => (+ <li key={description} className="flex items-center space-x-2">+ <IconCheck color="var(--success)" className="shrink-0" />+ <span className="font-medium">{description}</span>+ </li>+ ))}+ {requiredScopeRows.map((row) => (+ <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>+ {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>+ ))}+ </ul>+ )}+ {scopeGroups ? (+ <div className="flex flex-col">+ {scopeGroups.map((group) => (+ <ScopeAccessGroup+ key={group.label}+ group={group}+ onChangeRow={onChangeRow}+ onChangeGroup={onChangeGroup}+ dataAttrPrefix={dataAttrPrefix}+ />+ ))}+ </div>+ ) : (+ adjustableScopeRows.length > 0 && (+ <div className="flex flex-col">+ {adjustableScopeRows.map((row) => (+ <ScopeAccessRow key={row.key} row={row} onChange={onChangeRow} />+ ))}+ </div>+ )+ )}+ </>+ )+}diff --git a/frontend/src/lib/oauthScopeRows.ts b/frontend/src/lib/oauthScopeRows.tsnew file mode 100644index 000000000000..bec50034d11a--- /dev/null+++ b/frontend/src/lib/oauthScopeRows.ts@@ -0,0 +1,166 @@+import {+ API_SCOPES,+ clampScopeLevel,+ getScopeDescription,+ groupScopeRows,+ type ScopeAccessLevel,+ type ScopePickerGroup,+ type ScopePickerRow,+} from 'lib/scopes'++export const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'introspection']++const scopeObjectKey = (scope: string): string => (scope === '*' ? '*' : scope.split(':')[0])++export type OAuthScopeRow = ScopePickerRow & {+ /** Full sentence description at the granted level, for the locked (checkmark) list. */+ description: string+ /** Required floor — the grant can never go below this. 'none' when not required. */+ minLevel: ScopeAccessLevel+ /** Requested ceiling — the grant can never go above what the client asked for. */+ 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>++// The floor and the ceiling as the reasons a level is not available, in the words the row shows.+// The shared clamp and group control work from these, so a group set to write holds a read-only+// row at read and a group set to none holds a required row at read.+const oauthDisabledReasons = (+ minLevel: ScopeAccessLevel,+ maxLevel: ScopeAccessLevel,+ appName: string,+ alreadyGranted: boolean+): Partial<Record<ScopeAccessLevel, string>> => ({+ ...(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}` } : {}),+})++const WILDCARD_LABEL = 'All PostHog data'++// A request with this many adjustable rows or fewer shows a flat alphabetical list. Group+// headers only help when the list is long.+export const SCOPE_GROUPING_MIN_ROWS = 10++// Fallback for scopes absent from API_SCOPES (e.g. server-side scopes the local list lags+// behind) — derive a readable label from the raw key.+const humanizeScopeKey = (key: string): string => {+ const humanized = key.replace(/_/g, ' ')+ return humanized.charAt(0).toUpperCase() + humanized.slice(1)+}++// Required scopes are tracked per object at the action level that's required, so a+// required `obj:read` still lets the read-only toggle downgrade an optional `obj:write`.+export type RequiredLevel = 'read' | 'write'++export const requiredLevelsFromScopes = (requiredScopes: string[]): Map<string, RequiredLevel> => {+ const levels = new Map<string, RequiredLevel>()+ for (const scope of requiredScopes) {+ if (!scope.includes(':') && scope !== '*') {+ continue+ }+ const key = scopeObjectKey(scope)+ const level: RequiredLevel = scope === '*' || scope.endsWith(':write') ? 'write' : 'read'+ if (level === 'write' || !levels.has(key)) {+ levels.set(key, level)+ }+ }+ return levels+}++export type ScopeAccessSelections = { bulk: ScopeAccessLevel | null; overrides: Record<string, ScopeAccessLevel> }++// One row per scope object. The requested set caps the ceiling, the required set+// 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.+export function buildOAuthScopeRows(+ consentResourceScopes: string[],+ scopeAccessSelections: ScopeAccessSelections,+ 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 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)+ const grantedScope = scope === '*' && value === 'write' ? '*' : `${key}:${value}`+ return {+ key,+ label: key === '*' ? WILDCARD_LABEL : (apiScope?.objectName ?? humanizeScopeKey(key)),+ description: getScopeDescription(grantedScope) ?? grantedScope,+ info: apiScope?.info,+ warning: value === 'none' ? undefined : apiScope?.warnings?.[value],+ muted: value === 'none',+ disabledReasons,+ minLevel,+ maxLevel,+ value,+ locked: minLevel === maxLevel,+ alreadyGranted,+ }+ })+ return rows.sort((a, b) => a.label.localeCompare(b.label))+}++// The resource scopes the rows grant. `wildcardRead` gives the read-only form of `*`.+export function grantedResourceScopes(+ scopeRows: OAuthScopeRow[],+ requestedScopes: string[],+ wildcardRead: () => string[]+): string[] {+ return scopeRows.flatMap((row) => {+ if (row.value === 'none') {+ return []+ }+ if (row.key === '*') {+ return row.value === 'write' ? ['*'] : wildcardRead()+ }+ // Write grants read too, but clients diff the granted `scope` against what they+ // asked for, so a missing `:read` reads as a partial grant. Spell both out when+ // the client asked for both, and only then: granting a half it never requested+ // is the same mismatch in the other direction.+ if (row.value === 'write') {+ const readScope = `${row.key}:read`+ return requestedScopes.includes(readScope) ? [readScope, `${row.key}:write`] : [`${row.key}:write`]+ }+ return [`${row.key}:${row.value}`]+ })+}++// What the consent list shows for the identity scopes a client asked for, such as `openid`.+export function identityScopeDescriptions(scopes: string[]): string[] {+ return scopes+ .filter((scope) => IDENTITY_SCOPES.includes(scope))+ .map(getScopeDescription)+ .filter((description): description is string => !!description)+}++// The adjustable rows in groups, or null when the list is short enough to show flat.+export function scopeGroupsToShow(adjustableScopeRows: OAuthScopeRow[]): OAuthScopeGroup[] | null {+ return adjustableScopeRows.length > SCOPE_GROUPING_MIN_ROWS ? groupScopeRows(adjustableScopeRows) : null+}diff --git a/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsx b/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsxindex 37edbf99a491..c53043700bb0 100644--- a/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsx+++ b/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsx@@ -1,8 +1,8 @@import { useActions, useValues } from 'kea'-import { IconCheck } from '@posthog/icons'-import { LemonButton, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'+import { LemonButton, LemonCollapse, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'+import { OAuthScopeList } from 'lib/components/ScopeAccessRow/OAuthScopeList'import { LemonField } from 'lib/lemon-ui/LemonField'import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'@@ -32,10 +32,25 @@ export function OAuthDeviceAuthorize(): JSX.Element {decisionLoading,error,isStepUp,- scopeDescriptions,+ identityScopeDescriptions,+ requiredScopeRows,+ adjustableScopeRows,+ scopeGroups,+ allScopesRequired,+ scopeSummary,+ keptScopes,} = useValues(oauthDeviceAuthorizeLogic)- const { setUserCode, lookUpCode, setOrganizationId, setProjectId, loadProjects, approve, deny } =- useActions(oauthDeviceAuthorizeLogic)+ const {+ setUserCode,+ lookUpCode,+ setOrganizationId,+ setProjectId,+ loadProjects,+ approve,+ deny,+ setScopeAccess,+ setScopeGroupAccess,+ } = useActions(oauthDeviceAuthorizeLogic)if (decision) {const approved = decision === 'authorized'@@ -160,21 +175,33 @@ export function OAuthDeviceAuthorize(): JSX.Element {</div></AuthBanner>)}- <div>- <p className="mb-2 font-semibold">- {isStepUp- ? `${deviceGrant.client_name} keeps the access you gave it, and will also be able to:`- : `${deviceGrant.client_name} will be able to:`}- </p>- <ul className="max-h-64 overflow-y-auto space-y-1 pr-1">- {scopeDescriptions.map((description) => (- <li key={description} className="flex items-center gap-2">- <IconCheck color="var(--success)" className="shrink-0" />- <span>{description}</span>- </li>- ))}- </ul>- </div>+ <LemonCollapse+ panels={[+ {+ key: 'permissions',+ header: (+ <span className="font-semibold" data-attr="oauth-device-scope-summary">+ {scopeSummary}+ </span>+ ),+ content: (+ <div className="flex flex-col gap-3">+ <OAuthScopeList+ appName={deviceGrant.client_name}+ identityScopeDescriptions={identityScopeDescriptions}+ requiredScopeRows={requiredScopeRows}+ adjustableScopeRows={adjustableScopeRows}+ scopeGroups={scopeGroups}+ allScopesRequired={allScopesRequired}+ onChangeRow={setScopeAccess}+ onChangeGroup={setScopeGroupAccess}+ dataAttrPrefix="oauth-device-scope-group"+ />+ </div>+ ),+ },+ ]}+ />{error && <AuthBanner variant="danger">{error}</AuthBanner>}<div className="grid grid-cols-2 gap-2"><LemonButton@@ -196,7 +223,13 @@ export function OAuthDeviceAuthorize(): JSX.Element {size="large"onClick={approve}loading={decisionLoading}- disabledReason={projectId === null ? 'Select a project first' : undefined}+ disabledReason={+ projectId === null+ ? 'Select a project first'+ : keptScopes.length === 0+ ? 'Give at least one permission first'+ : undefined+ }>Approve</LemonButton>diff --git a/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.ts b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.tsindex 3f8363e5ab92..0fe520a0a0c0 100644--- a/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.ts+++ b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.ts@@ -16,6 +16,7 @@ const GRANT: DeviceGrantDetailsApi = {logo_uri: null,is_verified: false,scopes: ['openid', 'insight:read', 'insight:write', 'dashboard:write'],+ required_scopes: ['openid'],granted_scopes: [],expires_at: '2026-03-02T10:30:00Z',}@@ -45,12 +46,10 @@ describe('oauthDeviceAuthorizeLogic', () => {initKeaTests()})- const ALL = ['View your User ID', 'Write access to insights', 'Write access to dashboards']-it.each([- ['a first login lists every requested scope', [], ALL, false],+ ['a first login', [], false],[- 'a login that adds nothing in the project lists every scope',+ 'a login that adds nothing in the project',[{project_id: 42,@@ -58,28 +57,20 @@ describe('oauthDeviceAuthorizeLogic', () => {scopes: ['openid', 'insight:read', 'insight:write', 'dashboard:write'],},],- ALL,false,],+ ['a step-up', [{ project_id: 42, organization_id: null, scopes: ['openid', 'insight:read'] }], true],[- 'a step-up lists only the scopes it adds in the project',- [{ project_id: 42, organization_id: null, scopes: ['openid', 'insight:read'] }],- ['Write access to insights', 'Write access to dashboards'],- true,- ],- [- 'scopes granted in another organization count for nothing here',+ 'a login after a grant in another organization',[{ project_id: null, organization_id: 'another-org', scopes: ['openid', 'insight:read'] }],- ALL,false,],[- 'scopes granted in another project count for nothing here',+ 'a login after a grant in another project',[{ project_id: 7, organization_id: null, scopes: ['openid', 'insight:read'] }],- ALL,false,],- ])('%s', async (_name, grantedScopes, expectedDescriptions, isStepUp) => {+ ])('%s lets the person lower every scope the client does not require', async (_name, grantedScopes, isStepUp) => {useGrantMocks({ ...GRANT, granted_scopes: grantedScopes })const logic = oauthDeviceAuthorizeLogic()logic.mount()@@ -89,7 +80,28 @@ describe('oauthDeviceAuthorizeLogic', () => {logic.actions.setProjectId(42)expect(lookups).toEqual(['BCDF-GHJK'])- await expectLogic(logic).toMatchValues({ isStepUp, scopeDescriptions: expectedDescriptions })+ expect(logic.values.scopeRows.map((row) => [row.key, row.minLevel])).toEqual([+ ['dashboard', 'none'],+ ['insight', 'none'],+ ])+ await expectLogic(logic).toMatchValues({ isStepUp, scopeSummary: 'hog can view and change data in 2 areas.' })+ })++ it('approves only the scopes the person kept, at the level they picked', async () => {+ useGrantMocks(GRANT)+ const logic = oauthDeviceAuthorizeLogic()+ logic.mount()+ router.actions.push(urls.oauthDeviceAuthorize(), { code: 'bcdf-ghjk' })+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setProjectId(42)+ logic.actions.setScopeAccess('dashboard', 'none')+ logic.actions.setScopeAccess('insight', 'read')+ logic.actions.approve()+ await expectLogic(logic).toFinishAllListeners()++ expect(approvals).toEqual([{ user_code: 'BCDF-GHJK', project_id: 42, scopes: ['openid', 'insight:read'] }])+ await expectLogic(logic).toMatchValues({ scopeSummary: 'hog can view data in 1 area.' })})it("drops the previous organization's projects when the next ones fail to load", async () => {@@ -123,7 +135,13 @@ describe('oauthDeviceAuthorizeLogic', () => {logic.actions.approve()await expectLogic(logic).toFinishAllListeners()- expect(approvals).toEqual([{ user_code: 'BCDF-GHJK', project_id: 42 }])+ expect(approvals).toEqual([+ {+ user_code: 'BCDF-GHJK',+ project_id: 42,+ scopes: ['openid', 'dashboard:write', 'insight:read', 'insight:write'],+ },+ ])await expectLogic(logic).toMatchValues({ decision: 'authorized' })})diff --git a/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.ts b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.tsindex a56081d95728..6b343367fc11 100644--- a/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.ts+++ b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.ts@@ -3,7 +3,18 @@ import { loaders } from 'kea-loaders'import { urlToAction } from 'kea-router'import { ApiError } from 'lib/api-error'-import { getMinimumEquivalentScopes, getScopeDescription } from 'lib/scopes'+import {+ buildOAuthScopeRows,+ grantedResourceScopes,+ identityScopeDescriptions,+ requiredLevelsFromScopes,+ scopeGroupsToShow,+ type OAuthScopeGroup,+ type OAuthScopeRow,+ type RequiredLevel,+ type ScopeAccessSelections,+} from 'lib/oauthScopeRows'+import { type ScopeAccessLevel, countScopeRowsByLevel, getMinimumEquivalentScopes } from 'lib/scopes'import { userLogic } from 'scenes/userLogic'import {@@ -44,38 +55,71 @@ function isInvalidCode(error: unknown): boolean {// The project picker loads every page, so a project past the first page can still be picked.const PROJECTS_PAGE_SIZE = 100-// The scopes a step-up asks for beyond what the person already granted in the chosen project. A-// grant limited to another project or organization gives nothing here. Approving still grants every-// requested scope, so the client's token keeps the ones it had.+// The scopes the person already gave this client that work in the chosen project. A grant limited to+// another project or organization gives nothing here.+function grantedInProject(+ grant: DeviceGrantDetailsApi,+ projectId: number | null,+ organizationId: string | null+): string[] {+ return grant.granted_scopes+ .filter(+ (entry) =>+ (entry.project_id === null || entry.project_id === projectId) &&+ (entry.organization_id === null || entry.organization_id === organizationId)+ )+ .flatMap((entry) => entry.scopes)+}++// The scopes a step-up asks for beyond what the person already granted in the chosen project.function addedScopes(grant: DeviceGrantDetailsApi, projectId: number | null, organizationId: string | null): string[] {- const granted = new Set(- grant.granted_scopes- .filter(- (entry) =>- (entry.project_id === null || entry.project_id === projectId) &&- (entry.organization_id === null || entry.organization_id === organizationId)- )- .flatMap((entry) => entry.scopes)- )+ const granted = new Set(grantedInProject(grant, projectId, organizationId))return grant.scopes.filter((scope) => !granted.has(scope))}+const areas = (count: number): string => `${count} ${count === 1 ? 'area' : 'areas'}`++// One sentence for the collapsed permissions panel, counted from the levels the person picked.+function scopeSummary(rows: OAuthScopeRow[], appName: string): string {+ const { write, read } = countScopeRowsByLevel(rows)+ if (write && read) {+ return `${appName} can view and change data in ${areas(write)}, and view data in ${read} more.`+ }+ if (write) {+ return `${appName} can view and change data in ${areas(write)}.`+ }+ if (read) {+ return `${appName} can view data in ${areas(read)}.`+ }+ return `${appName} can only see your account details.`+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface oauthDeviceAuthorizeLogicValues {user: UserType | null // userLogic+ adjustableScopeRows: OAuthScopeRow[]+ allScopesRequired: boolean+ consentResourceScopes: string[]decision: DeviceDecisionEnumApi | nulldecisionLoading: booleandeviceGrant: DeviceGrantDetailsApi | nulldeviceGrantLoading: booleanerror: string | null+ identityScopeDescriptions: string[]isStepUp: boolean+ keptScopes: string[]organizationId: string | nullorganizations: OrganizationBasicType[]projectId: number | nullprojects: DeviceProject[]projectsError: string | nullprojectsLoading: boolean- scopeDescriptions: string[]+ requiredScopeLevels: Map<string, RequiredLevel>+ requiredScopeRows: OAuthScopeRow[]+ scopeAccessSelections: ScopeAccessSelections+ scopeGroups: OAuthScopeGroup[] | null+ scopeRows: OAuthScopeRow[]+ scopeSummary: stringuserCode: string}@@ -147,6 +191,20 @@ export interface oauthDeviceAuthorizeLogicActions {setProjectId: (projectId: number | null) => {projectId: number | null}+ setScopeAccess: (+ scopeObject: string,+ level: ScopeAccessLevel+ ) => {+ level: ScopeAccessLevel+ scopeObject: string+ }+ setScopeGroupAccess: (+ scopeObjects: string[],+ level: ScopeAccessLevel+ ) => {+ level: ScopeAccessLevel+ scopeObjects: string[]+ }setUserCode: (userCode: string) => {userCode: string}@@ -161,12 +219,21 @@ export interface oauthDeviceAuthorizeLogicMeta {projectId: number | null,organizationId: string | null) => boolean- scopeDescriptions: (+ identityScopeDescriptions: (deviceGrant: DeviceGrantDetailsApi | null) => string[]+ consentResourceScopes: (deviceGrant: DeviceGrantDetailsApi | null) => string[]+ requiredScopeLevels: (deviceGrant: DeviceGrantDetailsApi | null) => Map<string, RequiredLevel>+ scopeRows: (deviceGrant: DeviceGrantDetailsApi | null,- projectId: number | null,- organizationId: string | null,- isStepUp: boolean- ) => string[]+ consentResourceScopes: string[],+ requiredScopeLevels: Map<string, RequiredLevel>,+ scopeAccessSelections: ScopeAccessSelections+ ) => OAuthScopeRow[]+ requiredScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]+ adjustableScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]+ scopeGroups: (adjustableScopeRows: OAuthScopeRow[]) => OAuthScopeGroup[] | null+ allScopesRequired: (scopeRows: OAuthScopeRow[]) => boolean+ scopeSummary: (scopeRows: OAuthScopeRow[], deviceGrant: DeviceGrantDetailsApi | null) => string+ keptScopes: (deviceGrant: DeviceGrantDetailsApi | null, scopeRows: OAuthScopeRow[]) => string[]}}@@ -186,8 +253,29 @@ export const oauthDeviceAuthorizeLogic = kea<oauthDeviceAuthorizeLogicType>([setUserCode: (userCode: string) => ({ userCode }),setOrganizationId: (organizationId: string | null) => ({ organizationId }),setProjectId: (projectId: number | null) => ({ projectId }),+ setScopeAccess: (scopeObject: string, level: ScopeAccessLevel) => ({ scopeObject, level }),+ setScopeGroupAccess: (scopeObjects: string[], level: ScopeAccessLevel) => ({ scopeObjects, level }),}),reducers({+ // The person's picks, per scope object. Absent entries keep the requested level, and every+ // pick is clamped between the required floor and the requested ceiling in scopeRows.+ scopeAccessSelections: [+ { bulk: null, overrides: {} } as ScopeAccessSelections,+ {+ setScopeAccess: (state, { scopeObject, level }) => ({+ ...state,+ overrides: { ...state.overrides, [scopeObject]: level },+ }),+ setScopeGroupAccess: (state, { scopeObjects, level }) => ({+ ...state,+ overrides: {+ ...state.overrides,+ ...Object.fromEntries(scopeObjects.map((scopeObject) => [scopeObject, level])),+ },+ }),+ lookUpCodeSuccess: () => ({ bulk: null, overrides: {} }),+ },+ ],userCode: ['', { setUserCode: (_, { userCode }) => userCode.toUpperCase() }],organizationId: [null as string | null, { setOrganizationId: (_, { organizationId }) => organizationId }],projectId: [@@ -252,8 +340,13 @@ export const oauthDeviceAuthorizeLogic = kea<oauthDeviceAuthorizeLogicType>([if (!deviceGrant || projectId === null) {return null}- return (await oauthDeviceApproveCreate({ user_code: deviceGrant.user_code, project_id: projectId }))- .status+ return (+ await oauthDeviceApproveCreate({+ user_code: deviceGrant.user_code,+ project_id: projectId,+ scopes: values.keptScopes,+ })+ ).status},deny: async () => {if (!values.deviceGrant) {@@ -291,23 +384,75 @@ export const oauthDeviceAuthorizeLogic = kea<oauthDeviceAuthorizeLogicType>([return added > 0 && added < (deviceGrant?.scopes.length ?? 0)},],- // The page lists one line per resource, at the highest level asked for.- scopeDescriptions: [- (s) => [s.deviceGrant, s.projectId, s.organizationId, s.isStepUp],+ identityScopeDescriptions: [+ (s) => [s.deviceGrant],+ (deviceGrant: DeviceGrantDetailsApi | null): string[] =>+ identityScopeDescriptions(deviceGrant?.scopes ?? []),+ ],+ consentResourceScopes: [+ (s) => [s.deviceGrant],+ (deviceGrant: DeviceGrantDetailsApi | null): string[] =>+ getMinimumEquivalentScopes(deviceGrant?.scopes ?? []).filter((scope) => scope.includes(':')),+ ],+ requiredScopeLevels: [+ (s) => [s.deviceGrant],+ (deviceGrant: DeviceGrantDetailsApi | null): Map<string, RequiredLevel> =>+ requiredLevelsFromScopes(deviceGrant?.required_scopes ?? []),+ ],+ // One row per scope object, built the same way as on the OAuth consent screen. Only required+ // scopes set a floor: a device login replaces the client's stored token, so an earlier grant+ // gives the person no reason to keep that access.+ scopeRows: [+ (s) => [s.deviceGrant, s.consentResourceScopes, s.requiredScopeLevels, s.scopeAccessSelections],(deviceGrant: DeviceGrantDetailsApi | null,- projectId: number | null,- organizationId: string | null,- isStepUp: boolean- ): string[] =>+ consentResourceScopes: string[],+ requiredScopeLevels: Map<string, RequiredLevel>,+ scopeAccessSelections: ScopeAccessSelections+ ): OAuthScopeRow[] =>deviceGrant- ? getMinimumEquivalentScopes(- isStepUp ? addedScopes(deviceGrant, projectId, organizationId) : deviceGrant.scopes+ ? buildOAuthScopeRows(+ consentResourceScopes,+ scopeAccessSelections,+ requiredScopeLevels,+ new Map(),+ deviceGrant.client_name)- .map(getScopeDescription)- .filter((description): description is string => !!description): [],],+ requiredScopeRows: [+ (s) => [s.scopeRows],+ (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => row.locked),+ ],+ adjustableScopeRows: [+ (s) => [s.scopeRows],+ (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => !row.locked),+ ],+ scopeGroups: [+ (s) => [s.adjustableScopeRows],+ (adjustableScopeRows: OAuthScopeRow[]): OAuthScopeGroup[] | null => scopeGroupsToShow(adjustableScopeRows),+ ],+ allScopesRequired: [+ (s) => [s.scopeRows],+ (scopeRows: OAuthScopeRow[]): boolean => scopeRows.length > 0 && scopeRows.every((row) => row.locked),+ ],+ scopeSummary: [+ (s) => [s.scopeRows, s.deviceGrant],+ (scopeRows: OAuthScopeRow[], deviceGrant: DeviceGrantDetailsApi | null): string =>+ scopeSummary(scopeRows, deviceGrant?.client_name ?? ''),+ ],+ // What approval sends: the required scopes as requested, identity scopes included, and the+ // resource scopes at the level the person picked.+ keptScopes: [+ (s) => [s.deviceGrant, s.scopeRows],+ (deviceGrant: DeviceGrantDetailsApi | null, scopeRows: OAuthScopeRow[]): string[] => {+ if (!deviceGrant) {+ return []+ }+ const resources = grantedResourceScopes(scopeRows, deviceGrant.scopes, () => [])+ return Array.from(new Set([...deviceGrant.required_scopes, ...resources]))+ },+ ],}),listeners(({ actions, values }) => ({setOrganizationId: ({ organizationId }) => {diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsxindex f73f853f6d78..70e22e4bdecc 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx@@ -2,21 +2,18 @@ import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { useMemo, useState } from 'react'-import { IconCheck, IconCheckCircle, IconLock, IconPlus, IconWarning } from '@posthog/icons'+import { IconCheckCircle, IconLock, IconPlus, IconWarning } from '@posthog/icons'-import { ScopeAccessGroup } from 'lib/components/ScopeAccessRow/ScopeAccessGroup'-import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'+import { OAuthScopeList } from 'lib/components/ScopeAccessRow/OAuthScopeList'import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'import { LemonSelect } from 'lib/lemon-ui/LemonSelect'-import { LemonTag } from 'lib/lemon-ui/LemonTag'import { Link } from 'lib/lemon-ui/Link'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { Spinner } from 'lib/lemon-ui/Spinner'-import { Tooltip } from 'lib/lemon-ui/Tooltip'import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'import { organizationLogic } from 'scenes/organizationLogic'import ScopeAccessSelector from 'scenes/settings/user/scopes/ScopeAccessSelector'@@ -451,54 +448,17 @@ export const OAuthAuthorize = (): JSX.Element => {)}</div><div className="flex flex-col gap-3 px-4 sm:px-6 py-4">- {(identityScopeDescriptions.length > 0 || requiredScopeRows.length > 0) && (- <ul className="space-y-2">- {identityScopeDescriptions.map((description, idx) => (- <li key={idx} className="flex items-center space-x-2">- <IconCheck color="var(--success)" className="shrink-0" />- <span className="font-medium">{description}</span>- </li>- ))}- {requiredScopeRows.map((row) => (- <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>- {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>- ))}- </ul>- )}- {scopeRowsGrouped ? (- <div className="flex flex-col">- {scopeGroups.map((group) => (- <ScopeAccessGroup- key={group.label}- group={group}- onChangeRow={setScopeAccess}- onChangeGroup={setScopeGroupAccess}- dataAttrPrefix="oauth-scope-group"- />- ))}- </div>- ) : (- adjustableScopeRows.length > 0 && (- <div className="flex flex-col">- {adjustableScopeRows.map((row) => (- <ScopeAccessRow key={row.key} row={row} onChange={setScopeAccess} />- ))}- </div>- )- )}+ <OAuthScopeList+ appName={appName}+ identityScopeDescriptions={identityScopeDescriptions}+ requiredScopeRows={requiredScopeRows}+ adjustableScopeRows={adjustableScopeRows}+ scopeGroups={scopeRowsGrouped ? scopeGroups : null}+ allScopesRequired={allScopesRequired}+ onChangeRow={setScopeAccess}+ onChangeGroup={setScopeGroupAccess}+ dataAttrPrefix="oauth-scope-group"+ />{accessControlsApply && (<LemonBanner type="info" icon={<IconLock className="LemonBanner__icon" />}><strong className="block">Access controls still apply.</strong>diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.tsindex c53c1ca0a56e..270ae8166676 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts@@ -7,18 +7,20 @@ import { router, urlToAction } from 'kea-router'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { OAUTH_SCOPES_SUPPORTED } from 'lib/oauthScopes.generated'import {- API_SCOPES,- DEFAULT_OAUTH_SCOPES,- clampScopeLevel,- getMinimumEquivalentScopes,- getScopeDescription,- groupScopeRows,- type ScopePickerGroup,- type ScopeAccessLevel,- type ScopePickerRow,-} from 'lib/scopes'+ IDENTITY_SCOPES,+ SCOPE_GROUPING_MIN_ROWS,+ buildOAuthScopeRows,+ grantedResourceScopes,+ identityScopeDescriptions,+ requiredLevelsFromScopes,+ type OAuthScopeGroup,+ type OAuthScopeRow,+ type RequiredLevel,+ type ScopeAccessSelections,+} from 'lib/oauthScopeRows'+import { OAUTH_SCOPES_SUPPORTED } from 'lib/oauthScopes.generated'+import { DEFAULT_OAUTH_SCOPES, getMinimumEquivalentScopes, groupScopeRows, type ScopeAccessLevel } from 'lib/scopes'import { getAppContext } from 'lib/utils/getAppContext'import { userLogic } from 'scenes/userLogic'@@ -30,83 +32,6 @@ export type OAuthAuthorizationFormValues = {access_type: 'all' | 'organizations' | 'teams'}-const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'introspection']--const scopeObjectKey = (scope: string): string => (scope === '*' ? '*' : scope.split(':')[0])--export type OAuthScopeRow = ScopePickerRow & {- /** Full sentence description at the granted level, for the locked (checkmark) list. */- description: string- /** Required floor — the grant can never go below this. 'none' when not required. */- minLevel: ScopeAccessLevel- /** Requested ceiling — the grant can never go above what the client asked for. */- 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>--// The floor and the ceiling as the reasons a level is not available, in the words the row shows.-// The shared clamp and group control work from these, so a group set to write holds a read-only-// row at read and a group set to none holds a required row at read.-const oauthDisabledReasons = (- minLevel: ScopeAccessLevel,- maxLevel: ScopeAccessLevel,- appName: string,- alreadyGranted: boolean-): Partial<Record<ScopeAccessLevel, string>> => ({- ...(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}` } : {}),-})--const WILDCARD_LABEL = 'All PostHog data'--// A request with this many adjustable rows or fewer shows a flat alphabetical list. Group-// headers only help when the list is long.-export const SCOPE_GROUPING_MIN_ROWS = 10--// Fallback for scopes absent from API_SCOPES (e.g. server-side scopes the local list lags-// behind) — derive a readable label from the raw key.-const humanizeScopeKey = (key: string): string => {- const humanized = key.replace(/_/g, ' ')- return humanized.charAt(0).toUpperCase() + humanized.slice(1)-}--// Required scopes are tracked per object at the action level that's required, so a-// required `obj:read` still lets the read-only toggle downgrade an optional `obj:write`.-export type RequiredLevel = 'read' | 'write'--const requiredLevelsFromScopes = (requiredScopes: string[]): Map<string, RequiredLevel> => {- const levels = new Map<string, RequiredLevel>()- for (const scope of requiredScopes) {- if (!scope.includes(':') && scope !== '*') {- continue- }- const key = scopeObjectKey(scope)- const level: RequiredLevel = scope === '*' || scope.endsWith(':write') ? 'write' : 'read'- if (level === 'write' || !levels.has(key)) {- levels.set(key, level)- }- }- return levels-}-// `*` grants read+write to everything; its read-only form is every grantable object's read// scope. The server-computed list is authoritative, because it applies the app's ceiling.// The fallback only covers a missing app context, and takes the read scopes OAuth advertises@@ -244,10 +169,7 @@ export interface oauthAuthorizeLogicValues {requiredAccessLevel: 'organization' | 'team' | nullrequiredScopeLevels: Map<string, RequiredLevel>requiredScopeRows: OAuthScopeRow[]- scopeAccessSelections: {- bulk: ScopeAccessLevel | null- overrides: Record<string, ScopeAccessLevel>- }+ scopeAccessSelections: ScopeAccessSelectionsscopeGroups: OAuthScopeGroup[]scopeRows: OAuthScopeRow[]scopeRowsGrouped: boolean@@ -415,10 +337,7 @@ export interface oauthAuthorizeLogicMeta {) => string[]scopeRows: (consentResourceScopes: string[],- scopeAccessSelections: {- bulk: ScopeAccessLevel | null- overrides: Record<string, ScopeAccessLevel>- },+ scopeAccessSelections: ScopeAccessSelections,requiredScopeLevels: Map<string, RequiredLevel>,alreadyGrantedScopeLevels: Map<string, RequiredLevel>,appName: string@@ -568,10 +487,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([// requested ceiling, and every pick is clamped to [required floor, requested ceiling]// in scopeRows, so bulk actions can apply one level blindly to heterogeneous rows.scopeAccessSelections: [- { bulk: null, overrides: {} } as {- bulk: ScopeAccessLevel | null- overrides: Record<string, ScopeAccessLevel>- },+ { bulk: null, overrides: {} } as ScopeAccessSelections,{setScopeAccess: (state, { scopeObject, level }) => ({...state,@@ -824,11 +740,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([],identityScopeDescriptions: [(s) => [s.scopes],- (scopes: string[]): string[] =>- scopes- .filter((scope) => IDENTITY_SCOPES.includes(scope))- .map(getScopeDescription)- .filter(Boolean) as string[],+ (scopes: string[]): string[] => identityScopeDescriptions(scopes),],requiredScopeLevels: [(s) => [s.oauthApplication],@@ -883,40 +795,18 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([],(consentResourceScopes: string[],- scopeAccessSelections: { bulk: ScopeAccessLevel | null; overrides: Record<string, ScopeAccessLevel> },+ scopeAccessSelections: ScopeAccessSelections,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 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)- const grantedScope = scope === '*' && value === 'write' ? '*' : `${key}:${value}`- return {- key,- label: key === '*' ? WILDCARD_LABEL : (apiScope?.objectName ?? humanizeScopeKey(key)),- description: getScopeDescription(grantedScope) ?? grantedScope,- info: apiScope?.info,- warning: value === 'none' ? undefined : apiScope?.warnings?.[value],- muted: value === 'none',- disabledReasons,- minLevel,- maxLevel,- value,- locked: minLevel === maxLevel,- alreadyGranted,- }- })- return rows.sort((a, b) => a.label.localeCompare(b.label))+ return buildOAuthScopeRows(+ consentResourceScopes,+ scopeAccessSelections,+ requiredScopeLevels,+ alreadyGrantedScopeLevels,+ appName+ )},],// Locked rows (required at exactly the requested level) render as a plain checkmark@@ -957,23 +847,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([alreadyGrantedScopes: string[]): string[] => {const identity = scopes.filter((scope) => IDENTITY_SCOPES.includes(scope))- const resources = scopeRows.flatMap((row) => {- if (row.value === 'none') {- return []- }- if (row.key === '*') {- return row.value === 'write' ? ['*'] : wildcardReadScopes(oauthApplication)- }- // Write grants read too, but clients diff the granted `scope` against what they- // asked for, so a missing `:read` reads as a partial grant. Spell both out when- // the client asked for both, and only then: granting a half it never requested- // is the same mismatch in the other direction.- if (row.value === 'write') {- const readScope = `${row.key}:read`- return scopes.includes(readScope) ? [readScope, `${row.key}:write`] : [`${row.key}:write`]- }- return [`${row.key}:${row.value}`]- })+ const resources = grantedResourceScopes(scopeRows, scopes, () => wildcardReadScopes(oauthApplication))// 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 ?? []), ...alreadyGrantedScopes].filter(diff --git a/hog/src/commands/api/api.test.ts b/hog/src/commands/api/api.test.tsindex 5f581c7378fd..56e71b6c3d0e 100644--- a/hog/src/commands/api/api.test.ts+++ b/hog/src/commands/api/api.test.ts@@ -187,7 +187,7 @@ describe('hog api', () => {})expect(result.error()).toMatchObject({code: 'missing_scopes',- message: `The personal API key needs ${scopes} to call insight-create.`,+ message: `Your credentials need ${scopes} to call insight-create.`,})})@@ -234,4 +234,34 @@ describe('hog api', () => {expect(result.json()).toMatchObject({ usable: 2, tools: 3, projectAllowed: true })})++ test('a refused call from an OAuth login names every scope the login lacks, from its own scopes', async () => {+ const EU = 'https://eu.posthog.com'+ const record = {+ store: 'keychain',+ type: 'oauth',+ projectId: '42',+ host: EU,+ expiresAt: Date.UTC(2026, 0, 8),+ scopes: ['feature_flag:read'],+ loginId: 'login-1',+ }+ const result = await runHog(['api', 'call', 'insight-create', '{}'], {+ env: { CLAUDECODE: '1' },+ files: { '/home/test/.config/hog/settings.json': JSON.stringify({ logins: { [EU]: record }, host: EU }) },+ keychain: { [EU]: JSON.stringify({ accessToken: 'pha_token', refreshToken: 'phr_token' }) },+ apiTools: fakeLibrary([], {+ lookupFails: true,+ callResult: {+ ok: false,+ error: { code: 'permission_denied', message: 'denied', status: 403, missingScope: 'insight:write' },+ },+ }),+ })++ expect(result.error()).toMatchObject({+ code: 'missing_scopes',+ message: 'Your credentials need insight:write, query:read to call insight-create.',+ })+ })})diff --git a/hog/src/commands/auth/auth.test.ts b/hog/src/commands/auth/auth.test.tsindex 7c9d322b9055..0860da8e37b7 100644--- a/hog/src/commands/auth/auth.test.ts+++ b/hog/src/commands/auth/auth.test.ts@@ -168,6 +168,17 @@ describe('hog auth login', () => {expect(result.error()).toMatchObject({ code, hint: expect.any(String) })})+ test('--wait stores only the scopes the person approved', async () => {+ const result = await runHog(['auth', 'login', '--wait'], {+ env: { CLAUDECODE: '1' },+ files: { [PENDING_FILE]: PENDING },+ respond: deviceFlow(0, { status: 200, body: { ...APPROVED, scope: 'openid insight:read' } }),+ })++ expect(result.json()).toMatchObject({ status: 'logged_in', scopes: ['openid', 'insight:read'] })+ expect(JSON.parse(result.files[SETTINGS_FILE] ?? '{}').logins[EU].scopes).toEqual(['openid', 'insight:read'])+ })+test('--wait stores the token for the approved project in the keychain', async () => {const result = await runHog(['auth', 'login', '--wait'], {env: { CLAUDECODE: '1' },diff --git a/hog/src/posthog/api-tools.ts b/hog/src/posthog/api-tools.tsindex 298498571a00..566ac12afb3f 100644--- a/hog/src/posthog/api-tools.ts+++ b/hog/src/posthog/api-tools.ts@@ -33,7 +33,7 @@ export interface ToolRow {}const SCOPES_HINT =- 'Run `hog auth login` to create a key with the scopes the API tools need, or add the scopes to the key in PostHog under Settings, Personal API keys.'+ 'For a personal API key, add the scopes to it in PostHog under Settings, Personal API keys. For a login, run `hog auth login` again and keep these scopes when you approve it.'// "Events & properties" becomes "events-properties".export function groupSlug(name: string): string {@@ -142,11 +142,7 @@ export async function withApiConnection<T>(}export function missingScopesError(tool: string, scopes: readonly string[]): HogError {- return new HogError(- 'missing_scopes',- `The personal API key needs ${scopes.join(', ')} to call ${tool}.`,- SCOPES_HINT- )+ return new HogError('missing_scopes', `Your credentials need ${scopes.join(', ')} to call ${tool}.`, SCOPES_HINT)}export function toHogError(error: ApiToolError, tool?: string): HogError {diff --git a/posthog/api/oauth/device.py b/posthog/api/oauth/device.pyindex 5139f1739ad1..e3d02b81a7cf 100644--- a/posthog/api/oauth/device.py+++ b/posthog/api/oauth/device.py@@ -55,7 +55,7 @@ from posthog.models import Team, Userfrom posthog.models.oauth import OAuthApplication, OAuthDeviceGrant, live_oauth_access_tokens, live_oauth_refresh_tokensfrom posthog.models.organization_domain import OrganizationDomainfrom posthog.rate_limit import IPThrottle-from posthog.scopes import clamp_scopes_to_ceiling, resolve_requested_scopes+from posthog.scopes import clamp_scopes_to_ceiling, resolve_requested_scopes, scopes_not_coveredlogger = structlog.get_logger(__name__)@@ -360,6 +360,13 @@ class DeviceUserCodeSerializer(serializers.Serializer):class DeviceApprovalSerializer(DeviceUserCodeSerializer):project_id = serializers.IntegerField(help_text="The project the token is scoped to.")+ scopes = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ allow_empty=False,+ help_text="The requested scopes the person kept. Leave it out to grant every requested scope. It must "+ "include every scope in `required_scopes`, and nothing outside the requested scopes.",+ )class GrantedScopesSerializer(serializers.Serializer):@@ -384,6 +391,11 @@ class DeviceGrantDetailsSerializer(serializers.Serializer):scopes = serializers.ListField(child=serializers.CharField(), help_text="The scopes the token will carry if the person approves.")+ required_scopes = serializers.ListField(+ child=serializers.CharField(),+ help_text="The requested scopes the person can't leave out: the client's required scopes and identity "+ "scopes such as `openid`.",+ )granted_scopes = GrantedScopesSerializer(many=True,help_text="The scopes the person already gave this client, per project. A step-up in a project asks for "@@ -403,6 +415,13 @@ class DeviceDecisionSerializer(serializers.Serializer):)+def _required_scopes(requested: list[str], application: OAuthApplication) -> list[str]:+ """Return the requested scopes that approval always keeps: the client's required scopes, and the+ identity scopes, which grant no access to data."""+ required = set(application.required_scopes)+ return [scope for scope in requested if scope in required or ":" not in scope]++def _invalid_code() -> Response:return Response({@@ -413,6 +432,10 @@ def _invalid_code() -> Response:)+def _invalid_scope(description: str) -> Response:+ return Response({"error": "invalid_scope", "error_description": description}, status=status.HTTP_400_BAD_REQUEST)++def _unverified_client() -> Response:return Response({"error": "unverified_client", "error_description": UNVERIFIED_CLIENT_DESCRIPTION},@@ -512,6 +535,7 @@ class OAuthDeviceViewSet(viewsets.ViewSet):"logo_uri": application.logo_uri or None,"is_verified": application.is_verified,"scopes": (grant.scope or "").split(),+ "required_scopes": _required_scopes((grant.scope or "").split(), application),"granted_scopes": _granted_scopes(cast(User, request.user), application),"expires_at": grant.expires,}@@ -521,7 +545,7 @@ class OAuthDeviceViewSet(viewsets.ViewSet):@extend_schema(request=DeviceApprovalSerializer, responses={200: DeviceDecisionSerializer})@action(methods=["POST"], detail=False)def approve(self, request: Request) -> Response:- """Approve a device grant for one project. The token gets the scopes `lookup` showed."""+ """Approve a device grant for one project. The token gets the requested scopes the person kept."""# Late import: the views module imports this one for the token endpoint.from posthog.api.oauth.views import _gateway_blocklist_block, _impersonator_id_for_request # noqa: PLC0415@@ -574,6 +598,15 @@ class OAuthDeviceViewSet(viewsets.ViewSet):application = OAuthApplication.objects.filter(client_id=grant.client_id).first()if application is None or not application.is_verified:return _unverified_client()+ requested = (grant.scope or "").split()+ kept = serializer.validated_data.get("scopes")+ if kept is not None:+ # A requested `x:write` also covers `x:read`, so the person can lower write access to read.+ if scopes_not_covered(requested, kept):+ return _invalid_scope("You can only keep scopes the app asked for.")+ if scopes_not_covered(kept, _required_scopes(requested, application)):+ return _invalid_scope("The app needs some of the scopes you removed. Keep those to approve.")+ grant.scope = " ".join(sorted(set(kept)))if block := _gateway_blocklist_block(request, grant.scope or "", access_level="team", scoped_team_ids=[team.id]):@@ -581,10 +614,18 @@ class OAuthDeviceViewSet(viewsets.ViewSet):grant.user = cast(User, request.user)grant.scoped_teams = [team.id]grant.status = OAuthDeviceGrant.AUTHORIZED- grant.save(update_fields=["user", "scoped_teams", "status"])+ grant.save(update_fields=["user", "scoped_teams", "status", "scope"])logger.info("oauth_device_grant_approved", client_id=grant.client_id[:64], team_id=team.id)- _capture(request, "oauth_device_authorization_approved", grant, team_id=team.id)+ _capture(+ request,+ "oauth_device_authorization_approved",+ grant,+ team_id=team.id,+ scopes_requested=len(requested),+ scopes_granted=len((grant.scope or "").split()),+ scopes_chosen=kept is not None and set(kept) != set(requested),+ )return Response(DeviceDecisionSerializer({"status": grant.status}).data)@extend_schema(request=DeviceUserCodeSerializer, responses={200: DeviceDecisionSerializer})diff --git a/posthog/api/oauth/test_device.py b/posthog/api/oauth/test_device.pyindex fd91373b07e1..4ac8d4e31fad 100644--- a/posthog/api/oauth/test_device.py+++ b/posthog/api/oauth/test_device.py@@ -520,6 +520,65 @@ class TestOAuthDeviceGrant(APIBaseTest):lookup = self.client.post("/api/oauth_device/lookup/", {"user_code": started["user_code"]})self.assertEqual(lookup.json()["scopes"], ["dashboard:write", "insight:read"])+ self.assertEqual(lookup.json()["required_scopes"], ["insight:read"])++ @patch("posthog.api.oauth.device.posthoganalytics.capture")+ def test_the_token_carries_only_the_scopes_the_person_kept(self, capture) -> None:+ with time_machine.travel(START, tick=False) as clock:+ started = self._start()+ approved = self.client.post(+ "/api/oauth_device/approve/",+ {"user_code": started["user_code"], "project_id": self.team.id, "scopes": ["feature_flag:read"]},+ format="json",+ )+ clock.shift(timedelta(seconds=6))++ token = self._poll(started["device_code"])++ self.assertEqual(approved.status_code, status.HTTP_200_OK, approved.content)+ # The client asked for `feature_flag:write`, and the person lowered it to read.+ self.assertEqual(token.json()["scope"], "feature_flag:read")+ approval = next(c for c in capture.call_args_list if c.kwargs["event"] == "oauth_device_authorization_approved")+ self.assertEqual(+ {+ key: approval.kwargs["properties"][key]+ for key in ("scopes_requested", "scopes_granted", "scopes_chosen")+ },+ {"scopes_requested": 2, "scopes_granted": 1, "scopes_chosen": True},+ )++ @parameterized.expand(+ [+ ("a scope the client never asked for", ["insight:read", "feature_flag:read"], "only keep scopes"),+ ("without a scope the client requires", ["dashboard:write"], "needs some of the scopes"),+ ]+ )+ def test_approval_refuses_a_scope_list(self, _name: str, kept: list[str], description: str) -> None:+ OAuthApplication.objects.create(+ name="required",+ client_id="required-scopes-client",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_DEVICE_CODE,+ is_verified=True,+ redirect_uris="",+ algorithm="RS256",+ scopes=["insight:read"],+ optional_scopes=["dashboard:write"],+ )+ started = self._start(client_id="required-scopes-client", scope="dashboard:write")++ response = self.client.post(+ "/api/oauth_device/approve/",+ {"user_code": started["user_code"], "project_id": self.team.id, "scopes": kept},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "invalid_scope")+ self.assertIn(description, response.json()["error_description"])+ self.assertEqual(+ OAuthDeviceGrant.objects.get(user_code=started["user_code"]).status, OAuthDeviceGrant.AUTHORIZATION_PENDING+ )def test_disconnecting_the_app_drops_an_approved_device_grant_the_client_has_not_redeemed(self) -> None:with time_machine.travel(START, tick=False) as clock:diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 9633327f2290..ca346092a6be 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -738,7 +738,8 @@ def narrow_scopes_to_ceiling(original: Iterable[str], app_scopes: Iterable[str])if "*" in original_set:return original_list- narrowed = (original_set & ceiling) | (original_set & ALWAYS_ALLOWED_SCOPES)+ # A `:write` in the ceiling covers its `:read`, as at issue time in `clamp_scopes_to_ceiling`.+ narrowed = (original_set & _with_read_halves(ceiling)) | (original_set & ALWAYS_ALLOWED_SCOPES)if not narrowed and original_set:return Nonereturn sorted(narrowed)diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex 5ff48d612cc4..438de8b2ad36 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -365,6 +365,7 @@ class TestNarrowScopesToCeiling(SimpleTestCase):("empty_ceiling_is_noop", ["query:read", "insight:write"], [], ["query:read", "insight:write"]),("narrows_to_tightened_ceiling", ["query:read", "insight:write"], ["query:read"], ["query:read"]),("no_overlap_returns_none", ["insight:write"], ["query:read"], None),+ ("read_half_of_a_write_ceiling_survives", ["insight:read"], ["insight:write"], ["insight:read"]),("wildcard_left_untouched", ["*"], ["query:read"], ["*"]),("always_allowed_survive_narrowing",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4198f8d774fe..c993698367b4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -35021,6 +35021,8 @@ export namespace Schemas {user_code: string;/** The project the token is scoped to. */project_id: number;+ /** The requested scopes the person kept. Leave it out to grant every requested scope. It must include every scope in `required_scopes`, and nothing outside the requested scopes. */+ scopes?: string[];}/**@@ -35074,6 +35076,8 @@ export namespace Schemas {is_verified: boolean;/** The scopes the token will carry if the person approves. */scopes: string[];+ /** The requested scopes the person can't leave out: the client's required scopes and identity scopes such as `openid`. */+ required_scopes: string[];/** The scopes the person already gave this client, per project. A step-up in a project asks for these plus new ones, and the page lists only the new ones. */granted_scopes: GrantedScopes[];/** When the code expires. */