mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-03 08:10:27 +00:00
feat: grant and remove access from the access view (#12143)
* feat: show what a member, group or service account can access Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: grant and remove access from the access view Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: point the EE ref at the access view usage counters Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show an error when what it reads cannot load the item itself Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: close only the grant navigator on escape, not the access view Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: name groups in the access view's permission error Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: map /access to the acls scope and list each group once A token with scopes was refused before reaching the access endpoint, and a member in a workspace group and an instance group of the same name got that group twice, which broke the drawer's keyed list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: count every registered feature usage action Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read pinned script versions and resource references in what it reads Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: grant full-code apps under raw_app and show a branch from its first page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: type the navigator's reach map by plain string keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read the operating workspace and user in the access view GroupEditorDrawer is reachable from a session editor, where the navigation workspace and user are the parent's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: grant in the operating workspace, not the navigation one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read a full-code app's frontend source in what it reads Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: cover a member reading their group's access Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: navigator sees folder ownership held through a group Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: what it reads finds resources in JSX, Svelte and Vue source Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: the navigator names the operating user's own grants Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: what it reads matches SDK calls in a component's template Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: what it reads says which paths it finds and which it can't Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: size the groups page loading rows like the loaded ones Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: open a group's access from the groups page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: show access as a folder tree with links to each item Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: show a group's access to superadmins who are not workspace admins Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: escape closes only an open row menu in the access view Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: rows with a grant menu stay as tall as the rest of the tree Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: size the grant menu trigger to the tree row Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: accept instance groups as access view principals Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: update ee-repo-ref to c4e610999ca0d1abab06b1660cc48e486ab870b3 This commit updates the EE repository reference after PR #939 was merged in windmill-ee-private. Previous ee-repo-ref: da6bb1965702eb57237882e5fda6179f72294a06 New ee-repo-ref: c4e610999ca0d1abab06b1660cc48e486ab870b3 Automated by sync-ee-ref workflow. * chore: update ee-repo-ref to c4e610999ca0d1abab06b1660cc48e486ab870b3 This commit updates the EE repository reference after PR #939 was merged in windmill-ee-private. Previous ee-repo-ref: da6bb1965702eb57237882e5fda6179f72294a06 New ee-repo-ref: c4e610999ca0d1abab06b1660cc48e486ab870b3 Automated by sync-ee-ref workflow. * feat: parse item references beside assets Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: report what an item reads and who reads it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: load what an item reads from the server Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: describe who performs each read an item makes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read step paths with the runtime's path parser Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: grant only uncovered rows in the reads panel, show refusals in red Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: make disabled drill picker rows look disabled Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: say in the grant navigator when the principal already reads a row Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: correct the operator lock, app source error and admin intro texts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: move what an item reads into its own pull request Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: grant and revoke from one row button in the grant navigator Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: check the static access queries with sqlx macros Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: widen the grant success pill to fit its text Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: let the folder dialog's buttons and the grant navigator answer their own keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: let enter confirm the folder dialog when the row button kept focus Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: refuse an unknown principal when browsing items Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: lock a row's grant menu while it saves and show folder levels and empty folders Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: close a row's menu when its change starts so it does not reopen after the reload Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: settle the grant navigator on a failed folder load, search every page and return role lookup errors Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
windmill-internal-app[bot]
parent
0dd0a78384
commit
9f7d00ef4e
@@ -18,14 +18,20 @@ use windmill_api_auth::ApiAuthed;
|
||||
use windmill_common::{
|
||||
auth::fetch_authed_from_permissioned_as,
|
||||
db::UserDB,
|
||||
error::{Error, JsonResult},
|
||||
error::{Error, JsonResult, Result},
|
||||
workspaces::{check_operator_can_manage, ManageKind},
|
||||
DB,
|
||||
};
|
||||
|
||||
pub fn workspaced_service() -> Router {
|
||||
Router::new().route("/get", get(get_access))
|
||||
Router::new()
|
||||
.route("/get", get(get_access))
|
||||
.route("/browse_folders", get(browse_folders))
|
||||
.route("/browse_items", get(browse_items))
|
||||
}
|
||||
|
||||
const BROWSE_PAGE: i64 = 100;
|
||||
|
||||
/// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on
|
||||
/// purpose: they are test data attached to an item, not something access is granted to.
|
||||
const ITEM_TABLES: [(&str, &str, &str); 17] = [
|
||||
@@ -74,6 +80,12 @@ struct FolderAccess {
|
||||
owner: bool,
|
||||
/// The `extra_perms` keys (`u/<user>` or `g/<group>`) that grant the folder.
|
||||
via: Vec<String>,
|
||||
/// The principal's own entry in `extra_perms`: absent when none, false for read, true for write.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
grant: Option<bool>,
|
||||
/// Why the caller cannot change the principal's own entry. Set only where there is one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -82,6 +94,9 @@ struct ItemAccess {
|
||||
path: String,
|
||||
write: bool,
|
||||
reasons: Vec<Reason>,
|
||||
/// Why the caller cannot change the principal's own grant. Set only where there is one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -112,12 +127,27 @@ struct ItemRow {
|
||||
folder_write: bool,
|
||||
}
|
||||
|
||||
/// The `kind` column for a row of `table`. Full-code apps live in `app` too, but their grants must
|
||||
/// be written with kind `raw_app`, which git sync dispatches to `<path>.raw_app` rather than `.app`.
|
||||
fn kind_column(kind: &str, table: &str) -> String {
|
||||
if kind == "app" {
|
||||
format!(
|
||||
"CASE WHEN (SELECT raw_app FROM app_version \
|
||||
WHERE id = {table}.versions[array_upper({table}.versions, 1)]) \
|
||||
THEN 'raw_app' ELSE 'app' END"
|
||||
)
|
||||
} else {
|
||||
format!("'{kind}'::text")
|
||||
}
|
||||
}
|
||||
|
||||
fn items_query() -> String {
|
||||
let union = ITEM_TABLES
|
||||
.iter()
|
||||
.map(|(kind, table, filter)| {
|
||||
let kind = kind_column(kind, table);
|
||||
format!(
|
||||
"SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \
|
||||
"SELECT {kind} AS kind, path::text AS path, extra_perms FROM {table} \
|
||||
WHERE workspace_id = $1 {filter}"
|
||||
)
|
||||
})
|
||||
@@ -175,20 +205,15 @@ impl From<ItemRow> for ItemAccess {
|
||||
*write
|
||||
}
|
||||
});
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons }
|
||||
ItemAccess { kind: r.kind, path: r.path, write, reasons, blocked: None }
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
/// Splits `u/<user>` or `g/<group>` and refuses callers who may not look at that principal.
|
||||
fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a str, &'a str)> {
|
||||
let (prefix, name) = principal
|
||||
.split_once('/')
|
||||
.filter(|(_, name)| !name.is_empty())
|
||||
.filter(|(prefix, name)| matches!(*prefix, "u" | "g") && !name.is_empty())
|
||||
.ok_or_else(|| Error::BadRequest("principal must be u/<user> or g/<group>".into()))?;
|
||||
|
||||
// Another principal's list names paths the caller may not be able to read. A group's reach is
|
||||
@@ -196,8 +221,7 @@ async fn get_access(
|
||||
let allowed = authed.is_admin
|
||||
|| match prefix {
|
||||
"u" => name == authed.username,
|
||||
"g" => authed.groups.iter().any(|g| g == name),
|
||||
_ => false,
|
||||
_ => authed.groups.iter().any(|g| g == name),
|
||||
};
|
||||
if !allowed {
|
||||
return Err(Error::PermissionDenied(
|
||||
@@ -205,15 +229,36 @@ async fn get_access(
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok((prefix, name))
|
||||
}
|
||||
|
||||
let email = match prefix {
|
||||
/// The principal as it would be authenticated, with its groups and the folders it reaches.
|
||||
async fn fetch_target(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
prefix: &str,
|
||||
name: &str,
|
||||
principal: &str,
|
||||
) -> Result<windmill_common::db::Authed> {
|
||||
let email = target_email(db, w_id, prefix, name).await?;
|
||||
let mut target = fetch_authed_from_permissioned_as(principal, &email, w_id, db).await?;
|
||||
// A workspace group and an instance group can share a name, and both come back.
|
||||
target.groups.sort();
|
||||
target.groups.dedup();
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
/// The principal's email, empty for a group. Not found when the principal does not exist, so
|
||||
/// no route answers for a mistyped one as if it existed with no grants.
|
||||
async fn target_email(db: &DB, w_id: &str, prefix: &str, name: &str) -> Result<String> {
|
||||
Ok(match prefix {
|
||||
"u" => {
|
||||
let usr = sqlx::query!(
|
||||
"SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2",
|
||||
&w_id,
|
||||
w_id,
|
||||
name
|
||||
)
|
||||
.fetch_optional(&db)
|
||||
.fetch_optional(db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound(format!("user {name} not found")))?;
|
||||
if usr.disabled {
|
||||
@@ -224,15 +269,15 @@ async fn get_access(
|
||||
usr.email
|
||||
}
|
||||
"g" => {
|
||||
// Instance groups are granted through the same `g/<name>` keys, and the check above
|
||||
// Instance groups are granted through the same `g/<name>` keys, and the callers' check
|
||||
// lets their members ask, so a name from either table is a group here.
|
||||
let exists = sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)
|
||||
OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)",
|
||||
&w_id,
|
||||
w_id,
|
||||
name
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.fetch_one(db)
|
||||
.await?
|
||||
.unwrap_or(false);
|
||||
if !exists {
|
||||
@@ -245,12 +290,19 @@ async fn get_access(
|
||||
"principal must be u/<user> or g/<group>".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
let mut target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).await?;
|
||||
// A workspace group and an instance group can share a name, and both come back.
|
||||
target.groups.sort();
|
||||
target.groups.dedup();
|
||||
async fn get_access(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<AccessReport> {
|
||||
let (prefix, name) = check_principal(&authed, &principal)?;
|
||||
|
||||
let target = fetch_target(&db, &w_id, prefix, name, &principal).await?;
|
||||
|
||||
if target.is_admin {
|
||||
return Ok(Json(AccessReport {
|
||||
@@ -276,38 +328,54 @@ async fn get_access(
|
||||
.map(|f| f.0.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut via = sqlx::query!(
|
||||
"SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"
|
||||
"SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\",
|
||||
(extra_perms ->> $4)::boolean AS \"grant\"
|
||||
FROM folder WHERE workspace_id = $1 AND name = ANY($2)",
|
||||
&w_id,
|
||||
&folder_names,
|
||||
&perms
|
||||
&perms,
|
||||
&principal
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.name, r.via))
|
||||
.map(|r| (r.name, (r.via, r.grant)))
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
let mut folders = target
|
||||
.folders
|
||||
.iter()
|
||||
.map(|(name, write, owner)| FolderAccess {
|
||||
name: name.clone(),
|
||||
write: *write,
|
||||
owner: *owner,
|
||||
via: via.remove(name).unwrap_or_default(),
|
||||
.map(|(name, write, owner)| {
|
||||
let (via, grant) = via.remove(name).unwrap_or_default();
|
||||
// An owner keeps write whatever its entry says, so there is nothing to change.
|
||||
let blocked =
|
||||
(grant.is_some() && !*owner && !windmill_api_auth::is_owner(&authed, name))
|
||||
.then(|| folder_blocked(name));
|
||||
FolderAccess { name: name.clone(), write: *write, owner: *owner, via, grant, blocked }
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
folders.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
|
||||
let mut tx = user_db.begin(&target).await?;
|
||||
let items = sqlx::query_as::<_, ItemRow>(&items_query())
|
||||
let rows = sqlx::query_as::<_, ItemRow>(&items_query())
|
||||
.bind(&w_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(ItemAccess::from)
|
||||
.collect();
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let denied = manage_denied(&db, &w_id, &authed).await?;
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let direct = match prefix {
|
||||
"u" => r.user_grant.is_some(),
|
||||
_ => r.group_read.iter().any(|g| g == name),
|
||||
};
|
||||
let mut item = ItemAccess::from(r);
|
||||
if direct {
|
||||
item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path);
|
||||
}
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(AccessReport {
|
||||
principal,
|
||||
@@ -317,3 +385,204 @@ async fn get_access(
|
||||
items,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BrowseFolder {
|
||||
name: String,
|
||||
/// The principal's own entry in the folder's `extra_perms`: absent, read (false) or write.
|
||||
grant: Option<bool>,
|
||||
/// Owners always keep write; `acls/add` refuses to lower it.
|
||||
target_owner: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
struct BrowseItem {
|
||||
kind: String,
|
||||
path: String,
|
||||
grant: Option<bool>,
|
||||
#[sqlx(skip)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BrowseItems {
|
||||
items: Vec<BrowseItem>,
|
||||
has_more: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct BrowseItemsQuery {
|
||||
principal: String,
|
||||
/// Only paths starting with this, e.g. `f/billing/` or `u/alice/`.
|
||||
prefix: Option<String>,
|
||||
kind: Option<String>,
|
||||
search: Option<String>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
/// Why the caller cannot change grants on `path`, mirroring the checks `acls/add` makes.
|
||||
fn grant_blocked(authed: &ApiAuthed, path: &str) -> Option<String> {
|
||||
if authed.is_admin {
|
||||
return None;
|
||||
}
|
||||
let mut parts = path.splitn(3, '/');
|
||||
match (parts.next(), parts.next()) {
|
||||
(Some("u"), Some(owner)) if owner == authed.username => None,
|
||||
(Some("u"), Some(owner)) => {
|
||||
Some(format!("Only u/{owner} and workspace admins can share it"))
|
||||
}
|
||||
(Some("f"), Some(folder)) if windmill_api_auth::is_owner(authed, folder) => None,
|
||||
(Some("f"), Some(folder)) => Some(folder_blocked(folder)),
|
||||
_ => Some("Only workspace admins can share items under g/".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn folder_blocked(folder: &str) -> String {
|
||||
format!("Only admins of the workspace or of f/{folder} can share it")
|
||||
}
|
||||
|
||||
async fn browse_folders(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<Vec<BrowseFolder>> {
|
||||
let (prefix, name) = check_principal(&authed, &principal)?;
|
||||
// Ownership can come through one of the principal's groups, as in `/access/get`.
|
||||
let target = fetch_target(&db, &w_id, prefix, name, &principal).await?;
|
||||
let owned = target
|
||||
.folders
|
||||
.iter()
|
||||
.filter(|(_, _, owner)| *owner)
|
||||
.map(|(name, ..)| name.as_str())
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let mut folders = sqlx::query_as!(
|
||||
BrowseFolder,
|
||||
"SELECT name, (extra_perms ->> $2)::boolean AS \"grant\",
|
||||
$2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked
|
||||
FROM folder WHERE workspace_id = $1 ORDER BY name",
|
||||
&w_id,
|
||||
&principal
|
||||
)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
for folder in &mut folders {
|
||||
folder.target_owner |= owned.contains(folder.name.as_str());
|
||||
if !windmill_api_auth::is_owner(&authed, &folder.name) {
|
||||
folder.blocked = Some(folder_blocked(&folder.name));
|
||||
}
|
||||
}
|
||||
Ok(Json(folders))
|
||||
}
|
||||
|
||||
async fn browse_items(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(q): Query<BrowseItemsQuery>,
|
||||
) -> JsonResult<BrowseItems> {
|
||||
let (prefix, name) = check_principal(&authed, &q.principal)?;
|
||||
target_email(&db, &w_id, prefix, name).await?;
|
||||
let tables = ITEM_TABLES
|
||||
.iter()
|
||||
.filter(|(kind, ..)| {
|
||||
q.kind
|
||||
.as_deref()
|
||||
.map_or(true, |k| k == *kind || (k == "raw_app" && *kind == "app"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if tables.is_empty() {
|
||||
return Err(Error::BadRequest("unknown kind".into()));
|
||||
}
|
||||
// SAFETY: table names and filters come from the `ITEM_TABLES` constant, never from the request.
|
||||
let union = tables
|
||||
.iter()
|
||||
.map(|(kind, table, filter)| {
|
||||
let kind = kind_column(kind, table);
|
||||
format!(
|
||||
"SELECT {kind} AS kind, path::text AS path, (extra_perms ->> $2)::boolean AS \"grant\"
|
||||
FROM {table} WHERE workspace_id = $1 {filter}"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" UNION ALL ");
|
||||
let sql = format!(
|
||||
"SELECT kind, path, \"grant\" FROM ({union}) i
|
||||
WHERE ($3::text IS NULL OR starts_with(path, $3))
|
||||
AND ($4::text IS NULL OR strpos(lower(path), lower($4)) > 0)
|
||||
AND ($7::text IS NULL OR kind = $7)
|
||||
ORDER BY path, kind LIMIT $5 OFFSET $6"
|
||||
);
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let mut items = sqlx::query_as::<_, BrowseItem>(&sql)
|
||||
.bind(&w_id)
|
||||
.bind(&q.principal)
|
||||
.bind(q.prefix.as_deref().filter(|p| !p.is_empty()))
|
||||
.bind(q.search.as_deref().map(str::trim).filter(|s| !s.is_empty()))
|
||||
.bind(BROWSE_PAGE + 1)
|
||||
.bind(q.offset.unwrap_or(0).max(0))
|
||||
.bind(q.kind.as_deref())
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
let has_more = items.len() as i64 > BROWSE_PAGE;
|
||||
items.truncate(BROWSE_PAGE as usize);
|
||||
|
||||
let denied = manage_denied(&db, &w_id, &authed).await?;
|
||||
for item in &mut items {
|
||||
item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path);
|
||||
}
|
||||
Ok(Json(BrowseItems { items, has_more }))
|
||||
}
|
||||
|
||||
/// Operators may be barred from managing schedules and triggers, `/acls` included.
|
||||
/// Only a refusal becomes a lock text; any other error (the role lookup failing) is returned, so
|
||||
/// an outage is not shown as a decision.
|
||||
async fn manage_denied(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
authed: &ApiAuthed,
|
||||
) -> Result<Vec<(ManageKind, String)>> {
|
||||
let mut denied = vec![];
|
||||
if !authed.is_admin {
|
||||
for kind in [ManageKind::Schedules, ManageKind::Triggers] {
|
||||
match check_operator_can_manage(db, w_id, authed, kind).await {
|
||||
Ok(()) => {}
|
||||
// A plain sentence like the path rules' texts, so without the "Permission
|
||||
// denied: " prefix the error's display adds.
|
||||
Err(Error::PermissionDenied(reason)) => denied.push((kind, reason)),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(denied)
|
||||
}
|
||||
|
||||
/// Why the caller cannot change grants on this item: the operator gate first, then the path.
|
||||
fn item_blocked(
|
||||
authed: &ApiAuthed,
|
||||
denied: &[(ManageKind, String)],
|
||||
kind: &str,
|
||||
path: &str,
|
||||
) -> Option<String> {
|
||||
let manage_kind = match kind {
|
||||
"schedule" => Some(ManageKind::Schedules),
|
||||
k if k.ends_with("_trigger") => Some(ManageKind::Triggers),
|
||||
_ => None,
|
||||
};
|
||||
manage_kind
|
||||
.and_then(|mk| {
|
||||
denied
|
||||
.iter()
|
||||
.find(|(k, _)| *k == mk)
|
||||
.map(|(_, e)| e.clone())
|
||||
})
|
||||
.or_else(|| grant_blocked(authed, path))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user