diff --git a/backend/windmill-api-groups/src/access_reads.rs b/backend/windmill-api-groups/src/access_reads.rs index 5e30634a26..396a26c50b 100644 --- a/backend/windmill-api-groups/src/access_reads.rs +++ b/backend/windmill-api-groups/src/access_reads.rs @@ -102,7 +102,7 @@ pub enum RunsAs { }, } -#[derive(Serialize, Clone, Copy, PartialEq, Eq, Debug)] +#[derive(Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] #[serde(rename_all = "lowercase")] pub enum Access { Read, @@ -924,7 +924,9 @@ fn performer(who: Who, reader: &Reader, runners: &[Reader]) -> Reader { /// Credits every read in `graph` to whoever performs it, starting from the root's runner. fn tag(graph: &HashMap) -> Tagged { - let mut references: BTreeMap<(ItemKind, String, Reader), (Access, BTreeSet)> = + // Keyed by access too, so each source keeps what it does: the access view says which step + // reads an item and which one writes it. + let mut references: BTreeMap<(ItemKind, String, Reader, Access), BTreeSet> = BTreeMap::new(); let mut others: BTreeMap<(AssetKind, String, Reader), BTreeSet> = BTreeMap::new(); let (mut unreadable, mut too_deep, mut over_budget) = @@ -970,13 +972,10 @@ fn tag(graph: &HashMap) -> Tagged { let by = performer(local.who, &reader, &runners); match &local.target { Target::Item { kind, path, access } => { - let (merged, sources) = references - .entry((*kind, path.clone(), by)) - .or_insert((*access, BTreeSet::new())); - if *access == Access::Write { - *merged = Access::Write; - } - sources.insert(local.source.clone()); + references + .entry((*kind, path.clone(), by, *access)) + .or_default() + .insert(local.source.clone()); } Target::Asset { kind, path } => { others @@ -1008,7 +1007,7 @@ fn tag(graph: &HashMap) -> Tagged { Tagged { references: references .into_iter() - .map(|((kind, path, reader), (access, sources))| Reference { + .map(|((kind, path, reader, access), sources)| Reference { kind, path, access, @@ -1149,7 +1148,9 @@ mod tests { got, vec![ (Resource, "f/x/input", Read, account("u/bot")), + (Resource, "f/x/state", Read, Reader::Root), (Resource, "f/x/state", Write, Reader::Root), + (Resource, "f/x/state", Read, account("u/bot")), (Resource, "f/x/state", Write, account("u/bot")), (Variable, "f/x/front", Read, Reader::Viewer), (Variable, "f/x/runner_var", Read, account("u/runner")), diff --git a/docs/access-reads.md b/docs/access-reads.md index b185a26427..3ea59f501b 100644 --- a/docs/access-reads.md +++ b/docs/access-reads.md @@ -5,9 +5,11 @@ what a script, flow or app reads when it runs, with each read credited to the id runtime performs it as. Two features take a slice of that answer (`frontend/src/lib/components/access/detectNeeds.ts`): -- The access view's "What it reads" (`neededByGrantee`) lists what a member needs to run the - item: what whoever opens it reads, the item's own reads when it runs as its caller or as that - member, and the reads of a nested runnable that runs as that member. +- The access view's check after a grant (`neededByGrantee`, in `access/neededAccess.ts`) lists + what a member still needs to run the item: what whoever opens it reads, the item's own reads + when it runs as its caller or as that member, and the reads of a nested runnable that runs as + that member. When the item runs as an account, it also lists what that account can't open + (`neededByRunAs`), since every run fails then. Folder grants are not checked. - The run-as settings (`neededByRunAs`) list what an account needs when the item runs as it: the item's own reads and the reads of a nested runnable that runs as that account. diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte index b51786bbcd..9273cfb31f 100644 --- a/frontend/src/lib/components/AccessDrawer.svelte +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -1,5 +1,6 @@ - -
-
-
- What {path} reads - - What {principal} needs to run it: the resources and variables it reads, and the scripts and flows - its code starts. A step that calls a script or flow by path needs no grant on it. - -
-
- - {#if error} - {error} - {:else if !needs || !needed} - - {:else} - {#if runsAs} - - {kind === 'app' - ? 'Only what its frontend reads, as whoever opens it, is listed.' - : `What it reads needs no grant for ${principal}.`} - - {/if} - {#if needed.items.length} -
- {#each needed.items as item (item.kind + ':' + item.path)} - {@const key = `${item.kind}:${item.path}`} - {@const already = covered(item)} - {@const result = results[key]} - - {/each} -
- {:else} -

Nothing {principal} needs was found in {path}.

- {/if} - {#if needed.others.length} - - {needed.others.map((o) => `${o.kind} ${o.path}`).join(', ')}. Access to these is set on the - storage or data table itself. - - {/if} - {#if needs.errors.length} - - {needs.errors.join('; ')} - - {/if} -
- - - Finds paths written literally in its code and inputs. A path built while it runs, passed through - a helper, or read in a script it imports isn't found: grant it with "Grant". - - -
- {/if} -
diff --git a/frontend/src/lib/components/access/GrantNavigator.svelte b/frontend/src/lib/components/access/GrantNavigator.svelte index 96c33d52ea..a4415af3da 100644 --- a/frontend/src/lib/components/access/GrantNavigator.svelte +++ b/frontend/src/lib/components/access/GrantNavigator.svelte @@ -53,8 +53,8 @@ changes the grant on the whole folder. }: { principal: string access: PrincipalAccess - /** After each change to a grant, for the host to reload `access`. */ - onChange: () => void + /** After each change to a grant, with what changed, for the host to reload `access`. */ + onChange: (change: { kind: string; path: string; level: GrantLevel }) => void source?: GrantSource } = $props() @@ -467,7 +467,7 @@ changes the grant on the whole folder. const folder = folders?.find((f) => f.name === row.path) if (folder) folder.grant = row.grant } - onChange() + onChange({ kind: row.kind, path: row.path, level }) showDone(leaf.key, DONE[label] ?? 'Done') } catch (e) { sendUserToast(`Could not ${label.toLowerCase()} on ${pathOf(row)}: ${e?.body ?? e}`, true) diff --git a/frontend/src/lib/components/access/NeededAccess.svelte b/frontend/src/lib/components/access/NeededAccess.svelte new file mode 100644 index 0000000000..a8641b603b --- /dev/null +++ b/frontend/src/lib/components/access/NeededAccess.svelte @@ -0,0 +1,265 @@ + + + +{#snippet gapList(rows: GapRow[], to: string)} +
+

{to} can't open ({rows.length})

+
+ {#each rows as row (row.key)} + {@const result = results[`${to}|${row.key}`]} +
+ + + + {row.path} + + + + {row.use}{#if result === true}{' · '}granted just now{/if} + + {#if typeof result === 'string'} + Refused: {result} + {/if} + + + {row.level === 'write' ? 'Write' : 'Read'} + +
+ {/each} +
+
+{/snippet} + +{#snippet fixes( + rows: GapRow[], + to: string, + grantTitle: string, + grantText: string, + otherTitle: string, + otherText: string, + otherLink: string +)} + {@const remaining = left(rows, to)} +
+

Fix it one of two ways

+
+
+

{grantTitle}

+

{grantText}

+
+ +
+
+
+

{otherTitle}

+

{otherText}

+
+ +
+
+
+
+{/snippet} + +
+ {#if check.grantee.length} + {@const rows = check.grantee} + {@const what = rows.length === 1 ? 'thing it reads is' : 'things it reads are'} + {@const listed = rows.map((r) => r.path).join(', ')} +
+
+ +
+

+ Read on the {noun} was granted. {rows.length} + {what} missing. +

+

+ {#if opens} + Its frontend reads with the viewer's own access{check.account + ? `, while its runnables run as ${check.account.principal}` + : ''}. + {:else} + It runs as whoever starts it, so {principal} also needs access to what it reads. + {/if} +

+
+
+ {@render gapList(rows, principal)} + {#if opens} + {@render fixes( + rows, + principal, + 'Grant these', + `${principal} gets access to ${listed}. Its members can then read the values directly, outside the app.`, + 'Read it in a runnable instead', + `Runnables run as the app's account, so the app works for ${principal} without them seeing the values.`, + fixHref + )} + {:else} + {@render fixes( + rows, + principal, + 'Grant these', + `${principal} gets access to ${listed}. Its members can then read the values directly, outside the ${noun}.`, + 'Run it as an account instead', + `The ${noun} reads them with that account's access. ${principal} runs it without seeing the values.`, + fixHref + )} + {/if} +
+ {/if} + + {#if check.account?.rows.length} + {@const account = check.account} + {@const listed = account.rows.map((r) => r.path).join(', ')} +
+
+ +
+

+ {check.grantee.length + ? `The account it runs as can't open something either.` + : `${principal} needs nothing more, but the account it runs as does.`} +

+

+ It runs as {account.principal}, who can't open {pluralize( + account.rows.length, + 'thing' + )} it reads. Every run fails, whoever starts it. +

+
+
+ {@render gapList(account.rows, account.principal)} + {@render fixes( + account.rows, + account.principal, + `Grant ${account.principal}`, + `${account.principal} gets access to ${listed}, and the ${noun} works for everyone again.`, + opens ? 'Deploy it with another account' : 'Run it as another account', + `Pick an account that can already open ${listed}.`, + fixHref + )} +
+ {/if} + + {#if check.noAccount} + + They fail for everyone until the app is redeployed with one. Granting {principal} access won't + fix that. + + {/if} + +

+ + Only paths written in its code and inputs are found. + + What isn't found + {#snippet text()} + A path built while it runs, passed through a helper, or read in a script it imports isn't + found. To grant one of those, pick it in the Grant list. + {/snippet} + +

+ +
+ +
+
diff --git a/frontend/src/lib/components/access/detectNeeds.ts b/frontend/src/lib/components/access/detectNeeds.ts index ed8e30c383..add38b1896 100644 --- a/frontend/src/lib/components/access/detectNeeds.ts +++ b/frontend/src/lib/components/access/detectNeeds.ts @@ -15,16 +15,33 @@ export type Needs = AccessReads /** Unsaved editor content, scanned in place of the saved item. */ export type NeedsSource = AccessReadsSource & { kind?: RunnableKind } +/** One place that reaches an item, and what it does with it. */ +export type NeededUse = { + access: AccessReference['access'] + reader: AccessReader['type'] + source: string +} + /** Something access is granted on item by item, at the level its reads take. */ export type NeededItem = { kind: AccessReference['kind'] path: string level: 'read' | 'write' sources: string[] + uses: NeededUse[] +} + +/** Whether the access held on `item` covers the level it needs; `held` maps `kind:path` to whether it is write. */ +export function covers( + held: Map, + item: { kind: string; path: string; level: 'read' | 'write' } +): boolean { + const write = held.get(`${item.kind}:${item.path}`) + return write !== undefined && (write || item.level === 'read') } /** Something it reads that item grants do not cover (S3 objects, data tables, …). */ -export type OtherAsset = Omit +export type OtherAsset = Omit & { uses: Omit[] } export type NeededAccess = { items: NeededItem[]; others: OtherAsset[] } @@ -81,16 +98,23 @@ function select(needs: Needs, performs: (reader: AccessReader) => boolean): Need if (!performs(reference.reader)) continue const key = `${reference.kind}:${reference.path}` const level = reference.access === 'write' ? 'write' : 'read' + const uses = reference.sources.map((source) => ({ + access: reference.access, + reader: reference.reader.type, + source + })) const item = items.get(key) if (item) { if (level === 'write') item.level = 'write' item.sources = [...new Set([...item.sources, ...reference.sources])] + item.uses.push(...uses) } else { items.set(key, { kind: reference.kind, path: reference.path, level, - sources: reference.sources + sources: reference.sources, + uses }) } } @@ -98,10 +122,17 @@ function select(needs: Needs, performs: (reader: AccessReader) => boolean): Need for (const { reader, ...asset } of needs.others) { if (!performs(reader)) continue const key = `${asset.kind}:${asset.path}` + const uses = asset.sources.map((source) => ({ reader: reader.type, source })) const other = others.get(key) others.set( key, - other ? { ...other, sources: [...new Set([...other.sources, ...asset.sources])] } : asset + other + ? { + ...other, + sources: [...new Set([...other.sources, ...asset.sources])], + uses: [...other.uses, ...uses] + } + : { ...asset, uses } ) } return { items: [...items.values()], others: [...others.values()] } diff --git a/frontend/src/lib/components/access/neededAccess.test.ts b/frontend/src/lib/components/access/neededAccess.test.ts new file mode 100644 index 0000000000..1e63c13d6f --- /dev/null +++ b/frontend/src/lib/components/access/neededAccess.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import type { PrincipalAccess } from '$lib/gen' +import type { Needs } from './detectNeeds' +import { checkGrant, hasGap } from './neededAccess' + +const flow = { kind: 'flow', path: 'f/fin/close' } as const + +function needs(runs_as: Needs['runs_as']): Needs { + return { + runs_as, + references: [ + { kind: 'flow', path: 'f/fin/close', access: 'read', reader: { type: 'root' }, sources: [] }, + { + kind: 'resource', + path: 'f/fin/db', + access: 'read', + reader: { type: 'root' }, + sources: ['f/fin/close › a'] + }, + { + kind: 'variable', + path: 'f/fin/key', + access: 'read', + reader: { type: 'root' }, + sources: ['f/fin/close › b'] + } + ], + others: [], + errors: [] + } +} + +function reaches(principal: string, ...keys: string[]): PrincipalAccess { + return { + principal, + is_admin: false, + groups: [], + folders: [], + items: keys.map((key) => { + const [kind, path] = key.split(':') + return { kind, path, write: false, reasons: [] } + }) + } as unknown as PrincipalAccess +} + +describe('checkGrant', () => { + it('lists only what the grantee cannot open, never the item just granted', () => { + const check = checkGrant( + needs({ type: 'caller' }), + flow, + 'g/analysts', + reaches('g/analysts', 'flow:f/fin/close', 'variable:f/fin/key'), + undefined + ) + expect(check.grantee.map((r) => r.key)).toEqual(['resource:f/fin/db']) + expect(check.grantee[0].use).toBe('Read in step a') + expect(check.account).toBeUndefined() + }) + + it("checks the run-as account's access, not the grantee's, when the item runs as one", () => { + const check = checkGrant( + needs({ type: 'account', principal: 'u/bob' }), + flow, + 'g/analysts', + reaches('g/analysts', 'flow:f/fin/close'), + reaches('u/bob', 'resource:f/fin/db') + ) + expect(check.grantee).toEqual([]) + expect(check.account?.rows.map((r) => r.key)).toEqual(['variable:f/fin/key']) + expect(hasGap(check)).toBe(true) + }) +}) diff --git a/frontend/src/lib/components/access/neededAccess.ts b/frontend/src/lib/components/access/neededAccess.ts new file mode 100644 index 0000000000..966a07bd11 --- /dev/null +++ b/frontend/src/lib/components/access/neededAccess.ts @@ -0,0 +1,181 @@ +import { GranularAclService, type PrincipalAccess } from '$lib/gen' +import { + covers, + detectNeeds, + neededByGrantee, + neededByRunAs, + type NeededUse, + type Needs +} from './detectNeeds' + +/** The item a grant was just made on, `kind` as grants take it: `raw_app` for a full-code app. */ +export type ScannedItem = { kind: 'script' | 'flow' | 'app' | 'raw_app'; path: string } + +/** Something a principal cannot open, as one row of the dialog. */ +export type GapRow = { + key: string + kind: string + path: string + level: 'read' | 'write' + /** What the item does with it and where: "Read in step a". */ + use: string +} + +/** What the check after a grant found missing. Empty lists and no flag mean nothing to show. */ +export type GrantCheck = { + item: ScannedItem + /** What the grantee can't open among what it reads when it runs or opens the item. */ + grantee: GapRow[] + /** The account the item runs as, and what it can't open among what the item reads as it. */ + account?: { principal: string; rows: GapRow[] } + /** An app whose policy names no account: its runnables fail for everyone. */ + noAccount: boolean +} + +export function isScannable(kind: string): kind is ScannedItem['kind'] { + return kind === 'script' || kind === 'flow' || kind === 'app' || kind === 'raw_app' +} + +export function opensItem(kind: ScannedItem['kind']): boolean { + return kind === 'app' || kind === 'raw_app' +} + +export function hasGap(check: GrantCheck): boolean { + return check.grantee.length > 0 || !!check.account?.rows.length || check.noAccount +} + +/** `kind:path` of every item `access` reaches, to whether it can write it. */ +export function heldOf(access: PrincipalAccess): Map { + return new Map(access.items.map((i) => [`${i.kind}:${i.path}`, i.write])) +} + +/** + * What is missing once `principal` holds read on `item`: what it reads that `principal` can't + * open, and, when the item runs as an account, what that account can't open. `accountAccess` is + * undefined when the caller may not read the account's access, which leaves that part unchecked. + */ +export function checkGrant( + needs: Needs, + item: ScannedItem, + principal: string, + access: PrincipalAccess, + accountAccess: PrincipalAccess | undefined +): GrantCheck { + const grantee = access.is_admin + ? [] + : gapRows(neededByGrantee(needs, principal).items, item, heldOf(access)) + const runner = needs.runs_as.type === 'account' ? needs.runs_as.principal : undefined + const account = + runner && runner !== principal && accountAccess && !accountAccess.is_admin + ? { + principal: runner, + rows: gapRows(neededByRunAs(needs, runner).items, item, heldOf(accountAccess)) + } + : undefined + return { + item, + grantee, + account, + noAccount: opensItem(item.kind) && needs.runs_as.type === 'account' && !runner + } +} + +/** + * Scans `item` and checks it against `access`, what `principal` reaches once granted. The + * account's access is read only when the item runs as one, and a refusal (a member may read + * only their own access) leaves that part unchecked rather than failing the check. + */ +export async function runGrantCheck( + workspace: string, + item: ScannedItem, + principal: string, + access: PrincipalAccess +): Promise { + const needs = await detectNeeds(workspace, item.kind === 'raw_app' ? 'app' : item.kind, item.path) + const runner = needs.runs_as.type === 'account' ? needs.runs_as.principal : undefined + const accountAccess = + runner && runner !== principal + ? await GranularAclService.getPrincipalAccess({ workspace, principal: runner }).catch( + () => undefined + ) + : undefined + return checkGrant(needs, item, principal, access, accountAccess) +} + +/** Where the fix for `item`'s account is made: the run-as setting, or the app editor. */ +export function runAsHref(item: ScannedItem): string { + switch (item.kind) { + case 'flow': + return `/flows/edit/${item.path}?selected=settings-permissions` + case 'script': + return `/scripts/edit/${item.path}?metadata_open=true&settings_tab=permissions` + case 'app': + return `/apps/edit/${item.path}` + case 'raw_app': + return `/apps_raw/edit/${item.path}` + } +} + +/** The items among `items` that `held` does not cover, the scanned item itself left out. */ +function gapRows( + items: ReturnType['items'], + item: ScannedItem, + held: Map +): GapRow[] { + return items + .filter((i) => i.path !== item.path || !isScannable(i.kind)) + .filter((i) => !covers(held, i)) + .map((i) => ({ + key: `${i.kind}:${i.path}`, + kind: i.kind, + path: i.path, + level: i.level, + use: useLine(i.uses, item) + })) +} + +const VERBS = { write: 'Written', run: 'Started', read: 'Read' } as const +const STRENGTH = { read: 0, run: 1, write: 2 } as const + +/** Where a source sits in `item`: the scan names it `` or ` › `. */ +function where(source: string, item: ScannedItem, byViewer: boolean): string { + const at = source.indexOf(' › ') + const owner = at === -1 ? source : source.slice(0, at) + const part = at === -1 ? undefined : source.slice(at + 3) + if (owner !== item.path) { + return part === undefined ? `in ${owner}` : `in step ${part} of ${owner}` + } + if (byViewer) return part === undefined ? 'by its frontend' : `by its frontend, in ${part}` + if (part === undefined) { + return item.kind === 'script' + ? 'in its code' + : item.kind === 'flow' + ? 'in its inputs' + : 'in the app' + } + return item.kind === 'flow' + ? `in step ${part}` + : item.kind === 'script' + ? `in ${part}` + : `in runnable ${part}` +} + +/** What `item` does with something and where: "Written in step b; read in step a". */ +export function useLine(uses: NeededUse[], item: ScannedItem): string { + // A place that writes something reads it too, so it is said once, as a write. + const strongest = new Map() + for (const use of uses) { + const place = where(use.source, item, use.reader === 'viewer') + const seen = strongest.get(place) + if (seen === undefined || STRENGTH[use.access] > STRENGTH[seen]) + strongest.set(place, use.access) + } + return (['write', 'run', 'read'] as const) + .map((access) => ({ + verb: VERBS[access], + places: [...strongest].filter(([, a]) => a === access).map(([place]) => place) + })) + .filter((group) => group.places.length) + .map(({ verb, places }, i) => `${i ? verb.toLowerCase() : verb} ${places.join(', ')}`) + .join('; ') +} diff --git a/frontend/src/lib/components/flows/content/FlowSettings.svelte b/frontend/src/lib/components/flows/content/FlowSettings.svelte index 7028a5e962..2f7976ba0c 100644 --- a/frontend/src/lib/components/flows/content/FlowSettings.svelte +++ b/frontend/src/lib/components/flows/content/FlowSettings.svelte @@ -82,6 +82,7 @@ } function tabOf(id: string | undefined): FlowSettingsTab { if (id === 'settings-runtime' || (id && id in RUNTIME_ROW_OF_SELECTION)) return 'runtime' + if (id === 'settings-permissions') return 'permissions' return 'metadata' } // Follows the selection, and a click on a tab overrides it until the next one.