From 2efcb9b1d93161d1e19eac65cedcbd8d3e6dea3c Mon Sep 17 00:00:00 2001 From: hugocasa Date: Thu, 3 Dec 2026 10:31:00 +0100 Subject: [PATCH] fix: keep withheld admin rights in the tools preview, name what a partial author or the deploy rules hold back Co-Authored-By: Claude Opus 5.5 --- backend/tests/mcp_role_access.rs | 16 +++++ backend/windmill-api/openapi.yaml | 5 ++ backend/windmill-api/src/mcp/core.rs | 6 -- backend/windmill-api/src/mcp/role_access.rs | 68 +++++++++++++++++-- .../lib/components/mcp/McpAccessPicker.svelte | 24 ++++--- .../components/mcp/workspaceAccess.test.ts | 6 ++ .../src/lib/components/mcp/workspaceAccess.ts | 28 +++++--- .../components/settings/CreateToken.svelte | 36 +++++++--- .../settings/EditTokenScopesModal.svelte | 24 ++++--- .../components/settings/TokenDisplay.svelte | 9 ++- .../oauth/mcp_authorize/+page@(root).svelte | 56 +++++++-------- 11 files changed, 197 insertions(+), 81 deletions(-) diff --git a/backend/tests/mcp_role_access.rs b/backend/tests/mcp_role_access.rs index feca55640f..57fc70919f 100644 --- a/backend/tests/mcp_role_access.rs +++ b/backend/tests/mcp_role_access.rs @@ -157,6 +157,22 @@ async fn role_setting_caps_every_token(db: Pool) -> anyhow::Result<()> .filter_map(|t| t["name"].as_str()) .collect(); assert_eq!(names, ["in_set"], "{preview}"); + // A token holding back its owner's admin rights would list scripts only an admin reads. + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, email, label, super_admin, admin) + VALUES (encode(sha256('NOADMIN_TOKEN'::bytea), 'hex'), 'NOADMIN_TO', $1, 'mcp', false, false)", + ) + .bind(admin) + .execute(&db) + .await?; + let refused = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/mcp/gateway/oauth/server/runnable_tools?workspace_id=test-workspace" + )) + .bearer_auth("NOADMIN_TOKEN") + .send() + .await?; + assert!(!refused.status().is_success(), "{}", refused.status()); let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move { mcp( port, diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 42ebaab5ea..dfac0a1926 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -42272,6 +42272,11 @@ components: description: With `run_and_edit`, the kinds the caller's role edits. items: type: string + withheld: + type: array + description: With `build_and_run`, what is held back all the same - `scripts`, `flows` or `apps` the role does not author, and `deploy` where the deploy rules block the caller. + items: + type: string required: [id, name, access, limited] McpRoleSetting: diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index cddce0af0e..52b9a6434e 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -906,11 +906,6 @@ pub async fn add_www_authenticate_header_gateway( } } -/// The tools server's runner, for the consent page to list what a connection would get. Set -/// once the MCP server is set up; unset in a process that serves no MCP. -pub(crate) static PREVIEW_RUNNER: std::sync::OnceLock> = - std::sync::OnceLock::new(); - impl From for ToolsetEntry { fn from(tool: windmill_mcp::server::Tool) -> Self { ToolsetEntry { @@ -934,7 +929,6 @@ pub async fn setup_mcp_server( let backend = WindmillBackend::new(db.clone(), user_db, base_internal_url, auth_cache); let session_runner = SessionRunner::new(backend.clone()); let runner = Runner::new(backend); - let _ = PREVIEW_RUNNER.set(runner.clone()); let service_config = StreamableHttpServerConfig::default() .with_sse_keep_alive(Some(Duration::from_secs(15))) diff --git a/backend/windmill-api/src/mcp/role_access.rs b/backend/windmill-api/src/mcp/role_access.rs index efd794a737..47dc4b1d9b 100644 --- a/backend/windmill-api/src/mcp/role_access.rs +++ b/backend/windmill-api/src/mcp/role_access.rs @@ -9,7 +9,7 @@ use windmill_common::{ db::UserDB, error::{Error, JsonResult}, roles::{self, McpRoleAccess, McpRoleSetting, RoleCapabilities}, - workspaces::ProtectionRules, + workspaces::{check_deploy_rules, ProtectionRules, RuleCheckResult}, DB, }; use windmill_mcp::server::{ @@ -74,6 +74,9 @@ struct MemberAccess { can_run: bool, /// With `RunAndEdit`, what the role edits. edits: Vec<&'static str>, + /// With `BuildAndRun`, what is held back all the same: the kinds the role does not author, + /// and `deploy` where the deploy rules block the member. + withheld: Vec<&'static str>, } /// What a connection with `access` gets in each workspace, for `list_workspaces`. Community, where @@ -147,6 +150,14 @@ async fn accesses( ) .fetch_all(db) .await?; + let deployers_only: Vec = sqlx::query_scalar!( + "SELECT DISTINCT workspace_id FROM workspace_protection_rule + WHERE workspace_id = ANY($1) AND rules & $2 <> 0", + &ids, + ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS.bits() + ) + .fetch_all(db) + .await?; let instance = roles::instance_roles(db).await?; let mut out = HashMap::with_capacity(ids.len()); @@ -155,6 +166,7 @@ async fn accesses( let mut builds = true; let mut limit = None; let mut edits = vec![]; + let mut withheld = vec![]; let member = members.iter().find(|m| m.workspace_id == id); if let Some(m) = member { // Roles that cannot be read refuse every call there, as `caller_mcp_limit` does. @@ -178,6 +190,15 @@ async fn accesses( session = SessionAccess::ReadOnly; } builds = caps.is_author(); + if !caps.code { + withheld.push("scripts"); + } + if caps.flows == roles::AuthorLevel::None { + withheld.push("flows"); + } + if caps.apps == roles::AuthorLevel::None { + withheld.push("apps"); + } // Folder rights, not the role, gate these two. edits.extend(["resources", "variables"]); if caps.manage_schedules { @@ -205,8 +226,28 @@ async fn accesses( (_, SessionAccess::Full) if !builds => WorkspaceMcpAccess::RunAndEdit, (_, SessionAccess::Full) => WorkspaceMcpAccess::BuildAndRun, }; + // Checked per member, only where a rule keeps deploying to deployers. + if let Some(m) = member + .filter(|_| access == WorkspaceMcpAccess::BuildAndRun && deployers_only.contains(&id)) + { + let groups = + windmill_common::auth::get_groups_for_user(&id, &m.username, email, db).await?; + if matches!( + check_deploy_rules(&id, &m.username, &groups, m.is_admin || super_admin, db) + .await?, + RuleCheckResult::Blocked(_) + ) { + withheld.push("deploy"); + } + } + if access != WorkspaceMcpAccess::BuildAndRun { + withheld.clear(); + } let username = member.map(|m| m.username.clone()); - out.insert(id, MemberAccess { access, limit, username, can_run, edits }); + out.insert( + id, + MemberAccess { access, limit, username, can_run, edits, withheld }, + ); } Ok(out) } @@ -224,6 +265,10 @@ pub struct WorkspaceAccessEntry { /// With `run_and_edit`, the kinds the caller's role edits. #[serde(skip_serializing_if = "Vec::is_empty")] edits: Vec<&'static str>, + /// With `build_and_run`, what is held back all the same: `scripts`, `flows`, `apps` the role + /// does not author, and `deploy` where the deploy rules block the caller. + #[serde(skip_serializing_if = "Vec::is_empty")] + withheld: Vec<&'static str>, } #[derive(Deserialize)] @@ -313,6 +358,7 @@ pub async fn list_workspace_access( } else { vec![] }, + withheld: member.withheld.clone(), id: w.id, name: w.name, }); @@ -329,6 +375,8 @@ pub struct RunnableToolsQuery { /// workspace would list where the caller's role offers them as tools, with their arguments. pub async fn list_runnable_tools( Extension(db): Extension, + Extension(user_db): Extension, + Extension(auth_cache): Extension>, authed: ApiAuthed, Query(query): Query, ) -> JsonResult> { @@ -341,6 +389,12 @@ pub async fn list_runnable_tools( "A scope-restricted token cannot list its owner's tools".to_string(), )); } + // The listing runs with the owner's admin rights, which this token does not carry. + if authed.admin_withheld { + return Err(Error::NotAuthorized( + "A token without its owner's admin rights cannot list its owner's tools".to_string(), + )); + } let w_id = query.workspace_id; let username = accesses( &db, @@ -353,9 +407,13 @@ pub async fn list_runnable_tools( .remove(&w_id) .and_then(|m| m.username) .ok_or_else(|| Error::NotFound(format!("You are not a member of '{w_id}'")))?; - let runner = super::core::PREVIEW_RUNNER - .get() - .ok_or_else(|| Error::BadRequest("This server does not serve MCP".to_string()))?; + // Listing reads the database only, so no internal URL is needed. + let runner = windmill_mcp::server::Runner::new(super::core::WindmillBackend::new( + db.clone(), + user_db, + String::new(), + auth_cache, + )); let there: ApiAuthed = windmill_common::auth::fetch_authed_from_permissioned_as( &format!("u/{username}"), &authed.email, diff --git a/frontend/src/lib/components/mcp/McpAccessPicker.svelte b/frontend/src/lib/components/mcp/McpAccessPicker.svelte index bf6aee8a9b..1bba198f52 100644 --- a/frontend/src/lib/components/mcp/McpAccessPicker.svelte +++ b/frontend/src/lib/components/mcp/McpAccessPicker.svelte @@ -43,7 +43,9 @@ initialScopes?: string[] /** Names the level that narrows nothing. */ fullLabel?: string - /** Rendered between the access choice and the tool list. */ + /** Rendered right under the access choice, as part of it. */ + belowAccess?: Snippet + /** Rendered after the access choice. */ afterAccess?: Snippet /** Offers the chosen level's tools in a dialog. */ showTools?: boolean @@ -55,6 +57,7 @@ access = $bindable(), initialScopes = [], fullLabel = 'Build and run', + belowAccess, afterAccess, showTools = false }: Props = $props() @@ -90,18 +93,19 @@
- Access +
+ Access + {#if showTools && toolsetAccess} + + {/if} +