diff --git a/backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json b/backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json new file mode 100644 index 0000000000..88ab46d60b --- /dev/null +++ b/backend/.sqlx/query-4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "disabled", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011" +} diff --git a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json b/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json new file mode 100644 index 0000000000..b517bb1790 --- /dev/null +++ b/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json @@ -0,0 +1,30 @@ +{ + "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/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json b/backend/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json new file mode 100644 index 0000000000..ff34d0b0fb --- /dev/null +++ b/backend/.sqlx/query-fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)\n OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index add89eebfd..7aa161da8a 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -a9a0f4f5073d0f774fb7bd7f87b6e37e8d5356b4 +c4e610999ca0d1abab06b1660cc48e486ab870b3 diff --git a/backend/tests/access_view.rs b/backend/tests/access_view.rs new file mode 100644 index 0000000000..e3edf95494 --- /dev/null +++ b/backend/tests/access_view.rs @@ -0,0 +1,66 @@ +//! Another member's access lists paths the caller may not be able to read, so only a workspace +//! admin may ask for it. + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_member_cannot_read_another_members_access(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/w/test-workspace/access/get", + server.addr.port() + ); + let client = reqwest::Client::new(); + + sqlx::raw_sql( + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('test-workspace', 'ops', '', '{}'); + INSERT INTO usr_to_group (workspace_id, usr, group_) VALUES ('test-workspace', 'test-user-2', 'ops'); + INSERT INTO instance_group (name) VALUES ('sre'); + INSERT INTO email_to_igroup (email, igroup) VALUES ('test2@windmill.dev', 'sre')", + ) + .execute(&db) + .await?; + + // A member may read their own access and their groups', instance groups included, nobody + // else's. + for (principal, status) in [ + ("u/test-user", 403), + ("g/all", 403), + ("u/test-user-2", 200), + ("g/ops", 200), + ("g/sre", 200), + ] { + let resp = client + .get(&url) + .query(&[("principal", principal)]) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .send() + .await?; + assert_eq!(resp.status(), status, "{principal}: {}", resp.text().await?); + } + + // A scoped token reaches the route only if `/access` maps to a scope domain. + let scoped = client + .post(format!( + "http://localhost:{}/api/users/tokens/create", + server.addr.port() + )) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&serde_json::json!({ "label": "scoped", "scopes": ["acls:read"], "workspace_id": "test-workspace" })) + .send() + .await? + .text() + .await?; + let resp = client + .get(&url) + .query(&[("principal", "u/test-user-2")]) + .header("Authorization", format!("Bearer {scoped}")) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs new file mode 100644 index 0000000000..6fa159c008 --- /dev/null +++ b/backend/windmill-api-groups/src/access.rs @@ -0,0 +1,319 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! What a workspace member or group can reach, and why. + +use axum::{ + extract::{Extension, Path, Query}, + routing::get, + Json, Router, +}; +use serde::{Deserialize, Serialize}; +use windmill_api_auth::ApiAuthed; +use windmill_common::{ + auth::fetch_authed_from_permissioned_as, + db::UserDB, + error::{Error, JsonResult}, + DB, +}; + +pub fn workspaced_service() -> Router { + Router::new().route("/get", get(get_access)) +} + +/// `(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] = [ + ( + "script", + "script", + "AND archived = false AND deleted = false", + ), + ("flow", "flow", "AND archived = false"), + ("app", "app", ""), + ("resource", "resource", ""), + ("variable", "variable", ""), + ("schedule", "schedule", ""), + ("http_trigger", "http_trigger", ""), + ("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_trigger", ""), + ("azure_trigger", "azure_trigger", ""), + ("sqs_trigger", "sqs_trigger", ""), + ("email_trigger", "email_trigger", ""), +]; + +#[derive(Deserialize)] +struct AccessQuery { + /// `u/` or `g/`. + principal: String, +} + +#[derive(Serialize)] +struct AccessReport { + principal: String, + is_admin: bool, + groups: Vec, + folders: Vec, + items: Vec, +} + +#[derive(Serialize)] +struct FolderAccess { + name: String, + write: bool, + owner: bool, + /// The `extra_perms` keys (`u/` or `g/`) that grant the folder. + via: Vec, +} + +#[derive(Serialize)] +struct ItemAccess { + kind: String, + path: String, + write: bool, + reasons: Vec, +} + +#[derive(Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum Reason { + /// Under the principal's own `u//` path. + Own, + /// Under `g//` for a group the principal is in. + GroupPath { group: String }, + /// Shared with the principal directly. + User { write: bool }, + /// Shared with one of the principal's groups. + Group { group: String, write: bool }, + /// In a folder the principal can read. + Folder { folder: String, write: bool }, +} + +#[derive(sqlx::FromRow)] +struct ItemRow { + kind: String, + path: String, + own: bool, + path_group: Option, + user_grant: Option, + group_read: Vec, + group_write: Vec, + folder: Option, + folder_write: bool, +} + +fn items_query() -> String { + let union = ITEM_TABLES + .iter() + .map(|(kind, table, filter)| { + format!( + "SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \ + WHERE workspace_id = $1 {filter}" + ) + }) + .collect::>() + .join(" UNION ALL "); + // Rows come back through the principal's RLS session, so the set is what their jobs can read; + // the reasons below restate the same policies (see `pg_policies`) from the same session values. + format!( + "WITH s AS ( + SELECT current_setting('session.user') AS usr, + regexp_split_to_array(current_setting('session.groups'), ',') AS groups, + regexp_split_to_array(current_setting('session.pgroups'), ',') AS pgroups, + regexp_split_to_array(current_setting('session.folders_read'), ',') AS fr, + regexp_split_to_array(current_setting('session.folders_write'), ',') AS fw + ), items AS ({union}) + SELECT i.kind, i.path, + (split_part(i.path, '/', 1) = 'u' AND split_part(i.path, '/', 2) = s.usr) AS own, + CASE WHEN split_part(i.path, '/', 1) = 'g' AND split_part(i.path, '/', 2) = ANY(s.groups) + THEN split_part(i.path, '/', 2) END AS path_group, + (i.extra_perms ->> ('u/' || s.usr))::boolean AS user_grant, + ARRAY(SELECT substr(e.key, 3) FROM jsonb_each_text(i.extra_perms) e + WHERE e.key = ANY(s.pgroups) ORDER BY e.key) AS group_read, + ARRAY(SELECT substr(e.key, 3) FROM jsonb_each_text(i.extra_perms) e + WHERE e.key = ANY(s.pgroups) AND e.value::boolean ORDER BY e.key) AS group_write, + CASE WHEN split_part(i.path, '/', 1) = 'f' AND split_part(i.path, '/', 2) = ANY(s.fr) + THEN split_part(i.path, '/', 2) END AS folder, + (split_part(i.path, '/', 1) = 'f' AND split_part(i.path, '/', 2) = ANY(s.fw)) AS folder_write + FROM items i CROSS JOIN s + ORDER BY i.path, i.kind" + ) +} + +impl From for ItemAccess { + fn from(r: ItemRow) -> Self { + let mut reasons = vec![]; + if r.own { + reasons.push(Reason::Own); + } + if let Some(group) = r.path_group { + reasons.push(Reason::GroupPath { group }); + } + if let Some(write) = r.user_grant { + reasons.push(Reason::User { write }); + } + for group in r.group_read { + let write = r.group_write.contains(&group); + reasons.push(Reason::Group { group, write }); + } + if let Some(folder) = r.folder { + reasons.push(Reason::Folder { folder, write: r.folder_write }); + } + let write = reasons.iter().any(|r| match r { + Reason::Own | Reason::GroupPath { .. } => true, + Reason::User { write } | Reason::Group { write, .. } | Reason::Folder { write, .. } => { + *write + } + }); + ItemAccess { kind: r.kind, path: r.path, write, reasons } + } +} + +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) = 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 the access of another member or of a group you are not in" + .into(), + )); + } + + let email = match prefix { + "u" => { + let usr = sqlx::query!( + "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", + &w_id, + name + ) + .fetch_optional(&db) + .await? + .ok_or_else(|| Error::NotFound(format!("user {name} not found")))?; + if usr.disabled { + return Err(Error::BadRequest(format!( + "{name} is disabled, so nothing runs as them" + ))); + } + usr.email + } + "g" => { + // Instance groups are granted through the same `g/` keys, and the check above + // lets their members ask, so a name from either table is a group here. + let exists = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2) + OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)", + &w_id, + name + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if !exists { + return Err(Error::NotFound(format!("group {name} not found"))); + } + String::new() + } + _ => { + return Err(Error::BadRequest( + "principal must be u/ or g/".into(), + )) + } + }; + + let mut target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).await?; + // A workspace group and an instance group can share a name, and both come back. + target.groups.sort(); + target.groups.dedup(); + + if target.is_admin { + return Ok(Json(AccessReport { + principal, + is_admin: true, + groups: target.groups, + folders: vec![], + items: vec![], + })); + } + + let mut perms = target + .groups + .iter() + .map(|g| format!("g/{g}")) + .collect::>(); + if prefix == "u" { + perms.insert(0, format!("u/{name}")); + } + let folder_names = target + .folders + .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!\" + FROM folder WHERE workspace_id = $1 AND name = ANY($2)", + &w_id, + &folder_names, + &perms + ) + .fetch_all(&db) + .await? + .into_iter() + .map(|r| (r.name, r.via)) + .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(), + }) + .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()) + .bind(&w_id) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(ItemAccess::from) + .collect(); + tx.commit().await?; + + Ok(Json(AccessReport { + principal, + is_admin: false, + groups: target.groups, + folders, + items, + })) +} diff --git a/backend/windmill-api-groups/src/lib.rs b/backend/windmill-api-groups/src/lib.rs index 7abfa426ee..67bc1567f3 100644 --- a/backend/windmill-api-groups/src/lib.rs +++ b/backend/windmill-api-groups/src/lib.rs @@ -1,3 +1,4 @@ +pub mod access; pub mod folder_history; pub mod folders; pub mod granular_acls; diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 274bcb84ed..56217f53e1 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -25227,6 +25227,31 @@ paths: type: string description: Minimum semantic version across all workers (e.g. "1.583.0") + /w/{workspace}/access/get: + get: + summary: list what a workspace member or group can reach, and why + description: | + Workspace admins can query any principal; other members only themselves and the groups + they belong to. An admin principal reaches everything, so `items` is empty. + operationId: getPrincipalAccess + tags: + - granular_acl + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: principal + description: "`u/` or `g/`" + in: query + required: true + schema: + type: string + responses: + "200": + description: the principal's access + content: + application/json: + schema: + $ref: "#/components/schemas/PrincipalAccess" + /w/{workspace}/acls/get/{kind}/{path}: get: summary: get granular acls @@ -37240,6 +37265,66 @@ components: - script_path - is_flow + PrincipalAccess: + type: object + properties: + principal: + type: string + is_admin: + type: boolean + groups: + type: array + items: + type: string + folders: + type: array + items: + type: object + properties: + name: + type: string + write: + type: boolean + owner: + type: boolean + via: + description: the `u/` or `g/` grants on the folder that reach the principal + type: array + items: + type: string + required: [name, write, owner, via] + items: + type: array + items: + type: object + properties: + kind: + type: string + path: + type: string + write: + type: boolean + reasons: + type: array + items: + $ref: "#/components/schemas/AccessReason" + required: [kind, path, write, reasons] + required: [principal, is_admin, groups, folders, items] + + AccessReason: + type: object + properties: + type: + type: string + enum: [own, group_path, user, group, folder] + group: + type: string + folder: + type: string + write: + type: boolean + required: [type] + Group: type: object properties: diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 840e4da97b..b47a644131 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -679,6 +679,7 @@ pub async fn run_server( "/w/{workspace_id}", Router::new() // Reordered alphabetically + .nest("/access", windmill_api_groups::access::workspaced_service()) .nest("/acls", granular_acls::workspaced_service()) // CORS so the opaque-origin in-workspace app viewer (WIN-2006, // sandboxed /apps/get) can read the app definition by path diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index bf10e07e59..8549e673ba 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -424,7 +424,8 @@ impl ScopeDomain { "concurrency_groups" => Some(Self::ConcurrencyGroups), "oidc" => Some(Self::Oidc), "openapi" => Some(Self::Openapi), - "acls" => Some(Self::Acls), + // `/access` reports which grants reach a principal, so `acls` scopes cover it. + "acls" | "access" => Some(Self::Acls), "raw_apps" => Some(Self::RawApps), "agent_workers" => Some(Self::AgentWorkers), "mcp" => Some(Self::Mcp), diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 82206dcd16..00f4406816 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,13 +4,13 @@ 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 93 registered actions across thirty-six features (`ai_session`, `ai_chat`, +It currently carries 98 registered actions across thirty-nine 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`, +`command_script`, `mcp`, `mcp_workspace`, `mcp_external_client`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, `job_token_scopes`, `worker_draining`, `worker_group`, `worker_resource_stats`, `dev_workspace_isolation`, `slack_agent`, `variable_expiration`, -`anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the +`external_secret_ref`, `anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the product is uninstrumented, so new user-facing work is the opportunity to change that. ## When to instrument diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte new file mode 100644 index 0000000000..7d6e562676 --- /dev/null +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -0,0 +1,409 @@ + + +{#snippet chevron(key: string, open: boolean)} + + +{/snippet} + + + drawer?.closeDrawer()}> +
+

+ {#if isGroup} + What members of g/{name} can read through this group alone, and which grant gives each item. + Members may reach more through their own grants and other groups. + {:else} + What {principal} can read, and which grant gives each item. Jobs that run as + {principal} read exactly this set. + {/if} +

+ + {#if error} + {error} + {:else if !access} + + {:else if access.is_admin} + + {principal} is an admin of this workspace and can read and write every item in it. + + {:else} + {#if !isGroup} +
+ {#if access.groups.length} +
+ {#each access.groups as group (group)} + g/{group} + {/each} +
+ {:else} +

Not in any group.

+ {/if} +
+ {/if} + +
+
+
+ +
+