Files
windmill/backend/windmill-api/src/admin_reliance.rs
T
Ruben FiszelandClaude Opus 5.5 3ee1d6a4b8 feat: show what a token loses without its owner's admin rights (#12749)
* feat: warn what a token loses without its owner's admin rights

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: scope the admin-reliance report and make access refusals readable

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the admin switch visible under superadmin, resolve MCP favorites

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address review round on admin-reliance warnings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: require folder write only where a write scope reaches, honor group paths

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:13:08 +01:00

694 lines
24 KiB
Rust

//! What a token made without its owner's workspace admin rights cannot reach, that the owner
//! reaches only because they are admin. Read by the token forms before minting, and appended
//! to the refusals such a token meets.
use std::sync::Arc;
use axum::{extract::Request, middleware::Next, response::Response, Extension, Json};
use http::StatusCode;
use serde::{Deserialize, Serialize};
use windmill_api_auth::{
auth::maybe_get_workspace_id_from_path, ApiAuthed, AuthCache, OptJobAuthed,
};
use windmill_common::{
auth::{get_folders_for_user, get_groups_for_user},
client_ip::client_ip_of,
error::{Error, JsonResult, Result, ServerError},
scopes::ScopeDefinition,
DB,
};
use crate::token::ALL_SCOPES;
const MAX_FOLDERS: usize = 50;
const MAX_ASSETS: usize = 20;
const MAX_WORKSPACES: i64 = 50;
/// MCP scopes that serve the session toolset, which acts on the whole workspace. The others
/// name runnables (`scripts`, `flows`, `favorites`), endpoints, hub scripts or workspaces.
const MCP_SESSION_ACCESS: &[&str] = &["all", "session", "read_only", "read_run"];
/// Workspace actions only an admin can take, by the scope that would let a token attempt them.
const ADMIN_ONLY: &[(&str, &str)] = &[
("workspaces:write", "change workspace settings"),
(
"users:write",
"add, remove or change the role of workspace members",
),
("groups:write", "edit groups you do not own"),
("folders:write", "edit folders you do not own"),
];
#[derive(Deserialize)]
pub(crate) struct AdminRelianceRequest {
/// The workspaces the token will reach; omitted, every workspace the caller administers.
workspace_ids: Option<Vec<String>>,
/// The token's scopes; omitted, an unscoped token.
scopes: Option<Vec<String>>,
#[serde(default)]
read_only: bool,
}
#[derive(Serialize, Debug, PartialEq)]
pub(crate) struct AssetOutOfReach {
runnable_kind: String,
runnable_path: String,
kind: String,
path: String,
}
#[derive(Serialize, Debug)]
pub(crate) struct WorkspaceAdminReliance {
workspace_id: String,
/// The caller's username there, which a folder grant names.
username: String,
/// Folders within the scopes the caller cannot read (or write, see `folders_write`), first
/// `MAX_FOLDERS` by name.
folders: Vec<String>,
folders_total: usize,
/// The folders are ones the caller cannot write to, rather than cannot read: the token can
/// change items.
folders_write: bool,
/// Scripts, flows, apps, resources and variables under other users' `u/` paths, not shared
/// with the caller, within the scopes.
other_users_items: i64,
/// Resources that the runnables the scopes name reference in their code. The asset parsers
/// record no variables, so none are reported.
assets: Vec<AssetOutOfReach>,
admin_only: Vec<String>,
}
impl WorkspaceAdminReliance {
fn is_empty(&self) -> bool {
self.folders_total == 0
&& self.other_users_items == 0
&& self.assets.is_empty()
&& self.admin_only.is_empty()
}
}
/// Which item paths a set of scopes reaches.
#[derive(Debug, PartialEq)]
enum PathReach {
All,
Patterns(Vec<String>),
}
impl PathReach {
fn of(scopes: Option<&[String]>) -> Option<Self> {
let Some(scopes) = scopes else {
return Some(Self::All);
};
let mut patterns = vec![];
for scope in scopes {
match scope_paths(scope) {
Some(None) => return Some(Self::All),
Some(Some(p)) => patterns.extend(p),
None => {}
}
}
(!patterns.is_empty()).then_some(Self::Patterns(patterns))
}
/// Whether some path under `prefix` (ending with `/`) is reached.
fn covers_prefix(&self, prefix: &str) -> bool {
match self {
Self::All => true,
Self::Patterns(patterns) => patterns.iter().any(|p| match p.strip_suffix('*') {
Some(head) => prefix.starts_with(head) || head.starts_with(prefix),
None => p.starts_with(prefix),
}),
}
}
fn covers_other_users(&self, username: &str) -> bool {
let own = format!("u/{username}/");
match self {
Self::All => true,
Self::Patterns(patterns) => patterns.iter().any(|p| {
(p == "*" || p.starts_with("u/") || "u/".starts_with(p.trim_end_matches('*')))
&& !p.starts_with(&own)
}),
}
}
}
/// The item paths one scope reaches: `None` for a scope naming no items, `Some(None)` for
/// every path, else its path patterns.
fn scope_paths(scope: &str) -> Option<Option<Vec<String>>> {
if scope == "*" {
return Some(None);
}
let parts: Vec<&str> = scope.split(':').collect();
let domain = parts[0];
let resource_from = match domain {
// The session toolsets act on the whole workspace.
"mcp" => match parts.get(1).copied() {
Some("scripts" | "flows") => 2,
Some(access) if MCP_SESSION_ACCESS.contains(&access) => return Some(None),
_ => return None,
},
"jobs" if parts.get(1) == Some(&"run") => 3,
_ => {
let path_scoped = ALL_SCOPES
.iter()
.flat_map(|d| d.scopes.iter())
.any(|s| s.requires_resource_path && s.value.split(':').next() == Some(domain));
if !path_scoped {
return None;
}
2
}
};
let resource = parts
.get(resource_from..)
.map(|p| p.join(":"))
.unwrap_or_default();
if resource.is_empty() {
return Some(None);
}
Some(Some(resource.split(',').map(str::to_string).collect()))
}
/// The runnables a scope names by path, as `(usage_kind, pattern)`.
fn scope_runnables(scope: &str) -> Vec<(&'static str, String)> {
let parts: Vec<&str> = scope.split(':').collect();
let (kind, from) = match parts.as_slice() {
["mcp", "scripts", ..] => ("script", 2),
["mcp", "flows", ..] => ("flow", 2),
["jobs", "run", "scripts", ..] => ("script", 3),
["jobs", "run", "flows", ..] => ("flow", 3),
_ => return vec![],
};
let resource = parts.get(from..).map(|p| p.join(":")).unwrap_or_default();
resource
.split(',')
.filter(|p| !p.is_empty() && *p != "*")
.map(|p| (kind, p.to_string()))
.collect()
}
/// Whether the scopes reach the item of `domain` (`scripts`, `flows`, `apps`, `resources` or
/// `variables`) at `path`.
fn reaches_item(scopes: Option<&[String]>, domain: &str, path: &str) -> bool {
let Some(scopes) = scopes else {
return true;
};
scopes.iter().any(|scope| {
let parts: Vec<&str> = scope.split(':').collect();
// The domain the scope names items of, and where its path patterns start.
let (scope_domain, from) = match parts.as_slice() {
["*"] => return true,
["mcp", kind @ ("scripts" | "flows"), ..] => (*kind, 2),
["mcp", access, ..] => return MCP_SESSION_ACCESS.contains(access),
["jobs", "run", kind @ ("scripts" | "flows"), ..] => (*kind, 3),
[d, _, ..] => (*d, 2),
_ => return false,
};
if scope_domain != domain {
return false;
}
let resource = parts.get(from..).map(|p| p.join(":")).unwrap_or_default();
resource.is_empty() || resource.split(',').any(|p| pattern_matches(p, path))
})
}
fn pattern_matches(pattern: &str, path: &str) -> bool {
match pattern.strip_suffix('*') {
Some(head) => path.starts_with(head),
None => pattern == path,
}
}
/// The item paths the token can change, so a folder there it can only read still costs it
/// access. `None` when it changes no item.
fn write_reach(scopes: Option<&[String]>, read_only: bool) -> Option<PathReach> {
if read_only {
return None;
}
let Some(scopes) = scopes else {
return Some(PathReach::All);
};
// `mcp:all` with `mcp:read_only` or `mcp:read_run` is the Read levels of the toolset.
let mcp_narrowed = scopes
.iter()
.any(|s| s == "mcp:read_only" || s == "mcp:read_run");
let writing: Vec<String> = scopes
.iter()
.filter(|s| {
let mut parts = s.split(':');
match (parts.next(), parts.next()) {
(Some("*"), _) => true,
(Some("mcp"), Some(access)) => matches!(access, "all" | "session") && !mcp_narrowed,
(_, Some(action)) => action == "write",
_ => false,
}
})
.cloned()
.collect();
PathReach::of(Some(&writing))
}
fn admin_only_actions(scopes: Option<&[String]>, read_only: bool) -> Vec<String> {
if read_only {
return vec![];
}
let grants: Option<Vec<ScopeDefinition>> = scopes.map(|s| {
s.iter()
.filter_map(|s| ScopeDefinition::from_scope_string(s).ok())
.collect()
});
let unscoped = scopes.is_none_or(|s| s.iter().any(|s| s == "*"));
ADMIN_ONLY
.iter()
.filter(|(required, _)| {
unscoped
|| ScopeDefinition::from_required_scope_string(required).is_ok_and(|required| {
grants.iter().flatten().any(|grant| grant.grants(&required))
})
})
.map(|(_, what)| what.to_string())
.collect()
}
/// `mcp:favorites` stands for the caller's favorite scripts and flows in that workspace.
async fn expand_favorites(
db: &DB,
w_id: &str,
username: &str,
scopes: Option<&[String]>,
) -> Result<Option<Vec<String>>> {
let Some(scopes) = scopes else {
return Ok(None);
};
let mut out: Vec<String> = scopes
.iter()
.filter(|s| *s != "mcp:favorites")
.cloned()
.collect();
if out.len() < scopes.len() {
let favorites = sqlx::query!(
r#"SELECT favorite_kind::text AS "kind!", path FROM favorite
WHERE usr = $1 AND workspace_id = $2 AND favorite_kind IN ('script', 'flow')"#,
username,
w_id
)
.fetch_all(db)
.await?;
out.extend(
favorites
.into_iter()
.map(|f| format!("mcp:{}s:{}", f.kind, f.path)),
);
}
Ok(Some(out))
}
async fn workspace_reliance(
db: &DB,
w_id: &str,
username: &str,
email: &str,
req: &AdminRelianceRequest,
) -> Result<WorkspaceAdminReliance> {
let expanded = expand_favorites(db, w_id, username, req.scopes.as_deref()).await?;
let scopes = expanded.as_deref();
let reach = PathReach::of(scopes);
let groups = get_groups_for_user(w_id, username, email, db).await?;
let memberships = get_folders_for_user(w_id, username, &groups, db).await?;
let member_folders: Vec<String> = memberships
.iter()
.map(|(name, _, _)| name.clone())
.collect();
let writable_folders: Vec<&str> = memberships
.iter()
.filter(|(_, write, owner)| *write || *owner)
.map(|(name, _, _)| name.as_str())
.collect();
let writes = write_reach(scopes, req.read_only);
let mut perms: Vec<String> = groups.iter().map(|g| format!("g/{g}")).collect();
perms.push(format!("u/{username}"));
// Each listed folder, and whether the token can change items there (so reading is not enough).
let mut listed: Vec<(String, bool)> = vec![];
if let Some(reach) = &reach {
for f in sqlx::query_scalar!(
"SELECT name FROM folder WHERE workspace_id = $1 ORDER BY name",
w_id
)
.fetch_all(db)
.await?
{
let prefix = format!("f/{f}/");
if !reach.covers_prefix(&prefix) {
continue;
}
let needs_write = writes.as_ref().is_some_and(|w| w.covers_prefix(&prefix));
let short = if needs_write {
!writable_folders.contains(&f.as_str())
} else {
!member_folders.contains(&f)
};
if short {
listed.push((f, needs_write));
}
}
}
let folders_write = listed.iter().any(|(_, w)| *w);
let mut folders: Vec<String> = listed.into_iter().map(|(f, _)| f).collect();
let folders_total = folders.len();
folders.truncate(MAX_FOLDERS);
let other_users_items = if reach
.as_ref()
.is_some_and(|r| r.covers_other_users(username))
{
let own = format!("u/{username}/");
sqlx::query!(
r#"SELECT 'scripts' AS "domain!", path AS "path!" FROM script WHERE workspace_id = $1 AND NOT archived
AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3
UNION
SELECT 'flows', path FROM flow WHERE workspace_id = $1 AND NOT archived
AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3
UNION ALL
SELECT 'apps', path FROM app WHERE workspace_id = $1
AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3
UNION ALL
SELECT 'resources', path FROM resource WHERE workspace_id = $1
AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3
UNION ALL
SELECT 'variables', path FROM variable WHERE workspace_id = $1
AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3
LIMIT 10000"#,
w_id,
own,
&perms[..],
)
.fetch_all(db)
.await?
.into_iter()
.filter(|item| reaches_item(scopes, &item.domain, &item.path))
.count() as i64
} else {
0
};
let runnables: Vec<(&str, String)> = scopes
.iter()
.flat_map(|s| s.iter())
.flat_map(|s| scope_runnables(s))
.collect();
let mut assets = vec![];
if !runnables.is_empty() {
let own = format!("u/{username}/");
let candidates: Vec<AssetOutOfReach> = sqlx::query!(
r#"SELECT DISTINCT usage_kind::text AS "usage_kind!", usage_path, kind::text AS "kind!", path
FROM asset
WHERE workspace_id = $1 AND usage_kind IN ('script', 'flow')
AND kind = 'resource'
ORDER BY usage_path, path"#,
w_id
)
.fetch_all(db)
.await?
.into_iter()
.filter(|a| {
runnables
.iter()
.any(|(kind, p)| *kind == a.usage_kind && pattern_matches(p, &a.usage_path))
})
.filter(|a| {
// A member reads their own space, folders they are in and their groups' `g/` paths.
let mut segments = a.path.splitn(3, '/');
let (space, name) = (segments.next(), segments.next().unwrap_or_default());
!a.path.starts_with(&own)
&& !(space == Some("f") && member_folders.iter().any(|m| m == name))
&& !(space == Some("g") && groups.iter().any(|g| g == name))
})
.map(|a| AssetOutOfReach {
runnable_kind: a.usage_kind,
runnable_path: a.usage_path,
kind: a.kind,
path: a.path,
})
.collect();
if !candidates.is_empty() {
let paths: Vec<String> = candidates.iter().map(|a| a.path.clone()).collect();
let shared = sqlx::query_scalar!(
"SELECT path FROM resource
WHERE workspace_id = $1 AND path = ANY($2) AND extra_perms ?| $3",
w_id,
&paths[..],
&perms[..],
)
.fetch_all(db)
.await?;
assets = candidates
.into_iter()
.filter(|a| !shared.contains(&a.path))
.take(MAX_ASSETS)
.collect();
}
}
Ok(WorkspaceAdminReliance {
workspace_id: w_id.to_string(),
username: username.to_string(),
folders,
folders_total,
folders_write,
other_users_items,
assets,
admin_only: admin_only_actions(scopes, req.read_only),
})
}
/// For each workspace the caller administers among those asked, what a token with these
/// scopes would lose without their admin rights. Only a credential carrying those rights may
/// ask, since the answer names folders a member cannot see.
pub(crate) async fn admin_reliance(
authed: ApiAuthed,
Extension(db): Extension<DB>,
Json(req): Json<AdminRelianceRequest>,
) -> JsonResult<Vec<WorkspaceAdminReliance>> {
if authed.admin_withheld || authed.job_id.is_some() || authed.scopes.is_some() {
return Err(Error::PermissionDenied(
"Checking what a token would need admin rights for takes a credential carrying your admin rights"
.to_string(),
));
}
let memberships = sqlx::query!(
"SELECT workspace_id, username FROM usr
WHERE email = $1 AND is_admin AND NOT disabled
AND ($2::text[] IS NULL OR workspace_id = ANY($2))
ORDER BY workspace_id LIMIT $3",
authed.email,
req.workspace_ids.as_deref(),
MAX_WORKSPACES,
)
.fetch_all(&db)
.await?;
let mut out = vec![];
for m in memberships {
let reliance =
workspace_reliance(&db, &m.workspace_id, &m.username, &authed.email, &req).await?;
if !reliance.is_empty() {
out.push(reliance);
}
}
Ok(Json(out))
}
const WITHHELD_ADMIN_HINT: &str = "This credential does not carry your workspace admin rights: \
it is a token created without them, or a job such a token started, so it acts as a regular \
member here. If it needs access your admin role gave you, add yourself to the folder holding the \
item (as a writer to change it), or create a token with Workspace admin rights.";
/// Refusal bodies a 400 can carry that a missing grant explains.
fn reads_as_refusal(body: &str) -> bool {
let body = body.to_ascii_lowercase();
[
"permission",
"not a writer",
"owner",
"not authorized",
"admin",
]
.iter()
.any(|k| body.contains(k))
}
/// Appends [`WITHHELD_ADMIN_HINT`] to a workspace route's refusal (an [`Error`] response, never a
/// body a job chose) when the credential withholds admin rights its owner holds there.
/// Resolved only once a request has been refused, so requests that succeed pay nothing beyond
/// reading the header.
pub(crate) async fn hint_withheld_admin(req: Request, next: Next) -> Response {
let token = req
.headers()
.get(http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::to_string);
let path_vec: Vec<&str> = req.uri().path().split('/').collect();
let w_id = maybe_get_workspace_id_from_path(&path_vec);
let (Some(token), Some(w_id)) = (token, w_id) else {
return next.run(req).await;
};
let cache = req.extensions().get::<Arc<AuthCache>>().cloned();
let db = req.extensions().get::<DB>().cloned();
let client_ip = client_ip_of(req.extensions(), req.headers());
let res = next.run(req).await;
let status = res.status();
if !matches!(
status,
StatusCode::BAD_REQUEST
| StatusCode::UNAUTHORIZED
| StatusCode::FORBIDDEN
| StatusCode::NOT_FOUND
) || res.extensions().get::<ServerError>().is_none()
{
return res;
}
let (Some(cache), Some(db)) = (cache, db) else {
return res;
};
let Some(OptJobAuthed { authed, .. }) = cache
.get_opt_job_authed(Some(w_id.clone()), &token, client_ip)
.await
else {
return res;
};
if !authed.admin_withheld || authed.is_admin {
return res;
}
let owner_is_admin = sqlx::query_scalar!(
"SELECT is_admin FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled",
w_id,
authed.email
)
.fetch_optional(&db)
.await
.ok()
.flatten()
.unwrap_or(false);
if !owner_is_admin {
return res;
}
const MAX_HINTED_BODY: u64 = 64 * 1024;
if axum::body::HttpBody::size_hint(res.body())
.upper()
.is_none_or(|n| n > MAX_HINTED_BODY)
{
return res;
}
let (mut parts, body) = res.into_parts();
let Ok(bytes) = axum::body::to_bytes(body, MAX_HINTED_BODY as usize).await else {
return Response::from_parts(parts, axum::body::Body::empty());
};
let text = String::from_utf8_lossy(&bytes);
if status == StatusCode::BAD_REQUEST && !reads_as_refusal(&text) {
return Response::from_parts(parts, axum::body::Body::from(bytes));
}
parts.headers.remove(http::header::CONTENT_LENGTH);
Response::from_parts(
parts,
axum::body::Body::from(format!("{text}\n\n{WITHHELD_ADMIN_HINT}")),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn reach_follows_the_scopes() {
assert_eq!(PathReach::of(None), Some(PathReach::All));
assert_eq!(
PathReach::of(Some(&s(&["users:read", "mcp:endpoints:listJobs"]))),
None
);
assert_eq!(
PathReach::of(Some(&s(&["scripts:read"]))),
Some(PathReach::All)
);
assert_eq!(PathReach::of(Some(&s(&["mcp:all"]))), Some(PathReach::All));
assert_eq!(PathReach::of(Some(&s(&["mcp:workspaces:a,b"]))), None);
let r =
PathReach::of(Some(&s(&["scripts:read:f/etl/*", "jobs:run:flows:u/me/x"]))).unwrap();
assert!(r.covers_prefix("f/etl/"));
assert!(!r.covers_prefix("f/billing/"));
assert!(!r.covers_other_users("me"));
let r = PathReach::of(Some(&s(&["resources:read:f/*"]))).unwrap();
assert!(r.covers_prefix("f/billing/"));
assert!(!r.covers_other_users("me"));
let r = PathReach::of(Some(&s(&["variables:read:u/bob/*"]))).unwrap();
assert!(r.covers_other_users("me"));
}
#[test]
fn runnables_named_by_scopes() {
assert_eq!(
scope_runnables("mcp:scripts:f/etl/sync,f/etl/load"),
vec![
("script", "f/etl/sync".to_string()),
("script", "f/etl/load".to_string())
]
);
assert_eq!(
scope_runnables("jobs:run:flows:f/x/*"),
vec![("flow", "f/x/*".to_string())]
);
assert!(scope_runnables("mcp:scripts:*").is_empty());
assert!(scope_runnables("scripts:read:f/x/y").is_empty());
}
#[test]
fn admin_only_follows_the_scopes() {
assert_eq!(admin_only_actions(None, false).len(), ADMIN_ONLY.len());
assert!(admin_only_actions(None, true).is_empty());
assert!(admin_only_actions(Some(&s(&["scripts:write"])), false).is_empty());
assert_eq!(
admin_only_actions(Some(&s(&["workspaces:write"])), false),
vec!["change workspace settings".to_string()]
);
}
#[test]
fn item_reach_follows_domain_and_path() {
let sc = s(&["scripts:read:u/alice/x", "mcp:flows:u/bob/*"]);
assert!(reaches_item(Some(&sc), "scripts", "u/alice/x"));
assert!(!reaches_item(Some(&sc), "scripts", "u/bob/y"));
assert!(!reaches_item(Some(&sc), "resources", "u/alice/x"));
assert!(reaches_item(Some(&sc), "flows", "u/bob/y"));
assert!(reaches_item(
Some(&s(&["variables:read"])),
"variables",
"u/bob/v"
));
assert!(reaches_item(Some(&s(&["mcp:all"])), "apps", "u/bob/a"));
assert!(reaches_item(None, "apps", "u/bob/a"));
}
#[test]
fn write_access_follows_the_scopes() {
let w = |sc: &[&str]| write_reach(Some(&s(sc)), false);
assert_eq!(write_reach(None, false), Some(PathReach::All));
assert_eq!(write_reach(None, true), None);
assert_eq!(w(&["scripts:read", "jobs:run:scripts"]), None);
assert_eq!(w(&["mcp:all"]), Some(PathReach::All));
assert_eq!(w(&["mcp:read_run"]), None);
assert_eq!(w(&["mcp:scripts:f/x/y"]), None);
assert_eq!(w(&["mcp:all", "mcp:read_only"]), None);
// Writing reaches only where a write scope does, not every folder the token reads.
let mixed = w(&["scripts:read:f/etl/*", "variables:write:u/admin/*"]).unwrap();
assert!(!mixed.covers_prefix("f/etl/"));
assert!(w(&["scripts:write:f/x/*"]).unwrap().covers_prefix("f/x/"));
}
}