mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-29 08:06:46 +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
10268c071a
commit
f1f16b87f2
@@ -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] = [
|
||||
@@ -179,16 +185,11 @@ impl From<ItemRow> for ItemAccess {
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
/// Splits `u/<user>` or `g/<group>` and refuses callers who may not look at that principal.
|
||||
fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a str, &'a str)> {
|
||||
let (prefix, name) = principal
|
||||
.split_once('/')
|
||||
.filter(|(_, name)| !name.is_empty())
|
||||
.filter(|(prefix, name)| matches!(*prefix, "u" | "g") && !name.is_empty())
|
||||
.ok_or_else(|| Error::BadRequest("principal must be u/<user> or g/<group>".into()))?;
|
||||
|
||||
// Another principal's list names paths the caller may not be able to read. A group's reach is
|
||||
@@ -196,14 +197,24 @@ async fn get_access(
|
||||
let allowed = authed.is_admin
|
||||
|| match prefix {
|
||||
"u" => name == authed.username,
|
||||
"g" => authed.groups.iter().any(|g| g == name),
|
||||
_ => false,
|
||||
_ => authed.groups.iter().any(|g| g == name),
|
||||
};
|
||||
if !allowed {
|
||||
return Err(Error::PermissionDenied(
|
||||
"only workspace admins can view another member's access".into(),
|
||||
));
|
||||
}
|
||||
Ok((prefix, name))
|
||||
}
|
||||
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
let (prefix, name) = check_principal(&authed, &principal)?;
|
||||
|
||||
let email = match prefix {
|
||||
"u" => {
|
||||
@@ -312,3 +323,160 @@ 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);
|
||||
|
||||
// Operators may be barred from managing schedules and triggers, `/acls` included.
|
||||
let mut manage_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.clone()).await {
|
||||
manage_denied.push((kind, e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for item in &mut items {
|
||||
let manage_kind = match item.kind.as_str() {
|
||||
"schedule" => Some(ManageKind::Schedules),
|
||||
k if k.ends_with("_trigger") => Some(ManageKind::Triggers),
|
||||
_ => None,
|
||||
};
|
||||
item.blocked = manage_kind
|
||||
.and_then(|mk| {
|
||||
manage_denied
|
||||
.iter()
|
||||
.find(|(k, _)| *k == mk)
|
||||
.map(|(_, e)| e.clone())
|
||||
})
|
||||
.or_else(|| grant_blocked(&authed, &item.path));
|
||||
}
|
||||
Ok(Json(BrowseItems { items, has_more }))
|
||||
}
|
||||
|
||||
@@ -24998,6 +24998,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
|
||||
|
||||
@@ -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 92 registered actions across thirty-six features (`access_view`, `ai_session`, `ai_chat`,
|
||||
It currently carries 93 registered actions across thirty-six 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`, `debugger`, `trigger`, `command_script`,
|
||||
`mcp`, `mcp_workspace`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`,
|
||||
|
||||
@@ -8,31 +8,15 @@
|
||||
import { GranularAclService, type AccessReason, type PrincipalAccess } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { Tab, Tabs } from './common'
|
||||
import AccessGrantPanel from './access/AccessGrantPanel.svelte'
|
||||
import AddNeededAccess from './access/AddNeededAccess.svelte'
|
||||
import { KIND_LABELS } from './access/access'
|
||||
|
||||
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()
|
||||
@@ -40,6 +24,7 @@
|
||||
let search = $state('')
|
||||
let kind: string | undefined = $state()
|
||||
let nbDisplayed = $state(PAGE)
|
||||
let tab: 'access' | 'grant' = $state('access')
|
||||
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
|
||||
let requestId = 0
|
||||
|
||||
@@ -50,13 +35,18 @@
|
||||
search = ''
|
||||
kind = undefined
|
||||
nbDisplayed = PAGE
|
||||
tab = 'access'
|
||||
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) {
|
||||
@@ -64,6 +54,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
function selectTab(next: 'access' | 'grant') {
|
||||
tab = next
|
||||
if (next === 'grant') logFeatureUsage('access_view', 'grant_opened')
|
||||
}
|
||||
|
||||
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/'))
|
||||
|
||||
@@ -131,6 +128,16 @@
|
||||
{principal} is an admin of this workspace and can read and write every item in it.
|
||||
</Alert>
|
||||
{:else}
|
||||
<Tabs bind:selected={() => tab, (v) => selectTab(v as 'access' | 'grant')}>
|
||||
<Tab value="access" label="Access" />
|
||||
<Tab value="grant" label="Grant" />
|
||||
</Tabs>
|
||||
{/if}
|
||||
|
||||
{#if access && !access.is_admin && tab === 'grant'}
|
||||
<AddNeededAccess {principal} {reads} onGranted={reload} />
|
||||
<AccessGrantPanel {principal} onChanged={reload} />
|
||||
{:else if access && !access.is_admin}
|
||||
<Section label="Groups" small>
|
||||
{#if access.groups.length}
|
||||
<div class="flex flex-wrap gap-1">
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/common'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import { GranularAclService, type BrowseAccessFoldersResponse } from '$lib/gen'
|
||||
import { userStore, workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { debounce } from '$lib/utils'
|
||||
import { Folder, Lock, User } from 'lucide-svelte'
|
||||
import { KIND_LABELS, setGrant, type GrantLevel } from './access'
|
||||
|
||||
type Row = { kind: string; path: string; grant?: boolean | null; blocked?: string }
|
||||
|
||||
let { principal, onChanged }: { principal: string; onChanged: () => void } = $props()
|
||||
|
||||
let folders: BrowseAccessFoldersResponse | undefined = $state()
|
||||
/** `undefined` browses every path the caller can read. */
|
||||
let prefix: string | undefined = $state()
|
||||
let kind: string | undefined = $state()
|
||||
let search = $state('')
|
||||
let items: Row[] = $state([])
|
||||
let hasMore = $state(false)
|
||||
let loading = $state(false)
|
||||
let pending: Record<string, boolean> = $state({})
|
||||
// Responses are not ordered: an answer for an earlier filter must not replace a later one.
|
||||
let requestId = 0
|
||||
|
||||
const ownPrefix = $derived(`u/${$userStore?.username}/`)
|
||||
const selectedFolder = $derived(
|
||||
prefix?.startsWith('f/') ? folders?.find((f) => `f/${f.name}/` === prefix) : undefined
|
||||
)
|
||||
const kindItems = Object.entries(KIND_LABELS).map(([value, label]) => ({ value, label }))
|
||||
|
||||
async function load(): Promise<void> {
|
||||
void loadItems(true)
|
||||
try {
|
||||
folders = await GranularAclService.browseAccessFolders({
|
||||
workspace: $workspaceStore!,
|
||||
principal
|
||||
})
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not load folders: ${e?.body ?? e}`, true)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadItems(reset: boolean): Promise<void> {
|
||||
const id = ++requestId
|
||||
loading = true
|
||||
try {
|
||||
const page = await GranularAclService.browseAccessItems({
|
||||
workspace: $workspaceStore!,
|
||||
principal,
|
||||
prefix,
|
||||
kind,
|
||||
search: search.trim() || undefined,
|
||||
offset: reset ? 0 : items.length
|
||||
})
|
||||
if (id !== requestId) return
|
||||
items = reset ? page.items : [...items, ...page.items]
|
||||
hasMore = page.has_more
|
||||
} catch (e) {
|
||||
if (id === requestId) sendUserToast(`Could not load items: ${e?.body ?? e}`, true)
|
||||
} finally {
|
||||
if (id === requestId) loading = false
|
||||
}
|
||||
}
|
||||
|
||||
const reloadSoon = debounce(() => loadItems(true), 250).debounced
|
||||
|
||||
load()
|
||||
|
||||
function selectScope(next: string | undefined) {
|
||||
prefix = next
|
||||
void loadItems(true)
|
||||
}
|
||||
|
||||
function level(grant: boolean | null | undefined): GrantLevel {
|
||||
return grant == undefined ? 'none' : grant ? 'write' : 'read'
|
||||
}
|
||||
|
||||
async function change(
|
||||
rowKind: string,
|
||||
path: string,
|
||||
next: GrantLevel,
|
||||
apply: (g: boolean | null) => void
|
||||
) {
|
||||
const key = `${rowKind}:${path}`
|
||||
pending[key] = true
|
||||
try {
|
||||
await setGrant($workspaceStore!, rowKind, path, principal, next)
|
||||
apply(next === 'none' ? null : next === 'write')
|
||||
onChanged()
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not change access to ${path}: ${e?.body ?? e}`, true)
|
||||
} finally {
|
||||
delete pending[key]
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet levelPicker(
|
||||
value: GrantLevel,
|
||||
blocked: string | undefined,
|
||||
busy: boolean,
|
||||
onSelect: (v: GrantLevel) => void
|
||||
)}
|
||||
<div class="flex items-center gap-1" title={blocked}>
|
||||
{#if blocked}
|
||||
<Lock size={12} class="text-secondary shrink-0" aria-label={blocked} />
|
||||
{/if}
|
||||
<ToggleButtonGroup
|
||||
selected={value}
|
||||
disabled={!!blocked || busy}
|
||||
noWFull
|
||||
onSelected={(v) => v !== value && onSelect(v)}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="none" label="None" small {item} />
|
||||
<ToggleButton value="read" label="Read" small {item} />
|
||||
<ToggleButton value="write" label="Write" small {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<div class="flex gap-4 min-h-[400px]">
|
||||
<nav class="w-56 shrink-0 flex flex-col gap-0.5 text-xs" aria-label="Where to browse">
|
||||
<button
|
||||
class="text-left px-2 py-1.5 rounded-md hover:bg-surface-hover {prefix === undefined
|
||||
? 'bg-surface-selected font-medium text-emphasis'
|
||||
: 'text-primary'}"
|
||||
onclick={() => selectScope(undefined)}
|
||||
>
|
||||
Everything you can read
|
||||
</button>
|
||||
<button
|
||||
class="text-left px-2 py-1.5 rounded-md hover:bg-surface-hover flex items-center gap-1.5 {prefix ===
|
||||
ownPrefix
|
||||
? 'bg-surface-selected font-medium text-emphasis'
|
||||
: 'text-primary'}"
|
||||
onclick={() => selectScope(ownPrefix)}
|
||||
>
|
||||
<User size={12} />
|
||||
<span class="truncate">{ownPrefix}</span>
|
||||
</button>
|
||||
<div class="px-2 pt-3 pb-1 text-2xs font-semibold text-secondary">Folders</div>
|
||||
{#each folders ?? [] as folder (folder.name)}
|
||||
<button
|
||||
class="text-left px-2 py-1.5 rounded-md hover:bg-surface-hover flex items-center gap-1.5 {prefix ===
|
||||
`f/${folder.name}/`
|
||||
? 'bg-surface-selected font-medium text-emphasis'
|
||||
: 'text-primary'}"
|
||||
onclick={() => selectScope(`f/${folder.name}/`)}
|
||||
>
|
||||
<Folder size={12} />
|
||||
<span class="truncate grow">f/{folder.name}</span>
|
||||
{#if folder.target_owner}
|
||||
<span class="text-2xs text-secondary">owner</span>
|
||||
{:else if folder.grant != undefined}
|
||||
<span class="text-2xs text-secondary">{folder.grant ? 'write' : 'read'}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{:else}
|
||||
<p class="px-2 text-2xs text-secondary">{folders ? 'No folder you can read.' : 'Loading…'}</p>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<div class="grow min-w-0 flex flex-col gap-3">
|
||||
{#if selectedFolder}
|
||||
{@const folder = selectedFolder}
|
||||
<div class="flex items-center justify-between gap-4 rounded-md border px-3 py-2">
|
||||
<div class="flex flex-col">
|
||||
<span class="text-xs font-medium text-emphasis">The whole folder f/{folder.name}</span>
|
||||
<span class="text-2xs text-secondary">
|
||||
{folder.target_owner
|
||||
? `${principal} owns this folder and always keeps write.`
|
||||
: 'Covers every item in it, including ones added later.'}
|
||||
</span>
|
||||
</div>
|
||||
{@render levelPicker(
|
||||
folder.target_owner ? 'write' : level(folder.grant),
|
||||
folder.target_owner ? `${principal} owns f/${folder.name}` : folder.blocked,
|
||||
!!pending[`folder:${folder.name}`],
|
||||
(v) => change('folder', folder.name, v, (g) => (folder.grant = g))
|
||||
)}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex gap-2">
|
||||
<TextInput
|
||||
bind:value={() => search, (v) => ((search = String(v ?? '')), reloadSoon())}
|
||||
inputProps={{ placeholder: 'Search paths' }}
|
||||
size="sm"
|
||||
class="grow"
|
||||
/>
|
||||
<div class="w-48">
|
||||
<Select
|
||||
items={kindItems}
|
||||
bind:value={() => kind, (v) => ((kind = v), loadItems(true))}
|
||||
placeholder="All kinds"
|
||||
clearable
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-2xs text-secondary">
|
||||
Only {principal}'s own grants are shown. It may also reach an item through a group or a
|
||||
folder: the Access tab lists those.
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col divide-y border rounded-md">
|
||||
{#each items as item (item.kind + ':' + item.path)}
|
||||
<div class="flex items-center justify-between gap-4 px-3 py-1.5">
|
||||
<div class="flex flex-col min-w-0">
|
||||
<span class="font-mono text-2xs truncate text-emphasis">{item.path}</span>
|
||||
<span class="text-2xs text-secondary">{KIND_LABELS[item.kind] ?? item.kind}</span>
|
||||
</div>
|
||||
{@render levelPicker(
|
||||
level(item.grant),
|
||||
item.blocked,
|
||||
!!pending[`${item.kind}:${item.path}`],
|
||||
(v) => change(item.kind, item.path, v, (g) => (item.grant = g))
|
||||
)}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="px-3 py-4 text-xs text-secondary">
|
||||
{loading ? 'Loading…' : 'No item matches.'}
|
||||
</p>
|
||||
{/each}
|
||||
</div>
|
||||
{#if hasMore}
|
||||
<Button variant="subtle" unifiedSize="sm" {loading} onClick={() => loadItems(false)}>
|
||||
Load more
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,186 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Button } from '$lib/components/common'
|
||||
import Checkbox from '$lib/components/common/checkbox/Checkbox.svelte'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import { GranularAclService } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { debounce } from '$lib/utils'
|
||||
import { Info, Search } from 'lucide-svelte'
|
||||
import { setGrant } from './access'
|
||||
import { detectNeeds, type Needs, type RunnableKind } from './detectNeeds'
|
||||
|
||||
let {
|
||||
principal,
|
||||
reads,
|
||||
onGranted
|
||||
}: {
|
||||
principal: string
|
||||
/** `kind:path` of every item the principal already reads, through any grant. */
|
||||
reads: Set<string>
|
||||
onGranted: () => void
|
||||
} = $props()
|
||||
|
||||
let runnableKind: RunnableKind = $state('flow')
|
||||
let runnablePath: string | undefined = $state()
|
||||
let filterText = $state('')
|
||||
let candidates: { value: string; label: string }[] = $state([])
|
||||
let needs: Needs | undefined = $state()
|
||||
let detecting = $state(false)
|
||||
let selected: Record<string, boolean> = $state({})
|
||||
let results: Record<string, string> = $state({})
|
||||
let granting = $state(false)
|
||||
|
||||
async function loadCandidates() {
|
||||
const page = await GranularAclService.browseAccessItems({
|
||||
workspace: $workspaceStore!,
|
||||
principal,
|
||||
kind: runnableKind,
|
||||
search: filterText.trim() || undefined
|
||||
})
|
||||
candidates = page.items.map((i) => ({ value: i.path, label: i.path }))
|
||||
}
|
||||
const loadCandidatesSoon = debounce(loadCandidates, 250).debounced
|
||||
|
||||
function setKind(next: RunnableKind) {
|
||||
runnableKind = next
|
||||
runnablePath = undefined
|
||||
needs = undefined
|
||||
void loadCandidates()
|
||||
}
|
||||
|
||||
async function detect() {
|
||||
if (!runnablePath) return
|
||||
detecting = true
|
||||
results = {}
|
||||
try {
|
||||
needs = await detectNeeds($workspaceStore!, runnableKind, runnablePath)
|
||||
selected = Object.fromEntries(
|
||||
needs.items.map((i) => [`${i.kind}:${i.path}`, !reads.has(`${i.kind}:${i.path}`)])
|
||||
)
|
||||
} finally {
|
||||
detecting = false
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
loadCandidates()
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-3 rounded-md border p-3">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-xs font-semibold text-emphasis">Add what a flow, script or app reads</span>
|
||||
<span class="text-2xs text-secondary">
|
||||
Finds 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>
|
||||
<div class="flex gap-2 items-center">
|
||||
<ToggleButtonGroup selected={runnableKind} noWFull onSelected={(v) => setKind(v)}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="flow" label="Flow" small {item} />
|
||||
<ToggleButton value="script" label="Script" small {item} />
|
||||
<ToggleButton value="app" label="App" small {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
<div class="grow">
|
||||
<Select
|
||||
items={candidates}
|
||||
bind:value={() => runnablePath, (v) => ((runnablePath = v), (needs = undefined))}
|
||||
bind:filterText={() => filterText, (v) => ((filterText = v), loadCandidatesSoon())}
|
||||
placeholder={runnableKind === 'app' ? 'Pick an app' : `Pick a ${runnableKind}`}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
startIcon={{ icon: Search }}
|
||||
disabled={!runnablePath}
|
||||
loading={detecting}
|
||||
onClick={detect}
|
||||
>
|
||||
Find what it reads
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{#if needs}
|
||||
{#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={(e) => (selected[key] = e.currentTarget.checked)}
|
||||
/>
|
||||
<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 {runnablePath}.
|
||||
</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 from the list below.
|
||||
</span>
|
||||
<Button
|
||||
variant="accent"
|
||||
unifiedSize="sm"
|
||||
disabled={selectedCount === 0}
|
||||
loading={granting}
|
||||
onClick={grant}
|
||||
>
|
||||
Grant read on {selectedCount}
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</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