diff --git a/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json b/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json new file mode 100644 index 0000000000..040cd620cb --- /dev/null +++ b/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\",\n $2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked\n FROM folder WHERE workspace_id = $1 ORDER BY name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "grant", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "target_owner!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "blocked", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null, + null, + null + ] + }, + "hash": "0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002" +} diff --git a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json b/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json similarity index 53% rename from backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json rename to backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json index b517bb1790..d442fa8e18 100644 --- a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json +++ b/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json @@ -1,6 +1,6 @@ { "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)", + "query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\",\n (extra_perms ->> $4)::boolean AS \"grant\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)", "describe": { "columns": [ { @@ -12,19 +12,26 @@ "ordinal": 1, "name": "via!", "type_info": "TextArray" + }, + { + "ordinal": 2, + "name": "grant", + "type_info": "Bool" } ], "parameters": { "Left": [ "Text", "TextArray", - "TextArray" + "TextArray", + "Text" ] }, "nullable": [ false, + null, null ] }, - "hash": "81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41" + "hash": "15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7" } diff --git a/backend/tests/access_view.rs b/backend/tests/access_view.rs index e3edf95494..40ca9c9773 100644 --- a/backend/tests/access_view.rs +++ b/backend/tests/access_view.rs @@ -1,5 +1,8 @@ //! Another member's access lists paths the caller may not be able to read, so only a workspace //! admin may ask for it. +//! +//! The auth cache is process-wide and keyed by workspace and token, so a test that gives +//! test-user-2 other groups or folders than another test does signs in with a token of its own. use sqlx::{Pool, Postgres}; @@ -64,3 +67,68 @@ async fn test_member_cannot_read_another_members_access(db: Pool) -> a Ok(()) } + +/// The navigator writes grants with the kind it is given, and `acls/add` sends a full-code app's +/// change to git sync only under `raw_app`. `blocked` must refuse what `acls/add` would refuse. +#[sqlx::test(fixtures("base"))] +async fn test_browse_items_kind_and_blocked(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms, created_by) + VALUES ('test-workspace', 'fin', 'fin', '{u/test-user}', '{\"u/test-user-2\": false}', 'test-user'); + INSERT INTO app (id, workspace_id, path, summary, policy, versions, extra_perms) + VALUES (1, 'test-workspace', 'f/fin/dash', '', '{}', '{1}', '{}'); + INSERT INTO app_version (id, app_id, value, created_by, raw_app) + VALUES (1, 1, '{}', 'test-user', true); + INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('BROWSE_TOKEN'::bytea), 'hex'), 'BROWSE_TOK', 'BROWSE_TOKEN', + 'test2@windmill.dev', 'browse', false);", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/w/test-workspace/access/browse_items", + server.addr.port() + ); + let browse = |token: &str| { + reqwest::Client::new() + .get(&url) + .query(&[("principal", "u/test-user-2"), ("prefix", "f/fin/")]) + .header("Authorization", format!("Bearer {token}")) + .send() + }; + + let member: serde_json::Value = browse("BROWSE_TOKEN") + .await? + .error_for_status()? + .json() + .await?; + assert_eq!( + member["items"], + serde_json::json!([{ + "kind": "raw_app", + "path": "f/fin/dash", + "grant": null, + "blocked": "Only admins of the workspace or of f/fin can share it" + }]) + ); + + let admin: serde_json::Value = browse("SECRET_TOKEN") + .await? + .error_for_status()? + .json() + .await?; + assert_eq!(admin["items"][0]["blocked"], serde_json::Value::Null); + + // A mistyped principal is refused rather than listed as holding nothing. + let resp = reqwest::Client::new() + .get(&url) + .query(&[("principal", "g/does_not_exist")]) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await?; + assert_eq!(resp.status(), 404, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs index 6fa159c008..9e790016e7 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)] @@ -112,12 +127,27 @@ struct ItemRow { folder_write: bool, } +/// The `kind` column for a row of `table`. Full-code apps live in `app` too, but their grants must +/// be written with kind `raw_app`, which git sync dispatches to `.raw_app` rather than `.app`. +fn kind_column(kind: &str, table: &str) -> String { + if kind == "app" { + format!( + "CASE WHEN (SELECT raw_app FROM app_version \ + WHERE id = {table}.versions[array_upper({table}.versions, 1)]) \ + THEN 'raw_app' ELSE 'app' END" + ) + } else { + format!("'{kind}'::text") + } +} + fn items_query() -> String { let union = ITEM_TABLES .iter() .map(|(kind, table, filter)| { + let kind = kind_column(kind, table); format!( - "SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \ + "SELECT {kind} AS kind, path::text AS path, extra_perms FROM {table} \ WHERE workspace_id = $1 {filter}" ) }) @@ -175,20 +205,15 @@ 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 } } } -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,8 +221,7 @@ 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( @@ -205,15 +229,36 @@ async fn get_access( .into(), )); } + Ok((prefix, name)) +} - let email = match prefix { +/// The principal as it would be authenticated, with its groups and the folders it reaches. +async fn fetch_target( + db: &DB, + w_id: &str, + prefix: &str, + name: &str, + principal: &str, +) -> Result { + let email = target_email(db, w_id, prefix, name).await?; + 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(); + Ok(target) +} + +/// The principal's email, empty for a group. Not found when the principal does not exist, so +/// no route answers for a mistyped one as if it existed with no grants. +async fn target_email(db: &DB, w_id: &str, prefix: &str, name: &str) -> Result { + Ok(match prefix { "u" => { let usr = sqlx::query!( "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", - &w_id, + w_id, name ) - .fetch_optional(&db) + .fetch_optional(db) .await? .ok_or_else(|| Error::NotFound(format!("user {name} not found")))?; if usr.disabled { @@ -224,15 +269,15 @@ async fn get_access( usr.email } "g" => { - // Instance groups are granted through the same `g/` keys, and the check above + // Instance groups are granted through the same `g/` keys, and the callers' check // 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, + w_id, name ) - .fetch_one(&db) + .fetch_one(db) .await? .unwrap_or(false); if !exists { @@ -245,12 +290,19 @@ async fn get_access( "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(); +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 target = fetch_target(&db, &w_id, prefix, name, &principal).await?; if target.is_admin { return Ok(Json(AccessReport { @@ -276,38 +328,54 @@ async fn get_access( .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!\" + "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\", + (extra_perms ->> $4)::boolean AS \"grant\" FROM folder WHERE workspace_id = $1 AND name = ANY($2)", &w_id, &folder_names, - &perms + &perms, + &principal ) .fetch_all(&db) .await? .into_iter() - .map(|r| (r.name, r.via)) + .map(|r| (r.name, (r.via, r.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(); Ok(Json(AccessReport { principal, @@ -317,3 +385,204 @@ async fn get_access( items, })) } + +#[derive(Serialize)] +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, + #[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 admins of the workspace or of f/{folder} can share it") +} + +async fn browse_folders( + 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)?; + // Ownership can come through one of the principal's groups, as in `/access/get`. + let target = fetch_target(&db, &w_id, prefix, name, &principal).await?; + let owned = target + .folders + .iter() + .filter(|(_, _, owner)| *owner) + .map(|(name, ..)| name.as_str()) + .collect::>(); + 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!\", NULL::text AS blocked + FROM folder WHERE workspace_id = $1 ORDER BY name", + &w_id, + &principal + ) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + for folder in &mut folders { + folder.target_owner |= owned.contains(folder.name.as_str()); + 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 { + let (prefix, name) = check_principal(&authed, &q.principal)?; + target_email(&db, &w_id, prefix, name).await?; + let tables = ITEM_TABLES + .iter() + .filter(|(kind, ..)| { + q.kind + .as_deref() + .map_or(true, |k| k == *kind || (k == "raw_app" && *kind == "app")) + }) + .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)| { + let kind = kind_column(kind, table); + format!( + "SELECT {kind} 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) + AND ($7::text IS NULL OR kind = $7) + 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)) + .bind(q.kind.as_deref()) + .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. +/// Only a refusal becomes a lock text; any other error (the role lookup failing) is returned, so +/// an outage is not shown as a decision. +async fn manage_denied( + db: &DB, + w_id: &str, + authed: &ApiAuthed, +) -> Result> { + let mut denied = vec![]; + if !authed.is_admin { + for kind in [ManageKind::Schedules, ManageKind::Triggers] { + match check_operator_can_manage(db, w_id, authed, kind).await { + Ok(()) => {} + // A plain sentence like the path rules' texts, so without the "Permission + // denied: " prefix the error's display adds. + Err(Error::PermissionDenied(reason)) => denied.push((kind, reason)), + Err(e) => return Err(e), + } + } + } + Ok(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 242e3a6bb1..6a6e43152a 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -26903,6 +26903,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 @@ -39543,6 +39639,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 @@ -39559,6 +39661,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/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte index 7d6e562676..7a0261cb2f 100644 --- a/frontend/src/lib/components/AccessDrawer.svelte +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -8,11 +8,16 @@ import Row from './table/Row.svelte' import RowIcon from './common/table/RowIcon.svelte' import { Tooltip } from './meltComponents' + import Popover from './meltComponents/Popover.svelte' + import DropdownV2 from './DropdownV2.svelte' import { GranularAclService, type PrincipalAccess } from '$lib/gen' import { useOperatingWorkspace } from './operatingWorkspace.svelte' + import { sendUserToast } from '$lib/toast' import { logFeatureUsage } from '$lib/utils/featureUsage' - import { pluralize } from '$lib/utils' + import { pluralize, type Item } from '$lib/utils' import { itemHref } from './offboarding-utils' + import GrantNavigator, { navigatorMaxHeight } from './access/GrantNavigator.svelte' + import { KIND_LABELS, setGrant, type GrantLevel } from './access/access' import { buildAccessTree, flattenAccessTree, @@ -27,6 +32,9 @@ ExternalLink, Folder, FolderTree, + Loader2, + Lock, + Plus, User, Users } from 'lucide-svelte' @@ -39,26 +47,6 @@ // A short list opens fully, so every item shows at once. A longer one starts at its folders. const OPEN_UP_TO = 30 - 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() @@ -69,6 +57,15 @@ /** Rows opened or closed by hand, by path prefix. The rest follow `expandAll`. */ let openState: Record = $state({}) let expandAll: boolean | undefined = $state() + let grantOpen = $state(false) + let navigator: GrantNavigator | undefined = $state() + /** The row menu that is open, as `kind:path`. */ + let openMenu: string | undefined = $state() + /** The row whose grant is being written, as `kind:path`. Its menu would otherwise send the + * same change again before the tree reloads with the new level. */ + let changing: string | undefined = $state() + let grantPopover: Popover | undefined = $state() + let grantAnchor: HTMLElement | undefined = $state() // Responses are not ordered: a slow answer for the previous principal must not land on this one. let requestId = 0 @@ -81,13 +78,18 @@ nbDisplayed = PAGE openState = {} expandAll = undefined + grantOpen = false drawer?.openDrawer() logFeatureUsage('access_view', 'opened', { key: target }) + await reload() + } + + async function reload(): Promise { const id = ++requestId try { const result = await GranularAclService.getPrincipalAccess({ workspace: $operatingWorkspace!, - principal: nextPrincipal + principal }) if (id === requestId) access = result } catch (e) { @@ -95,6 +97,76 @@ } } + function setGrantOpen(next: boolean) { + if (next) placeGrantPopover() + grantOpen = next + if (next) logFeatureUsage('access_view', 'grant_opened') + } + + // The side is picked once, for the navigator's tallest height: melt fits the popover to the room + // on the side it first lands on, so a list that grows later would never flip on its own. + function placeGrantPopover() { + if (!grantAnchor) return + const rect = grantAnchor.getBoundingClientRect() + const gutter = 8 + const spaceBelow = window.innerHeight - rect.bottom - gutter + const spaceAbove = rect.top - gutter + const below = navigatorMaxHeight() <= spaceBelow || spaceBelow >= spaceAbove + grantPopover?.updatePositioning({ + placement: below ? 'bottom-end' : 'top-end', + strategy: 'absolute', + gutter, + overflowPadding: 16, + flip: false, + fitViewport: true, + overlap: false + }) + } + + /** The principal's own entry on an item: `true` for write, `false` for read. */ + function ownItemGrant(item: AccessItem): boolean | undefined { + const reason = item.reasons.find((r) => + isGroup ? r.type === 'group' && r.group === name : r.type === 'user' + ) + return reason ? !!reason.write : undefined + } + + async function changeGrant(kind: string, path: string, level: GrantLevel) { + if (changing) return + changing = `${kind}:${path}` + // The spinner replaces the menu before its close reaches `bind:open`, so a stale + // `openMenu` would reopen it after the reload and swallow the next Escape. + openMenu = undefined + try { + await setGrant($operatingWorkspace!, kind, path, principal, level) + } catch (e) { + const what = kind === 'folder' ? `f/${path}` : path + sendUserToast(`Could not change access to ${what}: ${e?.body ?? e}`, true) + } + await reload() + changing = undefined + } + + /** `current` is the grant's level: `true` for write, `false` for read. */ + function grantActions(kind: string, path: string, current: boolean): Item[] { + return [ + { + displayName: 'Read', + disabled: current === false, + action: () => changeGrant(kind, path, 'read') + }, + { + displayName: 'Write', + disabled: current === true, + action: () => changeGrant(kind, path, 'write') + }, + { displayName: 'Remove', type: 'delete', action: () => changeGrant(kind, path, 'none') } + ] + } + + // 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]))) + const name = $derived(principal.slice(2)) const isGroup = $derived(principal.startsWith('g/')) const who = $derived(isGroup ? `members of ${principal}` : principal) @@ -163,13 +235,29 @@ return `${principal} is a member of ${node.key}, so ${principal} can write every item under ${node.key}/, including items added later.` } - /** Grants on the item itself. What its folder or space gives is said once, on that row. */ + /** Grants on the item itself, which decide whether its level reads as its own. */ function itemGrants(item: AccessItem): string[] { return item.reasons.flatMap((r) => r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : [] ) } + /** Every reason the item is held: its own grants, then its folder or space. */ + function itemReasons(item: AccessItem): string[] { + const labels = item.reasons.map((r) => + r.type === 'user' + ? 'Shared directly' + : r.type === 'group' + ? viaLabel(`g/${r.group}`) + : r.type === 'folder' + ? `Through f/${r.folder}` + : r.type === 'group_path' + ? `Through g/${r.group}` + : 'Own path' + ) + return [...new Set(labels)] + } + function levelClass(item: AccessItem, grants: string[], owner: AccessOwnerNode): string { if (!grants.length) return 'text-hint' return item.write && owner.whole && !owner.write ? 'font-semibold text-emphasis' : '' @@ -205,6 +293,49 @@ {/snippet} +{#snippet grantMenu(kind: string, path: string, current: boolean, blocked: string | undefined)} + {#if blocked} + + + {#snippet text()}{blocked}{/snippet} + + {:else if changing === `${kind}:${path}`} + + + + {:else} + {@const key = `${kind}:${path}`} + openMenu === key, + (next) => { + if (next) openMenu = key + else if (openMenu === key) openMenu = undefined + } + } + /> + {/if} +{/snippet} + + + { + if (e.key !== 'Escape' || (!grantOpen && !openMenu)) return + e.stopPropagation() + e.preventDefault() + if (grantOpen && navigator?.escape(e.target)) return + grantOpen = false + openMenu = undefined + }} +/> + drawer?.closeDrawer()}>
@@ -213,8 +344,8 @@ 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. + What {principal} can read, and which grant gives each item. + {#if access && !access.is_admin}Jobs that run as {principal} read exactly this set.{/if} {/if}

@@ -242,6 +373,36 @@ {/if}
+ {#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}
Name Access - Granted by + Granted by + @@ -335,7 +497,15 @@ {#snippet text()}{ownerExplanation(node)}{/snippet} - {ownerGrant(node)} + {ownerGrant(node)} + + {@const folder = node.key.startsWith('f/') + ? foldersByName.get(node.key.slice(2)) + : undefined} + {#if folder && !folder.owner && folder.grant != undefined} + {@render grantMenu('folder', folder.name, folder.grant, folder.blocked)} + {/if} + {:else if row.type === 'subfolder'} toggle(row.node.key, row.open)}> @@ -351,7 +521,8 @@
- + + {:else} {@const item = row.item} @@ -388,7 +559,13 @@ >{item.write ? 'Write' : 'Read'} - {grants.join(', ')} + {itemReasons(item).join(', ')} + + {@const own = ownItemGrant(item)} + {#if own !== undefined} + {@render grantMenu(item.kind, item.path, own, item.blocked)} + {/if} + {/if} {/each} diff --git a/frontend/src/lib/components/DrillPicker.svelte b/frontend/src/lib/components/DrillPicker.svelte index 0a973e0431..80635a55c1 100644 --- a/frontend/src/lib/components/DrillPicker.svelte +++ b/frontend/src/lib/components/DrillPicker.svelte @@ -13,7 +13,8 @@ level *up*. Filter (internal or `externalFilter`) is global across all leaves and ignores the current scope. --> + +
{ setHoverHighlight(key) tooltipEnter(e.currentTarget as HTMLElement, leaf) }} + onmousemove={leafActions && !isHl ? () => setHoverHighlight(key) : undefined} onmouseleave={tooltipLeave} > - e.preventDefault()} - onclickcapture={(e: MouseEvent) => { - // Capture, not a delegated onclick: the picker is portalled outside the app root, - // where a delegated handler runs after SvelteKit's link handler has already - // followed the href, too late for preventDefault to keep a plain click on `pick`. - if (href && isNewTabClick(e)) return - e.preventDefault() - pick(leaf, e.metaKey || e.ctrlKey) - }} + +
- {@render defaultLeafIcon(leaf)} - -
e.preventDefault()} + onclickcapture={inert + ? undefined + : (e: MouseEvent) => { + // Capture, not a delegated onclick: the picker is portalled outside the app root, + // where a delegated handler runs after SvelteKit's link handler has already + // followed the href, too late for preventDefault to keep a plain click on `pick`. + if (href && isNewTabClick(e)) return + e.preventDefault() + pick(leaf, e.metaKey || e.ctrlKey) + }} > - {#if leaf.secondary} -
{leaf.label}
-
- {secondary ?? leaf.secondary} -
- {:else} -
- {secondary ?? leaf.label} -
+ {@render defaultLeafIcon(leaf)} + +
+ {#if leaf.secondary} +
{leaf.label}
+
+ {secondary ?? leaf.secondary} +
+ {:else} +
+ {secondary ?? leaf.label} +
+ {/if} +
+ + {#if leafActions} + + {#if badge} + {badge.label} + {/if} + + {:else if leafBadge || leafAction} + +
+ {#if action} + + + {/if} + {#if badge} +
+ {badge.label} +
+ {/if} +
+ {/if} +
+ {#if actions.length} + +
+ {#if mainAction && !done} + + + + {/if}
- - - {#if leafBadge || leafAction} - -
- {#if action} - - - {/if} - {#if badge} -
- {badge.label} -
- {/if} + {/if} + {#if done} + +
+ + {done}
{/if}
@@ -753,6 +909,11 @@ leaves and ignores the current scope. > {@render defaultBranchIcon(entry.node)} {entry.node.label} + {#if entry.node.badge} + {entry.node.badge} + {/if} {#if entry.node.loading} {/if} @@ -767,6 +928,8 @@ leaves and ignores the current scope.
Loading…
+ {:else if currentBranch?.note} +
{currentBranch.note}
{/if}
{/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..803b0caaaf --- /dev/null +++ b/frontend/src/lib/components/access/GrantNavigator.svelte @@ -0,0 +1,535 @@ + + + + + +{#snippet leafIcon(leaf: DrillLeaf)} + +{/snippet} + + diff --git a/frontend/src/lib/components/access/access.ts b/frontend/src/lib/components/access/access.ts new file mode 100644 index 0000000000..08d8df97bb --- /dev/null +++ b/frontend/src/lib/components/access/access.ts @@ -0,0 +1,70 @@ +import { + GranularAclService, + type BrowseAccessFoldersResponse, + type BrowseAccessItemsResponse +} from '$lib/gen' + +export type GrantLevel = 'none' | 'read' | 'write' + +/** Where the Grant navigator reads and changes grants. Without one it uses the API, in the + * operating workspace. */ +export type GrantSource = { + /** The caller's own `u/` space, listed first. */ + ownSpace: string + folders: () => Promise + items: (query: { + prefix?: string + search?: string + offset?: number + }) => Promise + /** Sets the principal's own entry, as `setGrant` does. */ + set: (kind: string, path: string, level: GrantLevel) => Promise +} + +type AclKind = Parameters[0]['kind'] + +export const KIND_LABELS: Record = { + script: 'Script', + flow: 'Flow', + app: 'App', + raw_app: 'Full-code 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/common/button/Button.svelte b/frontend/src/lib/components/common/button/Button.svelte index 9a3b9fe6ac..e514c0686f 100644 --- a/frontend/src/lib/components/common/button/Button.svelte +++ b/frontend/src/lib/components/common/button/Button.svelte @@ -516,9 +516,11 @@ 'rounded-md m-0 p-0 center-center h-full', variant === 'border' ? 'border-0 border-r border-y ' : 'border-0', 'rounded-r-md !rounded-l-none', - size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm' - ? '!w-8' - : '!w-10', + unifiedSize === 'xs' || unifiedSize === '2xs' + ? '!w-6' + : size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm' + ? '!w-8' + : '!w-10', dropdownBtnClasses )} > diff --git a/frontend/src/lib/components/drillPicker.ts b/frontend/src/lib/components/drillPicker.ts index 7ef6922599..2461a7687f 100644 --- a/frontend/src/lib/components/drillPicker.ts +++ b/frontend/src/lib/components/drillPicker.ts @@ -35,6 +35,19 @@ export type DrillLeaf = { plainLabel?: boolean } +/** Something a leaf row offers (see the picker's `leafActions`). */ +export type DrillLeafAction = { + label: string + icon?: DrillIcon + /** What running it does, shown under its label in the row's dropdown. */ + hint?: string + /** The row's button, with the others in its dropdown; the first one is otherwise. */ + preferred?: boolean + loading?: boolean + disabled?: boolean + run: () => void +} + /** Branch node — interior entry the user drills into. */ export type DrillBranch = { type: 'branch' @@ -44,6 +57,11 @@ export type DrillBranch = { children: DrillNode[] /** Show a spinner alongside the branch (async loading in progress). */ loading?: boolean + /** Plain text on the right of the branch's row ("Read"), like a leaf's `leafBadge`. */ + badge?: string + /** A line under the branch's entries once drilled in and loaded, for a branch whose entries + * never leave it empty ("f/x has no items yet"), so the picker's "Empty" cannot show. */ + note?: string /** Hide from search index traversal. Used by the workspace adapter to * keep the cross-kind 'all' branch out of search (its leaves are * duplicates of the per-kind branches' leaves). */ diff --git a/frontend/src/lib/components/offboarding-utils.ts b/frontend/src/lib/components/offboarding-utils.ts index b920979b7f..d9f5b584cd 100644 --- a/frontend/src/lib/components/offboarding-utils.ts +++ b/frontend/src/lib/components/offboarding-utils.ts @@ -109,6 +109,8 @@ export function itemHref(kind: string, path: string): string | undefined { case 'app': case 'apps': return `/apps/get/${path}` + case 'raw_app': + return `/apps_raw/get/${path}` case 'resource': case 'resources': return `/resources#/resource/${path}`