feat: grant and remove access from the access view (#12143)

* feat: show what a member, group or service account can access

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: grant and remove access from the access view

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: point the EE ref at the access view usage counters

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: show an error when what it reads cannot load the item itself

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: close only the grant navigator on escape, not the access view

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: name groups in the access view's permission error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: map /access to the acls scope and list each group once

A token with scopes was refused before reaching the access endpoint, and a
member in a workspace group and an instance group of the same name got that
group twice, which broke the drawer's keyed list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: count every registered feature usage action

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read pinned script versions and resource references in what it reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: grant full-code apps under raw_app and show a branch from its first page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: type the navigator's reach map by plain string keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read the operating workspace and user in the access view

GroupEditorDrawer is reachable from a session editor, where the navigation
workspace and user are the parent's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: grant in the operating workspace, not the navigation one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read a full-code app's frontend source in what it reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: cover a member reading their group's access

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: navigator sees folder ownership held through a group

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: what it reads finds resources in JSX, Svelte and Vue source

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: the navigator names the operating user's own grants

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: what it reads matches SDK calls in a component's template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: what it reads says which paths it finds and which it can't

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: size the groups page loading rows like the loaded ones

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: open a group's access from the groups page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show access as a folder tree with links to each item

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: show a group's access to superadmins who are not workspace admins

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: escape closes only an open row menu in the access view

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: rows with a grant menu stay as tall as the rest of the tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: size the grant menu trigger to the tree row

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: accept instance groups as access view principals

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to c4e610999ca0d1abab06b1660cc48e486ab870b3

This commit updates the EE repository reference after PR #939 was merged in windmill-ee-private.

Previous ee-repo-ref: da6bb1965702eb57237882e5fda6179f72294a06

New ee-repo-ref: c4e610999ca0d1abab06b1660cc48e486ab870b3

Automated by sync-ee-ref workflow.

* chore: update ee-repo-ref to c4e610999ca0d1abab06b1660cc48e486ab870b3

This commit updates the EE repository reference after PR #939 was merged in windmill-ee-private.

Previous ee-repo-ref: da6bb1965702eb57237882e5fda6179f72294a06

New ee-repo-ref: c4e610999ca0d1abab06b1660cc48e486ab870b3

Automated by sync-ee-ref workflow.

* feat: parse item references beside assets

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: report what an item reads and who reads it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: load what an item reads from the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: describe who performs each read an item makes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read step paths with the runtime's path parser

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: grant only uncovered rows in the reads panel, show refusals in red

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: make disabled drill picker rows look disabled

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: say in the grant navigator when the principal already reads a row

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: correct the operator lock, app source error and admin intro texts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: move what an item reads into its own pull request

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: grant and revoke from one row button in the grant navigator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: check the static access queries with sqlx macros

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: widen the grant success pill to fit its text

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: let the folder dialog's buttons and the grant navigator answer their own keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: let enter confirm the folder dialog when the row button kept focus

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse an unknown principal when browsing items

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: lock a row's grant menu while it saves and show folder levels and empty folders

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: close a row's menu when its change starts so it does not reopen after the reload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: settle the grant navigator on a failed folder load, search every page and return role lookup errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
Guilhem
2026-12-02 18:34:51 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent 0dd0a78384
commit 9f7d00ef4e
12 changed files with 1621 additions and 164 deletions
@@ -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"
}
@@ -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"
}
+68
View File
@@ -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<Postgres>) -> 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<Postgres>) -> 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(())
}
+307 -38
View File
@@ -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/<user>` or `g/<group>`) that grant the folder.
via: Vec<String>,
/// 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<bool>,
/// 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<String>,
}
#[derive(Serialize)]
@@ -82,6 +94,9 @@ struct ItemAccess {
path: String,
write: bool,
reasons: Vec<Reason>,
/// 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<String>,
}
#[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 `<path>.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<ItemRow> 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<DB>,
Extension(user_db): Extension<UserDB>,
Path(w_id): Path<String>,
Query(AccessQuery { principal }): Query<AccessQuery>,
) -> JsonResult<AccessReport> {
/// Splits `u/<user>` or `g/<group>` 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/<user> or g/<group>".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<windmill_common::db::Authed> {
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<String> {
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/<name>` keys, and the check above
// Instance groups are granted through the same `g/<name>` 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/<user> or g/<group>".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<DB>,
Extension(user_db): Extension<UserDB>,
Path(w_id): Path<String>,
Query(AccessQuery { principal }): Query<AccessQuery>,
) -> JsonResult<AccessReport> {
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::<Vec<_>>();
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::<std::collections::HashMap<_, _>>();
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::<Vec<_>>();
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<bool>,
/// Owners always keep write; `acls/add` refuses to lower it.
target_owner: bool,
#[serde(skip_serializing_if = "Option::is_none")]
blocked: Option<String>,
}
#[derive(Serialize, sqlx::FromRow)]
struct BrowseItem {
kind: String,
path: String,
grant: Option<bool>,
#[sqlx(skip)]
#[serde(skip_serializing_if = "Option::is_none")]
blocked: Option<String>,
}
#[derive(Serialize)]
struct BrowseItems {
items: Vec<BrowseItem>,
has_more: bool,
}
#[derive(Deserialize)]
struct BrowseItemsQuery {
principal: String,
/// Only paths starting with this, e.g. `f/billing/` or `u/alice/`.
prefix: Option<String>,
kind: Option<String>,
search: Option<String>,
offset: Option<i64>,
}
/// Why the caller cannot change grants on `path`, mirroring the checks `acls/add` makes.
fn grant_blocked(authed: &ApiAuthed, path: &str) -> Option<String> {
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<DB>,
Extension(user_db): Extension<UserDB>,
Path(w_id): Path<String>,
Query(AccessQuery { principal }): Query<AccessQuery>,
) -> JsonResult<Vec<BrowseFolder>> {
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::<std::collections::HashSet<_>>();
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<DB>,
Extension(user_db): Extension<UserDB>,
Path(w_id): Path<String>,
Query(q): Query<BrowseItemsQuery>,
) -> JsonResult<BrowseItems> {
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::<Vec<_>>();
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::<Vec<_>>()
.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<Vec<(ManageKind, String)>> {
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<String> {
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))
}
+105
View File
@@ -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/<username>` or `g/<group>`"
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/<username>` or `g/<group>`"
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]
+206 -29
View File
@@ -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<string, string> = {
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<string, boolean> = $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<void> {
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 @@
</button>
{/snippet}
{#snippet grantMenu(kind: string, path: string, current: boolean, blocked: string | undefined)}
{#if blocked}
<Tooltip>
<Lock size={14} class="text-secondary" aria-label={blocked} />
{#snippet text()}{blocked}{/snippet}
</Tooltip>
{:else if changing === `${kind}:${path}`}
<span class="flex size-5 items-center justify-center -my-0.5" role="status" aria-label="Saving">
<Loader2 size={14} class="animate-spin text-secondary" />
</span>
{:else}
{@const key = `${kind}:${path}`}
<DropdownV2
disabled={!!changing}
size="xs"
fixedHeight={false}
class="-my-0.5"
items={grantActions(kind, path, current)}
bind:open={
() => openMenu === key,
(next) => {
if (next) openMenu = key
else if (openMenu === key) openMenu = undefined
}
}
/>
{/if}
{/snippet}
<!-- The drawer answers Escape on window too, and `preventEscape` is read after a popover or menu
has already closed, so with the Grant popover or a row menu open its Escape is taken here
before either sees it. The navigator's own dialog or row dropdown closes first. -->
<svelte:window
onkeydowncapture={(e) => {
if (e.key !== 'Escape' || (!grantOpen && !openMenu)) return
e.stopPropagation()
e.preventDefault()
if (grantOpen && navigator?.escape(e.target)) return
grantOpen = false
openMenu = undefined
}}
/>
<Drawer bind:this={drawer} size="1000px">
<DrawerContent title={`Access of ${principal}`} on:close={() => drawer?.closeDrawer()}>
<div class="flex flex-col gap-6">
@@ -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}
</p>
@@ -242,6 +373,36 @@
{/if}
<Section label={`Items (${access.items.length})`} small>
{#snippet action()}
<div bind:this={grantAnchor}>
<Popover
bind:this={grantPopover}
placement="bottom-end"
usePointerDownOutside
disableFocusTrap
closeOnOtherPopoverOpen
bind:isOpen={() => grantOpen, setGrantOpen}
openFocus="[data-workspace-picker-search]"
contentClasses="flex flex-col overflow-hidden"
>
{#snippet trigger()}
<Button
variant="default"
unifiedSize="sm"
nonCaptureEvent
startIcon={{ icon: Plus }}
>
Grant
</Button>
{/snippet}
{#snippet content()}
{#if access}
<GrantNavigator bind:this={navigator} {principal} {access} onChange={reload} />
{/if}
{/snippet}
</Popover>
</div>
{/snippet}
<div class="flex flex-col gap-2">
<div class="flex gap-2 items-center">
<TextInput
@@ -280,7 +441,8 @@
<tr>
<Cell head first>Name</Cell>
<Cell head>Access</Cell>
<Cell head last>Granted by</Cell>
<Cell head>Granted by</Cell>
<Cell head last actions />
</tr>
</Head>
<tbody>
@@ -335,7 +497,15 @@
{#snippet text()}{ownerExplanation(node)}{/snippet}
</Tooltip>
</Cell>
<Cell last>{ownerGrant(node)}</Cell>
<Cell>{ownerGrant(node)}</Cell>
<Cell last actions shouldStopPropagation>
{@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}
</Cell>
</Row>
{:else if row.type === 'subfolder'}
<Row hoverable on:click={() => toggle(row.node.key, row.open)}>
@@ -351,7 +521,8 @@
</div>
</Cell>
<Cell></Cell>
<Cell last></Cell>
<Cell></Cell>
<Cell last actions></Cell>
</Row>
{:else}
{@const item = row.item}
@@ -388,7 +559,13 @@
>{item.write ? 'Write' : 'Read'}</span
>
</Cell>
<Cell last>{grants.join(', ')}</Cell>
<Cell>{itemReasons(item).join(', ')}</Cell>
<Cell last actions>
{@const own = ownItemGrant(item)}
{#if own !== undefined}
{@render grantMenu(item.kind, item.path, own, item.blocked)}
{/if}
</Cell>
</tr>
{/if}
{/each}
+254 -91
View File
@@ -13,7 +13,8 @@ level *up*. Filter (internal or `externalFilter`) is global across all
leaves and ignores the current scope.
-->
<script lang="ts" generics="L">
import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
import { CheckCircle2, ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
import { fade, fly } from 'svelte/transition'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import SearchItems from '$lib/components/SearchItems.svelte'
import Portal from '$lib/components/Portal.svelte'
@@ -30,6 +31,7 @@ leaves and ignores the current scope.
type DrillBranch,
type DrillIcon,
type DrillLeaf,
type DrillLeafAction,
type DrillNode
} from './drillPicker'
import Badge from '$lib/components/common/badge/Badge.svelte'
@@ -39,7 +41,10 @@ leaves and ignores the current scope.
interface Props {
tree: DrillNode<L>[]
onPick: (leaf: DrillLeaf<L>) => void
/** Picking a leaf: a click, or Enter on its highlighted row. Without it, a click on a leaf
* does nothing and Enter runs the highlighted row's selected `leafActions` button, for a
* picker whose rows act only through their buttons. */
onPick?: (leaf: DrillLeaf<L>) => void
/** Drill path to land on initially. Empty = root. */
initialScope?: string[]
/** Composite key of the row to highlight initially. */
@@ -87,13 +92,22 @@ leaves and ignores the current scope.
leaf: DrillLeaf<L>
) => { icon: DrillIcon; label: string; title: string; run: () => void } | undefined
/** Status badge on the right of a leaf row. Returns `undefined` for a leaf with
* nothing to report. The hover action, when there is one, covers it. */
* nothing to report. The hover action, when there is one, covers it. With `leafActions` it
* is plain text and `color` is unused. */
leafBadge?: (leaf: DrillLeaf<L>) => { label: string; color: BadgeColor } | undefined
/** Where picking a leaf navigates, for a host whose pick is a navigation. The row then
* renders as a link: a plain click still goes through `onPick`, while a middle or
* ⌘/Ctrl-click opens it in a new tab — taking ⌘/Ctrl-click from `leafAction`, which
* keeps ⌘/Ctrl-Enter. */
leafHref?: (leaf: DrillLeaf<L>) => string | undefined
/** What a leaf row offers, laid over its end while the row is highlighted (hovered or reached
* with the arrow keys), so the row does not reflow: the `preferred` one (else the first) as a
* button, which Enter runs when there is no `onPick`, and the others in its dropdown. In
* place of `leafAction`, not with it. */
leafActions?: (leaf: DrillLeaf<L>) => DrillLeafAction[] | undefined
/** What a `leafActions` button just did on a leaf ("Read granted"), shown over the row's
* end, highlighted or not, while it returns a text. */
leafDone?: (leaf: DrillLeaf<L>) => string | undefined
}
let {
@@ -113,7 +127,9 @@ leaves and ignores the current scope.
rowTooltip,
leafAction,
leafBadge,
leafHref
leafHref,
leafActions,
leafDone
}: Props = $props()
let searchInput: TextInput | undefined = $state()
@@ -302,7 +318,9 @@ leaves and ignores the current scope.
// Ignored until the user actually moves the mouse. Prevents the
// cursor (parked over a row) from clobbering keyboard-driven
// selection when the layout shifts beneath it.
if (mouseActive) highlightedKey = key
// A row's open menu sits over the rows below it, and the pointer crosses them to reach it:
// moving the highlight would take the menu's button away.
if (mouseActive && !actionMenuOpen) highlightedKey = key
}
/** `alt` picks the row's second action (see `leafAction`) rather than the row
@@ -310,6 +328,10 @@ leaves and ignores the current scope.
* that only appears on hover. A leaf with no second action ignores it. */
function pick(leaf: DrillLeaf<L>, alt = false) {
if (leaf.disabled) return
if (!onPick) {
if (leaf.key === highlightedKey) runMainAction()
return
}
// The second action is the row's other destination (its editor, for the deployed page
// this tab shows), so it stays available on the current row the plain pick skips.
if (alt) {
@@ -323,6 +345,25 @@ leaves and ignores the current scope.
onPick(leaf)
}
function runMainAction() {
const action = mainAction
if (action && !action.disabled && !action.loading) runAction(action)
}
/** The button area's width when each row's action ran, the least its success pill takes. Read
* from `actionsWidth` live, the pill would resize on hover, which moves the highlighted row. */
let pillWidths: Record<string, number> = $state({})
function runAction(action: DrillLeafAction) {
if (highlightedKey) pillWidths[highlightedKey] = actionsWidth
action.run()
}
/** Fades out what lies under the highlighted row's buttons, which sit over its end. */
function fadeUnder(width: number): string {
const mask = `linear-gradient(to left, transparent ${width}px, #000 ${width + 16}px)`
return `mask-image: ${mask}; -webkit-mask-image: ${mask}`
}
// Single shared hover tooltip (opt-in via `rowTooltip`): one floating node
// re-anchored to the hovered row, instead of a popover per row — rows can
// number in the hundreds. Portaled to body because the picker often lives
@@ -385,6 +426,17 @@ leaves and ignores the current scope.
}
function handleSearchKeydown(e: KeyboardEvent) {
// A row's button has focus only after a click: it keeps its own keys, and Enter must not
// also reach the row. ↑/↓ and Escape return to the search field.
if ((e.target as HTMLElement | null)?.closest?.('[data-drill-action]')) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
focus()
if (e.key !== 'Escape') moveHighlight(e.key === 'ArrowDown' ? 1 : -1)
}
return
}
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
@@ -400,6 +452,8 @@ leaves and ignores the current scope.
// highlighted row so an unrelated Tab in an empty picker still
// falls through to natural focus movement.
if (e.key === 'Tab' && !highlightedKey) return
// Without `onPick`, Enter on a leaf runs its selected button, which Tab must not do.
if (e.key === 'Tab' && !onPick && leafForKey(highlightedKey!)) return
e.preventDefault()
e.stopPropagation()
mouseActive = false
@@ -484,6 +538,35 @@ leaves and ignores the current scope.
})
const branchLoading = $derived(currentBranch ? (currentBranch.loading ?? false) : rootLoading)
const highlightedNode = $derived.by<DrillNode<L> | undefined>(() => {
if (!highlightedKey) return undefined
if (isSearching) return (searchedItems ?? []).find((r) => r.leaf.key === highlightedKey)?.leaf
return entryList.find((e) => e.key === highlightedKey)?.node
})
const highlightedActions = $derived(
highlightedNode?.type === 'leaf' && !highlightedNode.disabled
? (leafActions?.(highlightedNode) ?? [])
: []
)
const mainAction = $derived(highlightedActions.find((a) => a.preferred) ?? highlightedActions[0])
const otherActions = $derived(highlightedActions.filter((a) => a !== mainAction))
let actionMenuOpen = $state(false)
/** Answers an Escape a host takes before the picker can: closes a row's dropdown, which hands
* focus back to its chevron, or leaves a row's button for the search field. False when neither
* applies, so the host closes instead. */
export function escape(target: EventTarget | null): boolean {
if (actionMenuOpen) {
actionMenuOpen = false
return true
}
if (!(target as HTMLElement | null)?.closest?.('[data-drill-action]')) return false
focus()
return true
}
let actionsWidth = $state(0)
</script>
<SearchItems
@@ -525,110 +608,183 @@ leaves and ignores the current scope.
{@const action = leaf.disabled ? undefined : leafAction?.(leaf)}
{@const badge = leafBadge?.(leaf)}
{@const href = leaf.disabled ? undefined : leafHref?.(leaf)}
{@const inert = !onPick}
{@const actions = isHl ? highlightedActions : []}
{@const done = leafDone?.(leaf)}
<!-- The row's action sits BESIDE the option rather than inside it: a button nested in
a button is invalid markup. The wrapper carries the row's padding, highlight and
hover group so the two still read as one row. -->
<!-- Hover is tracked on the wrapper, not on the option button: the row's action is a
sibling of that button, so entering it would otherwise read as leaving the row and
drop the highlight out from under the pointer. -->
<!-- A disabled option dims through `disabled:opacity-50` and shows its cursor on this wrapper:
the base `button:disabled` rule in tailwind.config.cjs outranks a plain `opacity-50` and
turns pointer events off on the button itself. -->
<!-- `leafActions` show only on the highlighted row, so a pointer that comes back after the
arrow keys moved the highlight takes it on its first move, not on the next row it enters. -->
<div
class="group flex items-center transition-colors pr-3 {baseClass} {isHl
class="group relative flex items-center transition-colors pr-3 {baseClass} {isHl
? 'bg-surface-hover'
: ''}"
: ''} {leaf.disabled ? 'cursor-not-allowed' : ''}"
onmouseenter={(e) => {
setHoverHighlight(key)
tooltipEnter(e.currentTarget as HTMLElement, leaf)
}}
onmousemove={leafActions && !isHl ? () => setHoverHighlight(key) : undefined}
onmouseleave={tooltipLeave}
>
<svelte:element
this={href ? 'a' : 'button'}
type={href ? undefined : 'button'}
{href}
id={idFor(key)}
role="option"
aria-selected={isHl}
data-nav-key={key}
aria-current={isCur ? 'true' : undefined}
aria-label={tip ? `${leaf.label} — ${tip}` : undefined}
class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur
? 'cursor-default text-emphasis font-medium'
: 'text-[color:inherit]'} {leaf.disabled ? 'opacity-50 cursor-not-allowed' : ''}"
disabled={href ? undefined : leaf.disabled}
tabindex={0}
onmousedown={(e: MouseEvent) => 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)
}}
<!-- With `leafActions`, what fades out under the row's buttons; `contents` otherwise. -->
<div
class={leafActions ? 'min-w-0 flex-1 flex items-center' : 'contents'}
style={actions.length ? fadeUnder(actionsWidth) : undefined}
>
{@render defaultLeafIcon(leaf)}
<!-- Centred in a two-line row's height so a one-line leaf sits where a two-line
one's pair does, rather than riding high against the top. A list with no
second line anywhere (a picker's pages) keeps its rows one line tall. -->
<div
class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight ? 'min-h-[2.25rem]' : ''}"
<svelte:element
this={href ? 'a' : inert ? 'div' : 'button'}
type={href || inert ? undefined : 'button'}
{href}
id={idFor(key)}
role="option"
aria-selected={isHl}
aria-disabled={inert && leaf.disabled ? 'true' : undefined}
data-nav-key={key}
aria-current={isCur ? 'true' : undefined}
aria-label={tip ? `${leaf.label} — ${tip}` : undefined}
class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur
? 'cursor-default text-emphasis font-medium'
: 'text-[color:inherit]'} {inert
? leaf.disabled
? 'opacity-50'
: 'cursor-default'
: 'disabled:opacity-50'}"
disabled={href || inert ? undefined : leaf.disabled}
tabindex={inert ? -1 : 0}
onmousedown={(e: MouseEvent) => 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}
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
<div class="text-2xs text-hint font-normal font-mono truncate">
{secondary ?? leaf.secondary}
</div>
{:else}
<div
class="text-xs text-primary font-normal truncate {secondary === undefined &&
leaf.plainLabel
? ''
: 'font-mono'}"
>
{secondary ?? leaf.label}
</div>
{@render defaultLeafIcon(leaf)}
<!-- Centred in a two-line row's height so a one-line leaf sits where a two-line
one's pair does, rather than riding high against the top. A list with no
second line anywhere (a picker's pages) keeps its rows one line tall. -->
<div
class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight
? 'min-h-[2.25rem]'
: ''}"
>
{#if leaf.secondary}
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
<div class="text-2xs text-hint font-normal font-mono truncate">
{secondary ?? leaf.secondary}
</div>
{:else}
<div
class="text-xs text-primary font-normal truncate {secondary === undefined &&
leaf.plainLabel
? ''
: 'font-mono'}"
>
{secondary ?? leaf.label}
</div>
{/if}
</div>
</svelte:element>
{#if leafActions}
<!-- Plain text beside the row's buttons, which sit over it while the row is
highlighted: a filled badge reads as one more button. -->
{#if badge}
<span class="shrink-0 pl-2 text-xs text-secondary">{badge.label}</span>
{/if}
<!-- Keyed on the props rather than on this leaf's own badge or action, so a picker
that has either holds the column open on every row: paths then truncate at one
column and the button lands in the same place down the list. -->
{:else if leafBadge || leafAction}
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
side by side or shifting the row as one replaces the other. -->
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
{#if action}
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
visibility both fades with opacity and keeps the button out of the tab
order while it is out of sight — the picker's focus belongs to its
search field, and rows are reached with the arrow keys.
The classes sit on this wrapper, not on the Button: `wrapperClasses` is
twMerged with the button's own `flex`, which drops a conflicting
display and leaves it showing beside the badge. -->
<div
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
>
<Button
unifiedSize="xs"
variant="default"
title={action.title}
startIcon={{ icon: action.icon }}
onClick={action.run}
wrapperClasses="shrink-0"
>
{action.label}
</Button>
</div>
{/if}
{#if badge}
<div
class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action
? 'group-hover:invisible group-hover:opacity-0'
: ''}"
>
<Badge small color={badge.color}>{badge.label}</Badge>
</div>
{/if}
</div>
{/if}
</div>
{#if actions.length}
<!-- Over the row's end, so a row keeps its layout whether or not it shows them. -->
<div
class="absolute inset-y-0 right-3 flex items-center gap-1"
bind:clientWidth={actionsWidth}
>
{#if mainAction && !done}
<!-- Local, so it waits for the pill to leave but not for a hover. -->
<span data-drill-action in:fade={{ delay: 150, duration: 100 }}>
<Button
unifiedSize="sm"
variant="default"
startIcon={mainAction.icon ? { icon: mainAction.icon } : undefined}
loading={mainAction.loading}
disabled={mainAction.disabled}
onClick={() => mainAction && runAction(mainAction)}
dropdownItems={otherActions.map((a) => ({
label: a.label,
description: a.hint,
icon: a.icon,
disabled: a.disabled || a.loading,
onClick: () => runAction(a)
}))}
bind:dropdownOpen={actionMenuOpen}
>
{mainAction.label}
</Button>
</span>
{/if}
</div>
</svelte:element>
<!-- Keyed on the props rather than on this leaf's own badge or action, so a picker
that has either holds the column open on every row: paths then truncate at one
column and the button lands in the same place down the list. -->
{#if leafBadge || leafAction}
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
side by side or shifting the row as one replaces the other. -->
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
{#if action}
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
visibility both fades with opacity and keeps the button out of the tab
order while it is out of sight — the picker's focus belongs to its
search field, and rows are reached with the arrow keys.
The classes sit on this wrapper, not on the Button: `wrapperClasses` is
twMerged with the button's own `flex`, which drops a conflicting
display and leaves it showing beside the badge. -->
<div
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
>
<Button
unifiedSize="xs"
variant="default"
title={action.title}
startIcon={{ icon: action.icon }}
onClick={action.run}
wrapperClasses="shrink-0"
>
{action.label}
</Button>
</div>
{/if}
{#if badge}
<div
class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action
? 'group-hover:invisible group-hover:opacity-0'
: ''}"
>
<Badge small color={badge.color}>{badge.label}</Badge>
</div>
{/if}
{/if}
{#if done}
<!-- SaveButton's success pill, over the row's button and its dropdown chevron. -->
<div
class="absolute inset-y-0 my-auto h-7 right-3 z-10 flex items-center justify-center gap-1.5 px-2 rounded-md text-xs font-medium whitespace-nowrap bg-green-200 dark:bg-green-800 text-green-800 dark:text-green-200"
style={pillWidths[leaf.key] ? `min-width: ${pillWidths[leaf.key]}px` : undefined}
role="status"
transition:fly={{ y: -10, duration: 150 }}
>
<CheckCircle2 size={14} class="shrink-0" />
{done}
</div>
{/if}
</div>
@@ -753,6 +909,11 @@ leaves and ignores the current scope.
>
{@render defaultBranchIcon(entry.node)}
<span class="flex-1 truncate">{entry.node.label}</span>
{#if entry.node.badge}
<span class="shrink-0 pl-2 text-xs font-sans font-normal text-secondary"
>{entry.node.badge}</span
>
{/if}
{#if entry.node.loading}
<Loader2 size={12} class="animate-spin text-tertiary" />
{/if}
@@ -767,6 +928,8 @@ leaves and ignores the current scope.
<div role="status" class="px-3 py-1.5 text-xs text-tertiary flex items-center gap-2">
<Loader2 size={14} class="animate-spin" /> Loading…
</div>
{:else if currentBranch?.note}
<div role="status" class="px-3 py-2 text-xs text-tertiary">{currentBranch.note}</div>
{/if}
</div>
{/if}
@@ -0,0 +1,535 @@
<!--
@component
The access view's "+ Grant" list: the caller's own `u/` folder and every folder, with their items.
A row does nothing when clicked. The highlighted row offers each change to the principal's own
grant on it that changes what the principal can do (grant read or write, revoke write or read),
the most useful one as its button and the others in its dropdown. The "All of f/x" row
changes the grant on the whole folder.
-->
<script module lang="ts">
/** The navigator's tallest height, `max-h-[min(460px,60vh)]` below, for its host to place it. */
export function navigatorMaxHeight(): number {
return Math.min(460, window.innerHeight * 0.6)
}
</script>
<script lang="ts">
import DrillPicker from '$lib/components/DrillPicker.svelte'
import type { DrillLeaf, DrillLeafAction, DrillNode } from '$lib/components/drillPicker'
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
import {
GranularAclService,
type AccessReason,
type BrowseAccessFoldersResponse,
type BrowseAccessItemsResponse,
type PrincipalAccess
} from '$lib/gen'
import {
useOperatingUser,
useOperatingWorkspace
} from '$lib/components/operatingWorkspace.svelte'
import { sendUserToast } from '$lib/toast'
import { debounce } from '$lib/utils'
import { Folder, User, Users } from 'lucide-svelte'
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
import { setOverlayHost } from '$lib/components/common/overlayHost.svelte'
import { setGrant, type GrantLevel, type GrantSource } from './access'
const operatingWorkspace = useOperatingWorkspace()
const operatingUser = useOperatingUser()
type Row = BrowseAccessItemsResponse['items'][number]
/** `kind` `folder` is the "All of f/x" row, its `path` the folder name. */
type Leaf = Row & { owner?: boolean }
/** What the principal holds on a row besides its own entry: the level, `undefined` where the
* access report cannot tell, and where it comes from, in the access table's words. */
type Inherited = { level: GrantLevel | undefined; hows: string[] }
let {
principal,
access,
onChange,
source
}: {
principal: string
access: PrincipalAccess
/** After each change to a grant, for the host to reload `access`. */
onChange: () => void
source?: GrantSource
} = $props()
const api: GrantSource = {
get ownSpace() {
return `u/${operatingUser.current?.username}`
},
folders: () =>
GranularAclService.browseAccessFolders({ workspace: $operatingWorkspace!, principal }),
items: (query) =>
GranularAclService.browseAccessItems({
workspace: $operatingWorkspace!,
principal,
...query
}),
set: (kind, path, level) => setGrant($operatingWorkspace!, kind, path, principal, level)
}
const data = $derived(source ?? api)
const own = $derived(data.ownSpace)
let picker: { focus: () => void; escape: (target: EventTarget | null) => boolean } | undefined =
$state()
let folders: BrowseAccessFoldersResponse | undefined = $state()
/** Rows by top-level branch (`u/alice`, `f/billing`), then by `kind:path`. */
let rows: Record<string, Record<string, Row>> = $state({})
let loading: Record<string, boolean> = $state({})
const loaded = new Set<string>()
/** Branches whose every page has arrived, so no rows there means the folder has no items. */
let complete: Record<string, boolean> = $state({})
/** The change in flight, as `kind:path:label`. */
let pending: string | undefined = $state()
/** Runs before this time are ignored: the second press of a double click or Enter would
* otherwise run the button that took the first one's place. */
let settledUntil = 0
function branchOf(path: string): string {
return path.split('/', 2).join('/')
}
function merge(items: Row[]) {
for (const item of items) {
const branch = branchOf(item.path)
rows[branch] ??= {}
rows[branch][`${item.kind}:${item.path}`] = item
}
}
async function loadFolders() {
try {
folders = await data.folders()
} catch (e) {
sendUserToast(`Could not load folders: ${e?.body ?? e}`, true)
// The picker shows its loader for as long as there are no folders.
folders = []
}
}
async function loadBranch(branch: string) {
if (loaded.has(branch)) return
loaded.add(branch)
loading[branch] = true
try {
let offset = 0
while (true) {
const page = await data.items({ prefix: `${branch}/`, offset })
merge(page.items)
// The branch shows from its first page; later pages fill it in as they arrive.
loading[branch] = false
if (!page.has_more) break
offset += page.items.length
}
complete[branch] = true
} catch (e) {
loaded.delete(branch)
sendUserToast(`Could not load ${branch}: ${e?.body ?? e}`, true)
} finally {
loading[branch] = false
}
}
// The picker searches only the rows it holds, so matches anywhere are fetched into the tree.
let searchId = 0
const searchSoon = debounce(async (search: string) => {
const id = ++searchId
try {
let offset = 0
// Every page of matches, unless a newer search has replaced this one.
while (id === searchId) {
const page = await data.items({ search, offset })
merge(page.items)
if (!page.has_more) break
offset += page.items.length
}
} catch (e) {
sendUserToast(`Could not search: ${e?.body ?? e}`, true)
}
}, 250).debounced
loadFolders()
function itemLeaf(row: Row): DrillLeaf<Leaf> {
return {
type: 'leaf',
key: `${row.kind}:${row.path}`,
label: row.path.split('/').slice(2).join('/'),
secondary: row.path,
searchableText: row.path,
data: row,
disabled: !!row.blocked
}
}
function itemLeaves(branch: string): DrillLeaf<Leaf>[] {
return Object.values(rows[branch] ?? {})
.sort((a, b) => a.path.localeCompare(b.path) || a.kind.localeCompare(b.kind))
.map(itemLeaf)
}
function folderData(folder: BrowseAccessFoldersResponse[number]): Leaf {
return {
kind: 'folder',
path: folder.name,
grant: folder.grant,
blocked: folder.blocked,
owner: folder.target_owner
}
}
const tree = $derived.by<DrillNode<Leaf>[]>(() => {
const folderNames = new Set((folders ?? []).map((f) => `f/${f.name}`))
const others = Object.keys(rows)
.filter((b) => b !== own && !folderNames.has(b))
.sort()
return [
{
type: 'branch',
key: own,
label: own,
icon: User,
searchGroup: true,
loading: loading[own],
children: itemLeaves(own)
},
...(folders ?? []).map((folder): DrillNode<Leaf> => {
const branch = `f/${folder.name}`
const items = itemLeaves(branch)
const level = levelOf(folderData(folder), `folder:${folder.name}`)
return {
type: 'branch',
key: branch,
label: branch,
icon: Folder,
searchGroup: true,
loading: loading[branch],
badge: level === 'none' ? undefined : LEVEL_LABELS[level],
note:
complete[branch] && items.length === 0
? `${branch} has no items yet. A grant on the whole folder covers the items added later.`
: undefined,
children: [
{
type: 'leaf',
key: `folder:${folder.name}`,
label: `All of f/${folder.name}`,
searchableText: branch,
data: folderData(folder),
disabled: folder.target_owner || !!folder.blocked
},
...items
]
}
}),
// Other users' and groups' items appear once a search finds them.
...others.map(
(b): DrillNode<Leaf> => ({
type: 'branch',
key: b,
label: b,
icon: b.startsWith('g/') ? Users : User,
searchGroup: true,
children: itemLeaves(b)
})
)
]
})
const reasons = $derived(
new Map<string, AccessReason[]>(
access.items.map((i) => [`${i.kind}:${i.path}`, i.reasons] as const)
)
)
const reachedFolders = $derived(new Map(access.folders.map((f) => [f.name, f])))
const isGroup = $derived(principal.startsWith('g/'))
const who = $derived(isGroup ? `members of ${principal}` : principal)
/** What read and write let the principal do, by kind. */
const GIVES: Record<string, { read: string; write: string }> = {
folder: { read: 'read all its items, new ones included', write: 'edit and add items' },
script: { read: 'see and run it', write: 'edit it' },
flow: { read: 'see and run it', write: 'edit it' },
app: { read: 'open and use it', write: 'edit it' },
raw_app: { read: 'open and use it', write: 'edit it' },
resource: { read: 'use it and see its value', write: 'change its value' },
variable: { read: 'use it and see its value', write: 'change its value' },
schedule: { read: 'see it', write: 'edit, enable and disable it' }
}
const GIVES_OTHER = { read: 'see it', write: 'edit it' }
const LEVELS: GrantLevel[] = ['none', 'read', 'write']
const LEVEL_LABELS: Record<GrantLevel, string> = {
none: 'No access',
read: 'Read',
write: 'Write'
}
function maxLevel(a: GrantLevel, b: GrantLevel): GrantLevel {
return LEVELS.indexOf(a) >= LEVELS.indexOf(b) ? a : b
}
function entryLevel(grant: boolean | null | undefined): GrantLevel {
return grant == undefined ? 'none' : grant ? 'write' : 'read'
}
/** The principal's own entry on an item, which `grant` on its row holds. */
function isOwnEntry(r: AccessReason): boolean {
return r.type === 'user' || (r.type === 'group' && `g/${r.group}` === principal)
}
function reasonLabel(r: AccessReason): string {
switch (r.type) {
case 'folder':
return `through f/${r.folder}`
case 'group':
return `through g/${r.group}`
case 'own':
return `under ${principal}/`
case 'group_path':
return `under g/${r.group}/`
default:
return 'shared directly'
}
}
function inheritedOf(row: Leaf, key: string): Inherited {
if (row.kind === 'folder') {
if (row.owner) return { level: 'write', hows: ['folder admin'] }
const folder = reachedFolders.get(row.path)
const others = (folder?.via ?? []).filter((v) => v !== principal)
if (!folder || others.length === 0) return { level: 'none', hows: [] }
// `via` names the other entries without their levels, so next to the principal's own
// write the report cannot tell whether one of them gives write too.
const level = folder.grant === true ? undefined : folder.write ? 'write' : 'read'
return { level, hows: others.map((v) => `through ${v}`) }
}
const others = (reasons.get(key) ?? []).filter((r) => !isOwnEntry(r))
const level: GrantLevel =
others.length === 0
? 'none'
: others.some((r) => r.type === 'own' || r.type === 'group_path' || r.write)
? 'write'
: 'read'
return { level, hows: others.map(reasonLabel) }
}
/** The level held on a row. The own entry is read from the row, which a change made here
* updates before `access` reloads. */
function levelOf(row: Leaf, key: string): GrantLevel {
return maxLevel(inheritedOf(row, key).level ?? 'read', entryLevel(row.grant))
}
function pathOf(row: Leaf): string {
return row.kind === 'folder' ? `f/${row.path}` : row.path
}
/** Why a dimmed row can't be changed, for its tooltip. */
function lockedText(row: Leaf): string | undefined {
if (row.owner)
return `${principal} is an admin of f/${row.path}, so ${isGroup ? 'its members' : 'they'} can write every item in it.`
return row.blocked
}
/** Selected on a highlighted row, the first of these it offers. */
const PREFERRED = ['Grant read', 'Grant write', 'Revoke write', 'Revoke read']
function actionsFor(leaf: DrillLeaf<Leaf>): DrillLeafAction[] {
const row = leaf.data
const ownLevel = entryLevel(row.grant)
const inherited = inheritedOf(row, leaf.key)
const level = maxLevel(inherited.level ?? 'read', ownLevel)
const gives = GIVES[row.kind] ?? GIVES_OTHER
// In the order of the level each one leaves, so the buttons read from less to more access.
const changes: { label: string; to: GrantLevel; hint: string }[] = []
if (ownLevel !== 'none' && inherited.level === 'none') {
changes.push({
label: 'Revoke read',
to: 'none',
hint: `${who} can no longer ${gives.read}.`
})
}
if (level === 'none') {
changes.push({ label: 'Grant read', to: 'read', hint: `${who} can ${gives.read}.` })
}
if (ownLevel === 'write' && inherited.level !== 'write') {
changes.push({
label: 'Revoke write',
to: 'read',
hint: inherited.level
? `${who} can no longer ${gives.write}, only ${gives.read}.`
: `the grant becomes read, but ${who} may still write ${inherited.hows.join(' or ')}.`
})
}
if (level !== 'write') {
const folder =
row.kind !== 'folder' && ownLevel === 'none'
? (reasons.get(leaf.key) ?? []).find((r) => r.type === 'folder')?.folder
: undefined
changes.push({
label: 'Grant write',
to: 'write',
hint:
level === 'none'
? `${who} can ${gives.read}, and ${gives.write}.`
: `${who} can also ${gives.write}.` +
(folder ? ` This grant stays if f/${folder} is no longer shared.` : '')
})
}
const preferred = PREFERRED.find((label) => changes.some((c) => c.label === label))
return changes.map((c) => ({
label: c.label,
hint: c.hint,
preferred: c.label === preferred,
loading: pending === `${leaf.key}:${c.label}`,
disabled: pending !== undefined,
run: () => change(leaf, c.label, c.to)
}))
}
/** A change to a whole folder, waiting for the dialog. */
let confirming:
| { leaf: DrillLeaf<Leaf>; label: string; level: GrantLevel; hint: string }
| undefined = $state()
function change(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) {
if (pending !== undefined || Date.now() < settledUntil) return
if (leaf.data.kind !== 'folder') {
apply(leaf, label, level)
return
}
const hint = actionsFor(leaf).find((a) => a.label === label)?.hint ?? ''
confirming = { leaf, label, level, hint }
// Else the second press of a double click or Enter would confirm it at once.
settledUntil = Date.now() + 400
}
async function confirmFolder() {
if (!confirming || pending !== undefined || Date.now() < settledUntil) return
await apply(confirming.leaf, confirming.label, confirming.level)
confirming = undefined
}
function cancelFolder() {
if (pending !== undefined) return
confirming = undefined
picker?.focus()
}
/** Focus stays in the search field under the dialog, so its keys are answered here: the
* dialog's own window listener leaves alone keys that start inside a popover, which is where
* the access drawer shows this list. */
function dialogKeys(e: KeyboardEvent) {
if (!confirming || e.key === 'Tab') return
e.stopPropagation()
// A focused dialog button activates itself, so Enter on Cancel cancels.
const onButton = !!(e.target as HTMLElement | null)?.closest?.('[role="dialog"] button')
if (onButton && (e.key === 'Enter' || e.key === ' ')) return
e.preventDefault()
if (e.key === 'Enter') confirmFolder()
else if (e.key === 'Escape') cancelFolder()
}
/** Answers an Escape a host takes before the navigator can: cancels the folder dialog, or
* passes it to the picker. False when nothing here was open, so the host closes instead. */
export function escape(target: EventTarget | null): boolean {
if (confirming) {
cancelFolder()
return true
}
return !!picker?.escape(target)
}
let root: HTMLElement | undefined = $state()
// The dialog covers this list rather than the page: a click on a dialog over the page lands
// outside the drawer's popover, which closes it and the dialog with it.
setOverlayHost({ el: () => root, drawers: { val: [] }, active: () => true })
const DONE: Record<string, string> = {
'Grant read': 'Read granted',
'Grant write': 'Write granted',
'Revoke write': 'Write revoked',
'Revoke read': 'Access revoked'
}
/** The row a change just landed on, and what it did ("Read granted"), for 1.5s. */
let done: { key: string; text: string } | undefined = $state()
let doneTimer: ReturnType<typeof setTimeout> | undefined
function showDone(key: string, text: string) {
clearTimeout(doneTimer)
done = { key, text }
doneTimer = setTimeout(() => (done = undefined), 1000)
}
async function apply(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) {
const row = leaf.data
pending = `${leaf.key}:${label}`
try {
await data.set(row.kind, row.path, level)
row.grant = level === 'none' ? null : level === 'write'
if (row.kind === 'folder') {
const folder = folders?.find((f) => f.name === row.path)
if (folder) folder.grant = row.grant
}
onChange()
showDone(leaf.key, DONE[label] ?? 'Done')
} catch (e) {
sendUserToast(`Could not ${label.toLowerCase()} on ${pathOf(row)}: ${e?.body ?? e}`, true)
} finally {
pending = undefined
settledUntil = Date.now() + 400
// A click left focus on a button, which may be gone now.
picker?.focus()
}
}
</script>
{#snippet leafIcon(leaf: DrillLeaf<Leaf>)}
<RowIcon kind={leaf.data.kind as 'folder'} size={12} />
{/snippet}
<div
bind:this={root}
class="relative flex flex-col max-h-[min(460px,60vh)]"
onkeydowncapture={dialogKeys}
role="presentation"
>
{#if confirming}
{@const folder = pathOf(confirming.leaf.data)}
<ConfirmationModal
open
title="{confirming.label} on {folder}?"
confirmationText={confirming.label}
type={confirming.label.startsWith('Revoke') ? 'danger' : 'info'}
loading={pending !== undefined}
onConfirmed={confirmFolder}
onCanceled={cancelFolder}
>
<p>It applies to every item in {folder}: {confirming.hint}</p>
</ConfirmationModal>
{/if}
<DrillPicker
bind:this={picker}
{tree}
{leafIcon}
rowTooltip={(leaf) => lockedText(leaf.data)}
rootLoading={!folders}
onScopeChange={(scope) => scope.length === 1 && loadBranch(scope[0])}
onFilterChange={(filter) => filter.trim() && searchSoon(filter.trim())}
leafActions={actionsFor}
leafDone={(leaf) => (done && done.key === leaf.key ? done.text : undefined)}
leafBadge={(leaf) => {
const level = levelOf(leaf.data, leaf.key)
return level === 'none'
? undefined
: { label: LEVEL_LABELS[level], color: level === 'write' ? 'blue' : 'gray' }
}}
/>
</div>
@@ -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<BrowseAccessFoldersResponse>
items: (query: {
prefix?: string
search?: string
offset?: number
}) => Promise<BrowseAccessItemsResponse>
/** Sets the principal's own entry, as `setGrant` does. */
set: (kind: string, path: string, level: GrantLevel) => Promise<void>
}
type AclKind = Parameters<typeof GranularAclService.addGranularAcls>[0]['kind']
export const KIND_LABELS: Record<string, string> = {
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<void> {
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' }
})
}
}
@@ -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
)}
>
@@ -35,6 +35,19 @@ export type DrillLeaf<L> = {
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<L> = {
type: 'branch'
@@ -44,6 +57,11 @@ export type DrillBranch<L> = {
children: DrillNode<L>[]
/** 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). */
@@ -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}`