: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): replace checkbox/toggle scope UI with per-row access selectors and bulk actions (#69547)
Rafael Audibert081fafffffe6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e5f0bcf09fa4..9d92c8f2afb0 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6218,22 +6218,34 @@ snapshots:hash: v1.k794b7964.feeb8a0d0209ac3940b477fc7fa0d00f5dfb60032287d137fd5fc2a8413de4f9.zn_gEPsfVQEMHrZK3t43eLJ2O71Tz2YpA73L9mUuITkscenes-app-notebooks-nodes-support-tickets--with-tickets--light:hash: v1.k794b7964.df55bfe02bf0e0a2cc72e893a4205d201bcc2759795e7af8906b1282bbf15513.gy4PiyWfoVb3JcB-FHAIRUd3wiTZ7Xlekf3zovu2W58- scenes-app-oauth-authorize--broad-free-pick--dark:- hash: v1.k794b7964.eca28be57ac0144162a6d895c399d30a886320f308b9d3157129286690514f0e.iADKdes5GFM-oNiiyTrcb2M3kbZJBt-uqC7JM3Puz80- scenes-app-oauth-authorize--broad-free-pick--light:- hash: v1.k794b7964.e6b0b77067b13e5f5e0deeb570aa04c0295038501e1567d5843f715ca980a240.W5nBSasZq3VNgQzAJxwlphUK1bSBicXCs7F1-faksq8+ scenes-app-oauth-authorize--all-scopes-optional--dark:+ hash: v1.k794b7964.03746d2e3646b97e4af61e54557db2ccb6268512cda02721b819fa30980af155.ZPcclnqMQQh8Qi_v2Z3cnVA1_LaYFx8XXncRQ8NQAdc+ scenes-app-oauth-authorize--all-scopes-optional--light:+ hash: v1.k794b7964.b9e6458501f1e1453c09b5c4f517be93b0d584eaffe04b67a0f964df741bc1bc.uM9wMTVCC0eVQN2V0xG9F-O9jhHs58sSGillxFX4IbA+ scenes-app-oauth-authorize--all-scopes-required--dark:+ hash: v1.k794b7964.f79133052ebe57082e7d54c7e25b8483b12a6c804b7e3e01f33116c6d49c32ea.zDXZhgy1ifPP_MJmIxKnvEbEV_dO_BBV4WV3E6dArro+ scenes-app-oauth-authorize--all-scopes-required--light:+ hash: v1.k794b7964.9ec7b8dda3493225474350a6ce917aa090e54d38bc3e162a0db40382d8a37ef4.O61AjpIuCkHM2W08v3Go4ZZZFfW6rsbsDW2Zo7jNafgscenes-app-oauth-authorize--default-scopes--dark:hash: v1.k794b7964.eb963d4474577c3e6ab1539a88c2c12c086dabfe500b59122791c4c9d016b0aa.1IUh0u3HpX9cOsexOye74qk-G9kognT_OrIOkGZK6wQscenes-app-oauth-authorize--default-scopes--light:hash: v1.k794b7964.6e509ebff23ec9461cfe4f01a0dc0a38ab2728b909a3e7737847fec72b2900ce.ybpJDCeX4nPXMgkwRMGsGHBjfWCYJ8gJEGkif00EHnI+ scenes-app-oauth-authorize--many-optional-scopes--dark:+ hash: v1.k794b7964.fb3a7260213b0061fa034a5d0f32eaf18928c796cabef8ed7e81c1ccec6531c2.MdOEdBxuJgB1TIrJRXBXKWXvfP54wloX1xFr7YIX_gA+ scenes-app-oauth-authorize--many-optional-scopes--light:+ hash: v1.k794b7964.f2137366803db15fce878639b1ca68da0b8283ac02214e7077dc0b33db12c8b6.5ad7tFeP5sSvQoKu4YmunlNS0OJWRolciq2yNtPQmwo+ scenes-app-oauth-authorize--required-read-floor-with-optional-write--dark:+ hash: v1.k794b7964.7980c9cdc9dc5f54ebec0e86d9cd3824ddcb8454ce6f58c1d271cc71d135d4de.4puSj0lu-YAVKTbc9dQ38ghQcIldI7ZFdXqERvnxQzo+ scenes-app-oauth-authorize--required-read-floor-with-optional-write--light:+ hash: v1.k794b7964.f55c551b65a36c2fb9bd57640c916ff3e8b8f283650d69370f66895009e0b4b9.P4OFYvLBsLOismPO59w4-pZ_70C7QJlnK9432LedNBo+ scenes-app-oauth-authorize--wildcard-scope--dark:+ hash: v1.k794b7964.8b035078fadc6b11f4aa3a30367a1356eb72d80da3776adb7a29e2c3afa6bd06._Y__du-0jj-AhXl8TD6lHZusbX_fyJDtsiaWzDcul-A+ scenes-app-oauth-authorize--wildcard-scope--light:+ hash: v1.k794b7964.b64563db9a86ca6a0828ba3281d15f9db7450093d914757cd3fcb11038f846a6.QZK81phgoV3YAGWHpreJ0MkzCtnYErx2OaxCUSSEXUQscenes-app-oauth-authorize--with-required-scopes--dark:- hash: v1.k794b7964.3fe9af7334d0b50e09880656b7ebc5439bb5597a9d1477230f716b50bb66e541.SzypkXYYuz_EkgAtgVgeRIbCeinqykTpu8X6tWXqcIY+ hash: v1.k794b7964.7b42b6105523270e46edc34ac02da49532296ab5fcab8efbe16b28d3e96c2b87.uouQIu0vA1VQP26gZzv29xqcS8gLtMqbmRKVr1Z1a-4scenes-app-oauth-authorize--with-required-scopes--light:- hash: v1.k794b7964.fe6f39af4becb6dbd4f0eec038651d49de163b5f796cc09df915ac48dabf33be.BiXdR-5e62GYT4OKjaks-6qIajkwo4BolRjG9vYzGJY- scenes-app-oauth-authorize--with-scopes--dark:- hash: v1.k794b7964.cf1886509e6e3e174a30fbabf95e4beb354737da9fefa4cee76c1acce975b099.sM8oSihW9NrsWqD8fe2fbHjpHYGZIKy3tjurvsLviR4- scenes-app-oauth-authorize--with-scopes--light:- hash: v1.k794b7964.dec576f04202b266a066120556f3b26df1e84df3aef8013c7757e43d0e9a7805.ToaF37_eh0p0FohsJMEO68B5ytYOw1fxqYjEgvQ7ZOo+ hash: v1.k794b7964.e951fac95b4bfb2628774621d6ac6f479abf8e8d10efb58cbcfad998c62a96be.-ZMfxl773NvFryFdUT6AJlVnUiwplGzEUPhvBD6kSWwscenes-app-people-cohorts--cohort-edit-dynamic--dark:hash: v1.k794b7964.e2f3fed91cc1e603808a766fc8b3e457342e0a22e6ec1d157822ef8654bcdb6a.eLEFZ9RPmh6MbIH__SjcSgHgttnqBoYIkcfqXpwXZ9Yscenes-app-people-cohorts--cohort-edit-dynamic--light:diff --git a/frontend/src/scenes/settings/shared/ScopeAccessRow.tsx b/frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsxsimilarity index 89%rename from frontend/src/scenes/settings/shared/ScopeAccessRow.tsxrename to frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsxindex 027fae73ac2c..e46678af05cf 100644--- a/frontend/src/scenes/settings/shared/ScopeAccessRow.tsx+++ b/frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsx@@ -10,6 +10,8 @@ interface ScopeAccessRowProps {value: string/** Called with the new value when the user picks an option. */onChange: (value: string) => void+ /** Reason the No access option should be disabled. Set to a non-empty string to disable. */+ noneDisabledReason?: string/** Reason the Read option should be disabled. Set to a non-empty string to disable. */readDisabledReason?: string/** Reason the Write option should be disabled. Set to a non-empty string to disable. */@@ -26,6 +28,7 @@ export function ScopeAccessRow({label,value,onChange,+ noneDisabledReason,readDisabledReason,writeDisabledReason,info,@@ -36,7 +39,7 @@ export function ScopeAccessRow({<><div className="flex items-center justify-between gap-2 min-h-8 group"><div className={clsx('flex items-center gap-1', muted && 'text-muted')}>- <b className="transition-colors group-hover:text-highlight">{label}</b>+ <b>{label}</b>{info ? (<Tooltip title={info}><IconInfo className="text-secondary text-base" />@@ -47,7 +50,7 @@ export function ScopeAccessRow({onChange={onChange}value={value}options={[- { label: 'No access', value: 'none' },+ { label: 'No access', value: 'none', disabledReason: noneDisabledReason },{ label: 'Read', value: 'read', disabledReason: readDisabledReason },{ label: 'Write', value: 'write', disabledReason: writeDisabledReason },]}diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 145dbfeb29f2..dce8b1771d20 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -22,9 +22,9 @@ export type APIScope = {// both the picker warning (attached below) and the auto-select in personalAPIKeysLogic, so the rule// and the copy can't drift. `ScopeAccessRow` renders warnings as plain text — no markdown formatting.export const SCOPES_IMPLYING_FEATURE_FLAG_WRITE: Partial<Record<APIScopeObject, string>> = {- survey: 'Surveys with targeting also manage a feature flag, so this key needs feature_flag:write too.',+ survey: 'Surveys with targeting also manage a feature flag, so this key needs write access to feature flags too.',early_access_feature:- 'Early access features manage a linked feature flag, so this key needs feature_flag:write too.',+ 'Early access features manage a linked feature flag, so this key needs write access to feature flags too.',}export const API_SCOPES: APIScope[] = [@@ -157,9 +157,7 @@ export const API_SCOPES: APIScope[] = [key: 'project',objectName: 'Project',objectPlural: 'projects',- warnings: {- write: 'This scope can be used to create or modify projects, including settings about how data is ingested.',- },+ info: 'If you grant write access, this scope can be used to create or modify projects, including settings about how data is ingested.',},{ key: 'property_definition', objectName: 'Property definition', objectPlural: 'property definitions' },{ key: 'query', objectName: 'Query', objectPlural: 'queries', disabledActions: ['write'] },diff --git a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsxindex 9aee7cc95b5b..247b20119b34 100644--- a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx+++ b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx@@ -5,11 +5,11 @@ import { IconCode } from '@posthog/icons'import { LemonButton, LemonInput, LemonSelect, Link } from '@posthog/lemon-ui'import { BridgePage } from 'lib/components/BridgePage/BridgePage'+import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonField } from 'lib/lemon-ui/LemonField'import { SceneExport } from 'scenes/sceneTypes'-import { ScopeAccessRow } from 'scenes/settings/shared/ScopeAccessRow'import { urls } from 'scenes/urls'import { CLI_SCOPE_PRESETS, cliAuthorizeLogic } from './cliAuthorizeLogic'diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsxindex b64a7288ada4..53501e9386b5 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx@@ -52,6 +52,16 @@ const meta: Meta = {decorators: [mswDecorator({get: {+ // The logic loads projects per organization for users that have organizations+ '/api/organizations/:organization_id/projects/': {+ results: [+ {+ id: 1,+ name: 'Default Project',+ organization: '1',+ },+ ],+ },'/api/projects/': {results: [{@@ -88,6 +98,8 @@ export default metatype Story = StoryObj<{}>+// Identity-only request (openid/email/profile): permissions render as a plain checkmark list+// with no access selectors and no bulk actions.export const DefaultScopes: Story = {render: () => {useDelayedOnMountEffect(() => pushAuthorize())@@ -95,9 +107,10 @@ export const DefaultScopes: Story = {},}-// Explicit request where every requested scope is required: rows render as a plain locked list-// (no checkboxes) and the read-only toggle is hidden, since there is nothing to toggle.-export const WithScopes: Story = {+// Explicit request where every requested scope is required: rows render as a plain locked+// checkmark list (no access selectors) and the bulk actions are hidden, since there is nothing+// to choose.+export const AllScopesRequired: Story = {decorators: [withOAuthApplication({required_scopes: ['experiment:read', 'experiment:write', 'query:read', 'feature_flag:write'],@@ -109,9 +122,10 @@ export const WithScopes: Story = {},}-// Broad/deferred request (empty ceiling): nothing is required, so every row is deselectable and-// the read-only toggle is offered. This is the MCP case.-export const BroadFreePick: Story = {+// Broad/deferred request (nothing required): every row gets a No access / Read / Write selector+// capped at the requested level, plus the Select all / Read-only / Deselect all bulk actions.+// This is the MCP case.+export const AllScopesOptional: Story = {decorators: [withOAuthApplication({ required_scopes: [] })],render: () => {useDelayedOnMountEffect(() => pushAuthorize('experiment:read experiment:write query:read feature_flag:write'))@@ -119,9 +133,9 @@ export const BroadFreePick: Story = {},}-// Mixed: feature_flag:write is required but only read was requested (renders locked at write),-// and experiment:read is required but unrequested (appears as an extra locked row). Because some-// requested scopes stay declinable, the checkboxes remain.+// Mixed: feature_flag:write is required but only read was requested (locked at write), and+// experiment:read is required but unrequested (an extra locked row). Both render in the+// checkmark list with a "Required" tag, while the rest keep their access selectors.export const WithRequiredScopes: Story = {decorators: [withOAuthApplication({ required_scopes: ['experiment:read', 'feature_flag:write'] })],render: () => {@@ -129,3 +143,40 @@ export const WithRequiredScopes: Story = {return <App />},}++// A required read floor below a requested write: the row keeps its selector but "No access" is+// disabled — the user can drop the grant to read, never below the floor.+export const RequiredReadFloorWithOptionalWrite: Story = {+ decorators: [withOAuthApplication({ required_scopes: ['feature_flag:read'] })],+ render: () => {+ useDelayedOnMountEffect(() => pushAuthorize('feature_flag:write insight:write query:read'))+ return <App />+ },+}++// Wildcard request: a single "All PostHog data" row where Read expands to every grantable+// object's read scope and Write grants `*`.+export const WildcardScope: Story = {+ decorators: [withOAuthApplication({ required_scopes: [] })],+ render: () => {+ useDelayedOnMountEffect(() => pushAuthorize('*'))+ return <App />+ },+}++// A long optional list (every scope the PostHog MCP server supports) — the case the bulk+// actions exist for.+export const ManyOptionalScopes: Story = {+ decorators: [withOAuthApplication({ required_scopes: [] })],+ render: () => {+ useDelayedOnMountEffect(() =>+ pushAuthorize(+ 'openid profile email user:read user:write organization:read project:read project:write ' ++ 'feature_flag:read feature_flag:write experiment:read experiment:write insight:read ' ++ 'insight:write dashboard:read dashboard:write query:read survey:read survey:write ' ++ 'event_definition:read event_definition:write error_tracking:read logs:read tracing:read'+ )+ )+ return <App />+ },+}diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsxindex bff3d02bd4a2..17768e87598f 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx@@ -5,16 +5,17 @@ import { useMemo, useState } from 'react'import { IconCheck, IconCheckCircle, IconPlus, IconWarning } from '@posthog/icons'+import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'-import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonTag } from 'lib/lemon-ui/LemonTag'import { Link } from 'lib/lemon-ui/Link'import { Spinner } from 'lib/lemon-ui/Spinner'+import { Tooltip } from 'lib/lemon-ui/Tooltip'import { organizationLogic } from 'scenes/organizationLogic'import ScopeAccessSelector from 'scenes/settings/user/scopes/ScopeAccessSelector'@@ -22,7 +23,7 @@ import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNoticimport { AvailableFeature } from '~/types'import { SceneExport } from '../sceneTypes'-import { oauthAuthorizeLogic } from './oauthAuthorizeLogic'+import { ScopeAccessLevel, oauthAuthorizeLogic } from './oauthAuthorizeLogic'export const OAuthAuthorizeError = ({ title, description }: { title: string; description: string }): JSX.Element => {return (@@ -126,11 +127,11 @@ const InlineCreateForm = ({export const OAuthAuthorize = (): JSX.Element => {const {- scopeRows,+ requiredScopeRows,+ adjustableScopeRows,allScopesRequired,identityScopeDescriptions,- showReadOnlyToggle,- readOnlyMode,+ showReadOnlyBulkAction,oauthApplication,oauthApplicationLoading,allOrganizations,@@ -158,8 +159,8 @@ export const OAuthAuthorize = (): JSX.Element => {setShowCreateProject,setSelectedOrganization,setOauthAuthorizationValue,- setReadOnlyMode,- toggleDeniedScope,+ setScopeAccess,+ setAllScopeAccess,} = useActions(oauthAuthorizeLogic)const { isReadOnly: isImpersonationReadOnly, isImpersonated } = useValues(impersonationNoticeLogic)@@ -378,16 +379,32 @@ export const OAuthAuthorize = (): JSX.Element => {<div className="flex flex-col gap-3"><div className="flex items-center justify-between gap-2 flex-wrap"><div className="text-sm font-semibold uppercase text-muted">Permissions</div>- {showReadOnlyToggle && (- <LemonSegmentedButton- size="small"- value={readOnlyMode ? 'read' : 'full'}- onChange={(value) => setReadOnlyMode(value === 'read')}- options={[- { value: 'full', label: 'All requested' },- { value: 'read', label: 'Read-only' },- ]}- />+ {adjustableScopeRows.length > 1 && (+ <div className="flex items-center gap-1">+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => setAllScopeAccess('write')}+ >+ Select all+ </LemonButton>+ {showReadOnlyBulkAction && (+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => setAllScopeAccess('read')}+ >+ Read-only+ </LemonButton>+ )}+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => setAllScopeAccess('none')}+ >+ Deselect all+ </LemonButton>+ </div>)}</div>{resourceScopesLoading ? (@@ -397,43 +414,54 @@ export const OAuthAuthorize = (): JSX.Element => {</div>) : (<>- {identityScopeDescriptions.length > 0 && (+ {(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)" />+ <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>+ {!allScopesRequired && (+ <Tooltip title={`${appName} requires this permission`}>+ <LemonTag>Required</LemonTag>+ </Tooltip>+ )}+ </li>+ ))}</ul>)}- {scopeRows.length > 0 &&- (allScopesRequired ? (- <ul className="space-y-2">- {scopeRows.map((row) => (- <li key={row.key} className="flex items-center space-x-2">- <IconCheck color="var(--success)" />- <span className="font-medium">{row.description}</span>- </li>- ))}- </ul>- ) : (- <div className="flex flex-col gap-2">- {scopeRows.map((row) => (- <LemonCheckbox- key={row.key}- checked={row.granted}- onChange={() =>- row.toggleKey && toggleDeniedScope(row.toggleKey)- }- label={row.description}- disabledReason={- row.required ? `Required by ${appName}` : undefined- }- />- ))}- </div>- ))}+ {adjustableScopeRows.length > 0 && (+ <div className="flex flex-col">+ {adjustableScopeRows.map((row) => (+ <ScopeAccessRow+ key={row.key}+ label={row.label}+ info={row.info}+ muted={row.value === 'none'}+ value={row.value}+ onChange={(value) =>+ setScopeAccess(row.key, value as ScopeAccessLevel)+ }+ noneDisabledReason={+ row.minLevel !== 'none'+ ? `${appName} requires at least ${row.minLevel} access`+ : undefined+ }+ writeDisabledReason={+ row.maxLevel !== 'write'+ ? `Not requested by ${appName}`+ : undefined+ }+ warning={row.warning}+ />+ ))}+ </div>+ )}</>)}</div>diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.tsindex a97b7ba4802d..8d68fd7721e1 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts@@ -33,19 +33,49 @@ describe('oauthAuthorizeLogic', () => {expected: ['openid', 'feature_flag:write', 'insight:read'],},{- name: 'downgrades every write scope to read in read-only mode',+ name: 'downgrades every write scope to read with the bulk read-only action',scopes: ['openid', 'feature_flag:write', 'dashboard:write', 'query:read'],- apply: () => logic.actions.setReadOnlyMode(true),- expected: ['openid', 'feature_flag:read', 'dashboard:read', 'query:read'],+ apply: () => logic.actions.setAllScopeAccess('read'),+ expected: ['openid', 'dashboard:read', 'feature_flag:read', 'query:read'],},{- name: 'drops a denied object and keeps identity scopes',+ name: 'drops an object set to no access and keeps identity scopes',scopes: ['openid', 'email', 'feature_flag:write'],- apply: () => logic.actions.toggleDeniedScope('feature_flag'),+ apply: () => logic.actions.setScopeAccess('feature_flag', 'none'),expected: ['openid', 'email'],},{- name: 'grants the wildcard unchanged when read-only is off',+ name: 'drops every optional object with the bulk deselect action',+ scopes: ['openid', 'feature_flag:write', 'query:read'],+ apply: () => logic.actions.setAllScopeAccess('none'),+ expected: ['openid'],+ },+ {+ name: 'clamps the bulk select-all action to each requested ceiling',+ scopes: ['openid', 'feature_flag:write', 'query:read'],+ apply: () => {+ logic.actions.setAllScopeAccess('none')+ logic.actions.setAllScopeAccess('write')+ },+ expected: ['openid', 'feature_flag:write', 'query:read'],+ },+ {+ name: 'clamps a per-object write pick to read when only read was requested',+ scopes: ['openid', 'query:read'],+ apply: () => logic.actions.setScopeAccess('query', 'write'),+ expected: ['openid', 'query:read'],+ },+ {+ name: 'lets a per-object pick override a previous bulk action',+ scopes: ['openid', 'feature_flag:write', 'dashboard:write'],+ apply: () => {+ logic.actions.setAllScopeAccess('read')+ logic.actions.setScopeAccess('dashboard', 'write')+ },+ expected: ['openid', 'dashboard:write', 'feature_flag:read'],+ },+ {+ name: 'grants the wildcard unchanged at write level',scopes: ['openid', '*'],expected: ['openid', '*'],},@@ -57,14 +87,14 @@ describe('oauthAuthorizeLogic', () => {expect(logic.values.effectiveScopes).toEqual(expected)})- it('offers the read-only toggle for wildcard requests', () => {+ it('offers the bulk read-only action for wildcard requests', () => {logic.actions.setScopes(['*'])- expect(logic.values.showReadOnlyToggle).toBe(true)+ expect(logic.values.showReadOnlyBulkAction).toBe(true)})- it('expands the wildcard to read scopes in read-only mode', () => {+ it('expands the wildcard to read scopes when set to read level', () => {logic.actions.setScopes(['openid', '*'])- logic.actions.setReadOnlyMode(true)+ logic.actions.setScopeAccess('*', 'read')const scopes = logic.values.effectiveScopesexpect(scopes).toContain('openid')expect(scopes).toContain('feature_flag:read')@@ -85,15 +115,15 @@ describe('oauthAuthorizeLogic', () => {logo_uri: null,wildcard_read_scopes: ['insight:read', 'batch_import:read'],})- logic.actions.setReadOnlyMode(true)+ logic.actions.setScopeAccess('*', 'read')expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:read', 'batch_import:read'])})- it('drops a scope when its object is denied and re-adds it when toggled back', () => {+ it('drops a scope when its object is set to no access and re-adds it when selected again', () => {logic.actions.setScopes(['openid', 'feature_flag:write', 'insight:read'])- logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setScopeAccess('feature_flag', 'none')expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:read'])- logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setScopeAccess('feature_flag', 'write')expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'insight:read'])})@@ -107,36 +137,35 @@ describe('oauthAuthorizeLogic', () => {})}- it('ignores denial of a required object and marks its row required', () => {+ it('ignores a no-access pick on a fully required object and marks its row locked', () => {logic.actions.setScopes(['openid', 'feature_flag:write', 'insight:read'])withRequiredScopes(['feature_flag:write'])- logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setScopeAccess('feature_flag', 'none')expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'insight:read'])const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')- expect(row).toMatchObject({ required: true, granted: true })+ expect(row).toMatchObject({ locked: true, value: 'write' })})- it('keeps a required write scope at write level in read-only mode', () => {+ it('keeps a required write scope at write level under the bulk read-only action', () => {logic.actions.setScopes(['openid', 'feature_flag:write', 'dashboard:write'])withRequiredScopes(['feature_flag:write'])- logic.actions.setReadOnlyMode(true)- expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'dashboard:read'])+ logic.actions.setAllScopeAccess('read')+ expect(logic.values.effectiveScopes).toEqual(['openid', 'dashboard:read', 'feature_flag:write'])})- it('downgrades to read in read-only mode when only the read level is required', () => {+ it('downgrades to read under the bulk read-only action when only the read level is required', () => {logic.actions.setScopes(['openid', 'feature_flag:write'])withRequiredScopes(['feature_flag:read'])- logic.actions.setReadOnlyMode(true)+ logic.actions.setAllScopeAccess('read')expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:read'])- const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')- expect(row).toMatchObject({ required: true, granted: true })})it('marks all scopes required when every requested scope is required', () => {logic.actions.setScopes(['experiment:read', 'dashboard:write'])withRequiredScopes(['experiment:read', 'dashboard:write'])expect(logic.values.allScopesRequired).toBe(true)- expect(logic.values.showReadOnlyToggle).toBe(false)+ expect(logic.values.adjustableScopeRows).toEqual([])+ expect(logic.values.showReadOnlyBulkAction).toBe(false)})it('does not mark all required when a requested scope is declinable', () => {@@ -149,29 +178,24 @@ describe('oauthAuthorizeLogic', () => {logic.actions.setScopes(['openid', 'insight:read'])withRequiredScopes(['feature_flag:read'])const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')- expect(row).toMatchObject({ required: true, granted: true })+ expect(row).toMatchObject({ locked: true, value: 'read' })expect(logic.values.effectiveScopes).toEqual(expect.arrayContaining(['openid', 'insight:read', 'feature_flag:read']))expect(logic.values.effectiveScopes).toHaveLength(3)})- it('lets the user decline an optional write above a required read floor', () => {+ 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'])- const floor = logic.values.scopeRows.find((r) => r.key === 'feature_flag')- const upgrade = logic.values.scopeRows.find((r) => r.key === 'feature_flag:optional-write')- expect(floor).toMatchObject({ required: true, granted: true, toggleKey: null })- expect(upgrade).toMatchObject({ required: false, granted: true, toggleKey: 'feature_flag' })+ const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')+ expect(row).toMatchObject({ locked: false, minLevel: 'read', maxLevel: 'write', value: 'write' })expect(logic.values.effectiveScopes).toContain('feature_flag:write')- logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setScopeAccess('feature_flag', 'none')expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:read'])- expect(logic.values.scopeRows.find((r) => r.key === 'feature_flag:optional-write')).toMatchObject({- granted: false,- })- logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setScopeAccess('feature_flag', 'write')expect(logic.values.effectiveScopes).toContain('feature_flag:write')})@@ -179,19 +203,17 @@ describe('oauthAuthorizeLogic', () => {logic.actions.setScopes(['openid', 'feature_flag:read'])withRequiredScopes(['feature_flag:write'])const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')- expect(row).toMatchObject({ required: true, granted: true })+ expect(row).toMatchObject({ locked: true, value: 'write' })expect(row?.description).toContain('Write')expect(logic.values.effectiveScopes).toContain('feature_flag:write')expect(logic.values.effectiveScopes).not.toContain('feature_flag:read')})- it('resets read-only mode and denied scopes when scopes are reloaded', () => {+ it('resets access selections when scopes are reloaded', () => {logic.actions.setScopes(['openid', 'feature_flag:write'])- logic.actions.setReadOnlyMode(true)- logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setAllScopeAccess('read')+ logic.actions.setScopeAccess('feature_flag', 'none')logic.actions.setScopes(['openid', 'insight:write'])- expect(logic.values.readOnlyMode).toBe(false)- expect(logic.values.deniedScopeObjects).toEqual([])expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:write'])})diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.tsindex 9f40469e9cba..2cd886cc1438 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts@@ -29,9 +29,49 @@ const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'introspection']const scopeObjectKey = (scope: string): string => (scope === '*' ? '*' : scope.split(':')[0])-const toReadOnlyScope = (scope: string): string => (scope.endsWith(':write') ? `${scope.split(':')[0]}:read` : scope)+export type ScopeAccessLevel = 'none' | 'read' | 'write'-const WILDCARD_READ_DESCRIPTION = 'Read access to all PostHog data'+const ACCESS_LEVEL_ORDER: Record<ScopeAccessLevel, number> = { none: 0, read: 1, write: 2 }++const clampAccessLevel = (level: ScopeAccessLevel, min: ScopeAccessLevel, max: ScopeAccessLevel): ScopeAccessLevel => {+ if (ACCESS_LEVEL_ORDER[level] < ACCESS_LEVEL_ORDER[min]) {+ return min+ }+ if (ACCESS_LEVEL_ORDER[level] > ACCESS_LEVEL_ORDER[max]) {+ return max+ }+ return level+}++export type OAuthScopeRow = {+ /** Scope object key (e.g. 'feature_flag'), or '*' for the wildcard. */+ key: string+ /** Human name for the object (e.g. 'Feature flag'). */+ label: string+ /** Full sentence description at the granted level, for the locked (checkmark) list. */+ description: string+ /** Optional extra context from API_SCOPES, shown as an info tooltip. */+ info?: string | JSX.Element+ /** Warning for the currently selected level, if any. */+ warning?: string | JSX.Element+ /** 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'>+ /** Current (clamped) selection. */+ value: ScopeAccessLevel+ /** True when minLevel === maxLevel: nothing to choose, rendered as a locked checkmark row. */+ locked: boolean+}++const WILDCARD_LABEL = 'All PostHog data'++// 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`.@@ -119,8 +159,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([})),actions({setScopes: (scopes: string[]) => ({ scopes }),- setReadOnlyMode: (readOnly: boolean) => ({ readOnly }),- toggleDeniedScope: (scopeObject: string) => ({ scopeObject }),+ setScopeAccess: (scopeObject: string, level: ScopeAccessLevel) => ({ scopeObject, level }),+ setAllScopeAccess: (level: ScopeAccessLevel) => ({ level }),setRequiredAccessLevel: (requiredAccessLevel: 'organization' | 'team' | null) => ({ requiredAccessLevel }),setTeamHint: (teamId: number | null) => ({ teamId }),setScopesWereDefaulted: (scopesWereDefaulted: boolean) => ({ scopesWereDefaulted }),@@ -245,19 +285,22 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([setScopes: (_, { scopes }) => scopes,},],- readOnlyMode: [- false,- {- setReadOnlyMode: (_, { readOnly }) => readOnly,- setScopes: () => false,+ // 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]+ // 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>},- ],- deniedScopeObjects: [- [] as string[],{- toggleDeniedScope: (state, { scopeObject }) =>- state.includes(scopeObject) ? state.filter((s) => s !== scopeObject) : [...state, scopeObject],- setScopes: () => [],+ setScopeAccess: (state, { scopeObject, level }) => ({+ ...state,+ overrides: { ...state.overrides, [scopeObject]: level },+ }),+ setAllScopeAccess: (_, { level }) => ({ bulk: level, overrides: {} }),+ setScopes: () => ({ bulk: null, overrides: {} }),},],requiredAccessLevel: [@@ -503,19 +546,6 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([(oauthApplication: OAuthApplicationPublicMetadata | null): Map<string, RequiredLevel> =>requiredLevelsFromScopes(oauthApplication?.required_scopes ?? []),],- // Only surface the read-only toggle when at least one write scope is declinable- // (not required at write level). When every write scope is required, switching to- // read-only would change nothing, so the toggle is a confusing no-op.- showReadOnlyToggle: [- (s) => [s.consentResourceScopes, s.requiredScopeLevels],- (consentResourceScopes: string[], requiredScopeLevels: Map<string, RequiredLevel>): boolean =>- consentResourceScopes.some((scope) => {- if (!scope.endsWith(':write') && scope !== '*') {- return false- }- return requiredScopeLevels.get(scopeObjectKey(scope)) !== 'write'- }),- ],// 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@@ -531,129 +561,76 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([)},],+ // 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.scopeRows: [- (s) => [s.consentResourceScopes, s.deniedScopeObjects, s.readOnlyMode, s.requiredScopeLevels],+ (s) => [s.consentResourceScopes, s.scopeAccessSelections, s.requiredScopeLevels],(consentResourceScopes: string[],- deniedScopeObjects: string[],- readOnlyMode: boolean,+ scopeAccessSelections: { bulk: ScopeAccessLevel | null; overrides: Record<string, ScopeAccessLevel> },requiredScopeLevels: Map<string, RequiredLevel>- ): {- key: string- toggleKey: string | null- description: string- granted: boolean- required: boolean- }[] => {- const denied = new Set(deniedScopeObjects)- return consentResourceScopes.flatMap((scope) => {+ ): OAuthScopeRow[] => {+ const rows = consentResourceScopes.map((scope): OAuthScopeRow => {const key = scopeObjectKey(scope)- const requiredLevel = requiredScopeLevels.get(key)- if (requiredLevel === undefined) {- const downgrade = readOnlyMode- if (scope === '*') {- return [- {- key: '*',- toggleKey: '*',- description: downgrade- ? WILDCARD_READ_DESCRIPTION- : (getScopeDescription('*') ?? '*'),- granted: !denied.has('*'),- required: false,- },- ]- }- const effective = downgrade ? toReadOnlyScope(scope) : scope- return [- {- key,- toggleKey: key,- description: getScopeDescription(effective) ?? effective,- granted: !denied.has(key),- required: false,- },- ]- }- // The required floor renders locked. An optional write above a required- // read gets its own deniable row, so declining the upgrade doesn't take- // the required level with it. Read-only mode suppresses the upgrade row- // since the toggle already pins everything to read.- const floorScope = scope === '*' ? '*' : `${key}:${requiredLevel}`- const rows: {- key: string- toggleKey: string | null- description: string- granted: boolean- required: boolean- }[] = [- {- key,- toggleKey: null,- description: getScopeDescription(floorScope) ?? floorScope,- granted: true,- required: true,- },- ]- if (requiredLevel === 'read' && scope.endsWith(':write') && !readOnlyMode) {- rows.push({- key: `${key}:optional-write`,- toggleKey: key,- description: getScopeDescription(scope) ?? scope,- granted: !denied.has(key),- required: false,- })+ const maxLevel: 'read' | 'write' = scope === '*' || scope.endsWith(':write') ? 'write' : 'read'+ const minLevel: ScopeAccessLevel = requiredScopeLevels.get(key) ?? 'none'+ const selected = scopeAccessSelections.overrides[key] ?? scopeAccessSelections.bulk ?? maxLevel+ const value = clampAccessLevel(selected, minLevel, maxLevel)+ 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],+ minLevel,+ maxLevel,+ value,+ locked: minLevel === maxLevel,}- return rows})+ return rows.sort((a, b) => a.label.localeCompare(b.label))},],- // When every row is required the user has nothing to toggle, so the consent screen- // renders a plain locked list instead of disabled checkboxes that imply a choice.+ // Locked rows (required at exactly the requested level) render as a plain checkmark+ // list — there is nothing to choose — while adjustable rows get an access selector.+ requiredScopeRows: [+ (s) => [s.scopeRows],+ (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => row.locked),+ ],+ adjustableScopeRows: [+ (s) => [s.scopeRows],+ (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => !row.locked),+ ],allScopesRequired: [(s) => [s.scopeRows],- (scopeRows: { required: boolean }[]): boolean =>- scopeRows.length > 0 && scopeRows.every((row) => row.required),+ (scopeRows: OAuthScopeRow[]): boolean => scopeRows.length > 0 && scopeRows.every((row) => row.locked),+ ],+ // Only offer the bulk read-only action when it would change something — i.e. at least+ // one adjustable row can sit at write level.+ showReadOnlyBulkAction: [+ (s) => [s.adjustableScopeRows],+ (adjustableScopeRows: OAuthScopeRow[]): boolean =>+ adjustableScopeRows.some((row) => row.maxLevel === 'write'),],effectiveScopes: [- (s) => [- s.scopes,- s.consentResourceScopes,- s.deniedScopeObjects,- s.readOnlyMode,- s.requiredScopeLevels,- s.oauthApplication,- ],+ (s) => [s.scopes, s.scopeRows, s.oauthApplication],(scopes: string[],- consentResourceScopes: string[],- deniedScopeObjects: string[],- readOnlyMode: boolean,- requiredScopeLevels: Map<string, RequiredLevel>,+ scopeRows: OAuthScopeRow[],oauthApplication: OAuthApplicationPublicMetadata | null): string[] => {- const denied = new Set(deniedScopeObjects)const identity = scopes.filter((scope) => IDENTITY_SCOPES.includes(scope))- const resources = consentResourceScopes.flatMap((scope) => {- const key = scopeObjectKey(scope)- const requiredLevel = requiredScopeLevels.get(key)- if (requiredLevel === undefined) {- if (denied.has(key)) {- return []- }- if (scope === '*') {- return readOnlyMode ? wildcardReadScopes(oauthApplication) : ['*']- }- return [readOnlyMode ? toReadOnlyScope(scope) : scope]+ const resources = scopeRows.flatMap((row) => {+ if (row.value === 'none') {+ return []}- if (scope === '*') {- return ['*']+ if (row.key === '*') {+ return row.value === 'write' ? ['*'] : wildcardReadScopes(oauthApplication)}- // Denying the optional upgrade (or read-only mode) drops the grant to the- // required floor, never below it.- const upgradeActive =- requiredLevel === 'read' && scope.endsWith(':write') && !readOnlyMode && !denied.has(key)- return [upgradeActive ? scope : `${key}:${requiredLevel}`]+ return [`${row.key}:${row.value}`]})// Also grant the required strings verbatim: collapsing read+write pairs above// could otherwise drop a literal entry the server's set-difference check expects.diff --git a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsxindex 00a0334302e2..8c890e54471f 100644--- a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx+++ b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx@@ -5,11 +5,11 @@ import { IconPlus } from '@posthog/icons'import { LemonButton, LemonInput, LemonModal, LemonSelect } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { TeamMembershipLevel } from 'lib/constants'import { LemonField } from 'lib/lemon-ui/LemonField'import { APIKeyTable } from '../shared/APIKeyTable'-import { ScopeAccessRow } from '../shared/ScopeAccessRow'import { MAX_PROJECT_API_KEYS_PER_PROJECT, projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'function EditKeyModal(): JSX.Element {diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsxindex 4ec38025d5a0..2e273f7d11b6 100644--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx@@ -16,6 +16,7 @@ import {Tooltip,} from '@posthog/lemon-ui'+import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonField } from 'lib/lemon-ui/LemonField'@@ -25,7 +26,6 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { PersonalAPIKeyType } from '~/types'import { APIKeyTable } from '../shared/APIKeyTable'-import { ScopeAccessRow } from '../shared/ScopeAccessRow'import { personalAPIKeysLogic } from './personalAPIKeysLogic'import ScopeAccessSelector from './scopes/ScopeAccessSelector'