mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-04 00:06:39 +00:00
feat: grant and remove access from the access view
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
8e7ea2f905
commit
19d20dacf6
-30
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -18,14 +18,20 @@ use windmill_api_auth::ApiAuthed;
|
||||
use windmill_common::{
|
||||
auth::fetch_authed_from_permissioned_as,
|
||||
db::UserDB,
|
||||
error::{Error, JsonResult},
|
||||
error::{Error, JsonResult, Result},
|
||||
workspaces::{check_operator_can_manage, ManageKind},
|
||||
DB,
|
||||
};
|
||||
|
||||
pub fn workspaced_service() -> Router {
|
||||
Router::new().route("/get", get(get_access))
|
||||
Router::new()
|
||||
.route("/get", get(get_access))
|
||||
.route("/browse_folders", get(browse_folders))
|
||||
.route("/browse_items", get(browse_items))
|
||||
}
|
||||
|
||||
const BROWSE_PAGE: i64 = 100;
|
||||
|
||||
/// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on
|
||||
/// purpose: they are test data attached to an item, not something access is granted to.
|
||||
const ITEM_TABLES: [(&str, &str, &str); 17] = [
|
||||
@@ -74,6 +80,12 @@ struct FolderAccess {
|
||||
owner: bool,
|
||||
/// The `extra_perms` keys (`u/<user>` or `g/<group>`) that grant the folder.
|
||||
via: Vec<String>,
|
||||
/// The principal's own entry in `extra_perms`: absent when none, false for read, true for write.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
grant: Option<bool>,
|
||||
/// Why the caller cannot change the principal's own entry. Set only where there is one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -82,6 +94,9 @@ struct ItemAccess {
|
||||
path: String,
|
||||
write: bool,
|
||||
reasons: Vec<Reason>,
|
||||
/// Why the caller cannot change the principal's own grant. Set only where there is one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -175,10 +190,32 @@ impl From<ItemRow> for ItemAccess {
|
||||
*write
|
||||
}
|
||||
});
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons }
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons, blocked: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits `u/<user>` or `g/<group>` and refuses callers who may not look at that principal.
|
||||
fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a str, &'a str)> {
|
||||
let (prefix, name) = principal
|
||||
.split_once('/')
|
||||
.filter(|(prefix, name)| matches!(*prefix, "u" | "g") && !name.is_empty())
|
||||
.ok_or_else(|| Error::BadRequest("principal must be u/<user> or g/<group>".into()))?;
|
||||
|
||||
// Another principal's list names paths the caller may not be able to read. A group's reach is
|
||||
// contained in each member's, so its members may see it.
|
||||
let allowed = authed.is_admin
|
||||
|| match prefix {
|
||||
"u" => name == authed.username,
|
||||
_ => authed.groups.iter().any(|g| g == name),
|
||||
};
|
||||
if !allowed {
|
||||
return Err(Error::PermissionDenied(
|
||||
"only workspace admins can view another member's access".into(),
|
||||
));
|
||||
}
|
||||
Ok((prefix, name))
|
||||
}
|
||||
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
@@ -186,24 +223,7 @@ async fn get_access(
|
||||
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 (prefix, name) = check_principal(&authed, &principal)?;
|
||||
|
||||
let email = match prefix {
|
||||
"u" => {
|
||||
@@ -268,39 +288,54 @@ async fn get_access(
|
||||
.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!\"
|
||||
let mut via = sqlx::query_as::<_, (String, Vec<String>, Option<bool>)>(
|
||||
"SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k),
|
||||
(extra_perms ->> $4)::boolean
|
||||
FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
&w_id,
|
||||
&folder_names,
|
||||
&perms
|
||||
)
|
||||
.bind(&w_id)
|
||||
.bind(&folder_names)
|
||||
.bind(&perms)
|
||||
.bind(&principal)
|
||||
.fetch_all(&db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.name, r.via))
|
||||
.map(|(name, via, grant)| (name, (via, grant)))
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
let mut folders = target
|
||||
.folders
|
||||
.iter()
|
||||
.map(|(name, write, owner)| FolderAccess {
|
||||
name: name.clone(),
|
||||
write: *write,
|
||||
owner: *owner,
|
||||
via: via.remove(name).unwrap_or_default(),
|
||||
.map(|(name, write, owner)| {
|
||||
let (via, grant) = via.remove(name).unwrap_or_default();
|
||||
// An owner keeps write whatever its entry says, so there is nothing to change.
|
||||
let blocked = (grant.is_some() && !*owner && !windmill_api_auth::is_owner(&authed, name))
|
||||
.then(|| folder_blocked(name));
|
||||
FolderAccess { name: name.clone(), write: *write, owner: *owner, via, grant, blocked }
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
folders.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
|
||||
let mut tx = user_db.begin(&target).await?;
|
||||
let items = sqlx::query_as::<_, ItemRow>(&items_query())
|
||||
let rows = sqlx::query_as::<_, ItemRow>(&items_query())
|
||||
.bind(&w_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(ItemAccess::from)
|
||||
.collect();
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let denied = manage_denied(&db, &w_id, &authed).await;
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let direct = match prefix {
|
||||
"u" => r.user_grant.is_some(),
|
||||
_ => r.group_read.iter().any(|g| g == name),
|
||||
};
|
||||
let mut item = ItemAccess::from(r);
|
||||
if direct {
|
||||
item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path);
|
||||
}
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut groups = target.groups;
|
||||
groups.sort();
|
||||
@@ -312,3 +347,170 @@ async fn get_access(
|
||||
items,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
struct BrowseFolder {
|
||||
name: String,
|
||||
/// The principal's own entry in the folder's `extra_perms`: absent, read (false) or write.
|
||||
grant: Option<bool>,
|
||||
/// Owners always keep write; `acls/add` refuses to lower it.
|
||||
target_owner: bool,
|
||||
#[sqlx(skip)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
struct BrowseItem {
|
||||
kind: String,
|
||||
path: String,
|
||||
grant: Option<bool>,
|
||||
#[sqlx(skip)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BrowseItems {
|
||||
items: Vec<BrowseItem>,
|
||||
has_more: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct BrowseItemsQuery {
|
||||
principal: String,
|
||||
/// Only paths starting with this, e.g. `f/billing/` or `u/alice/`.
|
||||
prefix: Option<String>,
|
||||
kind: Option<String>,
|
||||
search: Option<String>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
/// Why the caller cannot change grants on `path`, mirroring the checks `acls/add` makes.
|
||||
fn grant_blocked(authed: &ApiAuthed, path: &str) -> Option<String> {
|
||||
if authed.is_admin {
|
||||
return None;
|
||||
}
|
||||
let mut parts = path.splitn(3, '/');
|
||||
match (parts.next(), parts.next()) {
|
||||
(Some("u"), Some(owner)) if owner == authed.username => None,
|
||||
(Some("u"), Some(owner)) => {
|
||||
Some(format!("Only u/{owner} and workspace admins can share it"))
|
||||
}
|
||||
(Some("f"), Some(folder)) if windmill_api_auth::is_owner(authed, folder) => None,
|
||||
(Some("f"), Some(folder)) => Some(folder_blocked(folder)),
|
||||
_ => Some("Only workspace admins can share items under g/".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn folder_blocked(folder: &str) -> String {
|
||||
format!("Only workspace admins and owners of f/{folder} can share it")
|
||||
}
|
||||
|
||||
async fn browse_folders(
|
||||
authed: ApiAuthed,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<Vec<BrowseFolder>> {
|
||||
check_principal(&authed, &principal)?;
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let mut folders = sqlx::query_as::<_, BrowseFolder>(
|
||||
"SELECT name, (extra_perms ->> $2)::boolean AS \"grant\", $2 = ANY(owners) AS target_owner
|
||||
FROM folder WHERE workspace_id = $1 ORDER BY name",
|
||||
)
|
||||
.bind(&w_id)
|
||||
.bind(&principal)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
for folder in &mut folders {
|
||||
if !windmill_api_auth::is_owner(&authed, &folder.name) {
|
||||
folder.blocked = Some(folder_blocked(&folder.name));
|
||||
}
|
||||
}
|
||||
Ok(Json(folders))
|
||||
}
|
||||
|
||||
async fn browse_items(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(q): Query<BrowseItemsQuery>,
|
||||
) -> JsonResult<BrowseItems> {
|
||||
check_principal(&authed, &q.principal)?;
|
||||
let tables = ITEM_TABLES
|
||||
.iter()
|
||||
.filter(|(kind, ..)| q.kind.as_deref().map_or(true, |k| k == *kind))
|
||||
.collect::<Vec<_>>();
|
||||
if tables.is_empty() {
|
||||
return Err(Error::BadRequest("unknown kind".into()));
|
||||
}
|
||||
// SAFETY: table names and filters come from the `ITEM_TABLES` constant, never from the request.
|
||||
let union = tables
|
||||
.iter()
|
||||
.map(|(kind, table, filter)| {
|
||||
format!(
|
||||
"SELECT '{kind}'::text AS kind, path::text AS path, (extra_perms ->> $2)::boolean AS \"grant\"
|
||||
FROM {table} WHERE workspace_id = $1 {filter}"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" UNION ALL ");
|
||||
let sql = format!(
|
||||
"SELECT kind, path, \"grant\" FROM ({union}) i
|
||||
WHERE ($3::text IS NULL OR starts_with(path, $3))
|
||||
AND ($4::text IS NULL OR strpos(lower(path), lower($4)) > 0)
|
||||
ORDER BY path, kind LIMIT $5 OFFSET $6"
|
||||
);
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let mut items = sqlx::query_as::<_, BrowseItem>(&sql)
|
||||
.bind(&w_id)
|
||||
.bind(&q.principal)
|
||||
.bind(q.prefix.as_deref().filter(|p| !p.is_empty()))
|
||||
.bind(q.search.as_deref().map(str::trim).filter(|s| !s.is_empty()))
|
||||
.bind(BROWSE_PAGE + 1)
|
||||
.bind(q.offset.unwrap_or(0).max(0))
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let has_more = items.len() as i64 > BROWSE_PAGE;
|
||||
items.truncate(BROWSE_PAGE as usize);
|
||||
|
||||
let denied = manage_denied(&db, &w_id, &authed).await;
|
||||
for item in &mut items {
|
||||
item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path);
|
||||
}
|
||||
Ok(Json(BrowseItems { items, has_more }))
|
||||
}
|
||||
|
||||
/// Operators may be barred from managing schedules and triggers, `/acls` included.
|
||||
async fn manage_denied(db: &DB, w_id: &str, authed: &ApiAuthed) -> Vec<(ManageKind, String)> {
|
||||
let mut denied = vec![];
|
||||
if !authed.is_admin {
|
||||
for kind in [ManageKind::Schedules, ManageKind::Triggers] {
|
||||
if let Err(e) = check_operator_can_manage(db, w_id, authed, kind).await {
|
||||
denied.push((kind, e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
denied
|
||||
}
|
||||
|
||||
/// Why the caller cannot change grants on this item: the operator gate first, then the path.
|
||||
fn item_blocked(
|
||||
authed: &ApiAuthed,
|
||||
denied: &[(ManageKind, String)],
|
||||
kind: &str,
|
||||
path: &str,
|
||||
) -> Option<String> {
|
||||
let manage_kind = match kind {
|
||||
"schedule" => Some(ManageKind::Schedules),
|
||||
k if k.ends_with("_trigger") => Some(ManageKind::Triggers),
|
||||
_ => None,
|
||||
};
|
||||
manage_kind
|
||||
.and_then(|mk| denied.iter().find(|(k, _)| *k == mk).map(|(_, e)| e.clone()))
|
||||
.or_else(|| grant_blocked(authed, path))
|
||||
}
|
||||
|
||||
@@ -25051,6 +25051,102 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/PrincipalAccess"
|
||||
|
||||
/w/{workspace}/access/browse_folders:
|
||||
get:
|
||||
summary: list the folders the caller can read, with the principal's direct grant on each
|
||||
operationId: browseAccessFolders
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: principal
|
||||
description: "`u/<username>` or `g/<group>`"
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: folders
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
grant:
|
||||
description: the principal's entry in the folder's extra_perms; absent when none, false for read, true for write
|
||||
type: boolean
|
||||
nullable: true
|
||||
target_owner:
|
||||
type: boolean
|
||||
blocked:
|
||||
description: why the caller cannot change this grant
|
||||
type: string
|
||||
required: [name, target_owner]
|
||||
|
||||
/w/{workspace}/access/browse_items:
|
||||
get:
|
||||
summary: list items the caller can read, with the principal's direct grant on each
|
||||
operationId: browseAccessItems
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: principal
|
||||
description: "`u/<username>` or `g/<group>`"
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
- name: prefix
|
||||
description: only paths starting with this, e.g. `f/billing/`
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: kind
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: search
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: offset
|
||||
in: query
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
description: a page of 100 items
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
path:
|
||||
type: string
|
||||
grant:
|
||||
type: boolean
|
||||
nullable: true
|
||||
blocked:
|
||||
description: why the caller cannot change this grant
|
||||
type: string
|
||||
required: [kind, path]
|
||||
has_more:
|
||||
type: boolean
|
||||
required: [items, has_more]
|
||||
|
||||
/w/{workspace}/acls/get/{kind}/{path}:
|
||||
get:
|
||||
summary: get granular acls
|
||||
@@ -37072,6 +37168,12 @@ components:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
grant:
|
||||
description: the principal's own entry on the folder; absent when none, false for read, true for write
|
||||
type: boolean
|
||||
blocked:
|
||||
description: why the caller cannot change the principal's own entry; set only where there is one
|
||||
type: string
|
||||
required: [name, write, owner, via]
|
||||
items:
|
||||
type: array
|
||||
@@ -37088,6 +37190,9 @@ components:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/AccessReason"
|
||||
blocked:
|
||||
description: why the caller cannot change the principal's own grant; set only where there is one
|
||||
type: string
|
||||
required: [kind, path, write, reasons]
|
||||
required: [principal, is_admin, groups, folders, items]
|
||||
|
||||
|
||||
@@ -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 94 registered actions across thirty-seven features (`access_view`, `ai_session`, `ai_chat`,
|
||||
It currently carries 95 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`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Badge, Drawer, DrawerContent, Section, Skeleton } from './common'
|
||||
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'
|
||||
@@ -8,32 +8,22 @@
|
||||
import RowIcon from './common/table/RowIcon.svelte'
|
||||
import { GranularAclService, type AccessReason, type PrincipalAccess } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import type { Item } from '$lib/utils'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { Lock, Plus } from 'lucide-svelte'
|
||||
import Tooltip from './meltComponents/Tooltip.svelte'
|
||||
import Popover from './meltComponents/Popover.svelte'
|
||||
import DropdownV2 from './DropdownV2.svelte'
|
||||
import AddNeededAccess from './access/AddNeededAccess.svelte'
|
||||
import GrantNavigator, { navigatorMaxHeight } from './access/GrantNavigator.svelte'
|
||||
import { KIND_LABELS, setGrant, type GrantLevel } from './access/access'
|
||||
import type { RunnableKind } from './access/detectNeeds'
|
||||
|
||||
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()
|
||||
@@ -41,6 +31,10 @@
|
||||
let search = $state('')
|
||||
let kind: string | undefined = $state()
|
||||
let nbDisplayed = $state(PAGE)
|
||||
let grantOpen = $state(false)
|
||||
let grantPopover: Popover | undefined = $state()
|
||||
let grantAnchor: HTMLElement | undefined = $state()
|
||||
let needsOf: { kind: RunnableKind; path: string } | undefined = $state()
|
||||
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
|
||||
let requestId = 0
|
||||
|
||||
@@ -51,13 +45,19 @@
|
||||
search = ''
|
||||
kind = undefined
|
||||
nbDisplayed = PAGE
|
||||
grantOpen = false
|
||||
needsOf = undefined
|
||||
drawer?.openDrawer()
|
||||
logFeatureUsage('access_view', 'opened', { key: target })
|
||||
await reload()
|
||||
}
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
const id = ++requestId
|
||||
try {
|
||||
const result = await GranularAclService.getPrincipalAccess({
|
||||
workspace: $workspaceStore!,
|
||||
principal: nextPrincipal
|
||||
principal
|
||||
})
|
||||
if (id === requestId) access = result
|
||||
} catch (e) {
|
||||
@@ -65,6 +65,74 @@
|
||||
}
|
||||
}
|
||||
|
||||
function setGrantOpen(next: boolean) {
|
||||
if (next) placeGrantPopover()
|
||||
grantOpen = next
|
||||
if (next) logFeatureUsage('access_view', 'grant_opened')
|
||||
}
|
||||
|
||||
// The side is picked once, for the navigator's tallest height: melt fits the popover to the room
|
||||
// on the side it first lands on, so a list that grows later would never flip on its own.
|
||||
function placeGrantPopover() {
|
||||
if (!grantAnchor) return
|
||||
const rect = grantAnchor.getBoundingClientRect()
|
||||
const gutter = 8
|
||||
const spaceBelow = window.innerHeight - rect.bottom - gutter
|
||||
const spaceAbove = rect.top - gutter
|
||||
const below = navigatorMaxHeight() <= spaceBelow || spaceBelow >= spaceAbove
|
||||
grantPopover?.updatePositioning({
|
||||
placement: below ? 'bottom-end' : 'top-end',
|
||||
strategy: 'absolute',
|
||||
gutter,
|
||||
overflowPadding: 16,
|
||||
flip: false,
|
||||
fitViewport: true,
|
||||
overlap: false
|
||||
})
|
||||
}
|
||||
|
||||
function findReads(kind: RunnableKind, path: string) {
|
||||
grantOpen = false
|
||||
needsOf = { kind, path }
|
||||
}
|
||||
|
||||
/** The principal's own entry on an item: `true` for write, `false` for read. */
|
||||
function ownItemGrant(item: PrincipalAccess['items'][number]): boolean | undefined {
|
||||
const reason = item.reasons.find((r) =>
|
||||
isGroup ? r.type === 'group' && r.group === name : r.type === 'user'
|
||||
)
|
||||
return reason ? !!reason.write : undefined
|
||||
}
|
||||
|
||||
async function changeGrant(kind: string, path: string, level: GrantLevel) {
|
||||
try {
|
||||
await setGrant($workspaceStore!, kind, path, principal, level)
|
||||
} catch (e) {
|
||||
const what = kind === 'folder' ? `f/${path}` : path
|
||||
sendUserToast(`Could not change access to ${what}: ${e?.body ?? e}`, true)
|
||||
}
|
||||
await reload()
|
||||
}
|
||||
|
||||
/** `current` is the grant's level: `true` for write, `false` for read. */
|
||||
function grantActions(kind: string, path: string, current: boolean): Item[] {
|
||||
return [
|
||||
{
|
||||
displayName: 'Read',
|
||||
disabled: current === false,
|
||||
action: () => changeGrant(kind, path, 'read')
|
||||
},
|
||||
{
|
||||
displayName: 'Write',
|
||||
disabled: current === true,
|
||||
action: () => changeGrant(kind, path, 'write')
|
||||
},
|
||||
{ displayName: 'Remove', type: 'delete', action: () => changeGrant(kind, path, 'none') }
|
||||
]
|
||||
}
|
||||
|
||||
const reads = $derived(new Set((access?.items ?? []).map((i) => `${i.kind}:${i.path}`)))
|
||||
|
||||
const name = $derived(principal.slice(2))
|
||||
const isGroup = $derived(principal.startsWith('g/'))
|
||||
|
||||
@@ -110,6 +178,17 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet grantMenu(kind: string, path: string, current: boolean, blocked: string | undefined)}
|
||||
{#if blocked}
|
||||
<Tooltip>
|
||||
<Lock size={14} class="text-secondary" aria-label={blocked} />
|
||||
{#snippet text()}{blocked}{/snippet}
|
||||
</Tooltip>
|
||||
{:else}
|
||||
<DropdownV2 items={grantActions(kind, path, current)} />
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
<Drawer bind:this={drawer} size="1000px">
|
||||
<DrawerContent title={`Access of ${principal}`} on:close={() => drawer?.closeDrawer()}>
|
||||
<div class="flex flex-col gap-6">
|
||||
@@ -151,7 +230,8 @@
|
||||
<tr>
|
||||
<Cell head first>Folder</Cell>
|
||||
<Cell head>Access</Cell>
|
||||
<Cell head last>Why</Cell>
|
||||
<Cell head>Why</Cell>
|
||||
<Cell head last />
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody class="divide-y">
|
||||
@@ -159,7 +239,7 @@
|
||||
<tr>
|
||||
<Cell first>f/{folder.name}</Cell>
|
||||
<Cell>{folder.write ? 'Write' : 'Read'}</Cell>
|
||||
<Cell last>
|
||||
<Cell>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#if folder.owner}
|
||||
<Badge color="blue">Owner</Badge>
|
||||
@@ -169,6 +249,11 @@
|
||||
{/each}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell last>
|
||||
{#if !folder.owner && folder.grant != undefined}
|
||||
{@render grantMenu('folder', folder.name, folder.grant, folder.blocked)}
|
||||
{/if}
|
||||
</Cell>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
@@ -179,7 +264,54 @@
|
||||
</Section>
|
||||
|
||||
<Section label={`Items (${access.items.length})`} small>
|
||||
{#snippet action()}
|
||||
<div bind:this={grantAnchor}>
|
||||
<Popover
|
||||
bind:this={grantPopover}
|
||||
placement="bottom-end"
|
||||
usePointerDownOutside
|
||||
disableFocusTrap
|
||||
closeOnOtherPopoverOpen
|
||||
bind:isOpen={() => grantOpen, setGrantOpen}
|
||||
openFocus="[data-workspace-picker-search]"
|
||||
contentClasses="flex flex-col overflow-hidden"
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
nonCaptureEvent
|
||||
startIcon={{ icon: Plus }}
|
||||
>
|
||||
Grant
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
{#if access}
|
||||
<GrantNavigator
|
||||
{principal}
|
||||
{access}
|
||||
onGranted={reload}
|
||||
onFindReads={findReads}
|
||||
/>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Popover>
|
||||
</div>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-2">
|
||||
{#if needsOf}
|
||||
{#key `${needsOf.kind}:${needsOf.path}`}
|
||||
<AddNeededAccess
|
||||
{principal}
|
||||
kind={needsOf.kind}
|
||||
path={needsOf.path}
|
||||
{reads}
|
||||
onGranted={reload}
|
||||
onClose={() => (needsOf = undefined)}
|
||||
/>
|
||||
{/key}
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<TextInput
|
||||
bind:value={search}
|
||||
@@ -209,11 +341,13 @@
|
||||
<Cell head first>Kind</Cell>
|
||||
<Cell head>Path</Cell>
|
||||
<Cell head>Access</Cell>
|
||||
<Cell head last>Why</Cell>
|
||||
<Cell head>Why</Cell>
|
||||
<Cell head last />
|
||||
</tr>
|
||||
</Head>
|
||||
<tbody class="divide-y">
|
||||
{#each filteredItems.slice(0, nbDisplayed) as item (item.kind + ':' + item.path)}
|
||||
{@const own = ownItemGrant(item)}
|
||||
<tr>
|
||||
<Cell first>
|
||||
<span class="flex items-center gap-1.5">
|
||||
@@ -223,7 +357,7 @@
|
||||
</Cell>
|
||||
<Cell><span class="font-mono text-2xs">{item.path}</span></Cell>
|
||||
<Cell>{item.write ? 'Write' : 'Read'}</Cell>
|
||||
<Cell last>
|
||||
<Cell>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each item.reasons as reason, i (i)}
|
||||
{@const level = reasonAccess(reason)}
|
||||
@@ -235,6 +369,11 @@
|
||||
{/each}
|
||||
</div>
|
||||
</Cell>
|
||||
<Cell last>
|
||||
{#if own !== undefined}
|
||||
{@render grantMenu(item.kind, item.path, own, item.blocked)}
|
||||
{/if}
|
||||
</Cell>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
|
||||
@@ -573,7 +573,7 @@ leaves and ignores the current scope.
|
||||
{#if leafBadge || leafAction}
|
||||
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
|
||||
side by side or shifting the row as one replaces the other. -->
|
||||
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
|
||||
<div class="shrink-0 min-w-[4.5rem] grid justify-items-end items-center pl-2">
|
||||
{#if action}
|
||||
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
|
||||
visibility both fades with opacity and keeps the button out of the tab
|
||||
@@ -583,7 +583,7 @@ leaves and ignores the current scope.
|
||||
twMerged with the button's own `flex`, which drops a conflicting
|
||||
display and leaves it showing beside the badge. -->
|
||||
<div
|
||||
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
|
||||
class="col-start-1 row-start-1 whitespace-nowrap invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
|
||||
>
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Button, Skeleton } from '$lib/components/common'
|
||||
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { Info, X } from 'lucide-svelte'
|
||||
import { setGrant } from './access'
|
||||
import { detectNeeds, type Needs, type RunnableKind } from './detectNeeds'
|
||||
|
||||
let {
|
||||
principal,
|
||||
kind,
|
||||
path,
|
||||
reads,
|
||||
onGranted,
|
||||
onClose
|
||||
}: {
|
||||
principal: string
|
||||
kind: RunnableKind
|
||||
path: string
|
||||
/** `kind:path` of every item the principal already reads, through any grant. */
|
||||
reads: Set<string>
|
||||
onGranted: () => void
|
||||
onClose: () => void
|
||||
} = $props()
|
||||
|
||||
let needs: Needs | undefined = $state()
|
||||
let error: string | undefined = $state()
|
||||
let selected: Record<string, boolean> = $state({})
|
||||
let results: Record<string, string> = $state({})
|
||||
let granting = $state(false)
|
||||
|
||||
// The host keys this component on the runnable, so it detects once per runnable.
|
||||
detectNeeds($workspaceStore!, kind, path)
|
||||
.then((found) => {
|
||||
needs = found
|
||||
selected = Object.fromEntries(
|
||||
found.items.map((i) => [`${i.kind}:${i.path}`, !reads.has(`${i.kind}:${i.path}`)])
|
||||
)
|
||||
})
|
||||
.catch((e) => (error = `${e?.body ?? e}`))
|
||||
|
||||
async function grant() {
|
||||
if (!needs) return
|
||||
granting = true
|
||||
for (const item of needs.items) {
|
||||
const key = `${item.kind}:${item.path}`
|
||||
if (!selected[key]) continue
|
||||
try {
|
||||
await setGrant($workspaceStore!, item.kind, item.path, principal, 'read')
|
||||
results[key] = 'Granted'
|
||||
selected[key] = false
|
||||
} catch (e) {
|
||||
results[key] = `${e?.body ?? e}`
|
||||
}
|
||||
}
|
||||
granting = false
|
||||
onGranted()
|
||||
}
|
||||
|
||||
const selectedCount = $derived(Object.values(selected).filter(Boolean).length)
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-3 rounded-md border p-3">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="flex flex-col gap-0.5 min-w-0">
|
||||
<span class="text-xs font-semibold text-emphasis truncate">What {path} reads</span>
|
||||
<span class="text-2xs text-secondary">
|
||||
The resources and variables it reads when it runs, so {principal} can run it. The scripts and
|
||||
flows it calls need no grant.
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
title="Dismiss"
|
||||
onClick={onClose}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<Alert type="error" size="xs" title="Could not read {path}">{error}</Alert>
|
||||
{:else if !needs}
|
||||
<Skeleton layout={[[2], 0.5, [2]]} />
|
||||
{:else}
|
||||
{#if needs.items.length}
|
||||
<div class="flex flex-col divide-y border rounded-md">
|
||||
{#each needs.items as item (item.kind + ':' + item.path)}
|
||||
{@const key = `${item.kind}:${item.path}`}
|
||||
{@const already = reads.has(key)}
|
||||
<label class="flex items-start gap-2 px-3 py-1.5 text-xs">
|
||||
<Checkbox
|
||||
class="mt-0.5"
|
||||
checked={selected[key]}
|
||||
disabled={already || granting}
|
||||
onChange={() => (selected[key] = !selected[key])}
|
||||
/>
|
||||
<span class="flex flex-col grow min-w-0">
|
||||
<span class="font-mono text-2xs text-emphasis truncate">{item.path}</span>
|
||||
<span class="text-2xs text-secondary truncate">
|
||||
{item.kind === 'resource' ? 'Resource' : 'Variable'}, read by {item.sources.join(
|
||||
', '
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<span class="text-2xs text-secondary shrink-0">
|
||||
{results[key] ?? (already ? 'Already reads it' : 'Read')}
|
||||
</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-xs text-secondary">No resource or variable found in {path}.</p>
|
||||
{/if}
|
||||
{#if needs.others.length}
|
||||
<Alert type="info" size="xs" title="Also used, not granted here">
|
||||
{needs.others.map((o) => `${o.kind} ${o.path}`).join(', ')}. Access to these is set on the
|
||||
storage or data table itself.
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if needs.errors.length}
|
||||
<Alert type="warning" size="xs" title="Some of it could not be read">
|
||||
{needs.errors.join('; ')}
|
||||
</Alert>
|
||||
{/if}
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="flex items-center gap-1 text-2xs text-secondary">
|
||||
<Info size={12} class="shrink-0" />
|
||||
A path the code builds while it runs can't be found. Grant it with "Grant".
|
||||
</span>
|
||||
<Button
|
||||
variant="accent"
|
||||
unifiedSize="sm"
|
||||
disabled={selectedCount === 0}
|
||||
loading={granting}
|
||||
onClick={grant}
|
||||
>
|
||||
Grant read on {selectedCount}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,259 @@
|
||||
<!--
|
||||
@component
|
||||
The access view's "+ Grant" list: the caller's own `u/` folder and every folder, with their items.
|
||||
Picking a row grants the principal read on it; the "All of f/x" row grants the whole folder.
|
||||
-->
|
||||
<script module lang="ts">
|
||||
/** The navigator's tallest height, `max-h-[min(420px,60vh)]` below, for its host to place it. */
|
||||
export function navigatorMaxHeight(): number {
|
||||
return Math.min(420, window.innerHeight * 0.6)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import DrillPicker from '$lib/components/DrillPicker.svelte'
|
||||
import type { DrillLeaf, DrillNode } from '$lib/components/drillPicker'
|
||||
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
|
||||
import {
|
||||
GranularAclService,
|
||||
type BrowseAccessFoldersResponse,
|
||||
type BrowseAccessItemsResponse,
|
||||
type PrincipalAccess
|
||||
} from '$lib/gen'
|
||||
import { userStore, workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { debounce } from '$lib/utils'
|
||||
import { Folder, ScanSearch, User, Users } from 'lucide-svelte'
|
||||
import { setGrant } from './access'
|
||||
import type { RunnableKind } from './detectNeeds'
|
||||
|
||||
type Row = BrowseAccessItemsResponse['items'][number]
|
||||
/** `kind` `folder` is the "All of f/x" row, its `path` the folder name. */
|
||||
type Leaf = Row & { owner?: boolean }
|
||||
|
||||
let {
|
||||
principal,
|
||||
access,
|
||||
onGranted,
|
||||
onFindReads
|
||||
}: {
|
||||
principal: string
|
||||
access: PrincipalAccess
|
||||
onGranted: () => void
|
||||
onFindReads: (kind: RunnableKind, path: string) => void
|
||||
} = $props()
|
||||
|
||||
const own = $derived(`u/${$userStore?.username}`)
|
||||
|
||||
let folders: BrowseAccessFoldersResponse | undefined = $state()
|
||||
/** Rows by top-level branch (`u/alice`, `f/billing`), then by `kind:path`. */
|
||||
let rows: Record<string, Record<string, Row>> = $state({})
|
||||
let loading: Record<string, boolean> = $state({})
|
||||
const loaded = new Set<string>()
|
||||
|
||||
function branchOf(path: string): string {
|
||||
return path.split('/', 2).join('/')
|
||||
}
|
||||
|
||||
function merge(items: Row[]) {
|
||||
for (const item of items) {
|
||||
const branch = branchOf(item.path)
|
||||
rows[branch] ??= {}
|
||||
rows[branch][`${item.kind}:${item.path}`] = item
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFolders() {
|
||||
try {
|
||||
folders = await GranularAclService.browseAccessFolders({
|
||||
workspace: $workspaceStore!,
|
||||
principal
|
||||
})
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not load folders: ${e?.body ?? e}`, true)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBranch(branch: string) {
|
||||
if (loaded.has(branch)) return
|
||||
loaded.add(branch)
|
||||
loading[branch] = true
|
||||
try {
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const page = await GranularAclService.browseAccessItems({
|
||||
workspace: $workspaceStore!,
|
||||
principal,
|
||||
prefix: `${branch}/`,
|
||||
offset
|
||||
})
|
||||
merge(page.items)
|
||||
if (!page.has_more) break
|
||||
offset += page.items.length
|
||||
}
|
||||
} catch (e) {
|
||||
loaded.delete(branch)
|
||||
sendUserToast(`Could not load ${branch}: ${e?.body ?? e}`, true)
|
||||
} finally {
|
||||
loading[branch] = false
|
||||
}
|
||||
}
|
||||
|
||||
// The picker searches only the rows it holds, so matches anywhere are fetched into the tree.
|
||||
const searchSoon = debounce(async (search: string) => {
|
||||
try {
|
||||
const page = await GranularAclService.browseAccessItems({
|
||||
workspace: $workspaceStore!,
|
||||
principal,
|
||||
search
|
||||
})
|
||||
merge(page.items)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not search: ${e?.body ?? e}`, true)
|
||||
}
|
||||
}, 250).debounced
|
||||
|
||||
loadFolders()
|
||||
|
||||
function itemLeaf(row: Row): DrillLeaf<Leaf> {
|
||||
return {
|
||||
type: 'leaf',
|
||||
key: `${row.kind}:${row.path}`,
|
||||
label: row.path.split('/').slice(2).join('/'),
|
||||
secondary: row.path,
|
||||
searchableText: row.path,
|
||||
data: row,
|
||||
disabled: !!row.blocked
|
||||
}
|
||||
}
|
||||
|
||||
function itemLeaves(branch: string): DrillLeaf<Leaf>[] {
|
||||
return Object.values(rows[branch] ?? {})
|
||||
.sort((a, b) => a.path.localeCompare(b.path) || a.kind.localeCompare(b.kind))
|
||||
.map(itemLeaf)
|
||||
}
|
||||
|
||||
const tree = $derived.by<DrillNode<Leaf>[]>(() => {
|
||||
const folderNames = new Set((folders ?? []).map((f) => `f/${f.name}`))
|
||||
const others = Object.keys(rows)
|
||||
.filter((b) => b !== own && !folderNames.has(b))
|
||||
.sort()
|
||||
return [
|
||||
{
|
||||
type: 'branch',
|
||||
key: own,
|
||||
label: own,
|
||||
icon: User,
|
||||
searchGroup: true,
|
||||
loading: loading[own],
|
||||
children: itemLeaves(own)
|
||||
},
|
||||
...(folders ?? []).map(
|
||||
(folder): DrillNode<Leaf> => ({
|
||||
type: 'branch',
|
||||
key: `f/${folder.name}`,
|
||||
label: `f/${folder.name}`,
|
||||
icon: Folder,
|
||||
searchGroup: true,
|
||||
loading: loading[`f/${folder.name}`],
|
||||
children: [
|
||||
{
|
||||
type: 'leaf',
|
||||
key: `folder:${folder.name}`,
|
||||
label: `All of f/${folder.name}`,
|
||||
searchableText: `f/${folder.name}`,
|
||||
data: {
|
||||
kind: 'folder',
|
||||
path: folder.name,
|
||||
grant: folder.grant,
|
||||
blocked: folder.blocked,
|
||||
owner: folder.target_owner
|
||||
},
|
||||
disabled: folder.target_owner || !!folder.blocked
|
||||
},
|
||||
...itemLeaves(`f/${folder.name}`)
|
||||
]
|
||||
})
|
||||
),
|
||||
// Other users' and groups' items appear once a search finds them.
|
||||
...others.map(
|
||||
(b): DrillNode<Leaf> => ({
|
||||
type: 'branch',
|
||||
key: b,
|
||||
label: b,
|
||||
icon: b.startsWith('g/') ? Users : User,
|
||||
searchGroup: true,
|
||||
children: itemLeaves(b)
|
||||
})
|
||||
)
|
||||
]
|
||||
})
|
||||
|
||||
const reaches = $derived(
|
||||
new Map([
|
||||
...access.items.map((i) => [`${i.kind}:${i.path}`, i.write] as const),
|
||||
...access.folders.map((f) => [`folder:${f.name}`, f.write] as const)
|
||||
])
|
||||
)
|
||||
|
||||
async function grant(leaf: DrillLeaf<Leaf>) {
|
||||
const row = leaf.data
|
||||
if (row.grant != undefined) return
|
||||
try {
|
||||
await setGrant($workspaceStore!, row.kind, row.path, principal, 'read')
|
||||
row.grant = false
|
||||
if (row.kind === 'folder') {
|
||||
const folder = folders?.find((f) => f.name === row.path)
|
||||
if (folder) folder.grant = false
|
||||
}
|
||||
onGranted()
|
||||
} catch (e) {
|
||||
const what = row.kind === 'folder' ? `f/${row.path}` : row.path
|
||||
sendUserToast(`Could not grant ${what}: ${e?.body ?? e}`, true)
|
||||
}
|
||||
}
|
||||
|
||||
function tooltip(leaf: DrillLeaf<Leaf>): string | undefined {
|
||||
const row = leaf.data
|
||||
if (row.owner) return `${principal} owns f/${row.path} and always keeps write`
|
||||
if (row.blocked) return row.blocked
|
||||
if (row.grant != undefined)
|
||||
return `Already granted ${row.grant ? 'write' : 'read'}: change it from the table`
|
||||
return undefined
|
||||
}
|
||||
|
||||
function isRunnable(kind: string): kind is RunnableKind {
|
||||
return kind === 'flow' || kind === 'script' || kind === 'app'
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet leafIcon(leaf: DrillLeaf<Leaf>)}
|
||||
<RowIcon kind={leaf.data.kind as 'folder'} size={12} />
|
||||
{/snippet}
|
||||
|
||||
<div class="flex flex-col max-h-[min(420px,60vh)]">
|
||||
<DrillPicker
|
||||
{tree}
|
||||
onPick={grant}
|
||||
{leafIcon}
|
||||
rootLoading={!folders}
|
||||
onScopeChange={(scope) => scope.length === 1 && loadBranch(scope[0])}
|
||||
onFilterChange={(filter) => filter.trim() && searchSoon(filter.trim())}
|
||||
rowTooltip={tooltip}
|
||||
leafBadge={(leaf) => {
|
||||
const write = reaches.get(leaf.key)
|
||||
return write === undefined
|
||||
? undefined
|
||||
: { label: write ? 'Writes' : 'Reads', color: write ? 'blue' : 'gray' }
|
||||
}}
|
||||
leafAction={(leaf) =>
|
||||
isRunnable(leaf.data.kind)
|
||||
? {
|
||||
icon: ScanSearch,
|
||||
label: 'What it reads',
|
||||
title: `Grant what ${leaf.data.path} reads when it runs`,
|
||||
run: () => onFindReads(leaf.data.kind as RunnableKind, leaf.data.path)
|
||||
}
|
||||
: undefined}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,50 @@
|
||||
import { GranularAclService } from '$lib/gen'
|
||||
|
||||
export type GrantLevel = 'none' | 'read' | 'write'
|
||||
|
||||
type AclKind = Parameters<typeof GranularAclService.addGranularAcls>[0]['kind']
|
||||
|
||||
export 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'
|
||||
}
|
||||
|
||||
/** Sets `principal`'s own entry on an item or folder (`kind` `folder`, `path` the folder name). */
|
||||
export async function setGrant(
|
||||
workspace: string,
|
||||
kind: string,
|
||||
path: string,
|
||||
principal: string,
|
||||
level: GrantLevel
|
||||
): Promise<void> {
|
||||
if (level === 'none') {
|
||||
await GranularAclService.removeGranularAcls({
|
||||
workspace,
|
||||
kind: kind as AclKind,
|
||||
path,
|
||||
requestBody: { owner: principal }
|
||||
})
|
||||
} else {
|
||||
await GranularAclService.addGranularAcls({
|
||||
workspace,
|
||||
kind: kind as AclKind,
|
||||
path,
|
||||
requestBody: { owner: principal, write: level === 'write' }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { AppService, AssetService, FlowService, ScriptService, type AssetKind } from '$lib/gen'
|
||||
import { inferAssets } from '$lib/infer'
|
||||
import type { SupportedLanguage } from '$lib/common'
|
||||
|
||||
export type RunnableKind = 'script' | 'flow' | 'app'
|
||||
|
||||
/** Something a runnable reads that access is granted on, item by item. */
|
||||
export type NeededItem = { kind: 'resource' | 'variable'; path: string; sources: string[] }
|
||||
|
||||
/** Something it reads that item grants do not cover (S3 objects, data tables, …). */
|
||||
export type OtherAsset = { kind: AssetKind | string; path: string; sources: string[] }
|
||||
|
||||
export type Needs = { items: NeededItem[]; others: OtherAsset[]; errors: string[] }
|
||||
|
||||
const MAX_DEPTH = 4
|
||||
const ITEM_PATH = /^[ufg]\/[^/]+\/.+/
|
||||
const STATIC_REF = /^\$(res|var):(.+)$/
|
||||
// The asset parser finds resources but has no variable kind, so literal variable reads are matched
|
||||
// here. A path the code builds at run time is found by neither.
|
||||
const VARIABLE_CALL = /\b(?:getVariable|get_variable)\(\s*["'`]([^"'`]+)["'`]/g
|
||||
|
||||
/**
|
||||
* What a script, flow or app reads when it runs, to grant to the account it runs as. The scripts
|
||||
* and flows it calls by path are followed for what they read, but need no grant themselves: the
|
||||
* runnable resolves them with its own access, not the account's.
|
||||
*/
|
||||
export async function detectNeeds(
|
||||
workspace: string,
|
||||
kind: RunnableKind,
|
||||
path: string
|
||||
): Promise<Needs> {
|
||||
const items = new Map<string, NeededItem>()
|
||||
const others = new Map<string, OtherAsset>()
|
||||
const errors: string[] = []
|
||||
const visited = new Set<string>()
|
||||
|
||||
function add(assetKind: string, assetPath: string, source: string) {
|
||||
const key = `${assetKind}:${assetPath}`
|
||||
const target =
|
||||
(assetKind === 'resource' || assetKind === 'variable') && ITEM_PATH.test(assetPath)
|
||||
? items
|
||||
: others
|
||||
const existing = target.get(key)
|
||||
if (existing) {
|
||||
if (!existing.sources.includes(source)) existing.sources.push(source)
|
||||
} else {
|
||||
target.set(key, { kind: assetKind as any, path: assetPath, sources: [source] })
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCode(language: string | undefined, content: string, source: string) {
|
||||
const result = await inferAssets(language as SupportedLanguage | undefined, content)
|
||||
if (result.status === 'ok') {
|
||||
for (const asset of result.assets) add(asset.kind, asset.path, source)
|
||||
}
|
||||
for (const match of content.matchAll(VARIABLE_CALL)) add('variable', match[1], source)
|
||||
}
|
||||
|
||||
async function recorded(usageKind: 'script' | 'flow', usagePath: string, source: string) {
|
||||
const [assets] = await AssetService.listAssetsByUsage({
|
||||
workspace,
|
||||
requestBody: { usages: [{ kind: usageKind, path: usagePath }] }
|
||||
})
|
||||
for (const asset of (assets ?? []) as { kind: string; path: string }[]) {
|
||||
add(asset.kind, asset.path, source)
|
||||
}
|
||||
}
|
||||
|
||||
/** Walks a flow or app definition for static references, inline code and calls by path. */
|
||||
async function walk(value: unknown, source: string, depth: number) {
|
||||
const pending: Promise<void>[] = []
|
||||
const visit = (node: unknown, label: string) => {
|
||||
if (typeof node === 'string') {
|
||||
const ref = STATIC_REF.exec(node)
|
||||
if (ref) add(ref[1] === 'res' ? 'resource' : 'variable', ref[2], label)
|
||||
return
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach((child) => visit(child, label))
|
||||
return
|
||||
}
|
||||
if (!node || typeof node !== 'object') return
|
||||
const obj = node as Record<string, unknown>
|
||||
const name =
|
||||
typeof obj.summary === 'string' && obj.summary
|
||||
? obj.summary
|
||||
: typeof obj.name === 'string'
|
||||
? obj.name
|
||||
: typeof obj.id === 'string'
|
||||
? obj.id
|
||||
: undefined
|
||||
const here = name ? `${source} › ${name}` : label
|
||||
if (typeof obj.content === 'string' && typeof obj.language === 'string') {
|
||||
pending.push(scanCode(obj.language, obj.content, here))
|
||||
}
|
||||
const calledKind =
|
||||
obj.runType === 'script' || obj.runType === 'flow'
|
||||
? obj.runType
|
||||
: obj.type === 'script' || obj.type === 'flow'
|
||||
? obj.type
|
||||
: undefined
|
||||
if (calledKind && typeof obj.path === 'string' && !obj.path.startsWith('hub/')) {
|
||||
pending.push(follow(calledKind, obj.path, depth + 1))
|
||||
}
|
||||
for (const [key, child] of Object.entries(obj)) {
|
||||
if (key !== 'content') visit(child, here)
|
||||
}
|
||||
}
|
||||
visit(value, source)
|
||||
await Promise.all(pending)
|
||||
}
|
||||
|
||||
async function follow(runnableKind: RunnableKind, runnablePath: string, depth: number) {
|
||||
const key = `${runnableKind}:${runnablePath}`
|
||||
if (visited.has(key) || depth > MAX_DEPTH) return
|
||||
visited.add(key)
|
||||
try {
|
||||
if (runnableKind === 'script') {
|
||||
const script = await ScriptService.getScriptByPath({ workspace, path: runnablePath })
|
||||
await Promise.all([
|
||||
recorded('script', runnablePath, runnablePath),
|
||||
scanCode(script.language, script.content, runnablePath),
|
||||
walk(script.schema, runnablePath, depth)
|
||||
])
|
||||
} else if (runnableKind === 'flow') {
|
||||
const flow = await FlowService.getFlowByPath({ workspace, path: runnablePath })
|
||||
await Promise.all([
|
||||
recorded('flow', runnablePath, runnablePath),
|
||||
walk(flow.value, runnablePath, depth),
|
||||
walk(flow.schema, runnablePath, depth)
|
||||
])
|
||||
} else {
|
||||
// Apps record no asset usages, so their inline code is parsed here.
|
||||
const app = await AppService.getAppByPath({ workspace, path: runnablePath })
|
||||
await walk(app.value, runnablePath, depth)
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push(`${runnablePath}: ${e?.body ?? e}`)
|
||||
}
|
||||
}
|
||||
|
||||
await follow(kind, path, 0)
|
||||
const byPath = (a: { path: string }, b: { path: string }) => a.path.localeCompare(b.path)
|
||||
return {
|
||||
items: [...items.values()].sort(byPath),
|
||||
others: [...others.values()].sort(byPath),
|
||||
errors
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user