From 19d20dacf6d0c50d155f448e0385a6a4cfd99809 Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Mon, 2 Nov 2026 00:29:01 -0800 Subject: [PATCH] feat: grant and remove access from the access view Co-Authored-By: Claude Opus 5.5 --- ...4880fffdb7b2b91b678a6c315070d6fad7b41.json | 30 -- backend/windmill-api-groups/src/access.rs | 276 +++++++++++++++--- backend/windmill-api/openapi.yaml | 105 +++++++ docs/feature-telemetry.md | 2 +- .../src/lib/components/AccessDrawer.svelte | 191 ++++++++++-- .../src/lib/components/DrillPicker.svelte | 4 +- .../components/access/AddNeededAccess.svelte | 143 +++++++++ .../components/access/GrantNavigator.svelte | 259 ++++++++++++++++ frontend/src/lib/components/access/access.ts | 50 ++++ .../src/lib/components/access/detectNeeds.ts | 149 ++++++++++ 10 files changed, 1113 insertions(+), 96 deletions(-) delete mode 100644 backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json create mode 100644 frontend/src/lib/components/access/AddNeededAccess.svelte create mode 100644 frontend/src/lib/components/access/GrantNavigator.svelte create mode 100644 frontend/src/lib/components/access/access.ts create mode 100644 frontend/src/lib/components/access/detectNeeds.ts diff --git a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json b/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json deleted file mode 100644 index b517bb1790..0000000000 --- a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "name", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "via!", - "type_info": "TextArray" - } - ], - "parameters": { - "Left": [ - "Text", - "TextArray", - "TextArray" - ] - }, - "nullable": [ - false, - null - ] - }, - "hash": "81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41" -} diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs index 4a43b84412..e92bab3e4d 100644 --- a/backend/windmill-api-groups/src/access.rs +++ b/backend/windmill-api-groups/src/access.rs @@ -18,14 +18,20 @@ use windmill_api_auth::ApiAuthed; use windmill_common::{ auth::fetch_authed_from_permissioned_as, db::UserDB, - error::{Error, JsonResult}, + error::{Error, JsonResult, Result}, + workspaces::{check_operator_can_manage, ManageKind}, DB, }; pub fn workspaced_service() -> Router { - Router::new().route("/get", get(get_access)) + Router::new() + .route("/get", get(get_access)) + .route("/browse_folders", get(browse_folders)) + .route("/browse_items", get(browse_items)) } +const BROWSE_PAGE: i64 = 100; + /// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on /// purpose: they are test data attached to an item, not something access is granted to. const ITEM_TABLES: [(&str, &str, &str); 17] = [ @@ -74,6 +80,12 @@ struct FolderAccess { owner: bool, /// The `extra_perms` keys (`u/` or `g/`) that grant the folder. via: Vec, + /// The principal's own entry in `extra_perms`: absent when none, false for read, true for write. + #[serde(skip_serializing_if = "Option::is_none")] + grant: Option, + /// Why the caller cannot change the principal's own entry. Set only where there is one. + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, } #[derive(Serialize)] @@ -82,6 +94,9 @@ struct ItemAccess { path: String, write: bool, reasons: Vec, + /// Why the caller cannot change the principal's own grant. Set only where there is one. + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, } #[derive(Serialize)] @@ -175,10 +190,32 @@ impl From for ItemAccess { *write } }); - ItemAccess { kind: r.kind, path: r.path, write, reasons } + ItemAccess { kind: r.kind, path: r.path, write, reasons, blocked: None } } } +/// Splits `u/` or `g/` and refuses callers who may not look at that principal. +fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a str, &'a str)> { + let (prefix, name) = principal + .split_once('/') + .filter(|(prefix, name)| matches!(*prefix, "u" | "g") && !name.is_empty()) + .ok_or_else(|| Error::BadRequest("principal must be u/ or g/".into()))?; + + // Another principal's list names paths the caller may not be able to read. A group's reach is + // contained in each member's, so its members may see it. + let allowed = authed.is_admin + || match prefix { + "u" => name == authed.username, + _ => authed.groups.iter().any(|g| g == name), + }; + if !allowed { + return Err(Error::PermissionDenied( + "only workspace admins can view another member's access".into(), + )); + } + Ok((prefix, name)) +} + async fn get_access( authed: ApiAuthed, Extension(db): Extension, @@ -186,24 +223,7 @@ async fn get_access( Path(w_id): Path, Query(AccessQuery { principal }): Query, ) -> JsonResult { - let (prefix, name) = principal - .split_once('/') - .filter(|(_, name)| !name.is_empty()) - .ok_or_else(|| Error::BadRequest("principal must be u/ or g/".into()))?; - - // Another principal's list names paths the caller may not be able to read. A group's reach is - // contained in each member's, so its members may see it. - let allowed = authed.is_admin - || match prefix { - "u" => name == authed.username, - "g" => authed.groups.iter().any(|g| g == name), - _ => false, - }; - if !allowed { - return Err(Error::PermissionDenied( - "only workspace admins can view another member's access".into(), - )); - } + let (prefix, name) = check_principal(&authed, &principal)?; let email = match prefix { "u" => { @@ -268,39 +288,54 @@ async fn get_access( .iter() .map(|f| f.0.clone()) .collect::>(); - let mut via = sqlx::query!( - "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\" + let mut via = sqlx::query_as::<_, (String, Vec, Option)>( + "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k), + (extra_perms ->> $4)::boolean FROM folder WHERE workspace_id = $1 AND name = ANY($2)", - &w_id, - &folder_names, - &perms ) + .bind(&w_id) + .bind(&folder_names) + .bind(&perms) + .bind(&principal) .fetch_all(&db) .await? .into_iter() - .map(|r| (r.name, r.via)) + .map(|(name, via, grant)| (name, (via, grant))) .collect::>(); let mut folders = target .folders .iter() - .map(|(name, write, owner)| FolderAccess { - name: name.clone(), - write: *write, - owner: *owner, - via: via.remove(name).unwrap_or_default(), + .map(|(name, write, owner)| { + let (via, grant) = via.remove(name).unwrap_or_default(); + // An owner keeps write whatever its entry says, so there is nothing to change. + let blocked = (grant.is_some() && !*owner && !windmill_api_auth::is_owner(&authed, name)) + .then(|| folder_blocked(name)); + FolderAccess { name: name.clone(), write: *write, owner: *owner, via, grant, blocked } }) .collect::>(); folders.sort_by(|a, b| a.name.cmp(&b.name)); let mut tx = user_db.begin(&target).await?; - let items = sqlx::query_as::<_, ItemRow>(&items_query()) + let rows = sqlx::query_as::<_, ItemRow>(&items_query()) .bind(&w_id) .fetch_all(&mut *tx) - .await? - .into_iter() - .map(ItemAccess::from) - .collect(); + .await?; tx.commit().await?; + let denied = manage_denied(&db, &w_id, &authed).await; + let items = rows + .into_iter() + .map(|r| { + let direct = match prefix { + "u" => r.user_grant.is_some(), + _ => r.group_read.iter().any(|g| g == name), + }; + let mut item = ItemAccess::from(r); + if direct { + item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path); + } + item + }) + .collect(); let mut groups = target.groups; groups.sort(); @@ -312,3 +347,170 @@ async fn get_access( items, })) } + +#[derive(Serialize, sqlx::FromRow)] +struct BrowseFolder { + name: String, + /// The principal's own entry in the folder's `extra_perms`: absent, read (false) or write. + grant: Option, + /// Owners always keep write; `acls/add` refuses to lower it. + target_owner: bool, + #[sqlx(skip)] + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, +} + +#[derive(Serialize, sqlx::FromRow)] +struct BrowseItem { + kind: String, + path: String, + grant: Option, + #[sqlx(skip)] + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, +} + +#[derive(Serialize)] +struct BrowseItems { + items: Vec, + has_more: bool, +} + +#[derive(Deserialize)] +struct BrowseItemsQuery { + principal: String, + /// Only paths starting with this, e.g. `f/billing/` or `u/alice/`. + prefix: Option, + kind: Option, + search: Option, + offset: Option, +} + +/// Why the caller cannot change grants on `path`, mirroring the checks `acls/add` makes. +fn grant_blocked(authed: &ApiAuthed, path: &str) -> Option { + if authed.is_admin { + return None; + } + let mut parts = path.splitn(3, '/'); + match (parts.next(), parts.next()) { + (Some("u"), Some(owner)) if owner == authed.username => None, + (Some("u"), Some(owner)) => { + Some(format!("Only u/{owner} and workspace admins can share it")) + } + (Some("f"), Some(folder)) if windmill_api_auth::is_owner(authed, folder) => None, + (Some("f"), Some(folder)) => Some(folder_blocked(folder)), + _ => Some("Only workspace admins can share items under g/".to_string()), + } +} + +fn folder_blocked(folder: &str) -> String { + format!("Only workspace admins and owners of f/{folder} can share it") +} + +async fn browse_folders( + authed: ApiAuthed, + Extension(user_db): Extension, + Path(w_id): Path, + Query(AccessQuery { principal }): Query, +) -> JsonResult> { + check_principal(&authed, &principal)?; + let mut tx = user_db.begin(&authed).await?; + let mut folders = sqlx::query_as::<_, BrowseFolder>( + "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\", $2 = ANY(owners) AS target_owner + FROM folder WHERE workspace_id = $1 ORDER BY name", + ) + .bind(&w_id) + .bind(&principal) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + for folder in &mut folders { + if !windmill_api_auth::is_owner(&authed, &folder.name) { + folder.blocked = Some(folder_blocked(&folder.name)); + } + } + Ok(Json(folders)) +} + +async fn browse_items( + authed: ApiAuthed, + Extension(db): Extension, + Extension(user_db): Extension, + Path(w_id): Path, + Query(q): Query, +) -> JsonResult { + check_principal(&authed, &q.principal)?; + let tables = ITEM_TABLES + .iter() + .filter(|(kind, ..)| q.kind.as_deref().map_or(true, |k| k == *kind)) + .collect::>(); + if tables.is_empty() { + return Err(Error::BadRequest("unknown kind".into())); + } + // SAFETY: table names and filters come from the `ITEM_TABLES` constant, never from the request. + let union = tables + .iter() + .map(|(kind, table, filter)| { + format!( + "SELECT '{kind}'::text AS kind, path::text AS path, (extra_perms ->> $2)::boolean AS \"grant\" + FROM {table} WHERE workspace_id = $1 {filter}" + ) + }) + .collect::>() + .join(" UNION ALL "); + let sql = format!( + "SELECT kind, path, \"grant\" FROM ({union}) i + WHERE ($3::text IS NULL OR starts_with(path, $3)) + AND ($4::text IS NULL OR strpos(lower(path), lower($4)) > 0) + ORDER BY path, kind LIMIT $5 OFFSET $6" + ); + let mut tx = user_db.begin(&authed).await?; + let mut items = sqlx::query_as::<_, BrowseItem>(&sql) + .bind(&w_id) + .bind(&q.principal) + .bind(q.prefix.as_deref().filter(|p| !p.is_empty())) + .bind(q.search.as_deref().map(str::trim).filter(|s| !s.is_empty())) + .bind(BROWSE_PAGE + 1) + .bind(q.offset.unwrap_or(0).max(0)) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + let has_more = items.len() as i64 > BROWSE_PAGE; + items.truncate(BROWSE_PAGE as usize); + + let denied = manage_denied(&db, &w_id, &authed).await; + for item in &mut items { + item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path); + } + Ok(Json(BrowseItems { items, has_more })) +} + +/// Operators may be barred from managing schedules and triggers, `/acls` included. +async fn manage_denied(db: &DB, w_id: &str, authed: &ApiAuthed) -> Vec<(ManageKind, String)> { + let mut denied = vec![]; + if !authed.is_admin { + for kind in [ManageKind::Schedules, ManageKind::Triggers] { + if let Err(e) = check_operator_can_manage(db, w_id, authed, kind).await { + denied.push((kind, e.to_string())); + } + } + } + denied +} + +/// Why the caller cannot change grants on this item: the operator gate first, then the path. +fn item_blocked( + authed: &ApiAuthed, + denied: &[(ManageKind, String)], + kind: &str, + path: &str, +) -> Option { + let manage_kind = match kind { + "schedule" => Some(ManageKind::Schedules), + k if k.ends_with("_trigger") => Some(ManageKind::Triggers), + _ => None, + }; + manage_kind + .and_then(|mk| denied.iter().find(|(k, _)| *k == mk).map(|(_, e)| e.clone())) + .or_else(|| grant_blocked(authed, path)) +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 45433bea8f..e10e1625ca 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -25051,6 +25051,102 @@ paths: schema: $ref: "#/components/schemas/PrincipalAccess" + /w/{workspace}/access/browse_folders: + get: + summary: list the folders the caller can read, with the principal's direct grant on each + operationId: browseAccessFolders + tags: + - granular_acl + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: principal + description: "`u/` or `g/`" + in: query + required: true + schema: + type: string + responses: + "200": + description: folders + content: + application/json: + schema: + type: array + items: + type: object + properties: + name: + type: string + grant: + description: the principal's entry in the folder's extra_perms; absent when none, false for read, true for write + type: boolean + nullable: true + target_owner: + type: boolean + blocked: + description: why the caller cannot change this grant + type: string + required: [name, target_owner] + + /w/{workspace}/access/browse_items: + get: + summary: list items the caller can read, with the principal's direct grant on each + operationId: browseAccessItems + tags: + - granular_acl + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: principal + description: "`u/` or `g/`" + in: query + required: true + schema: + type: string + - name: prefix + description: only paths starting with this, e.g. `f/billing/` + in: query + schema: + type: string + - name: kind + in: query + schema: + type: string + - name: search + in: query + schema: + type: string + - name: offset + in: query + schema: + type: integer + responses: + "200": + description: a page of 100 items + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: + type: object + properties: + kind: + type: string + path: + type: string + grant: + type: boolean + nullable: true + blocked: + description: why the caller cannot change this grant + type: string + required: [kind, path] + has_more: + type: boolean + required: [items, has_more] + /w/{workspace}/acls/get/{kind}/{path}: get: summary: get granular acls @@ -37072,6 +37168,12 @@ components: type: array items: type: string + grant: + description: the principal's own entry on the folder; absent when none, false for read, true for write + type: boolean + blocked: + description: why the caller cannot change the principal's own entry; set only where there is one + type: string required: [name, write, owner, via] items: type: array @@ -37088,6 +37190,9 @@ components: type: array items: $ref: "#/components/schemas/AccessReason" + blocked: + description: why the caller cannot change the principal's own grant; set only where there is one + type: string required: [kind, path, write, reasons] required: [principal, is_admin, groups, folders, items] diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 0dac23ee36..2beaee7c16 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,7 +4,7 @@ anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick" without any identifying data leaving the instance. -It currently carries 94 registered actions across thirty-seven features (`access_view`, `ai_session`, `ai_chat`, +It currently carries 95 registered actions across thirty-seven features (`access_view`, `ai_session`, `ai_chat`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, `flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`, `command_script`, `mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`, diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte index 5dbf8c83aa..52bcfb9472 100644 --- a/frontend/src/lib/components/AccessDrawer.svelte +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -1,5 +1,5 @@ +{#snippet grantMenu(kind: string, path: string, current: boolean, blocked: string | undefined)} + {#if blocked} + + + {#snippet text()}{blocked}{/snippet} + + {:else} + + {/if} +{/snippet} + drawer?.closeDrawer()}>
@@ -151,7 +230,8 @@ Folder Access - Why + Why + @@ -159,7 +239,7 @@ f/{folder.name} {folder.write ? 'Write' : 'Read'} - +
{#if folder.owner} Owner @@ -169,6 +249,11 @@ {/each}
+ + {#if !folder.owner && folder.grant != undefined} + {@render grantMenu('folder', folder.name, folder.grant, folder.blocked)} + {/if} + {/each} @@ -179,7 +264,54 @@
+ {#snippet action()} +
+ grantOpen, setGrantOpen} + openFocus="[data-workspace-picker-search]" + contentClasses="flex flex-col overflow-hidden" + > + {#snippet trigger()} + + {/snippet} + {#snippet content()} + {#if access} + + {/if} + {/snippet} + +
+ {/snippet}
+ {#if needsOf} + {#key `${needsOf.kind}:${needsOf.path}`} + (needsOf = undefined)} + /> + {/key} + {/if}
Kind Path Access - Why + Why + {#each filteredItems.slice(0, nbDisplayed) as item (item.kind + ':' + item.path)} + {@const own = ownItemGrant(item)} @@ -223,7 +357,7 @@ {item.path} {item.write ? 'Write' : 'Read'} - +
{#each item.reasons as reason, i (i)} {@const level = reasonAccess(reason)} @@ -235,6 +369,11 @@ {/each}
+ + {#if own !== undefined} + {@render grantMenu(item.kind, item.path, own, item.blocked)} + {/if} + {/each} diff --git a/frontend/src/lib/components/DrillPicker.svelte b/frontend/src/lib/components/DrillPicker.svelte index a92ef11ddf..1245781f81 100644 --- a/frontend/src/lib/components/DrillPicker.svelte +++ b/frontend/src/lib/components/DrillPicker.svelte @@ -573,7 +573,7 @@ leaves and ignores the current scope. {#if leafBadge || leafAction} -
+
{#if action} + + {#if error} + {error} + {:else if !needs} + + {:else} + {#if needs.items.length} +
+ {#each needs.items as item (item.kind + ':' + item.path)} + {@const key = `${item.kind}:${item.path}`} + {@const already = reads.has(key)} + + {/each} +
+ {:else} +

No resource or variable found in {path}.

+ {/if} + {#if needs.others.length} + + {needs.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} +
+ + + A path the code builds while it runs can't be found. Grant it with "Grant". + + +
+ {/if} +
diff --git a/frontend/src/lib/components/access/GrantNavigator.svelte b/frontend/src/lib/components/access/GrantNavigator.svelte new file mode 100644 index 0000000000..a943b939dd --- /dev/null +++ b/frontend/src/lib/components/access/GrantNavigator.svelte @@ -0,0 +1,259 @@ + + + + + +{#snippet leafIcon(leaf: DrillLeaf)} + +{/snippet} + +
+ scope.length === 1 && loadBranch(scope[0])} + onFilterChange={(filter) => filter.trim() && searchSoon(filter.trim())} + rowTooltip={tooltip} + leafBadge={(leaf) => { + const write = reaches.get(leaf.key) + return write === undefined + ? undefined + : { label: write ? 'Writes' : 'Reads', color: write ? 'blue' : 'gray' } + }} + leafAction={(leaf) => + isRunnable(leaf.data.kind) + ? { + icon: ScanSearch, + label: 'What it reads', + title: `Grant what ${leaf.data.path} reads when it runs`, + run: () => onFindReads(leaf.data.kind as RunnableKind, leaf.data.path) + } + : undefined} + /> +
diff --git a/frontend/src/lib/components/access/access.ts b/frontend/src/lib/components/access/access.ts new file mode 100644 index 0000000000..7943202a54 --- /dev/null +++ b/frontend/src/lib/components/access/access.ts @@ -0,0 +1,50 @@ +import { GranularAclService } from '$lib/gen' + +export type GrantLevel = 'none' | 'read' | 'write' + +type AclKind = Parameters[0]['kind'] + +export const KIND_LABELS: Record = { + script: 'Script', + flow: 'Flow', + app: 'App', + resource: 'Resource', + variable: 'Variable', + schedule: 'Schedule', + http_trigger: 'HTTP route', + websocket_trigger: 'WebSocket trigger', + kafka_trigger: 'Kafka trigger', + nats_trigger: 'NATS trigger', + postgres_trigger: 'Postgres trigger', + mqtt_trigger: 'MQTT trigger', + amqp_trigger: 'AMQP trigger', + gcp_trigger: 'GCP Pub/Sub trigger', + azure_trigger: 'Azure trigger', + sqs_trigger: 'SQS trigger', + email_trigger: 'Email trigger' +} + +/** Sets `principal`'s own entry on an item or folder (`kind` `folder`, `path` the folder name). */ +export async function setGrant( + workspace: string, + kind: string, + path: string, + principal: string, + level: GrantLevel +): Promise { + if (level === 'none') { + await GranularAclService.removeGranularAcls({ + workspace, + kind: kind as AclKind, + path, + requestBody: { owner: principal } + }) + } else { + await GranularAclService.addGranularAcls({ + workspace, + kind: kind as AclKind, + path, + requestBody: { owner: principal, write: level === 'write' } + }) + } +} diff --git a/frontend/src/lib/components/access/detectNeeds.ts b/frontend/src/lib/components/access/detectNeeds.ts new file mode 100644 index 0000000000..06e5fa5c85 --- /dev/null +++ b/frontend/src/lib/components/access/detectNeeds.ts @@ -0,0 +1,149 @@ +import { AppService, AssetService, FlowService, ScriptService, type AssetKind } 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[] } + +/** 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 Needs = { items: NeededItem[]; others: OtherAsset[]; errors: string[] } + +const MAX_DEPTH = 4 +const ITEM_PATH = /^[ufg]\/[^/]+\/.+/ +const STATIC_REF = /^\$(res|var):(.+)$/ +// The asset parser finds resources but has no variable kind, so literal variable reads are matched +// here. A path the code builds at run time is found by neither. +const VARIABLE_CALL = /\b(?:getVariable|get_variable)\(\s*["'`]([^"'`]+)["'`]/g + +/** + * 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. + */ +export async function detectNeeds( + workspace: string, + kind: RunnableKind, + path: string +): Promise { + const items = new Map() + const others = new Map() + const errors: string[] = [] + const visited = new Set() + + 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] }) + } + } + + async function scanCode(language: string | undefined, content: string, source: string) { + const result = await inferAssets(language as SupportedLanguage | undefined, content) + if (result.status === 'ok') { + for (const asset of result.assets) add(asset.kind, asset.path, source) + } + for (const match of content.matchAll(VARIABLE_CALL)) add('variable', match[1], source) + } + + 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) + } + } + + /** 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/')) { + pending.push(follow(calledKind, obj.path, depth + 1)) + } + for (const [key, child] of Object.entries(obj)) { + if (key !== 'content') visit(child, here) + } + } + visit(value, source) + await Promise.all(pending) + } + + async function follow(runnableKind: RunnableKind, runnablePath: string, depth: number) { + const key = `${runnableKind}:${runnablePath}` + if (visited.has(key) || depth > MAX_DEPTH) return + visited.add(key) + try { + if (runnableKind === 'script') { + const script = await ScriptService.getScriptByPath({ workspace, path: runnablePath }) + await Promise.all([ + 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 }) + await walk(app.value, runnablePath, depth) + } + } catch (e) { + errors.push(`${runnablePath}: ${e?.body ?? e}`) + } + } + + await follow(kind, path, 0) + 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 + } +}