feat: check what a script, flow or app reads after a grant in the access view

This commit is contained in:
Guilhem Lemouel
2026-12-01 03:36:45 -08:00
parent 2a4cb1faa3
commit 06bb3408d0
11 changed files with 651 additions and 245 deletions
+11 -10
View File
@@ -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<NodeKey, Fetched>) -> Tagged {
let mut references: BTreeMap<(ItemKind, String, Reader), (Access, BTreeSet<String>)> =
// 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<String>> =
BTreeMap::new();
let mut others: BTreeMap<(AssetKind, String, Reader), BTreeSet<String>> = BTreeMap::new();
let (mut unreadable, mut too_deep, mut over_budget) =
@@ -970,13 +972,10 @@ fn tag(graph: &HashMap<NodeKey, Fetched>) -> 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<NodeKey, Fetched>) -> 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")),
+5 -3
View File
@@ -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.
+72 -22
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { Alert, Badge, Button, Drawer, DrawerContent, Section, Skeleton } from './common'
import Modal from './common/modal/Modal.svelte'
import TextInput from './text_input/TextInput.svelte'
import Select from './select/Select.svelte'
import DataTable from './table/DataTable.svelte'
@@ -16,10 +17,16 @@
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { pluralize, type Item } from '$lib/utils'
import { itemHref } from './offboarding-utils'
import AddNeededAccess from './access/AddNeededAccess.svelte'
import NeededAccess from './access/NeededAccess.svelte'
import GrantNavigator, { navigatorMaxHeight } from './access/GrantNavigator.svelte'
import { KIND_LABELS, setGrant, type GrantLevel } from './access/access'
import type { RunnableKind } from './access/detectNeeds'
import {
hasGap,
isScannable,
opensItem,
runGrantCheck,
type GrantCheck
} from './access/neededAccess'
import {
buildAccessTree,
flattenAccessTree,
@@ -68,7 +75,10 @@
let changing: string | undefined = $state()
let grantPopover: Popover | undefined = $state()
let grantAnchor: HTMLElement | undefined = $state()
let needsOf: { kind: RunnableKind; path: string } | undefined = $state()
/** What the last grant on a script, flow or app left missing, shown when anything is. */
let grantCheck: GrantCheck | undefined = $state()
let checkOpen = $state(false)
let checkId = 0
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
let requestId = 0
@@ -82,7 +92,8 @@
openState = {}
expandAll = undefined
grantOpen = false
needsOf = undefined
checkOpen = false
checkId++
drawer?.openDrawer()
logFeatureUsage('access_view', 'opened', { key: target })
await reload()
@@ -127,9 +138,29 @@
})
}
function findReads(kind: RunnableKind, path: string) {
grantOpen = false
needsOf = { kind, path }
/** After a grant from the navigator: reloads, then checks what the item reads. No check on a
* folder, which can hold hundreds of items. */
async function granted(change: { kind: string; path: string; level: GrantLevel }) {
const id = ++checkId
const target = principal
await reload()
const { kind, path, level } = change
if (level === 'none' || !isScannable(kind) || !access || id !== checkId) return
let check: GrantCheck
try {
check = await runGrantCheck($operatingWorkspace!, { kind, path }, target, access)
} catch (e) {
if (id === checkId) sendUserToast(`Could not check what ${path} reads: ${e?.body ?? e}`, true)
return
}
if (id !== checkId) return
if (hasGap(check)) {
grantCheck = check
grantOpen = false
checkOpen = true
} else {
sendUserToast(`${target} can ${opensItem(kind) ? 'open' : 'run'} ${path}`)
}
}
/** The principal's own entry on an item: `true` for write, `false` for read. */
@@ -170,7 +201,6 @@
]
}
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])))
@@ -274,10 +304,22 @@
// necessarily the one the new tab would otherwise open.
function withWorkspace(href: string): string {
const [route, hash] = href.split(/#(.*)/s)
const query = `?workspace=${encodeURIComponent($operatingWorkspace ?? '')}`
const query = `${route.includes('?') ? '&' : '?'}workspace=${encodeURIComponent($operatingWorkspace ?? '')}`
return route + query + (hash !== undefined ? `#${hash}` : '')
}
function checkTitle(check: GrantCheck): string {
const { kind, path } = check.item
if (check.grantee.length) {
return opensItem(kind)
? `${principal} can't use all of ${path} yet`
: `${principal} can't run ${path} yet`
}
return check.account?.rows.length
? `${path} fails for everyone`
: `${path}'s runnables have no account`
}
function itemLink(kind: string, path: string): string | undefined {
const href = itemHref(kind, path)
return href ? withWorkspace(href) : undefined
@@ -404,24 +446,13 @@
{/snippet}
{#snippet content()}
{#if access}
<GrantNavigator bind:this={navigator} {principal} {access} onChange={reload} /> {/if}
<GrantNavigator bind:this={navigator} {principal} {access} onChange={granted} />
{/if}
{/snippet}
</Popover>
</div>
{/snippet}
<div class="flex flex-col gap-2">
{#if needsOf}
{#key `${needsOf.kind}:${needsOf.path}`}
<AddNeededAccess
{principal}
kind={needsOf.kind}
path={needsOf.path}
{held}
onGranted={reload}
onClose={() => (needsOf = undefined)}
/>
{/key}
{/if}
<div class="flex gap-2 items-center">
<TextInput
bind:value={search}
@@ -602,3 +633,22 @@
</div>
</DrawerContent>
</Drawer>
<Modal
bind:open={checkOpen}
title={grantCheck ? checkTitle(grantCheck) : ''}
kind="X"
enterConfirms={false}
class="sm:max-w-2xl"
>
{#if grantCheck}
<NeededAccess
check={grantCheck}
{principal}
href={withWorkspace}
grant={(row, to) => setGrant($operatingWorkspace!, row.kind, row.path, to, row.level)}
onGranted={reload}
onClose={() => (checkOpen = false)}
/>
{/if}
</Modal>
@@ -1354,6 +1354,13 @@
let selectedTab: 'metadata' | 'runtime' | 'permissions' | 'ui' | 'triggers' = $state(
(() => {
// The access view links here to change who the script runs as.
if (
untrack(() => searchParams).get('settings_tab') === 'permissions' &&
customUi?.settingsPanel?.disableRuntime !== true
) {
return 'permissions'
}
if (customUi?.settingsPanel?.disableMetadata !== true) {
// first option: either no custom UI or metadata is enabled
return 'metadata'
@@ -1,204 +0,0 @@
<script lang="ts">
import { Alert, Button, Skeleton } from '$lib/components/common'
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import { Info, X } from 'lucide-svelte'
import { setGrant } from './access'
import {
detectNeeds,
neededByGrantee,
type NeededItem,
type Needs,
type RunnableKind
} from './detectNeeds'
const operatingWorkspace = useOperatingWorkspace()
let {
principal,
kind,
path,
held,
onGranted,
onClose
}: {
principal: string
kind: RunnableKind
path: string
/** `kind:path` of every item the principal reaches through any grant, to whether it can write it. */
held: Map<string, boolean>
onGranted: () => void
onClose: () => void
} = $props()
const KIND_LABELS: Record<NeededItem['kind'], string> = {
resource: 'Resource',
variable: 'Variable',
script: 'Script',
flow: 'Flow'
}
let needs: Needs | undefined = $state()
let error: string | undefined = $state()
let selected: Record<string, boolean> = $state({})
/** Rows the last Grant sent: true once granted, the refusal's text when refused. */
let results: Record<string, true | string> = $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(
neededByGrantee(found, principal).items.map((i) => [`${i.kind}:${i.path}`, !covered(i)])
)
})
.catch((e) => (error = `${e?.body ?? e}`))
async function grant() {
if (!needed) return
granting = true
for (const item of needed.items) {
const key = `${item.kind}:${item.path}`
// A row covered since the scan, from the navigator or the table, is not sent: a grant
// replaces the principal's entry, so sending it at `item.level` can lower a write to read.
if (!selected[key] || covered(item)) continue
try {
await setGrant($operatingWorkspace!, item.kind, item.path, principal, item.level)
results[key] = true
selected[key] = false
} catch (e) {
results[key] = `${e?.body ?? e}`
}
}
granting = false
onGranted()
}
const selectedCount = $derived(
needed?.items.filter((i) => selected[`${i.kind}:${i.path}`] && !covered(i)).length ?? 0
)
</script>
<div class="flex flex-col gap-3 rounded-md border p-3">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs font-semibold text-emphasis truncate">What {path} reads</span>
<span class="text-2xs text-secondary">
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.
</span>
</div>
<Button
variant="subtle"
unifiedSize="xs"
iconOnly
startIcon={{ icon: X }}
title="Dismiss"
onClick={onClose}
/>
</div>
{#if error}
<Alert type="error" size="xs" title="Could not read {path}">{error}</Alert>
{:else if !needs || !needed}
<Skeleton layout={[[2], 0.5, [2]]} />
{:else}
{#if runsAs}
<Alert
type="info"
size="xs"
title={kind === 'app' ? `Its runnables run as ${runsAs}` : `Runs as ${runsAs}`}
>
{kind === 'app'
? 'Only what its frontend reads, as whoever opens it, is listed.'
: `What it reads needs no grant for ${principal}.`}
</Alert>
{/if}
{#if needed.items.length}
<div class="flex flex-col divide-y border rounded-md">
{#each needed.items as item (item.kind + ':' + item.path)}
{@const key = `${item.kind}:${item.path}`}
{@const already = covered(item)}
{@const result = results[key]}
<label class="flex items-start gap-2 px-3 py-1.5 text-xs">
<Checkbox
class="mt-0.5"
checked={selected[key] && !already}
disabled={already || granting}
onChange={() => (selected[key] = !selected[key])}
/>
<span class="flex flex-col grow min-w-0">
<span class="font-mono text-2xs text-emphasis truncate">{item.path}</span>
<span class="text-2xs text-secondary truncate">
{KIND_LABELS[item.kind]}, used by {item.sources.join(', ')}
</span>
{#if typeof result === 'string'}
<span class="text-2xs text-red-500">{result}</span>
{/if}
</span>
<span
class="text-2xs shrink-0 {typeof result === 'string'
? 'text-red-500'
: 'text-secondary'}"
>
{result === true
? 'Granted'
: typeof result === 'string'
? 'Not granted'
: status(item)}
</span>
</label>
{/each}
</div>
{:else}
<p class="text-xs text-secondary">Nothing {principal} needs was found in {path}.</p>
{/if}
{#if needed.others.length}
<Alert type="info" size="xs" title="Also used, not granted here">
{needed.others.map((o) => `${o.kind} ${o.path}`).join(', ')}. Access to these is set on the
storage or data table itself.
</Alert>
{/if}
{#if needs.errors.length}
<Alert type="warning" size="xs" title="Some of it could not be read">
{needs.errors.join('; ')}
</Alert>
{/if}
<div class="flex items-center justify-between gap-2">
<span class="flex items-center gap-1 text-2xs text-secondary">
<Info size={12} class="shrink-0" />
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".
</span>
<Button
variant="accent"
unifiedSize="sm"
disabled={selectedCount === 0}
loading={granting}
onClick={grant}
>
Grant access to {selectedCount}
</Button>
</div>
{/if}
</div>
@@ -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)
@@ -0,0 +1,265 @@
<!--
@component
What is missing after a grant on a script, flow or app: what it reads that the grantee can't open,
and what the account it runs as can't open, each with its two fixes.
-->
<script lang="ts">
import { Alert, Badge, Button } from '$lib/components/common'
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
import { Tooltip } from '$lib/components/meltComponents'
import { pluralize } from '$lib/utils'
import { AlertCircle, AlertTriangle, ExternalLink, Info } from 'lucide-svelte'
import { opensItem, runAsHref, type GapRow, type GrantCheck } from './neededAccess'
let {
check,
principal,
href,
grant,
onGranted,
onClose
}: {
check: GrantCheck
/** Who was just granted read on the item. */
principal: string
/** Turns an app route into a link to it in the workspace the drawer reports on. */
href: (route: string) => string
/** Grants `row` to `to`; a rejection's `body`, or its text, is shown as the refusal. */
grant: (row: GapRow, to: string) => Promise<void>
/** After a Grant, for the host to reload what the principal reaches. */
onGranted: () => void
onClose: () => void
} = $props()
const item = $derived(check.item)
const opens = $derived(opensItem(item.kind))
const noun = $derived(item.kind === 'flow' ? 'flow' : item.kind === 'script' ? 'script' : 'app')
const fixHref = $derived(href(runAsHref(item)))
/** By `<to>|<row key>`: true once granted, the refusal when refused. */
let results: Record<string, true | string> = $state({})
/** The principal whose rows are being granted. */
let running: string | undefined = $state()
function left(rows: GapRow[], to: string): GapRow[] {
return rows.filter((row) => results[`${to}|${row.key}`] !== true)
}
async function grantAll(rows: GapRow[], to: string) {
running = to
for (const row of left(rows, to)) {
const key = `${to}|${row.key}`
delete results[key]
try {
await grant(row, to)
results[key] = true
} catch (e) {
results[key] = `${e?.body ?? e}`
}
}
running = undefined
onGranted()
}
function grantLabel(rows: GapRow[]): string {
return rows.every((row) => row.level === 'read')
? `Grant read on ${rows.length}`
: `Grant ${rows.length}`
}
const done = $derived(
left(check.grantee, principal).length === 0 &&
(!check.account || left(check.account.rows, check.account.principal).length === 0)
)
</script>
{#snippet gapList(rows: GapRow[], to: string)}
<section class="flex flex-col gap-2">
<h3 class="text-xs font-semibold text-emphasis">{to} can't open ({rows.length})</h3>
<div class="border rounded-md divide-y">
{#each rows as row (row.key)}
{@const result = results[`${to}|${row.key}`]}
<div class="flex items-center gap-3 px-3 py-2.5">
<RowIcon kind={row.kind as 'script'} />
<span class="flex flex-col gap-0.5 min-w-0 grow">
<span class="text-xs font-semibold text-emphasis truncate" title={row.path}>
{row.path}
</span>
<!-- Spaces inside a block are trimmed, so the separator is written as text. -->
<span class="text-3xs text-hint truncate" title={row.use}>
{row.use}{#if result === true}{' · '}<span
class="text-green-700 dark:text-green-400 font-medium">granted just now</span
>{/if}
</span>
{#if typeof result === 'string'}
<span class="text-3xs text-red-700 dark:text-red-400">Refused: {result}</span>
{/if}
</span>
<Badge color={row.level === 'write' ? 'blue' : 'gray'}>
{row.level === 'write' ? 'Write' : 'Read'}
</Badge>
</div>
{/each}
</div>
</section>
{/snippet}
{#snippet fixes(
rows: GapRow[],
to: string,
grantTitle: string,
grantText: string,
otherTitle: string,
otherText: string,
otherLink: string
)}
{@const remaining = left(rows, to)}
<section class="flex flex-col gap-2">
<h3 class="text-xs font-semibold text-emphasis">Fix it one of two ways</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div class="flex flex-col gap-2 p-3 border rounded-md">
<p class="text-xs font-semibold text-emphasis">{grantTitle}</p>
<p class="text-xs text-secondary grow">{grantText}</p>
<div>
<Button
variant="accent"
unifiedSize="sm"
disabled={!remaining.length || (running !== undefined && running !== to)}
loading={running === to}
onClick={() => grantAll(rows, to)}
>
{remaining.length ? grantLabel(remaining) : 'Granted'}
</Button>
</div>
</div>
<div class="flex flex-col gap-2 p-3 border rounded-md">
<p class="text-xs font-semibold text-emphasis">{otherTitle}</p>
<p class="text-xs text-secondary grow">{otherText}</p>
<div>
<Button
variant="default"
unifiedSize="sm"
href={otherLink}
target="_blank"
endIcon={{ icon: ExternalLink }}
>
{opens ? 'Edit the app' : 'Open run-as setting'}
</Button>
</div>
</div>
</div>
</section>
{/snippet}
<div class="flex flex-col gap-5">
{#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(', ')}
<div class="flex flex-col gap-4">
<div class="flex items-start gap-2">
<AlertCircle size={16} class="text-yellow-600 shrink-0 mt-0.5" />
<div class="flex flex-col gap-0.5">
<p class="text-sm font-semibold text-emphasis">
Read on the {noun} was granted. {rows.length}
{what} missing.
</p>
<p class="text-xs text-secondary">
{#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}
</p>
</div>
</div>
{@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}
</div>
{/if}
{#if check.account?.rows.length}
{@const account = check.account}
{@const listed = account.rows.map((r) => r.path).join(', ')}
<div class="flex flex-col gap-4">
<div class="flex items-start gap-2">
<AlertTriangle size={16} class="text-red-600 shrink-0 mt-0.5" />
<div class="flex flex-col gap-0.5">
<p class="text-sm font-semibold text-emphasis">
{check.grantee.length
? `The account it runs as can't open something either.`
: `${principal} needs nothing more, but the account it runs as does.`}
</p>
<p class="text-xs text-secondary">
It runs as {account.principal}, who can't open {pluralize(
account.rows.length,
'thing'
)} it reads. Every run fails, whoever starts it.
</p>
</div>
</div>
{@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
)}
</div>
{/if}
{#if check.noAccount}
<Alert type="warning" size="xs" title="Its runnables have no account to run as">
They fail for everyone until the app is redeployed with one. Granting {principal} access won't
fix that.
</Alert>
{/if}
<p class="flex items-center gap-1.5 text-2xs text-secondary">
<Info size={12} class="shrink-0" />
Only paths written in its code and inputs are found.
<Tooltip>
<span class="text-accent cursor-help">What isn't found</span>
{#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}
</Tooltip>
</p>
<div class="flex justify-end gap-2 border-t pt-4">
<Button
variant={done ? 'accent' : 'default'}
unifiedSize="md"
disabled={running !== undefined}
onClick={onClose}
>
{done ? 'Done' : 'Not now'}
</Button>
</div>
</div>
@@ -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<string, boolean>,
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<AccessOtherAsset, 'reader'>
export type OtherAsset = Omit<AccessOtherAsset, 'reader'> & { uses: Omit<NeededUse, 'access'>[] }
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()] }
@@ -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)
})
})
@@ -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<string, boolean> {
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<GrantCheck> {
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<typeof neededByGrantee>['items'],
item: ScannedItem,
held: Map<string, boolean>
): 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 `<path>` or `<path> › <step, runnable or file>`. */
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<string, NeededUse['access']>()
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('; ')
}
@@ -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.