From 95c23fdf609d98288593a2e08c9f28eecfbde968 Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Wed, 4 Nov 2026 06:35:07 -0800 Subject: [PATCH] refactor: load what an item reads from the server Co-Authored-By: Claude Opus 5.5 --- .../src/lib/components/AccessDrawer.svelte | 4 +- .../components/access/AddNeededAccess.svelte | 85 ++++-- .../lib/components/access/detectNeeds.test.ts | 133 ++++---- .../src/lib/components/access/detectNeeds.ts | 285 ++++++------------ 4 files changed, 205 insertions(+), 302 deletions(-) diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte index c61f9f1831..aed86aaedb 100644 --- a/frontend/src/lib/components/AccessDrawer.svelte +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -162,7 +162,7 @@ ] } - const reads = $derived(new Set((access?.items ?? []).map((i) => `${i.kind}:${i.path}`))) + const held = $derived(new Map((access?.items ?? []).map((i) => [`${i.kind}:${i.path}`, i.write]))) // The tree's folder rows carry no grant of their own, so the menu reads it from here. const foldersByName = $derived(new Map((access?.folders ?? []).map((f) => [f.name, f]))) @@ -392,7 +392,7 @@ {principal} kind={needsOf.kind} path={needsOf.path} - {reads} + {held} onGranted={reload} onClose={() => (needsOf = undefined)} /> diff --git a/frontend/src/lib/components/access/AddNeededAccess.svelte b/frontend/src/lib/components/access/AddNeededAccess.svelte index ce637bf0d6..d17b1e3680 100644 --- a/frontend/src/lib/components/access/AddNeededAccess.svelte +++ b/frontend/src/lib/components/access/AddNeededAccess.svelte @@ -4,7 +4,13 @@ import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { Info, X } from 'lucide-svelte' import { setGrant } from './access' - import { detectNeeds, type Needs, type RunnableKind } from './detectNeeds' + import { + detectNeeds, + neededByGrantee, + type NeededItem, + type Needs, + type RunnableKind + } from './detectNeeds' const operatingWorkspace = useOperatingWorkspace() @@ -12,43 +18,69 @@ principal, kind, path, - reads, + held, onGranted, onClose }: { principal: string kind: RunnableKind path: string - /** `kind:path` of every item the principal already reads, through any grant. */ - reads: Set + /** `kind:path` of every item the principal reaches through any grant, to whether it can write it. */ + held: Map onGranted: () => void onClose: () => void } = $props() + const KIND_LABELS: Record = { + resource: 'Resource', + variable: 'Variable', + script: 'Script', + flow: 'Flow' + } + let needs: Needs | undefined = $state() let error: string | undefined = $state() let selected: Record = $state({}) let results: Record = $state({}) let granting = $state(false) + const needed = $derived(needs && neededByGrantee(needs, principal)) + /** The account the item's own reads are made as, when it is not the principal. */ + const runsAs = $derived( + needs?.runs_as.type === 'account' && needs.runs_as.principal !== principal + ? needs.runs_as.principal + : undefined + ) + + function covered(item: NeededItem): boolean { + const write = held.get(`${item.kind}:${item.path}`) + return write !== undefined && (write || item.level === 'read') + } + + function status(item: NeededItem): string { + if (covered(item)) return 'Already has it' + if (held.get(`${item.kind}:${item.path}`) === false) return 'Has read, needs write' + return item.level === 'write' ? 'Write' : 'Read' + } + // The host keys this component on the runnable, so it detects once per runnable. detectNeeds($operatingWorkspace!, kind, path) .then((found) => { needs = found selected = Object.fromEntries( - found.items.map((i) => [`${i.kind}:${i.path}`, !reads.has(`${i.kind}:${i.path}`)]) + neededByGrantee(found, principal).items.map((i) => [`${i.kind}:${i.path}`, !covered(i)]) ) }) .catch((e) => (error = `${e?.body ?? e}`)) async function grant() { - if (!needs) return + if (!needed) return granting = true - for (const item of needs.items) { + for (const item of needed.items) { const key = `${item.kind}:${item.path}` if (!selected[key]) continue try { - await setGrant($operatingWorkspace!, item.kind, item.path, principal, 'read') + await setGrant($operatingWorkspace!, item.kind, item.path, principal, item.level) results[key] = 'Granted' selected[key] = false } catch (e) { @@ -67,8 +99,8 @@
What {path} reads - The resources and variables it reads when it runs, so {principal} can run it. The scripts and - flows it calls need no grant. + 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} diff --git a/frontend/src/lib/components/access/detectNeeds.test.ts b/frontend/src/lib/components/access/detectNeeds.test.ts index 445d3f02aa..5aaa0a5733 100644 --- a/frontend/src/lib/components/access/detectNeeds.test.ts +++ b/frontend/src/lib/components/access/detectNeeds.test.ts @@ -1,91 +1,66 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' +import { neededByGrantee, neededByRunAs, type NeededAccess, type Needs } from './detectNeeds' -const readVariable = (path: string) => - `import * as wmill from "windmill-client"\nexport async function main() { return await wmill.getVariable("${path}") }\n` +const root = { type: 'root' } as const +const account = (principal: string) => ({ type: 'account', principal }) as const -vi.mock('$lib/gen', () => ({ - AppService: { - getAppByPath: vi.fn(async () => ({ - value: { - files: { - '/App.tsx': `export default () =>
{wmill.getVariable("f/x/browser_secret")}
`, - '/Db.svelte': `\n

{db}

`, - '/Secret.svelte': `\n{#await wmill.getVariable("f/x/template_secret") then s}

{s}

{/await}`, - '/notes.md': `getVariable("f/x/not_code")` - }, - runnables: {} +function needs(runs_as: Needs['runs_as']): Needs { + return { + runs_as, + references: [ + { + kind: 'variable', + path: 'f/x/front', + access: 'read', + reader: { type: 'viewer' }, + sources: ['f/x/app › /App.tsx'] + }, + { kind: 'resource', path: 'f/x/db', access: 'read', reader: root, sources: ['f/x/app › a'] }, + { kind: 'resource', path: 'f/x/db', access: 'write', reader: root, sources: ['f/x/app › b'] }, + { kind: 'script', path: 'f/x/helper', access: 'run', reader: root, sources: ['f/x/app › a'] }, + { + kind: 'variable', + path: 'f/x/bot_token', + access: 'read', + reader: account('u/bot'), + sources: ['f/x/bot'] } - })) - }, - AssetService: { listAssetsByUsage: vi.fn(async () => [[]]) }, - FlowService: { - getFlowByPath: vi.fn(async () => ({ - schema: {}, - value: { - modules: [ - { - id: 'a', - value: { type: 'script', path: 'f/x/step', hash: 'old', input_transforms: {} } - }, - { - id: 'b', - value: { - type: 'rawscript', - language: 'bun', - content: '', - input_transforms: { db: { type: 'static', value: '$res:f/x/db' } } - } - } - ] - } - })) - }, - ScriptService: { - getScriptByHash: vi.fn(async () => ({ - language: 'bun', - content: readVariable('f/x/pinned_secret'), - schema: {} - })), - getScriptByPath: vi.fn(async () => ({ - language: 'bun', - content: readVariable('f/x/latest_secret'), - schema: {} - })) - }, - ResourceService: { - getResource: vi.fn(async ({ path }: { path: string }) => ({ - value: - path === 'f/x/db' - ? { password: '$var:f/x/db_password', tls: { ca: '$res:f/x/ca' } } - : path === 'f/x/ca' - ? { cert: '$jsonvar:f/x/ca_cert' } - : {} - })) + ], + others: [{ kind: 'datatable', path: 'main', reader: root, sources: ['f/x/app › a'] }], + errors: [] } -})) -vi.mock('$lib/infer', () => ({ inferAssets: vi.fn(async () => ({ status: 'ok', assets: [] })) })) +} -import { detectNeeds } from './detectNeeds' +const rows = (access: NeededAccess) => access.items.map((i) => `${i.kind}:${i.path}:${i.level}`) -describe('detectNeeds', () => { - it('reads the pinned version of a called script and what its resources reference', async () => { - const needs = await detectNeeds('w', 'flow', 'f/x/flow') - expect(needs.items.map((i) => `${i.kind}:${i.path}`)).toEqual([ - 'resource:f/x/ca', - 'variable:f/x/ca_cert', - 'resource:f/x/db', - 'variable:f/x/db_password', - 'variable:f/x/pinned_secret' +describe('neededByGrantee', () => { + it('lists what the item reads when it runs as whoever starts it', () => { + const access = neededByGrantee(needs({ type: 'caller' }), 'u/alice') + expect(rows(access)).toEqual([ + 'variable:f/x/front:read', + 'resource:f/x/db:write', + 'script:f/x/helper:read' ]) - expect(needs.errors).toEqual([]) + expect(access.items[1].sources).toEqual(['f/x/app › a', 'f/x/app › b']) + expect(access.others.map((o) => o.path)).toEqual(['main']) }) - it("reads a full-code app's JSX and Svelte source files", async () => { - const needs = await detectNeeds('w', 'app', 'f/x/app') - expect(needs.items.map((i) => `${i.kind}:${i.path}`)).toEqual([ - 'resource:f/x/app_db', - 'variable:f/x/browser_secret', - 'variable:f/x/template_secret' + it('leaves out what an account reads unless the grantee is that account', () => { + const owned = needs(account('u/owner')) + expect(rows(neededByGrantee(owned, 'u/alice'))).toEqual(['variable:f/x/front:read']) + expect(rows(neededByGrantee(owned, 'u/bot'))).toEqual([ + 'variable:f/x/front:read', + 'variable:f/x/bot_token:read' + ]) + }) +}) + +describe('neededByRunAs', () => { + it('lists what the account reads, not what whoever opens the app reads', () => { + expect(rows(neededByRunAs(needs(account('u/bot')), 'u/bot'))).toEqual([ + 'resource:f/x/db:write', + 'script:f/x/helper:read', + 'variable:f/x/bot_token:read' ]) }) }) diff --git a/frontend/src/lib/components/access/detectNeeds.ts b/frontend/src/lib/components/access/detectNeeds.ts index 26af74a292..ed8e30c383 100644 --- a/frontend/src/lib/components/access/detectNeeds.ts +++ b/frontend/src/lib/components/access/detectNeeds.ts @@ -1,221 +1,108 @@ import { - AppService, - AssetService, - FlowService, - ResourceService, - ScriptService, - type AssetKind + GranularAclService, + type AccessOtherAsset, + type AccessReader, + type AccessReads, + type AccessReadsSource, + type AccessReference } from '$lib/gen' -import { inferAssets } from '$lib/infer' -import type { SupportedLanguage } from '$lib/common' export type RunnableKind = 'script' | 'flow' | 'app' -/** Something a runnable reads that access is granted on, item by item. */ -export type NeededItem = { kind: 'resource' | 'variable'; path: string; sources: string[] } +/** What an item reads when it runs, each read with who performs it. */ +export type Needs = AccessReads + +/** Unsaved editor content, scanned in place of the saved item. */ +export type NeedsSource = AccessReadsSource & { kind?: RunnableKind } + +/** 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[] +} /** Something it reads that item grants do not cover (S3 objects, data tables, …). */ -export type OtherAsset = { kind: AssetKind | string; path: string; sources: string[] } +export type OtherAsset = Omit -export type Needs = { items: NeededItem[]; others: OtherAsset[]; errors: string[] } - -const MAX_DEPTH = 4 -const ITEM_PATH = /^[ufg]\/[^/]+\/.+/ -const STATIC_REF = /^\$(res|var|jsonvar):(.+)$/ -const SOURCE_FILE = /\.(?:[cm]?[jt]sx?|svelte|vue)$/ -const COMPONENT_SCRIPT = /]*>([\s\S]*?)<\/script>/g -// The asset parser has no variable kind and rejects JSX, so literal reads are also matched here. -// A path the code builds at run time is found by neither. -const READ_CALL = /\b(getVariable|get_variable|getResource|get_resource)\(\s*["'`]([^"'`]+)["'`]/g +export type NeededAccess = { items: NeededItem[]; others: OtherAsset[] } /** - * What a script, flow or app reads when it runs, to grant to the account it runs as. The scripts - * and flows it calls by path are followed for what they read, but need no grant themselves: the - * runnable resolves them with its own access, not the account's. + * What a script, flow or app reads when it runs, and who performs each read: the server scans + * the item and everything it calls (`docs/access-reads.md`). `source` stands in for the saved + * item, as unsaved editor content. */ export async function detectNeeds( workspace: string, kind: RunnableKind, - path: string + path: string, + source?: NeedsSource ): Promise { - const items = new Map() - const others = new Map() - const errors: string[] = [] - const visited = new Set() + return await GranularAclService.getAccessReads({ + workspace, + requestBody: { kind, path: path || undefined, source } + }) +} - function add(assetKind: string, assetPath: string, source: string) { - const key = `${assetKind}:${assetPath}` - const target = - (assetKind === 'resource' || assetKind === 'variable') && ITEM_PATH.test(assetPath) - ? items - : others - const existing = target.get(key) - if (existing) { - if (!existing.sources.includes(source)) existing.sources.push(source) - } else { - target.set(key, { kind: assetKind as any, path: assetPath, sources: [source] }) - } - } +/** + * What `principal` needs to run the item: what whoever opens it reads, what the item reads when + * it runs as its caller or as `principal`, and what a runnable it reaches reads as `principal`. + */ +export function neededByGrantee(needs: Needs, principal: string): NeededAccess { + const runsAsGrantee = needs.runs_as.type === 'caller' || needs.runs_as.principal === principal + return select( + needs, + (reader) => + reader.type === 'viewer' || + (reader.type === 'root' && runsAsGrantee) || + (reader.type === 'account' && reader.principal === principal) + ) +} - /** `parsed` is the part of `content` the asset parser can read; literal calls are matched in all of it. */ - async function scanCode( - language: string | undefined, - content: string, - source: string, - parsed = content - ) { - const result = await inferAssets(language as SupportedLanguage | undefined, parsed) - if (result.status === 'ok') { - for (const asset of result.assets) add(asset.kind, asset.path, source) - } - for (const [, call, readPath] of content.matchAll(READ_CALL)) { - add(/resource/i.test(call) ? 'resource' : 'variable', readPath, source) - } - } +/** + * What `account` needs when the item runs as it: what the item reads, and what a runnable it + * reaches reads as `account`. A full-code app's frontend reads as whoever opens it, so none of + * that is listed. + */ +export function neededByRunAs(needs: Needs, account?: string): NeededAccess { + return select( + needs, + (reader) => + reader.type === 'root' || + (account !== undefined && reader.type === 'account' && reader.principal === account) + ) +} - async function recorded(usageKind: 'script' | 'flow', usagePath: string, source: string) { - const [assets] = await AssetService.listAssetsByUsage({ - workspace, - requestBody: { usages: [{ kind: usageKind, path: usagePath }] } - }) - for (const asset of (assets ?? []) as { kind: string; path: string }[]) { - add(asset.kind, asset.path, source) +/** One row per item: a write is needed when any read writes, and running an item takes read. */ +function select(needs: Needs, performs: (reader: AccessReader) => boolean): NeededAccess { + const items = new Map() + for (const reference of needs.references) { + if (!performs(reference.reader)) continue + const key = `${reference.kind}:${reference.path}` + const level = reference.access === 'write' ? 'write' : 'read' + const item = items.get(key) + if (item) { + if (level === 'write') item.level = 'write' + item.sources = [...new Set([...item.sources, ...reference.sources])] + } else { + items.set(key, { + kind: reference.kind, + path: reference.path, + level, + sources: reference.sources + }) } } - - /** Walks a flow or app definition for static references, inline code and calls by path. */ - async function walk(value: unknown, source: string, depth: number) { - const pending: Promise[] = [] - const visit = (node: unknown, label: string) => { - if (typeof node === 'string') { - const ref = STATIC_REF.exec(node) - if (ref) add(ref[1] === 'res' ? 'resource' : 'variable', ref[2], label) - return - } - if (Array.isArray(node)) { - node.forEach((child) => visit(child, label)) - return - } - if (!node || typeof node !== 'object') return - const obj = node as Record - const name = - typeof obj.summary === 'string' && obj.summary - ? obj.summary - : typeof obj.name === 'string' - ? obj.name - : typeof obj.id === 'string' - ? obj.id - : undefined - const here = name ? `${source} › ${name}` : label - if (typeof obj.content === 'string' && typeof obj.language === 'string') { - pending.push(scanCode(obj.language, obj.content, here)) - } - const calledKind = - obj.runType === 'script' || obj.runType === 'flow' - ? obj.runType - : obj.type === 'script' || obj.type === 'flow' - ? obj.type - : undefined - if (calledKind && typeof obj.path === 'string' && !obj.path.startsWith('hub/')) { - const hash = typeof obj.hash === 'string' ? obj.hash : undefined - pending.push(follow(calledKind, obj.path, depth + 1, hash)) - } - for (const [key, child] of Object.entries(obj)) { - if (key !== 'content') visit(child, here) - } - } - visit(value, source) - await Promise.all(pending) - } - - /** A step pinned to `hash` runs that version, so it is the one scanned, not the latest. */ - async function follow( - runnableKind: RunnableKind, - runnablePath: string, - depth: number, - hash?: string - ) { - const key = `${runnableKind}:${runnablePath}${hash ? `@${hash}` : ''}` - if (visited.has(key) || depth > MAX_DEPTH) return - visited.add(key) - try { - if (runnableKind === 'script') { - const script = hash - ? await ScriptService.getScriptByHash({ workspace, hash }) - : await ScriptService.getScriptByPath({ workspace, path: runnablePath }) - await Promise.all([ - // Recorded usages are the latest version's, so a pinned one relies on its code alone. - hash ? undefined : recorded('script', runnablePath, runnablePath), - scanCode(script.language, script.content, runnablePath), - walk(script.schema, runnablePath, depth) - ]) - } else if (runnableKind === 'flow') { - const flow = await FlowService.getFlowByPath({ workspace, path: runnablePath }) - await Promise.all([ - recorded('flow', runnablePath, runnablePath), - walk(flow.value, runnablePath, depth), - walk(flow.schema, runnablePath, depth) - ]) - } else { - // Apps record no asset usages, so their inline code is parsed here. - const app = await AppService.getAppByPath({ workspace, path: runnablePath }) - // A full-code app's frontend calls the SDK as its viewer, from source kept as plain - // strings under `files`, which the walk below cannot tell from other strings. - const files = (app.value as { files?: Record } | undefined)?.files ?? {} - await Promise.all([ - walk(app.value, runnablePath, depth), - ...Object.entries(files) - .filter(([name, content]) => SOURCE_FILE.test(name) && typeof content === 'string') - .map(([name, content]) => { - // The parser reads only script, but a component's template runs SDK calls too. - const code = /\.(?:svelte|vue)$/.test(name) - ? [...(content as string).matchAll(COMPONENT_SCRIPT)].map((m) => m[1]).join('\n') - : (content as string) - return scanCode('bun', content as string, `${runnablePath} › ${name}`, code) - }) - ]) - } - } catch (e) { - // The item itself unreadable is a failure of the whole scan, not a partial result. - if (depth === 0) throw e - errors.push(`${runnablePath}: ${e?.body ?? e}`) - } - } - - // A resource's `$var:`/`$jsonvar:`/`$res:` fields are resolved with the job's permissions when - // it runs, so whatever they name is needed as much as the resource itself. - const scannedResources = new Set() - async function followResource(resourcePath: string) { - if (scannedResources.has(resourcePath)) return - scannedResources.add(resourcePath) - try { - const resource = await ResourceService.getResource({ workspace, path: resourcePath }) - const nested: Promise[] = [] - const visit = (node: unknown) => { - if (typeof node === 'string') { - const ref = STATIC_REF.exec(node) - if (!ref) return - add(ref[1] === 'res' ? 'resource' : 'variable', ref[2], resourcePath) - if (ref[1] === 'res' && ITEM_PATH.test(ref[2])) nested.push(followResource(ref[2])) - } else if (node && typeof node === 'object') { - Object.values(node).forEach(visit) - } - } - visit(resource.value) - await Promise.all(nested) - } catch (e) { - errors.push(`${resourcePath}: ${e?.body ?? e}`) - } - } - - await follow(kind, path, 0) - await Promise.all( - [...items.values()].filter((i) => i.kind === 'resource').map((i) => followResource(i.path)) - ) - const byPath = (a: { path: string }, b: { path: string }) => a.path.localeCompare(b.path) - return { - items: [...items.values()].sort(byPath), - others: [...others.values()].sort(byPath), - errors + const others = new Map() + for (const { reader, ...asset } of needs.others) { + if (!performs(reader)) continue + const key = `${asset.kind}:${asset.path}` + const other = others.get(key) + others.set( + key, + other ? { ...other, sources: [...new Set([...other.sources, ...asset.sources])] } : asset + ) } + return { items: [...items.values()], others: [...others.values()] } }