diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs index 4a43b84412..85894e8543 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] = [ @@ -179,16 +185,11 @@ impl From for ItemAccess { } } -async fn get_access( - authed: ApiAuthed, - Extension(db): Extension, - Extension(user_db): Extension, - Path(w_id): Path, - Query(AccessQuery { principal }): Query, -) -> JsonResult { +/// 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(|(_, name)| !name.is_empty()) + .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 @@ -196,14 +197,24 @@ async fn get_access( let allowed = authed.is_admin || match prefix { "u" => name == authed.username, - "g" => authed.groups.iter().any(|g| g == name), - _ => false, + _ => 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, + Extension(user_db): Extension, + Path(w_id): Path, + Query(AccessQuery { principal }): Query, +) -> JsonResult { + let (prefix, name) = check_principal(&authed, &principal)?; let email = match prefix { "u" => { @@ -312,3 +323,160 @@ 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); + + // Operators may be barred from managing schedules and triggers, `/acls` included. + let mut manage_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.clone()).await { + manage_denied.push((kind, e.to_string())); + } + } + } + for item in &mut items { + let manage_kind = match item.kind.as_str() { + "schedule" => Some(ManageKind::Schedules), + k if k.ends_with("_trigger") => Some(ManageKind::Triggers), + _ => None, + }; + item.blocked = manage_kind + .and_then(|mk| { + manage_denied + .iter() + .find(|(k, _)| *k == mk) + .map(|(_, e)| e.clone()) + }) + .or_else(|| grant_blocked(&authed, &item.path)); + } + Ok(Json(BrowseItems { items, has_more })) +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index e498eac5c1..8f22237e0c 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -24998,6 +24998,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 diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 78a7320cdd..92a6342a1c 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 92 registered actions across thirty-six features (`access_view`, `ai_session`, `ai_chat`, +It currently carries 93 registered actions across thirty-six 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`, `debugger`, `trigger`, `command_script`, `mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte index b17f99646c..0a3888ce50 100644 --- a/frontend/src/lib/components/AccessDrawer.svelte +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -8,31 +8,15 @@ import { GranularAclService, type AccessReason, type PrincipalAccess } from '$lib/gen' import { workspaceStore } from '$lib/stores' import { logFeatureUsage } from '$lib/utils/featureUsage' + import { Tab, Tabs } from './common' + import AccessGrantPanel from './access/AccessGrantPanel.svelte' + import AddNeededAccess from './access/AddNeededAccess.svelte' + import { KIND_LABELS } from './access/access' type Target = 'self' | 'user' | 'service_account' | 'group' const PAGE = 100 - 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' - } - let drawer: Drawer | undefined = $state() let principal = $state('') let access: PrincipalAccess | undefined = $state() @@ -40,6 +24,7 @@ let search = $state('') let kind: string | undefined = $state() let nbDisplayed = $state(PAGE) + let tab: 'access' | 'grant' = $state('access') // Responses are not ordered: a slow answer for the previous principal must not land on this one. let requestId = 0 @@ -50,13 +35,18 @@ search = '' kind = undefined nbDisplayed = PAGE + tab = 'access' drawer?.openDrawer() logFeatureUsage('access_view', 'opened', { key: target }) + await reload() + } + + async function reload(): Promise { const id = ++requestId try { const result = await GranularAclService.getPrincipalAccess({ workspace: $workspaceStore!, - principal: nextPrincipal + principal }) if (id === requestId) access = result } catch (e) { @@ -64,6 +54,13 @@ } } + function selectTab(next: 'access' | 'grant') { + tab = next + if (next === 'grant') logFeatureUsage('access_view', 'grant_opened') + } + + const reads = $derived(new Set((access?.items ?? []).map((i) => `${i.kind}:${i.path}`))) + const name = $derived(principal.slice(2)) const isGroup = $derived(principal.startsWith('g/')) @@ -131,6 +128,16 @@ {principal} is an admin of this workspace and can read and write every item in it. {:else} + tab, (v) => selectTab(v as 'access' | 'grant')}> + + + + {/if} + + {#if access && !access.is_admin && tab === 'grant'} + + + {:else if access && !access.is_admin}
{#if access.groups.length}
diff --git a/frontend/src/lib/components/access/AccessGrantPanel.svelte b/frontend/src/lib/components/access/AccessGrantPanel.svelte new file mode 100644 index 0000000000..6eed7a322a --- /dev/null +++ b/frontend/src/lib/components/access/AccessGrantPanel.svelte @@ -0,0 +1,240 @@ + + +{#snippet levelPicker( + value: GrantLevel, + blocked: string | undefined, + busy: boolean, + onSelect: (v: GrantLevel) => void +)} +
+ {#if blocked} + + {/if} + v !== value && onSelect(v)} + > + {#snippet children({ item })} + + + + {/snippet} + +
+{/snippet} + +
+ + +
+ {#if selectedFolder} + {@const folder = selectedFolder} +
+
+ The whole folder f/{folder.name} + + {folder.target_owner + ? `${principal} owns this folder and always keeps write.` + : 'Covers every item in it, including ones added later.'} + +
+ {@render levelPicker( + folder.target_owner ? 'write' : level(folder.grant), + folder.target_owner ? `${principal} owns f/${folder.name}` : folder.blocked, + !!pending[`folder:${folder.name}`], + (v) => change('folder', folder.name, v, (g) => (folder.grant = g)) + )} +
+ {/if} + +
+ search, (v) => ((search = String(v ?? '')), reloadSoon())} + inputProps={{ placeholder: 'Search paths' }} + size="sm" + class="grow" + /> +
+ runnablePath, (v) => ((runnablePath = v), (needs = undefined))} + bind:filterText={() => filterText, (v) => ((filterText = v), loadCandidatesSoon())} + placeholder={runnableKind === 'app' ? 'Pick an app' : `Pick a ${runnableKind}`} + size="sm" + /> +
+ +
+ + {#if needs} + {#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 {runnablePath}. +

+ {/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 from the list below. + + +
+ {/if} +
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 + } +}