Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(scopes): clean up duplicated scope picker row logic (#112124)

Alex Lider0864177f32ff
diff --git a/frontend/src/lib/components/ScopeAccessRow/ScopeAccessGroup.tsx b/frontend/src/lib/components/ScopeAccessRow/ScopeAccessGroup.tsx
index 4b01de9a8176..fefc01bb8551 100644
--- a/frontend/src/lib/components/ScopeAccessRow/ScopeAccessGroup.tsx
+++ b/frontend/src/lib/components/ScopeAccessRow/ScopeAccessGroup.tsx
@@ -1,52 +1,46 @@
import clsx from 'clsx'
-import { type ReactNode, useId, useState } from 'react'
+import { useId, useState } from 'react'
import { IconChevronRight } from '@posthog/icons'
import { LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'
-import type { ScopeAccessLevel } from 'lib/scopes'
+import {
+ type ScopePickerGroup,
+ type ScopeAccessLevel,
+ countScopeRowsByLevel,
+ scopeGroupLevel,
+ scopeGroupDisabledReasons,
+ scopeGroupTooltip,
+} from 'lib/scopes'
+
+import { ScopeAccessRow } from './ScopeAccessRow'
interface ScopeAccessGroupProps {
- /** Group heading, such as a product area. */
- label: string
- /** How many rows in the group sit at each level, for the tags in the header. */
- counts: Record<ScopeAccessLevel, number>
- /** The level the group control shows as selected. Undefined when the rows disagree. */
- value: ScopeAccessLevel | undefined
- /** Called with the level the user picks for the whole group. */
- onChange: (level: ScopeAccessLevel) => 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. */
- writeDisabledReason?: string
- /** Tooltip on the selected level, for when some rows sit at another level. */
- valueTooltip?: string
+ group: ScopePickerGroup
+ onChangeRow: (scopeObject: string, level: ScopeAccessLevel) => void
+ onChangeGroup: (scopeObjects: string[], level: ScopeAccessLevel) => void
/** Whether the rows show on first render. */
defaultOpen?: boolean
/** Prefix of the `data-attr`s: `<prefix>-toggle-<slug>` on the toggle, `<prefix>-<slug>-<level>` on an option. */
dataAttrPrefix: string
- /** The rows of the group, rendered when the group is open. */
- children: ReactNode
}
+/** A collapsible group of scope rows with a control that sets every row at once. */
export function ScopeAccessGroup({
- label,
- counts,
- value,
- onChange,
- noneDisabledReason,
- readDisabledReason,
- writeDisabledReason,
- valueTooltip,
+ group,
+ onChangeRow,
+ onChangeGroup,
defaultOpen = false,
dataAttrPrefix,
- children,
}: ScopeAccessGroupProps): JSX.Element {
+ const { label, rows } = group
const [open, setOpen] = useState(defaultOpen)
const panelId = useId()
- const total = counts.none + counts.read + counts.write
+ const counts = countScopeRowsByLevel(rows)
+ const value = scopeGroupLevel(rows)
+ const disabledReasons = scopeGroupDisabledReasons(rows)
+ const valueTooltip = scopeGroupTooltip(rows, value)
+ const keys = rows.map((row) => row.key)
const groupSlug = label.toLowerCase().replace(/[^a-z0-9]+/g, '-')
return (
@@ -73,7 +67,7 @@ export function ScopeAccessGroup({
<div className="flex items-center gap-2 ml-auto shrink-0">
<span className="hidden @min-[36rem]/scope-group:flex items-center gap-2">
<span className="text-xs text-muted whitespace-nowrap">
- <span translate="no">{total}</span> {total === 1 ? 'permission' : 'permissions'}
+ <span translate="no">{rows.length}</span> {rows.length === 1 ? 'permission' : 'permissions'}
</span>
<span className="flex items-center gap-1">
{counts.none > 0 && (
@@ -97,13 +91,14 @@ export function ScopeAccessGroup({
<LemonSegmentedButton
size="xsmall"
value={value}
- onChange={(level) => onChange(level as ScopeAccessLevel)}
+ onChange={(level) => onChangeGroup(keys, level as ScopeAccessLevel)}
options={[
- { label: 'No access', value: 'none', disabledReason: noneDisabledReason },
- { label: 'Read', value: 'read', disabledReason: readDisabledReason },
- { label: 'Write', value: 'write', disabledReason: writeDisabledReason },
+ { label: 'No access', value: 'none' as const },
+ { label: 'Read', value: 'read' as const },
+ { label: 'Write', value: 'write' as const },
].map((option) => ({
...option,
+ disabledReason: disabledReasons[option.value],
// Tells a group change apart from a row change in autocapture.
'data-attr': `${dataAttrPrefix}-${groupSlug}-${option.value}`,
tooltip: option.value === value ? valueTooltip : undefined,
@@ -114,7 +109,9 @@ export function ScopeAccessGroup({
</div>
{open && (
<div id={panelId} className="flex flex-col pb-2 pl-7">
- {children}
+ {rows.map((row) => (
+ <ScopeAccessRow key={row.key} row={row} onChange={onChangeRow} />
+ ))}
</div>
)}
</div>
diff --git a/frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsx b/frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsx
index e46678af05cf..fb81cb3fd68c 100644
--- a/frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsx
+++ b/frontend/src/lib/components/ScopeAccessRow/ScopeAccessRow.tsx
@@ -3,38 +3,17 @@ import clsx from 'clsx'
import { IconInfo, IconWarning } from '@posthog/icons'
import { LemonSegmentedButton, Tooltip } from '@posthog/lemon-ui'
+import type { ScopeAccessLevel, ScopePickerRow } from 'lib/scopes'
+
interface ScopeAccessRowProps {
- /** Display label for the scope (e.g. 'Feature flag', 'Endpoint'). */
- label: string
- /** Currently selected action: 'none' | 'read' | 'write'. */
- 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. */
- writeDisabledReason?: string
- /** Optional tooltip content shown next to the label via an info icon. */
- info?: string | JSX.Element
- /** When true, the label is dimmed (e.g. when the row is contextually disabled). */
- muted?: boolean
- /** Optional warning content rendered as a sub-row below the main row. */
- warning?: string | JSX.Element | null
+ row: ScopePickerRow
+ /** Called with the row's scope object and the level the user picks. */
+ onChange: (scopeObject: string, level: ScopeAccessLevel) => void
}
-export function ScopeAccessRow({
- label,
- value,
- onChange,
- noneDisabledReason,
- readDisabledReason,
- writeDisabledReason,
- info,
- muted = false,
- warning,
-}: ScopeAccessRowProps): JSX.Element {
+/** One scope object in a picker: its label and a No access / Read / Write control. */
+export function ScopeAccessRow({ row, onChange }: ScopeAccessRowProps): JSX.Element {
+ const { key, label, info, value, muted, warning, disabledReasons } = row
return (
<>
<div className="flex items-center justify-between gap-2 min-h-8 group">
@@ -47,12 +26,12 @@ export function ScopeAccessRow({
) : null}
</div>
<LemonSegmentedButton
- onChange={onChange}
+ onChange={(level) => onChange(key, level as ScopeAccessLevel)}
value={value}
options={[
- { label: 'No access', value: 'none', disabledReason: noneDisabledReason },
- { label: 'Read', value: 'read', disabledReason: readDisabledReason },
- { label: 'Write', value: 'write', disabledReason: writeDisabledReason },
+ { label: 'No access', value: 'none', disabledReason: disabledReasons.none },
+ { label: 'Read', value: 'read', disabledReason: disabledReasons.read },
+ { label: 'Write', value: 'write', disabledReason: disabledReasons.write },
]}
size="xsmall"
/>
diff --git a/frontend/src/lib/integrations/PosthogConnect.tsx b/frontend/src/lib/integrations/PosthogConnect.tsx
index 2b9df395d17a..157dc6d3a470 100644
--- a/frontend/src/lib/integrations/PosthogConnect.tsx
+++ b/frontend/src/lib/integrations/PosthogConnect.tsx
@@ -8,7 +8,13 @@ import api from 'lib/api'
import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'
import { TZLabel } from 'lib/components/TZLabel'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
-import { API_SCOPES, scopeMatchesSearch, scopesArrayToObject, scopesObjectToArray } from 'lib/scopes'
+import {
+ API_SCOPES,
+ type ScopeAccessLevel,
+ scopeMatchesSearch,
+ scopesArrayToObject,
+ scopesObjectToArray,
+} from 'lib/scopes'
import { userLogic } from 'scenes/userLogic'
import { IntegrationType } from '~/types'
@@ -177,25 +183,28 @@ function ConnectModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => voi
{filteredScopes.length === 0 ? (
<div className="text-muted text-sm py-2">No scopes match "{searchTerm}"</div>
) : (
- filteredScopes.map((scope) => (
- <ScopeAccessRow
- key={scope.key}
- label={scope.objectName}
- info={scope.info}
- value={scopeActions[scope.key] ?? 'none'}
- onChange={(value) => setScopeAction(scope.key, value)}
- readDisabledReason={
- scope.disabledActions?.includes('read')
- ? 'Does not apply to this resource'
- : undefined
- }
- writeDisabledReason={
- scope.disabledActions?.includes('write')
- ? 'Does not apply to this resource'
- : undefined
- }
- />
- ))
+ filteredScopes.map((scope) => {
+ const disabledReason = (action: 'read' | 'write'): string | undefined =>
+ scope.disabledActions?.includes(action)
+ ? 'Does not apply to this resource'
+ : undefined
+ return (
+ <ScopeAccessRow
+ key={scope.key}
+ row={{
+ key: scope.key,
+ label: scope.objectName,
+ info: scope.info,
+ value: (scopeActions[scope.key] ?? 'none') as ScopeAccessLevel,
+ disabledReasons: {
+ read: disabledReason('read'),
+ write: disabledReason('write'),
+ },
+ }}
+ onChange={setScopeAction}
+ />
+ )
+ })
)}
</div>
</div>
diff --git a/frontend/src/lib/scopes.test.ts b/frontend/src/lib/scopes.test.ts
index b332ecaecc6d..22940bae611c 100644
--- a/frontend/src/lib/scopes.test.ts
+++ b/frontend/src/lib/scopes.test.ts
@@ -5,7 +5,11 @@ import {
API_SCOPE_GROUPS,
API_SCOPES,
API_SCOPES_OMITTED_FROM_MODAL,
+ type ScopePickerRow,
+ clampScopeLevel,
getScopeDescription,
+ scopeGroupLevel,
+ scopeGroupTooltip,
scopeMatchesSearch,
} from 'lib/scopes'
@@ -91,6 +95,45 @@ describe('API_SCOPE_GROUPS', () => {
})
})
+describe('scope access groups', () => {
+ const row = (key: string, value: ScopePickerRow['value'], disabledReasons = {}): ScopePickerRow => ({
+ key,
+ label: key,
+ value,
+ disabledReasons,
+ })
+
+ // The clamp has to go down for a level the row refuses and up for a level the app requires,
+ // because the key modal only has the first case and the consent screen has both.
+ it.each([
+ ['stays on an allowed level', row('a', 'none'), 'write', 'write'],
+ ['drops to read when write is refused', row('a', 'none', { write: 'Not requested' }), 'write', 'read'],
+ [
+ 'drops to none when read and write are refused',
+ row('a', 'none', { read: 'No', write: 'No' }),
+ 'write',
+ 'none',
+ ],
+ ['rises to read when none is refused', row('a', 'write', { none: 'Required' }), 'none', 'read'],
+ ])('%s', (_name, model, level, expected) => {
+ expect(clampScopeLevel(model, level as ScopePickerRow['value'])).toBe(expected)
+ })
+
+ it('never selects a level no row can take, and names each row reason in the tooltip', () => {
+ const rows = [
+ row('a', 'read', { write: 'Not requested by App' }),
+ row('b', 'read', { write: 'Not available for project scoped keys' }),
+ row('c', 'write'),
+ ]
+ expect(scopeGroupLevel(rows)).toBe('write')
+ expect(scopeGroupTooltip(rows, 'write')).toBe(
+ '1 of these permissions stays at read: Not requested by App. 1 of these permissions stays at read: Not available for project scoped keys.'
+ )
+ expect(scopeGroupLevel(rows.slice(0, 2))).toBe('read')
+ expect(scopeGroupLevel([row('a', 'read'), row('b', 'none')])).toBeUndefined()
+ })
+})
+
describe('scopeMatchesSearch', () => {
const featureFlag = { key: 'feature_flag', objectName: 'Feature flag', objectPlural: 'feature flags' }
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 006420472fe3..ee8494a82ff2 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -6,6 +6,79 @@ export const MAX_API_KEYS_PER_USER = 10 // Same as in posthog/api/personal_api_k
export type ScopeAccessLevel = 'none' | 'read' | 'write'
+const SCOPE_ACCESS_LEVELS: readonly ScopeAccessLevel[] = ['none', 'read', 'write']
+
+const SCOPE_ACCESS_LEVEL_LABELS: Record<ScopeAccessLevel, string> = { none: 'no access', read: 'read', write: 'write' }
+
+/**
+ * One scope object in a picker, with the levels it can take. The OAuth consent screen and the key
+ * modal both build this shape, so one group control serves both. A level with no disabled reason is
+ * available. The reason is the text the row's segment shows.
+ */
+export type ScopePickerRow = {
+ key: string
+ label: string
+ value: ScopeAccessLevel
+ disabledReasons: Partial<Record<ScopeAccessLevel, string>>
+ info?: string | JSX.Element
+ warning?: string | JSX.Element
+ /** True when the row is dimmed, for example at no access or when a project scoped key rules it out. */
+ muted?: boolean
+}
+
+export type ScopePickerGroup<Row extends ScopePickerRow = ScopePickerRow> = {
+ label: string
+ rows: Row[]
+}
+
+export const scopeRowAllows = (row: ScopePickerRow, level: ScopeAccessLevel): boolean => !row.disabledReasons[level]
+
+// The nearest available level: the same or a lower one first, so a group set to write holds a
+// read-only row at read, then a higher one, so a row an app requires at read never drops to none.
+export const clampScopeLevel = (row: ScopePickerRow, level: ScopeAccessLevel): ScopeAccessLevel => {
+ const index = SCOPE_ACCESS_LEVELS.indexOf(level)
+ const candidates = [...SCOPE_ACCESS_LEVELS.slice(0, index + 1).reverse(), ...SCOPE_ACCESS_LEVELS.slice(index + 1)]
+ return candidates.find((candidate) => scopeRowAllows(row, candidate)) ?? row.value
+}
+
+// The group shows a level as selected when each row is at that level after the clamp. A level no
+// row can take is never selected, which removes the tie between write and read in a group with no
+// writable row, and between none and read in a group of required rows.
+export const scopeGroupLevel = (rows: ScopePickerRow[]): ScopeAccessLevel | undefined =>
+ [...SCOPE_ACCESS_LEVELS]
+ .reverse()
+ .find(
+ (level) =>
+ rows.some((row) => scopeRowAllows(row, level)) &&
+ rows.every((row) => row.value === clampScopeLevel(row, level))
+ )
+
+// A level is disabled on the group when no row can take it. The reason is the rows' own.
+export const scopeGroupDisabledReasons = (rows: ScopePickerRow[]): Partial<Record<ScopeAccessLevel, string>> =>
+ Object.fromEntries(
+ SCOPE_ACCESS_LEVELS.flatMap((level) => {
+ const reason = rows.find((row) => !scopeRowAllows(row, level))?.disabledReasons[level]
+ return reason && rows.every((row) => !scopeRowAllows(row, level)) ? [[level, reason]] : []
+ })
+ )
+
+// Tooltip on the selected group level, for the rows that sit at another level after the clamp.
+// Each row gives the reason its own segment shows, so the text names the real cause.
+export const scopeGroupTooltip = (rows: ScopePickerRow[], level: ScopeAccessLevel | undefined): string | undefined => {
+ if (!level) {
+ return undefined
+ }
+ const counts = new Map<string, number>()
+ for (const row of rows.filter((row) => row.value !== level)) {
+ const note = `at ${SCOPE_ACCESS_LEVEL_LABELS[row.value]}: ${row.disabledReasons[level] ?? ''}`
+ counts.set(note, (counts.get(note) ?? 0) + 1)
+ }
+ const notes = [...counts].map(
+ ([note, count]) => `${count} of these permissions ${count === 1 ? 'stays' : 'stay'} ${note}.`
+ )
+ return notes.length > 0 ? notes.join(' ') : undefined
+}
+
export const countScopeRowsByLevel = (rows: { value: ScopeAccessLevel }[]): Record<ScopeAccessLevel, number> => {
const counts: Record<ScopeAccessLevel, number> = { none: 0, read: 0, write: 0 }
for (const row of rows) {
@@ -596,6 +669,19 @@ const SCOPE_GROUP_LABEL_BY_OBJECT: Record<string, string> = Object.fromEntries(
export const getScopeGroupLabel = (scopeObject: string): string =>
SCOPE_GROUP_LABEL_BY_OBJECT[scopeObject] ?? OTHER_SCOPE_GROUP_LABEL
+// The rows grouped by product area in API_SCOPE_GROUPS order. An object that is in no group goes in
+// the "Other" group at the end, so it still shows. A group with no row is left out.
+export const groupScopeRows = <Row extends ScopePickerRow>(rows: Row[]): ScopePickerGroup<Row>[] => {
+ const rowsByLabel = new Map<string, Row[]>()
+ for (const row of rows) {
+ const label = getScopeGroupLabel(row.key)
+ rowsByLabel.set(label, [...(rowsByLabel.get(label) ?? []), row])
+ }
+ return [...API_SCOPE_GROUPS.map(({ label }) => label), OTHER_SCOPE_GROUP_LABEL]
+ .filter((label) => rowsByLabel.has(label))
+ .map((label) => ({ label, rows: rowsByLabel.get(label) ?? [] }))
+}
+
export const DEFAULT_OAUTH_SCOPES = ['openid', 'email', 'profile']
export const getScopeDescription = (scope: string): string | undefined => {
diff --git a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx
index 247b20119b34..9b5ba189b6ba 100644
--- a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx
+++ b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx
@@ -9,6 +9,7 @@ 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 type { ScopeAccessLevel } from 'lib/scopes'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -167,31 +168,32 @@ export function CLIAuthorize(): JSX.Element {
) : (
filteredScopes.map(
({ key, objectName, disabledActions, warnings, info }) => {
- const selected = formScopeRadioValues[key]
- const warningAction =
- selected === 'read' || selected === 'write'
- ? selected
- : null
+ const value = (formScopeRadioValues[key] ??
+ 'none') as ScopeAccessLevel
+ const disabledReason = (
+ action: 'read' | 'write'
+ ): string | undefined =>
+ disabledActions?.includes(action)
+ ? 'Does not apply to this resource'
+ : undefined
return (
<ScopeAccessRow
key={key}
- label={objectName}
- info={info}
- value={selected ?? 'none'}
- onChange={(value) => setScopeRadioValue(key, value)}
- readDisabledReason={
- disabledActions?.includes('read')
- ? 'Does not apply to this resource'
- : undefined
- }
- writeDisabledReason={
- disabledActions?.includes('write')
- ? 'Does not apply to this resource'
- : undefined
- }
- warning={
- warningAction ? warnings?.[warningAction] : null
- }
+ row={{
+ key,
+ label: objectName,
+ info,
+ value,
+ warning:
+ value === 'none'
+ ? undefined
+ : warnings?.[value],
+ disabledReasons: {
+ read: disabledReason('read'),
+ write: disabledReason('write'),
+ },
+ }}
+ onChange={setScopeRadioValue}
/>
)
}
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
index c8884c4e7320..03bbd0c69c4d 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
@@ -4,6 +4,8 @@ import { useMemo, useState } from 'react'
import { IconCheck, IconCheckCircle, IconLock, IconPlus, IconWarning } from '@posthog/icons'
+import { ScopeAccessGroup } from 'lib/components/ScopeAccessRow/ScopeAccessGroup'
+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'
@@ -25,8 +27,6 @@ import { AvailableFeature } from '~/types'
import { SceneExport } from '../sceneTypes'
import { OAuthAuthorizeLayout } from './OAuthAuthorizeLayout'
import { oauthAuthorizeLogic } from './oauthAuthorizeLogic'
-import { OAuthScopeGroupControl } from './OAuthScopeGroupControl'
-import { OAuthScopeRowControl } from './OAuthScopeRowControl'
export const OAuthAuthorizeError = ({ title, description }: { title: string; description: string }): JSX.Element => {
return (
@@ -466,13 +466,12 @@ export const OAuthAuthorize = (): JSX.Element => {
{scopeRowsGrouped ? (
<div className="flex flex-col">
{scopeGroups.map((group) => (
- <OAuthScopeGroupControl
+ <ScopeAccessGroup
key={group.label}
- label={group.label}
- rows={group.rows}
- appName={appName}
+ group={group}
onChangeRow={setScopeAccess}
onChangeGroup={setScopeGroupAccess}
+ dataAttrPrefix="oauth-scope-group"
/>
))}
</div>
@@ -480,12 +479,7 @@ export const OAuthAuthorize = (): JSX.Element => {
adjustableScopeRows.length > 0 && (
<div className="flex flex-col">
{adjustableScopeRows.map((row) => (
- <OAuthScopeRowControl
- key={row.key}
- row={row}
- appName={appName}
- onChange={setScopeAccess}
- />
+ <ScopeAccessRow key={row.key} row={row} onChange={setScopeAccess} />
))}
</div>
)
diff --git a/frontend/src/scenes/oauth/OAuthScopeGroupControl.tsx b/frontend/src/scenes/oauth/OAuthScopeGroupControl.tsx
deleted file mode 100644
index 49f274aa0abb..000000000000
--- a/frontend/src/scenes/oauth/OAuthScopeGroupControl.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { ScopeAccessGroup } from 'lib/components/ScopeAccessRow/ScopeAccessGroup'
-import { countScopeRowsByLevel, type ScopeAccessLevel } from 'lib/scopes'
-
-import { type OAuthScopeRow, scopeGroupAccessLevel, scopeGroupLevelTooltip } from './oauthAuthorizeLogic'
-import { OAuthScopeRowControl } from './OAuthScopeRowControl'
-
-interface OAuthScopeGroupControlProps {
- label: string
- rows: OAuthScopeRow[]
- appName: string
- onChangeRow: (scopeObject: string, level: ScopeAccessLevel) => void
- onChangeGroup: (scopeObjects: string[], level: ScopeAccessLevel) => void
-}
-
-export function OAuthScopeGroupControl({
- label,
- rows,
- appName,
- onChangeRow,
- onChangeGroup,
-}: OAuthScopeGroupControlProps): JSX.Element {
- const groupLevel = scopeGroupAccessLevel(rows)
- const keys = rows.map((row) => row.key)
- const anyWritable = rows.some((row) => row.maxLevel === 'write')
- const allRequired = rows.every((row) => row.minLevel !== 'none')
-
- return (
- <ScopeAccessGroup
- label={label}
- counts={countScopeRowsByLevel(rows)}
- value={groupLevel}
- valueTooltip={scopeGroupLevelTooltip(rows, groupLevel, appName)}
- onChange={(level) => onChangeGroup(keys, level)}
- noneDisabledReason={allRequired ? `${appName} requires these permissions` : undefined}
- writeDisabledReason={anyWritable ? undefined : `Not requested by ${appName}`}
- dataAttrPrefix="oauth-scope-group"
- >
- {rows.map((row) => (
- <OAuthScopeRowControl key={row.key} row={row} appName={appName} onChange={onChangeRow} />
- ))}
- </ScopeAccessGroup>
- )
-}
diff --git a/frontend/src/scenes/oauth/OAuthScopeRowControl.tsx b/frontend/src/scenes/oauth/OAuthScopeRowControl.tsx
deleted file mode 100644
index 980493361cfa..000000000000
--- a/frontend/src/scenes/oauth/OAuthScopeRowControl.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'
-import type { ScopeAccessLevel } from 'lib/scopes'
-
-import type { OAuthScopeRow } from './oauthAuthorizeLogic'
-
-interface OAuthScopeRowControlProps {
- row: OAuthScopeRow
- appName: string
- onChange: (scopeObject: string, level: ScopeAccessLevel) => void
-}
-
-export function OAuthScopeRowControl({ row, appName, onChange }: OAuthScopeRowControlProps): JSX.Element {
- return (
- <ScopeAccessRow
- label={row.label}
- info={row.info}
- muted={row.value === 'none'}
- value={row.value}
- onChange={(value) => onChange(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}
- />
- )
-}
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
index f7b9106ec4a4..b7c849b8d946 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
@@ -2,19 +2,14 @@ import { MOCK_DEFAULT_USER } from 'lib/api.mock'
import { decodeParams, router } from 'kea-router'
-import { DEFAULT_OAUTH_SCOPES, getScopeGroupLabel } from 'lib/scopes'
+import { DEFAULT_OAUTH_SCOPES, getScopeGroupLabel, scopeGroupLevel, scopeGroupTooltip } from 'lib/scopes'
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { AppContext } from '~/types'
-import {
- describeOAuthError,
- oauthAuthorizeLogic,
- scopeGroupAccessLevel,
- scopeGroupLevelTooltip,
-} from './oauthAuthorizeLogic'
+import { describeOAuthError, oauthAuthorizeLogic } from './oauthAuthorizeLogic'
describe('oauthAuthorizeLogic', () => {
let logic: ReturnType<typeof oauthAuthorizeLogic.build>
@@ -519,16 +514,30 @@ describe('oauthAuthorizeLogic', () => {
})
it('sets every row of a group with one group action, clamped to each ceiling', () => {
+ logic.actions.loadOAuthApplicationSuccess({
+ name: 'Test app',
+ client_id: 'test-client',
+ is_verified: true,
+ logo_uri: null,
+ })
logic.actions.setScopes(['openid', 'session_recording:write', 'session_recording_playlist:read'])
logic.actions.setScopeGroupAccess(['session_recording', 'session_recording_playlist'], 'none')
expect(logic.values.effectiveScopes).toEqual(['openid'])
- expect(scopeGroupAccessLevel(logic.values.adjustableScopeRows)).toBe('none')
- expect(scopeGroupLevelTooltip(logic.values.adjustableScopeRows, 'none', 'Test app')).toBeUndefined()
+ expect(scopeGroupLevel(logic.values.adjustableScopeRows)).toBe('none')
+ expect(scopeGroupTooltip(logic.values.adjustableScopeRows, 'none')).toBeUndefined()
const [recordingRow, playlistRow] = logic.values.adjustableScopeRows
- const requiredRows = [{ ...recordingRow, minLevel: 'read' as const, value: 'read' as const }, playlistRow]
- expect(scopeGroupAccessLevel(requiredRows)).toBe('none')
- expect(scopeGroupLevelTooltip(requiredRows, 'none', 'Test app')).toBe(
- '1 of these permissions stays on. Test app requires it.'
+ const requiredRows = [
+ {
+ ...recordingRow,
+ minLevel: 'read' as const,
+ value: 'read' as const,
+ disabledReasons: { none: 'Test app requires at least read access' },
+ },
+ playlistRow,
+ ]
+ expect(scopeGroupLevel(requiredRows)).toBe('none')
+ expect(scopeGroupTooltip(requiredRows, 'none')).toBe(
+ '1 of these permissions stays at read: Test app requires at least read access.'
)
logic.actions.setScopeGroupAccess(['session_recording', 'session_recording_playlist'], 'write')
expect(logic.values.effectiveScopes).toEqual([
@@ -536,14 +545,14 @@ describe('oauthAuthorizeLogic', () => {
'session_recording:write',
'session_recording_playlist:read',
])
- expect(scopeGroupAccessLevel(logic.values.adjustableScopeRows)).toBe('write')
- expect(scopeGroupLevelTooltip(logic.values.adjustableScopeRows, 'write', 'Test app')).toBe(
- '1 of these permissions stays at read. Test app did not request write access.'
+ expect(scopeGroupLevel(logic.values.adjustableScopeRows)).toBe('write')
+ expect(scopeGroupTooltip(logic.values.adjustableScopeRows, 'write')).toBe(
+ '1 of these permissions stays at read: Not requested by Test app.'
)
logic.actions.setScopeAccess('session_recording', 'read')
- expect(scopeGroupAccessLevel(logic.values.adjustableScopeRows)).toBe('read')
+ expect(scopeGroupLevel(logic.values.adjustableScopeRows)).toBe('read')
logic.actions.setScopeAccess('session_recording_playlist', 'none')
- expect(scopeGroupAccessLevel(logic.values.adjustableScopeRows)).toBeUndefined()
+ expect(scopeGroupLevel(logic.values.adjustableScopeRows)).toBeUndefined()
})
})
})
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index c76af4656e11..057b43d90efa 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -9,14 +9,15 @@ import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { OAUTH_SCOPES_SUPPORTED } from 'lib/oauthScopes.generated'
import {
- API_SCOPE_GROUPS,
API_SCOPES,
DEFAULT_OAUTH_SCOPES,
+ clampScopeLevel,
getMinimumEquivalentScopes,
getScopeDescription,
- getScopeGroupLabel,
- OTHER_SCOPE_GROUP_LABEL,
+ groupScopeRows,
+ type ScopePickerGroup,
type ScopeAccessLevel,
+ type ScopePickerRow,
} from 'lib/scopes'
import { getAppContext } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'
@@ -33,83 +34,31 @@ const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'introspection']
const scopeObjectKey = (scope: string): string => (scope === '*' ? '*' : scope.split(':')[0])
-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
+export type OAuthScopeRow = ScopePickerRow & {
/** 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
}
-export type OAuthScopeGroup = {
- label: string
- rows: OAuthScopeRow[]
-}
-
-// A group action clamps each row to its own floor and ceiling, so a group set to write can hold
-// read-only rows at read. The group shows a level as selected when each row is at that level
-// after the clamp. A disabled level is never selected, which removes the tie between write and
-// read in a group with no writable row, and between none and read in a group of required rows.
-export const scopeGroupAccessLevel = (rows: OAuthScopeRow[]): ScopeAccessLevel | undefined => {
- const anyWritable = rows.some((row) => row.maxLevel === 'write')
- const allRequired = rows.every((row) => row.minLevel !== 'none')
- const levels: ScopeAccessLevel[] = ['write', 'read', 'none']
- return levels.find(
- (level) =>
- !(level === 'write' && !anyWritable) &&
- !(level === 'none' && allRequired) &&
- rows.every((row) => row.value === clampAccessLevel(level, row.minLevel, row.maxLevel))
- )
-}
+export type OAuthScopeGroup = ScopePickerGroup<OAuthScopeRow>
-// Tooltip for the selected group level when some rows sit at another level after the clamp.
-// A row sits lower when the app did not request the level, and higher when the app requires more.
-export const scopeGroupLevelTooltip = (
- rows: OAuthScopeRow[],
- level: ScopeAccessLevel | undefined,
+// 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
-): string | undefined => {
- if (!level) {
- return undefined
- }
- const lower = rows.filter((row) => ACCESS_LEVEL_ORDER[row.value] < ACCESS_LEVEL_ORDER[level]).length
- const higher = rows.filter((row) => ACCESS_LEVEL_ORDER[row.value] > ACCESS_LEVEL_ORDER[level]).length
- const stays = (count: number): string => `${count} of these permissions ${count === 1 ? 'stays' : 'stay'}`
- const notes: string[] = []
- if (lower > 0) {
- notes.push(`${stays(lower)} at read. ${appName} did not request write access.`)
- }
- if (higher > 0) {
- const where = level === 'none' ? 'on' : 'at write'
- notes.push(`${stays(higher)} ${where}. ${appName} requires ${higher === 1 ? 'it' : 'them'}.`)
- }
- return notes.length > 0 ? notes.join(' ') : undefined
-}
+): Partial<Record<ScopeAccessLevel, string>> => ({
+ ...(minLevel !== 'none' ? { none: `${appName} requires at least ${minLevel} access` } : {}),
+ ...(minLevel === 'write' ? { read: `${appName} requires write access` } : {}),
+ ...(maxLevel !== 'write' ? { write: `Not requested by ${appName}` } : {}),
+})
const WILDCARD_LABEL = 'All PostHog data'
@@ -445,7 +394,8 @@ export interface oauthAuthorizeLogicMeta {
bulk: ScopeAccessLevel | null
overrides: Record<string, ScopeAccessLevel>
},
- requiredScopeLevels: Map<string, RequiredLevel>
+ requiredScopeLevels: Map<string, RequiredLevel>,
+ appName: string
) => OAuthScopeRow[]
requiredScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
adjustableScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
@@ -879,18 +829,20 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
// sets the floor, and the user's selection is clamped between the two — so no pick
// (including bulk actions) can grant more than requested or less than required.
scopeRows: [
- (s) => [s.consentResourceScopes, s.scopeAccessSelections, s.requiredScopeLevels],
+ (s) => [s.consentResourceScopes, s.scopeAccessSelections, s.requiredScopeLevels, s.appName],
(
consentResourceScopes: string[],
scopeAccessSelections: { bulk: ScopeAccessLevel | null; overrides: Record<string, ScopeAccessLevel> },
- requiredScopeLevels: Map<string, RequiredLevel>
+ requiredScopeLevels: Map<string, RequiredLevel>,
+ appName: string
): OAuthScopeRow[] => {
const rows = consentResourceScopes.map((scope): OAuthScopeRow => {
const key = scopeObjectKey(scope)
const maxLevel: 'read' | 'write' = scope === '*' || scope.endsWith(':write') ? 'write' : 'read'
const minLevel: ScopeAccessLevel = requiredScopeLevels.get(key) ?? 'none'
+ const disabledReasons = oauthDisabledReasons(minLevel, maxLevel, appName)
const selected = scopeAccessSelections.overrides[key] ?? scopeAccessSelections.bulk ?? maxLevel
- const value = clampAccessLevel(selected, minLevel, 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 {
@@ -899,6 +851,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
description: getScopeDescription(grantedScope) ?? grantedScope,
info: apiScope?.info,
warning: value === 'none' ? undefined : apiScope?.warnings?.[value],
+ muted: value === 'none',
+ disabledReasons,
minLevel,
maxLevel,
value,
@@ -922,20 +876,9 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
(s) => [s.adjustableScopeRows],
(adjustableScopeRows: OAuthScopeRow[]): boolean => adjustableScopeRows.length > SCOPE_GROUPING_MIN_ROWS,
],
- // The adjustable rows, grouped by product area in API_SCOPE_GROUPS order. An object that is
- // not in the map goes in the "Other" group at the end, so it still shows.
scopeGroups: [
(s) => [s.adjustableScopeRows],
- (adjustableScopeRows: OAuthScopeRow[]): OAuthScopeGroup[] => {
- const rowsByLabel = new Map<string, OAuthScopeRow[]>()
- for (const row of adjustableScopeRows) {
- const label = getScopeGroupLabel(row.key)
- rowsByLabel.set(label, [...(rowsByLabel.get(label) ?? []), row])
- }
- return [...API_SCOPE_GROUPS.map(({ label }) => label), OTHER_SCOPE_GROUP_LABEL]
- .filter((label) => rowsByLabel.has(label))
- .map((label) => ({ label, rows: rowsByLabel.get(label) ?? [] }))
- },
+ (adjustableScopeRows: OAuthScopeRow[]): OAuthScopeGroup[] => groupScopeRows(adjustableScopeRows),
],
allScopesRequired: [
(s) => [s.scopeRows],
diff --git a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
index 8c890e54471f..6f0c7af36b0e 100644
--- a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
+++ b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
@@ -8,6 +8,7 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedAr
import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import type { ScopeAccessLevel } from 'lib/scopes'
import { APIKeyTable } from '../shared/APIKeyTable'
import { MAX_PROJECT_API_KEYS_PER_PROJECT, projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'
@@ -95,24 +96,27 @@ function EditKeyModal(): JSX.Element {
{filteredScopes.length === 0 ? (
<div className="text-muted text-sm py-2">No scopes match "{searchTerm}"</div>
) : (
- filteredScopes.map(({ key, label, disabledActions }) => (
- <ScopeAccessRow
- key={key}
- label={label}
- value={formScopeRadioValues[key] ?? 'none'}
- onChange={(value) => setScopeRadioValue(key, value)}
- readDisabledReason={
- disabledActions?.includes('read')
- ? 'Not available for project secret API keys'
- : undefined
- }
- writeDisabledReason={
- disabledActions?.includes('write')
- ? 'Not available for project secret API keys'
- : undefined
- }
- />
- ))
+ filteredScopes.map(({ key, label, disabledActions }) => {
+ const disabledReason = (action: 'read' | 'write'): string | undefined =>
+ disabledActions?.includes(action)
+ ? 'Not available for project secret API keys'
+ : undefined
+ return (
+ <ScopeAccessRow
+ key={key}
+ row={{
+ key,
+ label,
+ value: (formScopeRadioValues[key] ?? 'none') as ScopeAccessLevel,
+ disabledReasons: {
+ read: disabledReason('read'),
+ write: disabledReason('write'),
+ },
+ }}
+ onChange={setScopeRadioValue}
+ />
+ )
+ })
)}
</div>
</LemonField>
diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeyScopeGroup.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeyScopeGroup.tsx
deleted file mode 100644
index added33cf58e..000000000000
--- a/frontend/src/scenes/settings/user/PersonalAPIKeyScopeGroup.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { ScopeAccessGroup } from 'lib/components/ScopeAccessRow/ScopeAccessGroup'
-import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'
-import { countScopeRowsByLevel, type ScopeAccessLevel } from 'lib/scopes'
-
-import {
- type PersonalAPIKeyScopeGroup as PersonalAPIKeyScopeGroupType,
- scopeGroupAccessLevel,
- scopeGroupLevelTooltip,
-} from './personalAPIKeysLogic'
-
-interface PersonalAPIKeyScopeGroupProps {
- group: PersonalAPIKeyScopeGroupType
- defaultOpen: boolean
- onChangeRow: (scopeObject: string, level: ScopeAccessLevel) => void
- onChangeGroup: (scopeObjects: string[], level: ScopeAccessLevel) => void
-}
-
-export function PersonalAPIKeyScopeGroup({
- group,
- defaultOpen,
- onChangeRow,
- onChangeGroup,
-}: PersonalAPIKeyScopeGroupProps): JSX.Element {
- const { label, rows } = group
- const groupLevel = scopeGroupAccessLevel(rows)
- const keys = rows.map((row) => row.scope.key)
- // A level that no row can take is disabled on the group, with the reason the rows give.
- const groupDisabledReason = (reason: 'readDisabledReason' | 'writeDisabledReason'): string | undefined =>
- rows.every((row) => row[reason]) ? rows[0]?.[reason] : undefined
-
- return (
- <ScopeAccessGroup
- label={label}
- counts={countScopeRowsByLevel(rows)}
- value={groupLevel}
- valueTooltip={scopeGroupLevelTooltip(rows, groupLevel)}
- onChange={(level) => onChangeGroup(keys, level)}
- readDisabledReason={groupDisabledReason('readDisabledReason')}
- writeDisabledReason={groupDisabledReason('writeDisabledReason')}
- defaultOpen={defaultOpen}
- dataAttrPrefix="personal-api-key-scope-group"
- >
- {rows.map(({ scope, value, muted, readDisabledReason, writeDisabledReason }) => (
- <ScopeAccessRow
- key={scope.key}
- label={scope.objectName}
- info={scope.info}
- muted={muted}
- value={value}
- onChange={(level) => onChangeRow(scope.key, level as ScopeAccessLevel)}
- readDisabledReason={readDisabledReason}
- writeDisabledReason={writeDisabledReason}
- warning={value === 'none' ? undefined : scope.warnings?.[value]}
- />
- ))}
- </ScopeAccessGroup>
- )
-}
diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
index dbd10489d0ae..cb9e89479b5a 100644
--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
@@ -18,6 +18,7 @@ import {
} from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { ScopeAccessGroup } from 'lib/components/ScopeAccessRow/ScopeAccessGroup'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
@@ -27,7 +28,6 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { PersonalAPIKeyType } from '~/types'
import { APIKeyTable } from '../shared/APIKeyTable'
-import { PersonalAPIKeyScopeGroup } from './PersonalAPIKeyScopeGroup'
import { personalAPIKeysLogic } from './personalAPIKeysLogic'
import ScopeAccessSelector from './scopes/ScopeAccessSelector'
@@ -225,13 +225,14 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {
</div>
) : (
filteredScopeGroups.map((group) => (
- <PersonalAPIKeyScopeGroup
+ <ScopeAccessGroup
// A search opens every group, and clearing it closes them again.
key={`${group.label}-${searchTerm !== ''}`}
group={group}
defaultOpen={searchTerm !== ''}
onChangeRow={setScopeRadioValue}
onChangeGroup={setScopeGroupAccess}
+ dataAttrPrefix="personal-api-key-scope-group"
/>
))
)}
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
index 7c04c8b840a6..4bbd058df89d 100644
--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
@@ -13,12 +13,13 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import {
APIScope,
- API_SCOPE_GROUPS,
API_SCOPES,
- OTHER_SCOPE_GROUP_LABEL,
SCOPES_IMPLYING_FEATURE_FLAG_WRITE,
+ type ScopePickerGroup,
type ScopeAccessLevel,
- getScopeGroupLabel,
+ type ScopePickerRow,
+ clampScopeLevel,
+ groupScopeRows,
scopeMatchesSearch,
scopesArrayToObject,
scopesObjectToArray,
@@ -40,58 +41,10 @@ export type EditingKeyFormValues = Pick<
access_type?: 'all' | 'organizations' | 'teams'
}
-export type PersonalAPIKeyScopeRow = {
- scope: APIScope
- value: ScopeAccessLevel
- /** True when the row is dimmed because the key's access type rules it out. */
- muted: boolean
- readDisabledReason?: string
- writeDisabledReason?: string
-}
-
-export type PersonalAPIKeyScopeGroup = {
- label: string
- rows: PersonalAPIKeyScopeRow[]
-}
-
-// The highest level at or below `level` that the row can take.
-export const clampScopeLevel = (row: PersonalAPIKeyScopeRow, level: ScopeAccessLevel): ScopeAccessLevel => {
- if (level === 'write' && !row.writeDisabledReason) {
- return 'write'
- }
- if (level !== 'none' && !row.readDisabledReason) {
- return 'read'
- }
- return 'none'
-}
-
-// The group control shows a level as selected when each row is at that level after the clamp. A
-// level no row can take is never selected, which removes the tie between write and read in a group
-// with no writable row.
-export const scopeGroupAccessLevel = (rows: PersonalAPIKeyScopeRow[]): ScopeAccessLevel | undefined => {
- const levels: ScopeAccessLevel[] = ['write', 'read', 'none']
- return levels.find(
- (level) =>
- rows.some((row) => clampScopeLevel(row, level) === level) &&
- rows.every((row) => row.value === clampScopeLevel(row, level))
- )
-}
+/** A picker row for a personal API key, with the scope it stands for so the search can match it. */
+export type PersonalAPIKeyScopeRow = ScopePickerRow & { scope: APIScope }
-// Tooltip for the selected group level when some rows sit below it after the clamp. The clamp only
-// ever lowers a row, so a row that is not at the selected level is below it.
-export const scopeGroupLevelTooltip = (
- rows: PersonalAPIKeyScopeRow[],
- level: ScopeAccessLevel | undefined
-): string | undefined => {
- if (!level) {
- return undefined
- }
- const lower = rows.filter((row) => row.value !== level).length
- if (lower === 0) {
- return undefined
- }
- return `${lower} of these permissions ${lower === 1 ? 'stays' : 'stay'} lower, because ${level} access does not apply to ${lower === 1 ? 'it' : 'them'}.`
-}
+export type PersonalAPIKeyScopeGroup = ScopePickerGroup<PersonalAPIKeyScopeRow>
// The scopes array with each key set to its level. A write on a survey or early access feature also
// writes a feature flag (targeting / linked flag), so it implies feature_flag:write (see
@@ -550,32 +503,23 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([
: projectScoped
? 'Not available for project scoped keys'
: undefined
+ const value = (formScopeRadioValues[scope.key] ?? 'none') as ScopeAccessLevel
return {
scope,
- value: (formScopeRadioValues[scope.key] ?? 'none') as ScopeAccessLevel,
+ key: scope.key,
+ label: scope.objectName,
+ info: scope.info,
+ value,
+ warning: value === 'none' ? undefined : scope.warnings?.[value],
muted: Boolean(projectScoped),
- readDisabledReason: disabledReason('read'),
- writeDisabledReason: disabledReason('write'),
+ disabledReasons: { read: disabledReason('read'), write: disabledReason('write') },
}
}),
],
- // The rows that match the search, grouped by product area in API_SCOPE_GROUPS order. An object
- // that is in no group goes in the "Other" group at the end, so it still shows.
filteredScopeGroups: [
(s) => [s.searchTerm, s.scopeRows],
- (searchTerm: string, scopeRows: PersonalAPIKeyScopeRow[]): PersonalAPIKeyScopeGroup[] => {
- const rowsByLabel = new Map<string, PersonalAPIKeyScopeRow[]>()
- for (const row of scopeRows) {
- if (!scopeMatchesSearch(row.scope, searchTerm)) {
- continue
- }
- const label = getScopeGroupLabel(row.scope.key)
- rowsByLabel.set(label, [...(rowsByLabel.get(label) ?? []), row])
- }
- return [...API_SCOPE_GROUPS.map(({ label }) => label), OTHER_SCOPE_GROUP_LABEL]
- .filter((label) => rowsByLabel.has(label))
- .map((label) => ({ label, rows: rowsByLabel.get(label) ?? [] }))
- },
+ (searchTerm: string, scopeRows: PersonalAPIKeyScopeRow[]): PersonalAPIKeyScopeGroup[] =>
+ groupScopeRows(scopeRows.filter((row) => scopeMatchesSearch(row.scope, searchTerm))),
],
formScopeRadioValues: [
(s) => [s.editingKey],
@@ -840,9 +784,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([
// A group action clamps each row to the levels it can take, so a group set to write holds a
// read-only row at read and a project-scoped row at none.
setScopeGroupAccess: ({ keys, level }) => {
- const rowsByKey = new Map<string, PersonalAPIKeyScopeRow>(
- values.scopeRows.map((row) => [row.scope.key, row])
- )
+ const rowsByKey = new Map<string, PersonalAPIKeyScopeRow>(values.scopeRows.map((row) => [row.key, row]))
const levels = keys.flatMap((key): [string, ScopeAccessLevel][] => {
const row = rowsByKey.get(key)
return row ? [[key, clampScopeLevel(row, level)]] : []