mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-29 08:06:46 +00:00
feat: show what a member, group or service account can access
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b5d40c3e31
commit
8e7ea2f905
+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"
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! 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();
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.query(&[("principal", "u/test-user")])
|
||||
.header("Authorization", "Bearer SECRET_TOKEN_2")
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 403, "{}", resp.text().await?);
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.query(&[("principal", "u/test-user-2")])
|
||||
.header("Authorization", "Bearer SECRET_TOKEN_2")
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
/*
|
||||
* 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 another member's access".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" => {
|
||||
let exists = sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND 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 target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).await?;
|
||||
|
||||
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?;
|
||||
|
||||
let mut groups = target.groups;
|
||||
groups.sort();
|
||||
Ok(Json(AccessReport {
|
||||
principal,
|
||||
is_admin: false,
|
||||
groups,
|
||||
folders,
|
||||
items,
|
||||
}))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod access;
|
||||
pub mod folder_history;
|
||||
pub mod folders;
|
||||
pub mod granular_acls;
|
||||
|
||||
@@ -25026,6 +25026,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
|
||||
@@ -37020,6 +37045,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:
|
||||
|
||||
@@ -669,6 +669,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
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick"
|
||||
without any identifying data leaving the instance.
|
||||
|
||||
It currently carries 93 registered actions across thirty-six features (`ai_session`, `ai_chat`,
|
||||
It currently carries 94 registered actions across thirty-seven 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`,
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Badge, 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 RowIcon from './common/table/RowIcon.svelte'
|
||||
import { GranularAclService, type AccessReason, type PrincipalAccess } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
|
||||
type Target = 'self' | 'user' | 'service_account' | 'group'
|
||||
|
||||
const PAGE = 100
|
||||
|
||||
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)
|
||||
// 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
|
||||
drawer?.openDrawer()
|
||||
logFeatureUsage('access_view', 'opened', { key: target })
|
||||
const id = ++requestId
|
||||
try {
|
||||
const result = await GranularAclService.getPrincipalAccess({
|
||||
workspace: $workspaceStore!,
|
||||
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 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 filteredItems = $derived.by(() => {
|
||||
const q = search.trim().toLowerCase()
|
||||
return (access?.items ?? []).filter(
|
||||
(item) => (!kind || item.kind === kind) && (!q || item.path.toLowerCase().includes(q))
|
||||
)
|
||||
})
|
||||
|
||||
function reasonLabel(reason: AccessReason): string {
|
||||
switch (reason.type) {
|
||||
case 'own':
|
||||
return 'Own path'
|
||||
case 'group_path':
|
||||
return `Path of g/${reason.group}`
|
||||
case 'user':
|
||||
return `Shared with ${principal}`
|
||||
case 'group':
|
||||
return `Shared with g/${reason.group}`
|
||||
case 'folder':
|
||||
return `Folder f/${reason.folder}`
|
||||
}
|
||||
}
|
||||
|
||||
// `own` and `group_path` always grant write, so only grants that can be either say which.
|
||||
function reasonAccess(reason: AccessReason): string | undefined {
|
||||
if (reason.type === 'own' || reason.type === 'group_path') return undefined
|
||||
return reason.write ? 'write' : 'read'
|
||||
}
|
||||
|
||||
function folderVia(via: string): string {
|
||||
return via === principal ? 'Shared directly' : `Through ${via}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<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}
|
||||
<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>
|
||||
|
||||
<Section label="Folders" small>
|
||||
{#if access.folders.length}
|
||||
<DataTable size="xs">
|
||||
<Head>
|
||||
<tr>
|
||||
<Cell head first>Folder</Cell>
|
||||
<Cell head>Access</Cell>
|
||||
<Cell head last>Why</Cell>
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody class="divide-y">
|
||||
{#each access.folders as folder (folder.name)}
|
||||
<tr>
|
||||
<Cell first>f/{folder.name}</Cell>
|
||||
<Cell>{folder.write ? 'Write' : 'Read'}</Cell>
|
||||
<Cell last>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#if folder.owner}
|
||||
<Badge color="blue">Owner</Badge>
|
||||
{/if}
|
||||
{#each folder.via as via (via)}
|
||||
<Badge color="gray">{folderVia(via)}</Badge>
|
||||
{/each}
|
||||
</div>
|
||||
</Cell>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</DataTable>
|
||||
{:else}
|
||||
<p class="text-xs text-secondary">No folder is shared with {principal}.</p>
|
||||
{/if}
|
||||
</Section>
|
||||
|
||||
<Section label={`Items (${access.items.length})`} small>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex gap-2">
|
||||
<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>
|
||||
</div>
|
||||
{#if filteredItems.length}
|
||||
<DataTable
|
||||
size="xs"
|
||||
shouldLoadMore={filteredItems.length > nbDisplayed}
|
||||
loadMore={PAGE}
|
||||
on:loadMore={() => (nbDisplayed += PAGE)}
|
||||
>
|
||||
<Head>
|
||||
<tr>
|
||||
<Cell head first>Kind</Cell>
|
||||
<Cell head>Path</Cell>
|
||||
<Cell head>Access</Cell>
|
||||
<Cell head last>Why</Cell>
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody class="divide-y">
|
||||
{#each filteredItems.slice(0, nbDisplayed) as item (item.kind + ':' + item.path)}
|
||||
<tr>
|
||||
<Cell first>
|
||||
<span class="flex items-center gap-1.5">
|
||||
<RowIcon kind={item.kind as 'script'} size={14} />
|
||||
{KIND_LABELS[item.kind] ?? item.kind}
|
||||
</span>
|
||||
</Cell>
|
||||
<Cell><span class="font-mono text-2xs">{item.path}</span></Cell>
|
||||
<Cell>{item.write ? 'Write' : 'Read'}</Cell>
|
||||
<Cell last>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each item.reasons as reason, i (i)}
|
||||
{@const level = reasonAccess(reason)}
|
||||
<Badge color="gray">
|
||||
{reasonLabel(reason)}{#if level}<span class="text-secondary"
|
||||
> · {level}</span
|
||||
>{/if}
|
||||
</Badge>
|
||||
{/each}
|
||||
</div>
|
||||
</Cell>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</DataTable>
|
||||
{:else}
|
||||
<p class="text-xs text-secondary">
|
||||
{access.items.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 { userStore } from '$lib/stores'
|
||||
|
||||
let {
|
||||
offset = 0,
|
||||
@@ -16,6 +18,7 @@
|
||||
} = $props()
|
||||
|
||||
let drawer: Drawer | undefined = $state()
|
||||
let accessDrawer: AccessDrawer | undefined = $state()
|
||||
let mode: 'edit' | 'new' = $state('edit')
|
||||
let name: string = $state('')
|
||||
let canSave = $state(false)
|
||||
@@ -128,6 +131,17 @@
|
||||
{/key}
|
||||
</div>
|
||||
{#snippet actions()}
|
||||
{#if exists && ($userStore?.is_admin || $userStore?.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"
|
||||
@@ -142,6 +156,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
|
||||
|
||||
@@ -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 />
|
||||
|
||||
Reference in New Issue
Block a user