mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-17 00:20:51 +00:00
feat: show what a member, group or service account can access (#12142)
* feat: show what a member, group or service account can access 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: 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 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> * test: cover a member reading their group's access 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: 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. --------- 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:
co-authored by
Claude Opus 5.5
windmill-internal-app[bot]
parent
d0d37e04a5
commit
766825ed47
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "email",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "disabled",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "4fdbda2d728055d09bf39edb31bafb8df34fb94b89e86e6216677202c6bb3011"
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "name",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "via!",
|
||||
"type_info": "TextArray"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"TextArray",
|
||||
"TextArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)\n OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "?column?",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "fa97f5dfbe9772472b16e3987e58343102bb0a0195038d7fdac1e80dd45bf604"
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
a9a0f4f5073d0f774fb7bd7f87b6e37e8d5356b4
|
||||
c4e610999ca0d1abab06b1660cc48e486ab870b3
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Another member's access lists paths the caller may not be able to read, so only a workspace
|
||||
//! admin may ask for it.
|
||||
|
||||
use sqlx::{Pool, Postgres};
|
||||
|
||||
use windmill_test_utils::*;
|
||||
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn test_member_cannot_read_another_members_access(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let url = format!(
|
||||
"http://localhost:{}/api/w/test-workspace/access/get",
|
||||
server.addr.port()
|
||||
);
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
sqlx::raw_sql(
|
||||
"INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('test-workspace', 'ops', '', '{}');
|
||||
INSERT INTO usr_to_group (workspace_id, usr, group_) VALUES ('test-workspace', 'test-user-2', 'ops');
|
||||
INSERT INTO instance_group (name) VALUES ('sre');
|
||||
INSERT INTO email_to_igroup (email, igroup) VALUES ('test2@windmill.dev', 'sre')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
// A member may read their own access and their groups', instance groups included, nobody
|
||||
// else's.
|
||||
for (principal, status) in [
|
||||
("u/test-user", 403),
|
||||
("g/all", 403),
|
||||
("u/test-user-2", 200),
|
||||
("g/ops", 200),
|
||||
("g/sre", 200),
|
||||
] {
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.query(&[("principal", principal)])
|
||||
.header("Authorization", "Bearer SECRET_TOKEN_2")
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), status, "{principal}: {}", resp.text().await?);
|
||||
}
|
||||
|
||||
// A scoped token reaches the route only if `/access` maps to a scope domain.
|
||||
let scoped = client
|
||||
.post(format!(
|
||||
"http://localhost:{}/api/users/tokens/create",
|
||||
server.addr.port()
|
||||
))
|
||||
.header("Authorization", "Bearer SECRET_TOKEN_2")
|
||||
.json(&serde_json::json!({ "label": "scoped", "scopes": ["acls:read"], "workspace_id": "test-workspace" }))
|
||||
.send()
|
||||
.await?
|
||||
.text()
|
||||
.await?;
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.query(&[("principal", "u/test-user-2")])
|
||||
.header("Authorization", format!("Bearer {scoped}"))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
/*
|
||||
* Author: Ruben Fiszel
|
||||
* Copyright: Windmill Labs, Inc 2026
|
||||
* This file and its contents are licensed under the AGPLv3 License.
|
||||
* Please see the included NOTICE for copyright information and
|
||||
* LICENSE-AGPL for a copy of the license.
|
||||
*/
|
||||
|
||||
//! What a workspace member or group can reach, and why.
|
||||
|
||||
use axum::{
|
||||
extract::{Extension, Path, Query},
|
||||
routing::get,
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use windmill_api_auth::ApiAuthed;
|
||||
use windmill_common::{
|
||||
auth::fetch_authed_from_permissioned_as,
|
||||
db::UserDB,
|
||||
error::{Error, JsonResult},
|
||||
DB,
|
||||
};
|
||||
|
||||
pub fn workspaced_service() -> Router {
|
||||
Router::new().route("/get", get(get_access))
|
||||
}
|
||||
|
||||
/// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on
|
||||
/// purpose: they are test data attached to an item, not something access is granted to.
|
||||
const ITEM_TABLES: [(&str, &str, &str); 17] = [
|
||||
(
|
||||
"script",
|
||||
"script",
|
||||
"AND archived = false AND deleted = false",
|
||||
),
|
||||
("flow", "flow", "AND archived = false"),
|
||||
("app", "app", ""),
|
||||
("resource", "resource", ""),
|
||||
("variable", "variable", ""),
|
||||
("schedule", "schedule", ""),
|
||||
("http_trigger", "http_trigger", ""),
|
||||
("websocket_trigger", "websocket_trigger", ""),
|
||||
("kafka_trigger", "kafka_trigger", ""),
|
||||
("nats_trigger", "nats_trigger", ""),
|
||||
("postgres_trigger", "postgres_trigger", ""),
|
||||
("mqtt_trigger", "mqtt_trigger", ""),
|
||||
("amqp_trigger", "amqp_trigger", ""),
|
||||
("gcp_trigger", "gcp_trigger", ""),
|
||||
("azure_trigger", "azure_trigger", ""),
|
||||
("sqs_trigger", "sqs_trigger", ""),
|
||||
("email_trigger", "email_trigger", ""),
|
||||
];
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AccessQuery {
|
||||
/// `u/<username>` or `g/<group>`.
|
||||
principal: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AccessReport {
|
||||
principal: String,
|
||||
is_admin: bool,
|
||||
groups: Vec<String>,
|
||||
folders: Vec<FolderAccess>,
|
||||
items: Vec<ItemAccess>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct FolderAccess {
|
||||
name: String,
|
||||
write: bool,
|
||||
owner: bool,
|
||||
/// The `extra_perms` keys (`u/<user>` or `g/<group>`) that grant the folder.
|
||||
via: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ItemAccess {
|
||||
kind: String,
|
||||
path: String,
|
||||
write: bool,
|
||||
reasons: Vec<Reason>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
enum Reason {
|
||||
/// Under the principal's own `u/<user>/` path.
|
||||
Own,
|
||||
/// Under `g/<group>/` for a group the principal is in.
|
||||
GroupPath { group: String },
|
||||
/// Shared with the principal directly.
|
||||
User { write: bool },
|
||||
/// Shared with one of the principal's groups.
|
||||
Group { group: String, write: bool },
|
||||
/// In a folder the principal can read.
|
||||
Folder { folder: String, write: bool },
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ItemRow {
|
||||
kind: String,
|
||||
path: String,
|
||||
own: bool,
|
||||
path_group: Option<String>,
|
||||
user_grant: Option<bool>,
|
||||
group_read: Vec<String>,
|
||||
group_write: Vec<String>,
|
||||
folder: Option<String>,
|
||||
folder_write: bool,
|
||||
}
|
||||
|
||||
fn items_query() -> String {
|
||||
let union = ITEM_TABLES
|
||||
.iter()
|
||||
.map(|(kind, table, filter)| {
|
||||
format!(
|
||||
"SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \
|
||||
WHERE workspace_id = $1 {filter}"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" UNION ALL ");
|
||||
// Rows come back through the principal's RLS session, so the set is what their jobs can read;
|
||||
// the reasons below restate the same policies (see `pg_policies`) from the same session values.
|
||||
format!(
|
||||
"WITH s AS (
|
||||
SELECT current_setting('session.user') AS usr,
|
||||
regexp_split_to_array(current_setting('session.groups'), ',') AS groups,
|
||||
regexp_split_to_array(current_setting('session.pgroups'), ',') AS pgroups,
|
||||
regexp_split_to_array(current_setting('session.folders_read'), ',') AS fr,
|
||||
regexp_split_to_array(current_setting('session.folders_write'), ',') AS fw
|
||||
), items AS ({union})
|
||||
SELECT i.kind, i.path,
|
||||
(split_part(i.path, '/', 1) = 'u' AND split_part(i.path, '/', 2) = s.usr) AS own,
|
||||
CASE WHEN split_part(i.path, '/', 1) = 'g' AND split_part(i.path, '/', 2) = ANY(s.groups)
|
||||
THEN split_part(i.path, '/', 2) END AS path_group,
|
||||
(i.extra_perms ->> ('u/' || s.usr))::boolean AS user_grant,
|
||||
ARRAY(SELECT substr(e.key, 3) FROM jsonb_each_text(i.extra_perms) e
|
||||
WHERE e.key = ANY(s.pgroups) ORDER BY e.key) AS group_read,
|
||||
ARRAY(SELECT substr(e.key, 3) FROM jsonb_each_text(i.extra_perms) e
|
||||
WHERE e.key = ANY(s.pgroups) AND e.value::boolean ORDER BY e.key) AS group_write,
|
||||
CASE WHEN split_part(i.path, '/', 1) = 'f' AND split_part(i.path, '/', 2) = ANY(s.fr)
|
||||
THEN split_part(i.path, '/', 2) END AS folder,
|
||||
(split_part(i.path, '/', 1) = 'f' AND split_part(i.path, '/', 2) = ANY(s.fw)) AS folder_write
|
||||
FROM items i CROSS JOIN s
|
||||
ORDER BY i.path, i.kind"
|
||||
)
|
||||
}
|
||||
|
||||
impl From<ItemRow> for ItemAccess {
|
||||
fn from(r: ItemRow) -> Self {
|
||||
let mut reasons = vec![];
|
||||
if r.own {
|
||||
reasons.push(Reason::Own);
|
||||
}
|
||||
if let Some(group) = r.path_group {
|
||||
reasons.push(Reason::GroupPath { group });
|
||||
}
|
||||
if let Some(write) = r.user_grant {
|
||||
reasons.push(Reason::User { write });
|
||||
}
|
||||
for group in r.group_read {
|
||||
let write = r.group_write.contains(&group);
|
||||
reasons.push(Reason::Group { group, write });
|
||||
}
|
||||
if let Some(folder) = r.folder {
|
||||
reasons.push(Reason::Folder { folder, write: r.folder_write });
|
||||
}
|
||||
let write = reasons.iter().any(|r| match r {
|
||||
Reason::Own | Reason::GroupPath { .. } => true,
|
||||
Reason::User { write } | Reason::Group { write, .. } | Reason::Folder { write, .. } => {
|
||||
*write
|
||||
}
|
||||
});
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons }
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
let (prefix, name) = principal
|
||||
.split_once('/')
|
||||
.filter(|(_, name)| !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
|
||||
// contained in each member's, so its members may see it.
|
||||
let allowed = authed.is_admin
|
||||
|| match prefix {
|
||||
"u" => name == authed.username,
|
||||
"g" => authed.groups.iter().any(|g| g == name),
|
||||
_ => false,
|
||||
};
|
||||
if !allowed {
|
||||
return Err(Error::PermissionDenied(
|
||||
"only workspace admins can view the access of another member or of a group you are not in"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
let email = match prefix {
|
||||
"u" => {
|
||||
let usr = sqlx::query!(
|
||||
"SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2",
|
||||
&w_id,
|
||||
name
|
||||
)
|
||||
.fetch_optional(&db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound(format!("user {name} not found")))?;
|
||||
if usr.disabled {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"{name} is disabled, so nothing runs as them"
|
||||
)));
|
||||
}
|
||||
usr.email
|
||||
}
|
||||
"g" => {
|
||||
// Instance groups are granted through the same `g/<name>` keys, and the check above
|
||||
// lets their members ask, so a name from either table is a group here.
|
||||
let exists = sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)
|
||||
OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)",
|
||||
&w_id,
|
||||
name
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?
|
||||
.unwrap_or(false);
|
||||
if !exists {
|
||||
return Err(Error::NotFound(format!("group {name} not found")));
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::BadRequest(
|
||||
"principal must be u/<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();
|
||||
|
||||
if target.is_admin {
|
||||
return Ok(Json(AccessReport {
|
||||
principal,
|
||||
is_admin: true,
|
||||
groups: target.groups,
|
||||
folders: vec![],
|
||||
items: vec![],
|
||||
}));
|
||||
}
|
||||
|
||||
let mut perms = target
|
||||
.groups
|
||||
.iter()
|
||||
.map(|g| format!("g/{g}"))
|
||||
.collect::<Vec<_>>();
|
||||
if prefix == "u" {
|
||||
perms.insert(0, format!("u/{name}"));
|
||||
}
|
||||
let folder_names = target
|
||||
.folders
|
||||
.iter()
|
||||
.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!\"
|
||||
FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
&w_id,
|
||||
&folder_names,
|
||||
&perms
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.name, r.via))
|
||||
.collect::<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(),
|
||||
})
|
||||
.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())
|
||||
.bind(&w_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(ItemAccess::from)
|
||||
.collect();
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(Json(AccessReport {
|
||||
principal,
|
||||
is_admin: false,
|
||||
groups: target.groups,
|
||||
folders,
|
||||
items,
|
||||
}))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod access;
|
||||
pub mod folder_history;
|
||||
pub mod folders;
|
||||
pub mod granular_acls;
|
||||
|
||||
@@ -25227,6 +25227,31 @@ paths:
|
||||
type: string
|
||||
description: Minimum semantic version across all workers (e.g. "1.583.0")
|
||||
|
||||
/w/{workspace}/access/get:
|
||||
get:
|
||||
summary: list what a workspace member or group can reach, and why
|
||||
description: |
|
||||
Workspace admins can query any principal; other members only themselves and the groups
|
||||
they belong to. An admin principal reaches everything, so `items` is empty.
|
||||
operationId: getPrincipalAccess
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: principal
|
||||
description: "`u/<username>` or `g/<group>`"
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: the principal's access
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/PrincipalAccess"
|
||||
|
||||
/w/{workspace}/acls/get/{kind}/{path}:
|
||||
get:
|
||||
summary: get granular acls
|
||||
@@ -37240,6 +37265,66 @@ components:
|
||||
- script_path
|
||||
- is_flow
|
||||
|
||||
PrincipalAccess:
|
||||
type: object
|
||||
properties:
|
||||
principal:
|
||||
type: string
|
||||
is_admin:
|
||||
type: boolean
|
||||
groups:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
folders:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
write:
|
||||
type: boolean
|
||||
owner:
|
||||
type: boolean
|
||||
via:
|
||||
description: the `u/<user>` or `g/<group>` grants on the folder that reach the principal
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
required: [name, write, owner, via]
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
path:
|
||||
type: string
|
||||
write:
|
||||
type: boolean
|
||||
reasons:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/AccessReason"
|
||||
required: [kind, path, write, reasons]
|
||||
required: [principal, is_admin, groups, folders, items]
|
||||
|
||||
AccessReason:
|
||||
type: object
|
||||
properties:
|
||||
type:
|
||||
type: string
|
||||
enum: [own, group_path, user, group, folder]
|
||||
group:
|
||||
type: string
|
||||
folder:
|
||||
type: string
|
||||
write:
|
||||
type: boolean
|
||||
required: [type]
|
||||
|
||||
Group:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
@@ -679,6 +679,7 @@ pub async fn run_server(
|
||||
"/w/{workspace_id}",
|
||||
Router::new()
|
||||
// Reordered alphabetically
|
||||
.nest("/access", windmill_api_groups::access::workspaced_service())
|
||||
.nest("/acls", granular_acls::workspaced_service())
|
||||
// CORS so the opaque-origin in-workspace app viewer (WIN-2006,
|
||||
// sandboxed /apps/get) can read the app definition by path
|
||||
|
||||
@@ -424,7 +424,8 @@ impl ScopeDomain {
|
||||
"concurrency_groups" => Some(Self::ConcurrencyGroups),
|
||||
"oidc" => Some(Self::Oidc),
|
||||
"openapi" => Some(Self::Openapi),
|
||||
"acls" => Some(Self::Acls),
|
||||
// `/access` reports which grants reach a principal, so `acls` scopes cover it.
|
||||
"acls" | "access" => Some(Self::Acls),
|
||||
"raw_apps" => Some(Self::RawApps),
|
||||
"agent_workers" => Some(Self::AgentWorkers),
|
||||
"mcp" => Some(Self::Mcp),
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick"
|
||||
without any identifying data leaving the instance.
|
||||
|
||||
It currently carries 93 registered actions across thirty-six features (`ai_session`, `ai_chat`,
|
||||
It currently carries 98 registered actions across thirty-nine features (`access_view`, `ai_session`, `ai_chat`,
|
||||
`ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`,
|
||||
`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`,
|
||||
`command_script`, `mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`,
|
||||
`command_script`, `mcp`, `mcp_workspace`, `mcp_external_client`, `hub_script`, `usage_meter`, `sso_groups_claim`,
|
||||
`cloud_trial_offer`, `job_token_scopes`, `worker_draining`, `worker_group`,
|
||||
`worker_resource_stats`, `dev_workspace_isolation`, `slack_agent`, `variable_expiration`,
|
||||
`anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the
|
||||
`external_secret_ref`, `anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`). Nearly all of the
|
||||
product is uninstrumented, so new user-facing work is the opportunity to change that.
|
||||
|
||||
## When to instrument
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Badge, Button, Drawer, DrawerContent, Section, Skeleton } from './common'
|
||||
import TextInput from './text_input/TextInput.svelte'
|
||||
import Select from './select/Select.svelte'
|
||||
import DataTable from './table/DataTable.svelte'
|
||||
import Head from './table/Head.svelte'
|
||||
import Cell from './table/Cell.svelte'
|
||||
import Row from './table/Row.svelte'
|
||||
import RowIcon from './common/table/RowIcon.svelte'
|
||||
import { Tooltip } from './meltComponents'
|
||||
import { GranularAclService, type PrincipalAccess } from '$lib/gen'
|
||||
import { useOperatingWorkspace } from './operatingWorkspace.svelte'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { pluralize } from '$lib/utils'
|
||||
import { itemHref } from './offboarding-utils'
|
||||
import {
|
||||
buildAccessTree,
|
||||
flattenAccessTree,
|
||||
type AccessItem,
|
||||
type AccessOwnerNode
|
||||
} from './access/accessTree'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ChevronsDownUp,
|
||||
ChevronsUpDown,
|
||||
ExternalLink,
|
||||
Folder,
|
||||
FolderTree,
|
||||
User,
|
||||
Users
|
||||
} from 'lucide-svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
|
||||
type Target = 'self' | 'user' | 'service_account' | 'group'
|
||||
|
||||
const PAGE = 100
|
||||
// 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()
|
||||
let error: string | undefined = $state()
|
||||
let search = $state('')
|
||||
let kind: string | undefined = $state()
|
||||
let nbDisplayed = $state(PAGE)
|
||||
/** Rows opened or closed by hand, by path prefix. The rest follow `expandAll`. */
|
||||
let openState: Record<string, boolean> = $state({})
|
||||
let expandAll: boolean | undefined = $state()
|
||||
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
|
||||
let requestId = 0
|
||||
|
||||
export async function open(nextPrincipal: string, target: Target): Promise<void> {
|
||||
principal = nextPrincipal
|
||||
access = undefined
|
||||
error = undefined
|
||||
search = ''
|
||||
kind = undefined
|
||||
nbDisplayed = PAGE
|
||||
openState = {}
|
||||
expandAll = undefined
|
||||
drawer?.openDrawer()
|
||||
logFeatureUsage('access_view', 'opened', { key: target })
|
||||
const id = ++requestId
|
||||
try {
|
||||
const result = await GranularAclService.getPrincipalAccess({
|
||||
workspace: $operatingWorkspace!,
|
||||
principal: nextPrincipal
|
||||
})
|
||||
if (id === requestId) access = result
|
||||
} catch (e) {
|
||||
if (id === requestId) error = e?.body ?? String(e)
|
||||
}
|
||||
}
|
||||
|
||||
const name = $derived(principal.slice(2))
|
||||
const isGroup = $derived(principal.startsWith('g/'))
|
||||
const who = $derived(isGroup ? `members of ${principal}` : principal)
|
||||
|
||||
const kindItems = $derived.by(() => {
|
||||
const counts = new Map<string, number>()
|
||||
for (const item of access?.items ?? []) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1)
|
||||
return [...counts].map(([value, n]) => ({
|
||||
value,
|
||||
label: `${KIND_LABELS[value] ?? value} (${n})`
|
||||
}))
|
||||
})
|
||||
|
||||
const query = $derived(search.trim().toLowerCase())
|
||||
const filtering = $derived(!!query || !!kind)
|
||||
const allOpen = $derived(expandAll ?? (access?.items.length ?? 0) <= OPEN_UP_TO)
|
||||
const tree = $derived(access && !access.is_admin ? buildAccessTree(access) : [])
|
||||
const rows = $derived(
|
||||
flattenAccessTree(tree, {
|
||||
matches: (item) =>
|
||||
(!kind || item.kind === kind) && (!query || item.path.toLowerCase().includes(query)),
|
||||
isOpen: (key) => openState[key] ?? allOpen,
|
||||
filtering
|
||||
})
|
||||
)
|
||||
|
||||
function toggle(key: string, open: boolean): void {
|
||||
openState[key] = !open
|
||||
}
|
||||
|
||||
function toggleAll(): void {
|
||||
expandAll = !allOpen
|
||||
openState = {}
|
||||
}
|
||||
|
||||
function viaLabel(via: string): string {
|
||||
return via === principal ? 'Shared directly' : `Through ${via}`
|
||||
}
|
||||
|
||||
/** Where holding the whole folder or space comes from. Empty when only some items are shared. */
|
||||
function ownerGrant(node: AccessOwnerNode): string {
|
||||
if (!node.whole) return ''
|
||||
if (node.key.startsWith('f/')) {
|
||||
return [...(node.admin ? ['Folder admin'] : []), ...node.via.map(viaLabel)].join(', ')
|
||||
}
|
||||
return node.key === principal ? 'Own path' : `Through ${node.key}`
|
||||
}
|
||||
|
||||
function ownerExplanation(node: AccessOwnerNode): string {
|
||||
const verb = node.write ? 'write' : 'read'
|
||||
if (!node.whole) {
|
||||
return node.key.startsWith('f/')
|
||||
? `${node.key} itself isn't shared with ${principal}. Only the items listed under it are, one by one, so items added to ${node.key} later stay out of reach.`
|
||||
: `Only the items listed here are shared with ${principal}. Other items under ${node.key}/, and any added later, stay out of reach.`
|
||||
}
|
||||
if (node.key.startsWith('f/')) {
|
||||
return node.via.length
|
||||
? `${node.key} itself is shared with ${node.via.join(' and ')}, so ${who} can ${verb} every item in it, including items added later.`
|
||||
: `${principal} administers ${node.key}, so ${who} can write every item in it, including items added later.`
|
||||
}
|
||||
if (node.key === principal) {
|
||||
return isGroup
|
||||
? `Items under ${principal}/ belong to the group, so its members can write every one of them, including items added later.`
|
||||
: `Items under ${principal}/ belong to ${principal}, who can write every one of them, including items added later.`
|
||||
}
|
||||
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. */
|
||||
function itemGrants(item: AccessItem): string[] {
|
||||
return item.reasons.flatMap((r) =>
|
||||
r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : []
|
||||
)
|
||||
}
|
||||
|
||||
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' : ''
|
||||
}
|
||||
|
||||
// The drawer can report on the workspace a session editor acts in, which is not
|
||||
// necessarily the one the new tab would otherwise open.
|
||||
function withWorkspace(href: string): string {
|
||||
const [route, hash] = href.split(/#(.*)/s)
|
||||
const query = `?workspace=${encodeURIComponent($operatingWorkspace ?? '')}`
|
||||
return route + query + (hash !== undefined ? `#${hash}` : '')
|
||||
}
|
||||
|
||||
function itemLink(kind: string, path: string): string | undefined {
|
||||
const href = itemHref(kind, path)
|
||||
return href ? withWorkspace(href) : undefined
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet chevron(key: string, open: boolean)}
|
||||
<!-- Keyboard access only: its click bubbles to the row, which does the toggling. -->
|
||||
<button
|
||||
type="button"
|
||||
class="text-secondary shrink-0"
|
||||
aria-expanded={open}
|
||||
aria-label={`${open ? 'Collapse' : 'Expand'} ${key}`}
|
||||
>
|
||||
{#if open}
|
||||
<ChevronDown size={14} />
|
||||
{:else}
|
||||
<ChevronRight size={14} />
|
||||
{/if}
|
||||
</button>
|
||||
{/snippet}
|
||||
|
||||
<Drawer bind:this={drawer} size="1000px">
|
||||
<DrawerContent title={`Access of ${principal}`} on:close={() => drawer?.closeDrawer()}>
|
||||
<div class="flex flex-col gap-6">
|
||||
<p class="text-xs text-secondary">
|
||||
{#if isGroup}
|
||||
What members of g/{name} can read through this group alone, and which grant gives each item.
|
||||
Members may reach more through their own grants and other groups.
|
||||
{:else}
|
||||
What {principal} can read, and which grant gives each item. Jobs that run as
|
||||
{principal} read exactly this set.
|
||||
{/if}
|
||||
</p>
|
||||
|
||||
{#if error}
|
||||
<Alert type="error" title="Could not load access">{error}</Alert>
|
||||
{:else if !access}
|
||||
<Skeleton layout={[[2], 1, [6], 1, [12]]} />
|
||||
{:else if access.is_admin}
|
||||
<Alert type="info" title="Workspace admin">
|
||||
{principal} is an admin of this workspace and can read and write every item in it.
|
||||
</Alert>
|
||||
{:else}
|
||||
{#if !isGroup}
|
||||
<Section label="Groups" small>
|
||||
{#if access.groups.length}
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each access.groups as group (group)}
|
||||
<Badge color="gray">g/{group}</Badge>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-xs text-secondary">Not in any group.</p>
|
||||
{/if}
|
||||
</Section>
|
||||
{/if}
|
||||
|
||||
<Section label={`Items (${access.items.length})`} small>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex gap-2 items-center">
|
||||
<TextInput
|
||||
bind:value={search}
|
||||
inputProps={{ placeholder: 'Search paths' }}
|
||||
size="sm"
|
||||
class="grow"
|
||||
/>
|
||||
<div class="w-64">
|
||||
<Select
|
||||
items={kindItems}
|
||||
bind:value={kind}
|
||||
placeholder="All kinds"
|
||||
clearable
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
disabled={filtering}
|
||||
startIcon={{ icon: allOpen ? ChevronsDownUp : ChevronsUpDown }}
|
||||
on:click={toggleAll}
|
||||
>
|
||||
{allOpen ? 'Collapse all' : 'Expand all'}
|
||||
</Button>
|
||||
</div>
|
||||
{#if rows.length}
|
||||
<DataTable
|
||||
size="xs"
|
||||
shouldLoadMore={rows.length > nbDisplayed}
|
||||
loadMore={PAGE}
|
||||
on:loadMore={() => (nbDisplayed += PAGE)}
|
||||
>
|
||||
<Head>
|
||||
<tr>
|
||||
<Cell head first>Name</Cell>
|
||||
<Cell head>Access</Cell>
|
||||
<Cell head last>Granted by</Cell>
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody>
|
||||
{#each rows.slice(0, nbDisplayed) as row (row.type === 'item' ? `${row.item.kind}:${row.item.path}` : row.node.key)}
|
||||
{#if row.type === 'owner'}
|
||||
{@const node = row.node}
|
||||
{@const OwnerIcon = node.key.startsWith('f/')
|
||||
? Folder
|
||||
: node.key.startsWith('g/')
|
||||
? Users
|
||||
: User}
|
||||
<Row
|
||||
hoverable={row.count > 0}
|
||||
class="group"
|
||||
on:click={() => row.count > 0 && toggle(node.key, row.open)}
|
||||
>
|
||||
<Cell first>
|
||||
<div class="flex items-center gap-1.5">
|
||||
{#if row.count > 0}
|
||||
{@render chevron(node.key, row.open)}
|
||||
{:else}
|
||||
<span class="w-3.5 shrink-0"></span>
|
||||
{/if}
|
||||
<OwnerIcon size={14} class="text-secondary shrink-0" />
|
||||
<span class="font-semibold text-emphasis">{node.key}</span>
|
||||
<span class="text-secondary">{pluralize(row.count, 'item')}</span>
|
||||
{#if node.key.startsWith('f/')}
|
||||
<a
|
||||
href={withWorkspace(`/folders#${node.key}`)}
|
||||
target="_blank"
|
||||
class="text-secondary hover:text-emphasis opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
|
||||
aria-label={`Open ${node.key} in a new tab`}
|
||||
title={`Open ${node.key} in a new tab`}
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<ExternalLink size={12} />
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<!-- A badge is a level held on the folder or space itself; item rows show theirs as text. -->
|
||||
<Tooltip class="-my-0.5">
|
||||
<Badge
|
||||
color="gray"
|
||||
class={node.whole
|
||||
? 'border border-transparent py-0'
|
||||
: 'bg-transparent border border-dashed border-border-normal py-0'}
|
||||
>
|
||||
{node.whole ? (node.write ? 'Write' : 'Read') : 'Some items'}
|
||||
</Badge>
|
||||
{#snippet text()}{ownerExplanation(node)}{/snippet}
|
||||
</Tooltip>
|
||||
</Cell>
|
||||
<Cell last>{ownerGrant(node)}</Cell>
|
||||
</Row>
|
||||
{:else if row.type === 'subfolder'}
|
||||
<Row hoverable on:click={() => toggle(row.node.key, row.open)}>
|
||||
<Cell first>
|
||||
<div
|
||||
class="flex items-center gap-1.5"
|
||||
style="padding-left: {row.depth * 20}px"
|
||||
>
|
||||
{@render chevron(row.node.key, row.open)}
|
||||
<FolderTree size={14} class="text-secondary shrink-0" />
|
||||
<span class="font-medium text-emphasis">{row.node.name}</span>
|
||||
<span class="text-secondary">{pluralize(row.count, 'item')}</span>
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell></Cell>
|
||||
<Cell last></Cell>
|
||||
</Row>
|
||||
{:else}
|
||||
{@const item = row.item}
|
||||
{@const grants = itemGrants(item)}
|
||||
{@const href = itemLink(item.kind, item.path)}
|
||||
<tr>
|
||||
<Cell first>
|
||||
<div
|
||||
class="flex items-center gap-1.5"
|
||||
style="padding-left: {row.depth * 20}px"
|
||||
>
|
||||
<span class="w-3.5 shrink-0"></span>
|
||||
<span class="flex shrink-0" title={KIND_LABELS[item.kind] ?? item.kind}>
|
||||
<RowIcon kind={item.kind as 'script'} size={14} />
|
||||
</span>
|
||||
{#if href}
|
||||
<a
|
||||
{href}
|
||||
target="_blank"
|
||||
title={item.path}
|
||||
class="group/link inline-flex items-center gap-1 text-primary hover:underline"
|
||||
>{row.name}<ExternalLink
|
||||
size={12}
|
||||
class="opacity-0 group-hover/link:opacity-100 group-focus-visible/link:opacity-100 shrink-0"
|
||||
/></a
|
||||
>
|
||||
{:else}
|
||||
<span title={item.path}>{row.name}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell>
|
||||
<span class={levelClass(item, grants, row.owner)}
|
||||
>{item.write ? 'Write' : 'Read'}</span
|
||||
>
|
||||
</Cell>
|
||||
<Cell last>{grants.join(', ')}</Cell>
|
||||
</tr>
|
||||
{/if}
|
||||
{/each}
|
||||
</tbody>
|
||||
</DataTable>
|
||||
{:else}
|
||||
<p class="text-xs text-secondary">
|
||||
{access.items.length || access.folders.length
|
||||
? 'No item matches.'
|
||||
: `${principal} cannot read any item.`}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</Section>
|
||||
{/if}
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -2,8 +2,10 @@
|
||||
import { Button, Drawer, DrawerContent } from './common'
|
||||
import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte'
|
||||
import GroupEditor from './GroupEditor.svelte'
|
||||
import { Save } from 'lucide-svelte'
|
||||
import AccessDrawer from './AccessDrawer.svelte'
|
||||
import { Save, ShieldCheck } from 'lucide-svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { useOperatingUser } from './operatingWorkspace.svelte'
|
||||
|
||||
let {
|
||||
offset = 0,
|
||||
@@ -13,7 +15,9 @@
|
||||
onSaved?: (name: string, created: boolean) => void | Promise<void>
|
||||
} = $props()
|
||||
|
||||
const operatingUser = useOperatingUser()
|
||||
let drawer: Drawer | undefined = $state()
|
||||
let accessDrawer: AccessDrawer | undefined = $state()
|
||||
let mode: 'edit' | 'new' = $state('edit')
|
||||
let name: string = $state('')
|
||||
let canSave = $state(false)
|
||||
@@ -125,6 +129,17 @@
|
||||
{/key}
|
||||
</div>
|
||||
{#snippet actions()}
|
||||
{#if exists && (operatingUser.current?.is_admin || operatingUser.current?.is_super_admin || operatingUser.current?.groups.includes(name))}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="md"
|
||||
startIcon={{ icon: ShieldCheck }}
|
||||
title="What this group gives its members access to"
|
||||
onClick={() => accessDrawer?.open(`g/${name}`, 'group')}
|
||||
>
|
||||
Access
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
variant="accent"
|
||||
unifiedSize="md"
|
||||
@@ -139,6 +154,8 @@
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
|
||||
<AccessDrawer bind:this={accessDrawer} />
|
||||
|
||||
<!-- `alwaysPortal`: this drawer is opened from inside another drawer (the folder editor, itself
|
||||
reachable from a resource or variable form), and that outer drawer is a stacking context
|
||||
this dialog cannot climb out of on z-index alone. Left in place it paints under the drawer
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { PrincipalAccess } from '$lib/gen'
|
||||
import { buildAccessTree } from './accessTree'
|
||||
|
||||
const item = (path: string, reasons: PrincipalAccess['items'][number]['reasons']) => ({
|
||||
kind: 'script',
|
||||
path,
|
||||
write: false,
|
||||
reasons
|
||||
})
|
||||
|
||||
describe('buildAccessTree', () => {
|
||||
it('marks a folder or space whole only when it is held itself', () => {
|
||||
const tree = buildAccessTree({
|
||||
principal: 'u/alice',
|
||||
is_admin: false,
|
||||
groups: ['ops'],
|
||||
folders: [{ name: 'reporting', write: false, owner: false, via: ['g/ops'] }],
|
||||
items: [
|
||||
item('u/bob/shared_note', [{ type: 'group', group: 'ops', write: true }]),
|
||||
item('g/ops/oncall_page', [{ type: 'group_path', group: 'ops' }]),
|
||||
item('f/reporting/archive/q3_rollup', [{ type: 'folder', folder: 'reporting' }]),
|
||||
item('f/ledger/close_month', [{ type: 'group', group: 'ops', write: false }]),
|
||||
item('u/alice/scratch', [{ type: 'own' }])
|
||||
]
|
||||
})
|
||||
|
||||
expect(tree.map((n) => [n.key, n.whole])).toEqual([
|
||||
['u/alice', true],
|
||||
['f/ledger', false],
|
||||
['f/reporting', true],
|
||||
['g/ops', true],
|
||||
['u/bob', false]
|
||||
])
|
||||
expect(tree[2].subfolders.map((s) => s.key)).toEqual(['f/reporting/archive'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { PrincipalAccess } from '$lib/gen'
|
||||
|
||||
export type AccessItem = PrincipalAccess['items'][number]
|
||||
|
||||
/** A path segment under a folder or a space, like `archive` in `f/reporting/archive/q3_rollup`. */
|
||||
export interface AccessPathNode {
|
||||
/** The full path prefix, e.g. `f/reporting/archive`. */
|
||||
key: string
|
||||
name: string
|
||||
subfolders: AccessPathNode[]
|
||||
items: { item: AccessItem; name: string }[]
|
||||
}
|
||||
|
||||
/** A top-level row: a folder (`f/x`), a user's space (`u/x`) or a group's space (`g/x`). */
|
||||
export interface AccessOwnerNode extends AccessPathNode {
|
||||
/**
|
||||
* The folder or space itself is held, so every item in it is reachable, items added later
|
||||
* included. False when only some of its items are shared with the principal, one by one.
|
||||
*/
|
||||
whole: boolean
|
||||
/** The level that holding the whole folder or space gives. */
|
||||
write: boolean
|
||||
/** The `u/` or `g/` grants on the folder that reach the principal. */
|
||||
via: string[]
|
||||
/** The principal, or one of its groups, is an admin of the folder. */
|
||||
admin: boolean
|
||||
}
|
||||
|
||||
export type AccessTreeRow =
|
||||
| { type: 'owner'; node: AccessOwnerNode; depth: number; count: number; open: boolean }
|
||||
| { type: 'subfolder'; node: AccessPathNode; depth: number; count: number; open: boolean }
|
||||
| { type: 'item'; item: AccessItem; name: string; owner: AccessOwnerNode; depth: number }
|
||||
|
||||
/** Groups a principal's access by where each item lives, as the home page tree does. */
|
||||
export function buildAccessTree(access: PrincipalAccess): AccessOwnerNode[] {
|
||||
const owners = new Map<string, AccessOwnerNode>()
|
||||
const ownerNode = (key: string): AccessOwnerNode => {
|
||||
let node = owners.get(key)
|
||||
if (!node) {
|
||||
node = {
|
||||
key,
|
||||
name: key,
|
||||
whole: false,
|
||||
write: false,
|
||||
via: [],
|
||||
admin: false,
|
||||
subfolders: [],
|
||||
items: []
|
||||
}
|
||||
owners.set(key, node)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// A folder is held whole only through a grant on the folder itself. One that only shows up in
|
||||
// item paths has some of its items shared one by one, and nothing added to it later is reachable.
|
||||
for (const folder of access.folders) {
|
||||
Object.assign(ownerNode(`f/${folder.name}`), {
|
||||
whole: true,
|
||||
write: folder.write,
|
||||
via: folder.via,
|
||||
admin: folder.owner
|
||||
})
|
||||
}
|
||||
for (const item of access.items) {
|
||||
const segments = item.path.split('/')
|
||||
const owner = ownerNode(segments.slice(0, 2).join('/'))
|
||||
// The principal's own `u/` path, and the `g/` path of a group it is in, hold every item
|
||||
// under them with write. Any other user's or group's space is reached item by item.
|
||||
if (item.reasons.some((r) => r.type === 'own' || r.type === 'group_path')) {
|
||||
owner.whole = true
|
||||
owner.write = true
|
||||
}
|
||||
let parent: AccessPathNode = owner
|
||||
for (const segment of segments.slice(2, -1)) {
|
||||
let child = parent.subfolders.find((s) => s.name === segment)
|
||||
if (!child) {
|
||||
child = { key: `${parent.key}/${segment}`, name: segment, subfolders: [], items: [] }
|
||||
parent.subfolders.push(child)
|
||||
}
|
||||
parent = child
|
||||
}
|
||||
parent.items.push({ item, name: segments[segments.length - 1] })
|
||||
}
|
||||
|
||||
const rank = (node: AccessOwnerNode) =>
|
||||
node.key === access.principal
|
||||
? 0
|
||||
: node.key.startsWith('f/')
|
||||
? 1
|
||||
: node.key.startsWith('g/')
|
||||
? 2
|
||||
: 3
|
||||
const roots = [...owners.values()].sort((a, b) => rank(a) - rank(b) || a.key.localeCompare(b.key))
|
||||
roots.forEach(sortNode)
|
||||
return roots
|
||||
}
|
||||
|
||||
function sortNode(node: AccessPathNode): void {
|
||||
node.subfolders.sort((a, b) => a.name.localeCompare(b.name))
|
||||
node.items.sort((a, b) => a.name.localeCompare(b.name))
|
||||
node.subfolders.forEach(sortNode)
|
||||
}
|
||||
|
||||
export function countItems(node: AccessPathNode, matches: (item: AccessItem) => boolean): number {
|
||||
return (
|
||||
node.items.filter(({ item }) => matches(item)).length +
|
||||
node.subfolders.reduce((n, sub) => n + countItems(sub, matches), 0)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows to render, top to bottom. A filter opens every branch holding a match and drops the
|
||||
* rest; without one, every folder and space shows, a folder held whole with no items included.
|
||||
*/
|
||||
export function flattenAccessTree(
|
||||
roots: AccessOwnerNode[],
|
||||
{
|
||||
matches,
|
||||
isOpen,
|
||||
filtering
|
||||
}: {
|
||||
matches: (item: AccessItem) => boolean
|
||||
isOpen: (key: string) => boolean
|
||||
filtering: boolean
|
||||
}
|
||||
): AccessTreeRow[] {
|
||||
const rows: AccessTreeRow[] = []
|
||||
const walk = (node: AccessPathNode, owner: AccessOwnerNode, depth: number) => {
|
||||
for (const sub of node.subfolders) {
|
||||
const count = countItems(sub, matches)
|
||||
if (count === 0) continue
|
||||
const open = filtering || isOpen(sub.key)
|
||||
rows.push({ type: 'subfolder', node: sub, depth, count, open })
|
||||
if (open) walk(sub, owner, depth + 1)
|
||||
}
|
||||
for (const { item, name } of node.items) {
|
||||
if (matches(item)) rows.push({ type: 'item', item, name, owner, depth })
|
||||
}
|
||||
}
|
||||
for (const owner of roots) {
|
||||
const count = countItems(owner, matches)
|
||||
if (filtering && count === 0) continue
|
||||
const open = count > 0 && (filtering || isOpen(owner.key))
|
||||
rows.push({ type: 'owner', node: owner, depth: 0, count, open })
|
||||
if (open) walk(owner, owner, 1)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
@@ -42,8 +42,10 @@
|
||||
LogIn,
|
||||
RefreshCw,
|
||||
Users,
|
||||
ChevronDown
|
||||
ChevronDown,
|
||||
ShieldCheck
|
||||
} from 'lucide-svelte'
|
||||
import AccessDrawer from '$lib/components/AccessDrawer.svelte'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import SearchItems from '../SearchItems.svelte'
|
||||
import Cell from '../table/Cell.svelte'
|
||||
@@ -51,12 +53,14 @@
|
||||
import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte'
|
||||
import UserOffboardingModal from '$lib/components/UserOffboardingModal.svelte'
|
||||
import { isCloudHosted } from '$lib/cloud'
|
||||
import { truncate } from '$lib/utils'
|
||||
import { truncate, type Item } from '$lib/utils'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import { onDestroy, untrack } from 'svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { ArrowRightLeft, ExternalLink } from 'lucide-svelte'
|
||||
|
||||
let offboardingUser: string | undefined = $state(undefined)
|
||||
let accessDrawer: AccessDrawer | undefined = $state()
|
||||
let offboardingReassignOnly = $state(false)
|
||||
|
||||
// `role` is the member's workspace role, which `listUsers` returns but the spec's `User` omits.
|
||||
@@ -365,6 +369,90 @@
|
||||
let removeInstanceGroupConfirmedCallback: (() => void) | undefined = $state(undefined)
|
||||
let convertConfirmedCallback: (() => void) | undefined = $state(undefined)
|
||||
|
||||
function openAccess(user: User): void {
|
||||
accessDrawer?.open(
|
||||
`u/${user.username}`,
|
||||
user.is_service_account
|
||||
? 'service_account'
|
||||
: user.username === $userStore?.username
|
||||
? 'self'
|
||||
: 'user'
|
||||
)
|
||||
}
|
||||
|
||||
async function impersonate(username: string): Promise<void> {
|
||||
try {
|
||||
// Backend sets the impersonation cookie and returns the old token
|
||||
const oldToken = await UserService.impersonateServiceAccount({
|
||||
workspace: $workspaceStore ?? '',
|
||||
requestBody: { username }
|
||||
})
|
||||
if (oldToken) {
|
||||
sessionStorage.setItem('pre_impersonation_token', oldToken)
|
||||
sessionStorage.setItem('pre_impersonation_email', $userStore?.email ?? '')
|
||||
}
|
||||
window.location.href = '/'
|
||||
} catch (e) {
|
||||
sendUserToast('Failed to impersonate service account', true)
|
||||
}
|
||||
}
|
||||
|
||||
function offboard(username: string, reassignOnly: boolean): void {
|
||||
offboardingUser = username
|
||||
offboardingReassignOnly = reassignOnly
|
||||
}
|
||||
|
||||
function confirmConvert(username: string): void {
|
||||
convertConfirmedCallback = async () => {
|
||||
await convertUserToGroup(username)
|
||||
}
|
||||
}
|
||||
|
||||
const INSTANCE_GROUP_REMOVE_HINT =
|
||||
'Cannot remove users synced from instance groups. Either disable the user or remove them from the SCIM group.'
|
||||
|
||||
function rowActions(user: User): Item[] {
|
||||
const fromInstanceGroup = user.added_via?.source === 'instance_group'
|
||||
const convertible = !fromInstanceGroup && canConvertToGroup(user)
|
||||
return [
|
||||
{
|
||||
displayName: 'Access',
|
||||
icon: ShieldCheck,
|
||||
disabled: user.disabled,
|
||||
description: user.disabled ? 'Disabled: nothing runs as this user' : undefined,
|
||||
action: () => openAccess(user)
|
||||
},
|
||||
{
|
||||
displayName: 'Impersonate',
|
||||
icon: LogIn,
|
||||
hide: !(user.is_service_account && $userStore?.is_admin),
|
||||
disabled: !$enterpriseLicense,
|
||||
description: !$enterpriseLicense ? 'Requires Enterprise Edition' : undefined,
|
||||
action: () => impersonate(user.username)
|
||||
},
|
||||
{
|
||||
displayName: 'Reassign',
|
||||
icon: ArrowRightLeft,
|
||||
hide: fromInstanceGroup || convertible,
|
||||
action: () => offboard(user.username, true)
|
||||
},
|
||||
{
|
||||
displayName: 'Convert',
|
||||
hide: !convertible,
|
||||
action: () => confirmConvert(user.username)
|
||||
},
|
||||
{
|
||||
displayName: 'Remove',
|
||||
icon: UserMinus,
|
||||
type: 'delete',
|
||||
hide: convertible,
|
||||
disabled: fromInstanceGroup,
|
||||
description: fromInstanceGroup ? INSTANCE_GROUP_REMOVE_HINT : undefined,
|
||||
action: () => offboard(user.username, false)
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
// Auto-add/invite confirmation modal states
|
||||
let autoAddConfirmCallback: (() => void) | undefined = $state(undefined)
|
||||
let autoInviteDisableConfirmCallback: (() => void) | undefined = $state(undefined)
|
||||
@@ -962,87 +1050,7 @@
|
||||
/>
|
||||
</Cell>
|
||||
<Cell last actions class={index % 2 === 0 ? 'bg-surface-tertiary' : ''}>
|
||||
<div class="flex gap-1">
|
||||
{#if user.is_service_account && $userStore?.is_admin}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
startIcon={{ icon: LogIn }}
|
||||
disabled={!$enterpriseLicense}
|
||||
title={!$enterpriseLicense ? 'Requires Enterprise Edition' : undefined}
|
||||
onClick={async () => {
|
||||
try {
|
||||
// Backend sets the impersonation cookie and returns the old token
|
||||
const oldToken = await UserService.impersonateServiceAccount({
|
||||
workspace: $workspaceStore ?? '',
|
||||
requestBody: { username }
|
||||
})
|
||||
if (oldToken) {
|
||||
sessionStorage.setItem('pre_impersonation_token', oldToken)
|
||||
sessionStorage.setItem('pre_impersonation_email', $userStore?.email ?? '')
|
||||
}
|
||||
window.location.href = '/'
|
||||
} catch (e) {
|
||||
sendUserToast('Failed to impersonate service account', true)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Impersonate
|
||||
</Button>
|
||||
{/if}
|
||||
{#snippet removeUserButton(disabled: boolean)}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
destructive
|
||||
{disabled}
|
||||
onClick={() => {
|
||||
offboardingUser = username
|
||||
offboardingReassignOnly = false
|
||||
}}
|
||||
startIcon={{ icon: UserMinus }}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
{/snippet}
|
||||
|
||||
{#if added_via?.source === 'instance_group'}
|
||||
<div class="flex items-center gap-1">
|
||||
{@render removeUserButton(true)}
|
||||
<Tooltip
|
||||
>Cannot remove users synced from instance groups. Either disable the user or
|
||||
remove them from the SCIM group.</Tooltip
|
||||
>
|
||||
</div>
|
||||
{:else if canConvertToGroup(user)}
|
||||
<Button
|
||||
variant="accent"
|
||||
unifiedSize="sm"
|
||||
on:click={() => {
|
||||
convertConfirmedCallback = async () => {
|
||||
await convertUserToGroup(username)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Convert
|
||||
</Button>
|
||||
{:else}
|
||||
<div class="flex items-center gap-1">
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
offboardingUser = username
|
||||
offboardingReassignOnly = true
|
||||
}}
|
||||
startIcon={{ icon: ArrowRightLeft }}
|
||||
>
|
||||
Reassign
|
||||
</Button>
|
||||
{@render removeUserButton(false)}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<DropdownV2 items={rowActions(user)} />
|
||||
</Cell>
|
||||
</tr>
|
||||
{/each}
|
||||
@@ -1176,6 +1184,8 @@
|
||||
{/if}
|
||||
</Section>
|
||||
{/if}
|
||||
<AccessDrawer bind:this={accessDrawer} />
|
||||
|
||||
{#if offboardingUser}
|
||||
<UserOffboardingModal
|
||||
open={offboardingUser != null}
|
||||
|
||||
@@ -23,8 +23,10 @@
|
||||
PanelLeft,
|
||||
Star,
|
||||
FolderOpen,
|
||||
Users
|
||||
Users,
|
||||
ShieldCheck
|
||||
} from 'lucide-svelte'
|
||||
import AccessDrawer from '../AccessDrawer.svelte'
|
||||
import { sidebarPrefs } from './sidebarPrefs.svelte'
|
||||
import { goto } from '$lib/navigation'
|
||||
import { type Item } from '$lib/utils'
|
||||
@@ -96,6 +98,7 @@
|
||||
)
|
||||
|
||||
let deleteForkModal = $state<DeleteForkedWorkspaceModal>()
|
||||
let accessDrawer = $state<AccessDrawer>()
|
||||
|
||||
const { recent: recentChangelogs, hasNew } = readRecentChangelogs()
|
||||
let hasNewChangelogs = $state(hasNew)
|
||||
@@ -247,6 +250,17 @@
|
||||
icon: Settings,
|
||||
action: () => goto(USER_SETTINGS_HASH)
|
||||
},
|
||||
// A superadmin who is not a member has no `usr` row, so there is no access to list.
|
||||
...($userStore && !$userStore.non_member
|
||||
? [
|
||||
{
|
||||
displayName: 'My access',
|
||||
icon: ShieldCheck,
|
||||
action: () =>
|
||||
setTimeout(() => accessDrawer?.open(`u/${$userStore?.username}`, 'self'), 50)
|
||||
}
|
||||
]
|
||||
: []),
|
||||
...(!$roleCapabilities.code
|
||||
? [
|
||||
{
|
||||
@@ -407,4 +421,6 @@
|
||||
|
||||
<DeleteForkedWorkspaceModal bind:this={deleteForkModal} />
|
||||
|
||||
<AccessDrawer bind:this={accessDrawer} />
|
||||
|
||||
<DarkModeObserver bind:darkMode />
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import Row from '$lib/components/table/Row.svelte'
|
||||
import Badge from '$lib/components/common/badge/Badge.svelte'
|
||||
import { untrack } from 'svelte'
|
||||
import { page } from '$app/stores'
|
||||
import { DEMO_RESTRICTION_HINT, isDemoWorkspaceRestricted } from '$lib/cloud'
|
||||
|
||||
let restricted = $derived(
|
||||
@@ -54,6 +55,20 @@
|
||||
}
|
||||
})
|
||||
|
||||
// Deep link: #f/<name> opens that folder's drawer. The `f/` prefix keeps it apart from
|
||||
// global drawer hashes like #superadmin-settings, which a bare folder name could collide with.
|
||||
let handledHash = ''
|
||||
$effect(() => {
|
||||
const hash = $page.url.hash
|
||||
if (!hash.startsWith('#f/')) {
|
||||
handledHash = ''
|
||||
return
|
||||
}
|
||||
if (hash === handledHash || !folderEditorDrawer) return
|
||||
handledHash = hash
|
||||
folderEditorDrawer.initEdit(decodeURIComponent(hash.slice(3)))
|
||||
})
|
||||
|
||||
function computeMembers(owners: string[], extra_perms: Record<string, any>) {
|
||||
const members = new Set(owners)
|
||||
for (const [user, _] of Object.entries(extra_perms)) {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import { Button, Drawer, DrawerContent, Skeleton } from '$lib/components/common'
|
||||
import Dropdown from '$lib/components/DropdownV2.svelte'
|
||||
import GroupEditorDrawer from '$lib/components/GroupEditorDrawer.svelte'
|
||||
import AccessDrawer from '$lib/components/AccessDrawer.svelte'
|
||||
import InstanceGroupEditor from '$lib/components/InstanceGroupEditor.svelte'
|
||||
import GroupInfo from '$lib/components/GroupInfo.svelte'
|
||||
import PageHeader from '$lib/components/PageHeader.svelte'
|
||||
@@ -14,7 +15,7 @@
|
||||
import { userStore, workspaceStore, roleCapabilities } from '$lib/stores'
|
||||
import { useEditRights } from '$lib/operatorWriteRights'
|
||||
import { latestRequest } from '$lib/utils/latestRequest'
|
||||
import { Pen, Plus, Trash } from 'lucide-svelte'
|
||||
import { Pen, Plus, ShieldCheck, Trash } from 'lucide-svelte'
|
||||
import DataTable from '$lib/components/table/DataTable.svelte'
|
||||
import Head from '$lib/components/table/Head.svelte'
|
||||
import Cell from '$lib/components/table/Cell.svelte'
|
||||
@@ -32,6 +33,7 @@
|
||||
let groups: Group[] | undefined = $state(undefined)
|
||||
let instanceGroups: InstanceGroupWithWorkspaces[] | undefined = $state(undefined)
|
||||
let groupEditorDrawer: GroupEditorDrawer | undefined = $state()
|
||||
let accessDrawer: AccessDrawer | undefined = $state()
|
||||
|
||||
const groupLoads = latestRequest()
|
||||
async function loadGroups(): Promise<void> {
|
||||
@@ -61,6 +63,7 @@
|
||||
</script>
|
||||
|
||||
<GroupEditorDrawer bind:this={groupEditorDrawer} onSaved={loadGroups} />
|
||||
<AccessDrawer bind:this={accessDrawer} />
|
||||
|
||||
<Drawer bind:this={instanceGroupDrawer}>
|
||||
<DrawerContent
|
||||
@@ -122,9 +125,13 @@
|
||||
{#if groups === undefined}
|
||||
{#each new Array(4) as _}
|
||||
<tr>
|
||||
<td colspan="5">
|
||||
<Skeleton layout={[[2]]} />
|
||||
</td>
|
||||
<Cell first>
|
||||
<Skeleton layout={[[{ h: 0.75, w: 30 }], 0.25, [{ h: 0.75, w: 60 }], 0.25]} />
|
||||
</Cell>
|
||||
<Cell>
|
||||
<Skeleton layout={[[{ h: 0.75, w: 40 }]]} />
|
||||
</Cell>
|
||||
<Cell last actions />
|
||||
</tr>
|
||||
{/each}
|
||||
{:else}
|
||||
@@ -149,6 +156,16 @@
|
||||
<Cell last actions shouldStopPropagation>
|
||||
<Dropdown
|
||||
items={[
|
||||
{
|
||||
displayName: 'Access',
|
||||
icon: ShieldCheck,
|
||||
hide: !(
|
||||
$userStore?.is_admin ||
|
||||
$userStore?.is_super_admin ||
|
||||
$userStore?.groups.includes(name)
|
||||
),
|
||||
action: () => accessDrawer?.open(`g/${name}`, 'group')
|
||||
},
|
||||
{
|
||||
displayName: 'Manage group',
|
||||
icon: Pen,
|
||||
|
||||
Reference in New Issue
Block a user