diff --git a/backend/.sqlx/query-e93f5b749870394d8258b784bf4065d0d3d32856ead1a2a01d80566dfaac71e4.json b/backend/.sqlx/query-e93f5b749870394d8258b784bf4065d0d3d32856ead1a2a01d80566dfaac71e4.json new file mode 100644 index 0000000000..f1b19f3807 --- /dev/null +++ b/backend/.sqlx/query-e93f5b749870394d8258b784bf4065d0d3d32856ead1a2a01d80566dfaac71e4.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, name FROM workspace\n WHERE deleted = false AND ($2 OR EXISTS (\n SELECT 1 FROM usr WHERE workspace_id = workspace.id AND email = $1 AND disabled = false\n ))\n ORDER BY name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Bool" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "e93f5b749870394d8258b784bf4065d0d3d32856ead1a2a01d80566dfaac71e4" +} diff --git a/backend/.sqlx/query-cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b.json b/backend/.sqlx/query-ee761c085738bb22b01a48627e067b145f92f1c396817e4c13e50019fc085d6c.json similarity index 64% rename from backend/.sqlx/query-cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b.json rename to backend/.sqlx/query-ee761c085738bb22b01a48627e067b145f92f1c396817e4c13e50019fc085d6c.json index 8881f24f4d..22f1035e0c 100644 --- a/backend/.sqlx/query-cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b.json +++ b/backend/.sqlx/query-ee761c085738bb22b01a48627e067b145f92f1c396817e4c13e50019fc085d6c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT workspace_id, is_admin, operator, workspace_role FROM usr\n WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false", + "query": "SELECT workspace_id, username, is_admin, operator, workspace_role FROM usr\n WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false", "describe": { "columns": [ { @@ -10,16 +10,21 @@ }, { "ordinal": 1, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 2, "name": "is_admin", "type_info": "Bool" }, { - "ordinal": 2, + "ordinal": 3, "name": "operator", "type_info": "Bool" }, { - "ordinal": 3, + "ordinal": 4, "name": "workspace_role", "type_info": "Varchar" } @@ -34,8 +39,9 @@ false, false, false, + false, true ] }, - "hash": "cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b" + "hash": "ee761c085738bb22b01a48627e067b145f92f1c396817e4c13e50019fc085d6c" } diff --git a/backend/tests/mcp_list_run_gated.rs b/backend/tests/mcp_list_run_gated.rs index 9f0b889a05..c04884b5cc 100644 --- a/backend/tests/mcp_list_run_gated.rs +++ b/backend/tests/mcp_list_run_gated.rs @@ -140,6 +140,9 @@ async fn test_view_only_role_lists_no_runnable_tools(db: Pool) -> anyh ) .await?; let msg = run["error"]["message"].as_str().unwrap_or_default(); - assert!(msg.contains("read-only"), "run must stay refused: {run}"); + assert!( + msg.contains("in workspace test-workspace this session can only read"), + "run must stay refused: {run}" + ); Ok(()) } diff --git a/backend/tests/mcp_role_access.rs b/backend/tests/mcp_role_access.rs index e03719fe82..05d465eca8 100644 --- a/backend/tests/mcp_role_access.rs +++ b/backend/tests/mcp_role_access.rs @@ -140,6 +140,66 @@ async fn role_setting_caps_every_token(db: Pool) -> anyhow::Result<()> } assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty()); assert!(tools(port, WORKSPACE, "ROLEREAD_TOKEN").await.is_empty()); + // The consent page's preview of a sign-in bound here lists what the connection lists. + let preview: Value = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/w/test-workspace/mcp/runnable_tools" + )) + .bearer_auth("SECRET_TOKEN") + .send() + .await? + .json() + .await?; + let names: Vec<&str> = preview + .as_array() + .unwrap() + .iter() + .filter_map(|t| t["name"].as_str()) + .collect(); + assert_eq!(names, ["in_set"], "{preview}"); + // A credential holding back its owner's admin rights is previewed without them: a script only + // an admin reads is listed to the full credential alone. + sqlx::raw_sql( + "INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES + ('test-workspace', 'test-user-2', 'export function main() { return 1 }', '{}', '', '', 'u/test-user-2/private', 7788403, 'bun', ''); + INSERT INTO token (token_hash, token_prefix, email, label, super_admin, admin) + VALUES (encode(sha256('NOADMIN_TOKEN'::bytea), 'hex'), 'NOADMIN_TO', 'test@windmill.dev', 'mcp', false, false);", + ) + .execute(&db) + .await?; + set_access( + &db, + json!({"access": "runnables", "scripts": ["u/test-user/in_set", "u/test-user-2/private"]}), + ) + .await; + let preview = |bearer: &'static str| async move { + let tools: Value = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/w/test-workspace/mcp/runnable_tools" + )) + .bearer_auth(bearer) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let mut names: Vec = tools + .as_array() + .unwrap() + .iter() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect(); + names.sort(); + names + }; + assert_eq!(preview("SECRET_TOKEN").await, ["in_set", "private"]); + assert_eq!(preview("NOADMIN_TOKEN").await, ["in_set"]); + set_access( + &db, + json!({"access": "runnables", "scripts": ["u/test-user/in_set"]}), + ) + .await; let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move { mcp( port, @@ -168,7 +228,36 @@ async fn role_setting_caps_every_token(db: Pool) -> anyhow::Result<()> ); } + // A workspace that disables direct deployment lists the read-and-run tools, as the consent + // page shows it. + sqlx::raw_sql( + "UPDATE workspace_settings SET role_overrides = NULL WHERE workspace_id = 'test-workspace'; + INSERT INTO workspace_protection_rule (workspace_id, name, rules, bypass_groups, bypass_users) + VALUES ('test-workspace', 'locked', 1, '{}', '{}');", + ) + .execute(&db) + .await?; + windmill_common::roles::invalidate_workspace_roles_cache("test-workspace"); + windmill_common::workspaces::invalidate_protection_rules_cache("test-workspace"); + for t in ["ROLESESS_TOKEN", "ROLEUNBOUND_TOKEN"] { + let listed = tools(port, DEFAULT, t).await; + assert!( + has(&listed, "run_script") && !has(&listed, "deploy_workspace_item"), + "{t}: {listed:?}" + ); + } + sqlx::query("DELETE FROM workspace_protection_rule WHERE workspace_id = 'test-workspace'") + .execute(&db) + .await?; + windmill_common::workspaces::invalidate_protection_rules_cache("test-workspace"); + set_access(&db, json!({"access": "read_only"})).await; + // A connection covering several workspaces lists what the best of them gives. + let listed = tools(port, DEFAULT, "ROLEUNBOUND_TOKEN").await; + assert!( + has(&listed, "list_workspace_items") && !has(&listed, "run_script"), + "{listed:?}" + ); for url in [WORKSPACE, DEFAULT, GATEWAY] { let t = tools(port, url, "ROLEPLAIN_TOKEN").await; assert!(has(&t, "list_workspace_items"), "{url}: {t:?}"); @@ -188,12 +277,35 @@ async fn role_setting_caps_every_token(db: Pool) -> anyhow::Result<()> assert!( out["error"]["message"] .as_str() - .is_some_and(|m| m.contains("read-only")), + .is_some_and(|m| m.contains("in workspace test-workspace this session can only read")), "{out}" ); let out = call(DEFAULT, "ROLEUNBOUND_TOKEN", "list_workspaces", json!({})).await; assert!(out["result"].to_string().contains("read only"), "{out}"); + let listed = |bearer: &'static str| async move { + reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/mcp/gateway/oauth/server/workspace_access" + )) + .bearer_auth(bearer) + .send() + .await + .unwrap() + }; + let access: Value = listed("SECRET_TOKEN").await.json().await?; + let here = access + .as_array() + .unwrap() + .iter() + .find(|w| w["id"] == "test-workspace") + .unwrap(); + assert_eq!(here["access"], json!("read_only")); + assert!( + !listed("ROLEUNBOUND_TOKEN").await.status().is_success(), + "a scoped token must not list its owner's other workspaces" + ); + set_access(&db, json!({"access": "off"})).await; assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty()); assert_eq!( diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index bf3a2f098a..4d0836c24c 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -30019,6 +30019,67 @@ paths: items: $ref: "#/components/schemas/EndpointTool" + /mcp/gateway/oauth/server/workspace_access: + get: + summary: list what an MCP connection gets in each workspace + description: | + For each workspace the caller is a member of, what a connection asking for everything gets + there once their role and the workspace's rules have narrowed it. + operationId: listMcpWorkspaceAccess + tags: + - mcp_oauth + parameters: + - name: super_admin + in: query + description: As a connection carrying the caller's superadmin rights, in every workspace of the instance. + schema: + type: boolean + - name: with_counts + in: query + description: Count the scripts and flows offered as tools. + schema: + type: boolean + responses: + "200": + description: the workspaces and their access + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/McpWorkspaceAccess" + + /w/{workspace}/mcp/runnable_tools: + get: + summary: list the scripts and flows a role offers as MCP tools in a workspace + description: | + What a sign-in bound to the workspace lists where the caller's role offers scripts and + flows as tools, with their arguments; empty under any other role. Listed with the rights + the caller's credential carries in the workspace. + operationId: listMcpRunnableTools + tags: + - mcp_oauth + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: the tools + content: + application/json: + schema: + type: array + items: + type: object + properties: + name: + type: string + description: + type: string + parameters: + type: object + description: The JSON Schema of its arguments. + required: [name, description, parameters] + /mcp/gateway/oauth/server/client/{client_id}: get: summary: get an MCP client registered with Windmill's OAuth server @@ -42268,6 +42329,24 @@ components: additionalProperties: type: boolean + McpWorkspaceAccess: + type: object + properties: + id: + type: string + name: + type: string + access: + type: string + enum: [build_and_run, run_and_edit, read_and_run, read_only, runnables, "off"] + runnables: + type: integer + description: With `runnables`, how many scripts and flows are offered. + restricted: + type: boolean + description: With `build_and_run`, whether the caller's role still authors only some kinds, or the deploy rules block the caller. + required: [id, name, access, restricted] + McpRoleSetting: type: object description: The most a role's members may do through MCP, whatever their token grants (EE). Unset falls through to the layer below. diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index 01ccfd503c..38fa8287e6 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -883,12 +883,14 @@ async fn call_generated_tool( return Err(CallRefused::UnknownTool(format!("Unknown tool '{name}'"))); }; if !allowed(def, ctx.access) { - let token = match ctx.access { - SessionAccess::ReadAndRun => "can only read and run deployed scripts and flows", - _ => "is read-only", + // Named per workspace: a session covering several gives each its own access. + let can = match ctx.access { + SessionAccess::ReadAndRun => "only read and run deployed scripts and flows", + _ => "only read", }; return Err(CallRefused::NotAllowed(format!( - "Tool '{name}' changes or runs something, and this session {token}" + "Tool '{name}' changes or runs something, and in workspace {} this session can {can}", + ctx.w_id ))); } dispatch(ctx, name, args).await.ok_or_else(|| { diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 81b5c70982..c4161e91ce 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -845,6 +845,15 @@ pub async fn run_server( #[cfg(not(feature = "mcp"))] Router::new() }) + .nest("/mcp/runnable_tools", { + #[cfg(feature = "mcp")] + { + mcp::runnable_tools_service() + } + + #[cfg(not(feature = "mcp"))] + Router::new() + }) .nest("/ai", ai::workspaced_service()) .nest( "/ai_session_tools", diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 00709b5fbe..80dd009e26 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -14,7 +14,7 @@ use windmill_mcp::common::types::{ FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo, }; use windmill_mcp::server::{ - admits, session_limit, BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, + admits, session_in, BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, McpLimit, McpRequest, PathFilter, RunOutcome, SessionAccess, Tool, }; @@ -74,16 +74,12 @@ pub struct WindmillBackend { /// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. The /// chat alone lets a bypasser opt one session into working there directly, behind a confirmation /// an MCP client has no equivalent of, so a token stays held. -fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess { - let locked = rules.map_or(true, |rules| { +fn locked(rules: Option<&[ProtectionRuleset]>) -> bool { + rules.map_or(true, |rules| { rules .iter() .any(|r| r.rules.contains(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)) - }); - match access { - SessionAccess::Full if locked => SessionAccess::ReadAndRun, - other => other, - } + }) } impl WindmillBackend { @@ -93,26 +89,7 @@ impl WindmillBackend { w_id: &'a str, access: SessionAccess, ) -> BackendResult> { - let access = match self.mcp_limit(auth, w_id).await? { - Some(limit) => access.min(session_limit(w_id, &limit)?), - None => access, - }; - let access = match access { - SessionAccess::Full => { - let rules = get_protection_rules(w_id, &self.db).await.ok(); - workspace_access(access, rules.as_deref().map(Vec::as_slice)) - } - other => other, - }; - // A role without `run` reads only, whatever the token grants. The in-app chat applies the - // same rule (`resolveSessionAccess` in `chat/global/sessionAccess.ts`): change both. - let access = if access != SessionAccess::ReadOnly - && !self.can_run(auth, w_id).await.unwrap_or(true) - { - SessionAccess::ReadOnly - } else { - access - }; + let access = self.session_access(auth, w_id, access).await?; Ok(session::Ctx::new( auth, w_id, @@ -572,10 +549,30 @@ impl McpBackend for WindmillBackend { auth: &ApiAuthed, workspaces: &[WorkspaceInfo], access: SessionAccess, - ) -> BackendResult> { + ) -> BackendResult> { super::role_access::workspace_accesses(&self.db, &auth.email, workspaces, access).await } + async fn session_access( + &self, + auth: &ApiAuthed, + workspace_id: &str, + access: SessionAccess, + ) -> BackendResult { + // The in-app chat applies the same rules (`resolveSessionAccess` in + // `chat/global/sessionAccess.ts`): change both. + let limit = self.mcp_limit(auth, workspace_id).await?; + let rules = get_protection_rules(workspace_id, &self.db).await.ok(); + let can_run = self.can_run(auth, workspace_id).await.unwrap_or(true); + session_in( + workspace_id, + access, + limit.as_ref(), + locked(rules.as_deref().map(Vec::as_slice)), + can_run, + ) + } + async fn session_instructions( &self, auth: &ApiAuthed, @@ -906,6 +903,16 @@ pub async fn add_www_authenticate_header_gateway( } } +impl From for ToolsetEntry { + fn from(tool: windmill_mcp::server::Tool) -> Self { + ToolsetEntry { + name: tool.name.to_string(), + description: tool.description.map(|d| d.to_string()).unwrap_or_default(), + parameters: serde_json::Value::Object((*tool.input_schema).clone()), + } + } +} + /// Setup the MCP server with HTTP transport pub async fn setup_mcp_server( db: DB, @@ -1026,9 +1033,11 @@ struct ToolsetQuery { } #[derive(serde::Serialize)] -struct ToolsetEntry { +pub(crate) struct ToolsetEntry { name: String, description: String, + /// The JSON Schema of its arguments. + parameters: serde_json::Value, } /// The tools `/api/mcp` offers an `mcp:all` token at each access level, for the token @@ -1044,10 +1053,7 @@ async fn list_toolset_handler( Ok(Json( session::session_tools(access) .into_iter() - .map(|tool| ToolsetEntry { - name: tool.name.to_string(), - description: tool.description.map(|d| d.to_string()).unwrap_or_default(), - }) + .map(ToolsetEntry::from) .collect(), )) } @@ -1059,8 +1065,8 @@ pub fn toolset_service() -> Router { #[cfg(test)] mod tests { use super::{ - scoped_to_selection, serves_session_toolset, workspace_access, ProtectionRules, - ProtectionRuleset, SessionAccess, + locked, scoped_to_selection, serves_session_toolset, ProtectionRules, ProtectionRuleset, + SessionAccess, }; #[test] @@ -1073,14 +1079,12 @@ mod tests { bypass_users: vec!["admin".to_string()], fork_role_mapping: Default::default(), }; - let locked = [ruleset(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)]; + let held = [ruleset(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)]; let open = [ruleset(ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS)]; - use SessionAccess::*; - assert_eq!(workspace_access(Full, Some(&locked)), ReadAndRun); - assert_eq!(workspace_access(Full, None), ReadAndRun); - assert_eq!(workspace_access(Full, Some(&open)), Full); - assert_eq!(workspace_access(Full, Some(&[])), Full); - assert_eq!(workspace_access(ReadOnly, Some(&locked)), ReadOnly); + assert!(locked(Some(&held))); + assert!(locked(None)); + assert!(!locked(Some(&open))); + assert!(!locked(Some(&[]))); } #[test] diff --git a/backend/windmill-api/src/mcp/mod.rs b/backend/windmill-api/src/mcp/mod.rs index fe5caf9931..e784857be7 100644 --- a/backend/windmill-api/src/mcp/mod.rs +++ b/backend/windmill-api/src/mcp/mod.rs @@ -17,3 +17,4 @@ pub use core::{ extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service, reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint, }; +pub use role_access::runnable_tools_service; diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index 97b3d1e518..1d4e5c2fdd 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -1297,6 +1297,10 @@ pub fn gateway_authed_service() -> Router { Router::new() .route("/approve", post(gateway_oauth_approve)) .route("/client/{client_id}", get(get_registered_client)) + .route( + "/workspace_access", + get(super::role_access::list_workspace_access), + ) } #[cfg(test)] diff --git a/backend/windmill-api/src/mcp/role_access.rs b/backend/windmill-api/src/mcp/role_access.rs index 736bcad42a..600ac78c5f 100644 --- a/backend/windmill-api/src/mcp/role_access.rs +++ b/backend/windmill-api/src/mcp/role_access.rs @@ -2,13 +2,25 @@ use std::collections::HashMap; +use axum::{ + extract::{Path, Query}, + Extension, Json, +}; +use serde::{Deserialize, Serialize}; use windmill_api_auth::ApiAuthed; 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::{BackendResult, ErrorData, McpLimit, SessionAccess, WorkspaceInfo}; +use windmill_mcp::server::{ + session_in, workspace_mcp_url, BackendResult, ErrorData, McpLimit, PathFilter, SessionAccess, + WorkspaceInfo, +}; + +use super::utils::count_items; fn limit_of(setting: &McpRoleSetting) -> Option { match setting.access { @@ -43,38 +55,85 @@ pub(super) async fn mcp_limit( }) } -/// What a connection with `access` gets in each workspace, in three queries however many there -/// are. Community, where no role limits anything, queries nothing and lists none. +/// What a connection gets in one workspace, once its member's role and the workspace's rules have +/// narrowed the access it was granted. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkspaceMcpAccess { + BuildAndRun, + /// A role that authors no script, flow or app still edits what it may: schedules, triggers, + /// resources. + RunAndEdit, + ReadAndRun, + ReadOnly, + Runnables, + Off, +} + +struct MemberAccess { + access: WorkspaceMcpAccess, + /// The role's own limit there. + limit: Option, + username: Option, + can_run: bool, + /// With `RunAndEdit`, what the role edits. + edits: Vec<&'static str>, + /// With `BuildAndRun`, whether the role still authors only some kinds, or the deploy rules + /// block the member. + restricted: bool, +} + +/// What a connection with `access` gets in each workspace, for `list_workspaces`. Community, where +/// no role limits anything, queries nothing and lists none. pub(super) async fn workspace_accesses( db: &DB, email: &str, workspaces: &[WorkspaceInfo], access: SessionAccess, -) -> BackendResult> { +) -> BackendResult> { if !cfg!(feature = "enterprise") { return Ok(HashMap::new()); } - accesses(db, email, workspaces, access) + let ids = workspaces.iter().map(|w| w.id.clone()).collect(); + Ok(accesses(db, email, ids, access, false) .await - .map_err(|e| ErrorData::internal_error(e.to_string(), None)) + .map_err(|e| ErrorData::internal_error(e.to_string(), None))? + .into_iter() + .map(|(id, m)| { + let text = match m.access { + WorkspaceMcpAccess::BuildAndRun => "build and run".to_string(), + WorkspaceMcpAccess::RunAndEdit => { + format!("read and run, edit {}", m.edits.join(", ")) + } + WorkspaceMcpAccess::ReadAndRun => "read and run".to_string(), + WorkspaceMcpAccess::ReadOnly => "read only".to_string(), + WorkspaceMcpAccess::Runnables => { + format!("scripts and flows as tools, on {}", workspace_mcp_url(&id)) + } + WorkspaceMcpAccess::Off => "off".to_string(), + }; + (id, text) + }) + .collect()) } +/// `super_admin`: the connection carries its owner's superadmin rights. In three queries however many workspaces there are. async fn accesses( db: &DB, email: &str, - workspaces: &[WorkspaceInfo], + ids: Vec, access: SessionAccess, -) -> windmill_common::error::Result> { - let ids: Vec = workspaces.iter().map(|w| w.id.clone()).collect(); + super_admin: bool, +) -> windmill_common::error::Result> { let members = sqlx::query!( - "SELECT workspace_id, is_admin, operator, workspace_role FROM usr + "SELECT workspace_id, username, is_admin, operator, workspace_role FROM usr WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false", email, &ids ) .fetch_all(db) .await?; - let mut overrides: HashMap = sqlx::query!( + let mut overrides: HashMap> = sqlx::query!( "SELECT workspace_id, role_overrides FROM workspace_settings WHERE workspace_id = ANY($1) AND role_overrides IS NOT NULL", &ids @@ -82,11 +141,9 @@ async fn accesses( .fetch_all(db) .await? .into_iter() - .filter_map(|r| { - Some(( - r.workspace_id, - serde_json::from_value(r.role_overrides?).ok()?, - )) + .map(|r| { + let overrides = serde_json::from_value(r.role_overrides.unwrap_or_default()).ok(); + (r.workspace_id, overrides) }) .collect(); let locked: Vec = sqlx::query_scalar!( @@ -97,57 +154,251 @@ 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()); for id in ids { - let mut access = access; + let mut can_run = true; let mut builds = true; - if let Some(m) = members.iter().find(|m| m.workspace_id == id) { - let roles = - roles::effective_roles(&instance, &overrides.remove(&id).unwrap_or_default())?; + let mut restricted = false; + let mut limit = None; + let mut edits = 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. + let roles = overrides + .remove(&id) + .unwrap_or_else(|| Some(Default::default())) + .and_then(|o| roles::effective_roles(&instance, &o).ok()); let name = roles::resolve_role_name(m.workspace_role.clone(), m.operator); - let role = roles.iter().find(|r| r.name == name); - let limited = roles.iter().any(|r| r.mcp_limit().is_some()); - let limit = match role { - Some(role) => role.mcp_limit().and_then(limit_of), - None => limited.then_some(McpLimit::Off), + let role = roles.iter().flatten().find(|r| r.name == name); + limit = match (&roles, role) { + (Some(_), Some(role)) => role.mcp_limit().and_then(limit_of), + (Some(roles), None) => roles + .iter() + .any(|r| r.mcp_limit().is_some()) + .then_some(McpLimit::Off), + (None, _) => cfg!(feature = "enterprise").then_some(McpLimit::Off), }; - match limit { - None => {} - Some(McpLimit::ReadAndRun) => access = access.min(SessionAccess::ReadAndRun), - Some(McpLimit::ReadOnly) => access = SessionAccess::ReadOnly, - Some(McpLimit::Runnables { .. }) => { - out.insert( - id, - "scripts and flows as tools, on this workspace's own MCP URL", - ); - continue; - } - Some(McpLimit::Off) => { - out.insert(id, "off"); - continue; - } - } - if !m.is_admin { + if !m.is_admin && !super_admin { let caps = role.map_or(RoleCapabilities::NONE, |r| r.capabilities); - if !caps.run { - access = SessionAccess::ReadOnly; - } + can_run = caps.run; builds = caps.is_author(); + restricted = !caps.code + || caps.flows == roles::AuthorLevel::None + || caps.apps == roles::AuthorLevel::None; + // Folder rights, not the role, gate these two. + edits.extend(["resources", "variables"]); + if caps.manage_schedules { + edits.push("schedules"); + } + if caps.manage_triggers { + edits.push("triggers"); + } } } - if access == SessionAccess::Full && (!builds || locked.contains(&id)) { - access = SessionAccess::ReadAndRun; + let session = session_in(&id, access, limit.as_ref(), locked.contains(&id), can_run); + let access = match (&limit, session) { + (Some(McpLimit::Runnables { .. }), Err(_)) => WorkspaceMcpAccess::Runnables, + (_, Err(_)) => WorkspaceMcpAccess::Off, + (_, Ok(SessionAccess::ReadOnly)) => WorkspaceMcpAccess::ReadOnly, + (_, Ok(SessionAccess::ReadAndRun)) => WorkspaceMcpAccess::ReadAndRun, + (_, Ok(SessionAccess::Full)) if !builds => WorkspaceMcpAccess::RunAndEdit, + (_, Ok(SessionAccess::Full)) => WorkspaceMcpAccess::BuildAndRun, + }; + // Checked per member, only where a rule keeps deploying to deployers. + if let Some(m) = member.filter(|_| { + access == WorkspaceMcpAccess::BuildAndRun && !restricted && deployers_only.contains(&id) + }) { + let groups = + windmill_common::auth::get_groups_for_user(&id, &m.username, email, db).await?; + restricted = matches!( + check_deploy_rules(&id, &m.username, &groups, m.is_admin || super_admin, db) + .await?, + RuleCheckResult::Blocked(_) + ); } + let restricted = restricted && access == WorkspaceMcpAccess::BuildAndRun; + let username = member.map(|m| m.username.clone()); out.insert( id, - match access { - SessionAccess::ReadOnly => "read only", - SessionAccess::ReadAndRun => "read and run", - SessionAccess::Full => "build and run", - }, + MemberAccess { access, limit, username, can_run, edits, restricted }, ); } Ok(out) } + +#[derive(Serialize)] +pub struct WorkspaceAccessEntry { + id: String, + name: String, + access: WorkspaceMcpAccess, + /// With `runnables`, how many scripts and flows the caller would be offered. + #[serde(skip_serializing_if = "Option::is_none")] + runnables: Option, + /// With `build_and_run`, whether the role still authors only some kinds, or the deploy rules + /// block the caller. + restricted: bool, +} + +#[derive(Deserialize)] +pub struct WorkspaceAccessQuery { + /// As a connection carrying the caller's superadmin rights: every workspace of the instance. + #[serde(default)] + super_admin: bool, + #[serde(default)] + with_counts: bool, +} + +/// GET /api/mcp/gateway/oauth/server/workspace_access: what an MCP connection gets in each +/// workspace the caller is a member of, for the consent page to show. +pub async fn list_workspace_access( + Extension(db): Extension, + Extension(user_db): Extension, + authed: ApiAuthed, + Query(query): Query, +) -> JsonResult> { + // A token confined to some workspaces or routes must not learn of its owner's other ones. + if authed + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:"))) + { + return Err(Error::NotAuthorized( + "A scope-restricted token cannot list its owner's workspaces".to_string(), + )); + } + if query.super_admin { + windmill_api_auth::require_super_admin(&db, &authed).await?; + } + let workspaces = sqlx::query!( + "SELECT id, name FROM workspace + WHERE deleted = false AND ($2 OR EXISTS ( + SELECT 1 FROM usr WHERE workspace_id = workspace.id AND email = $1 AND disabled = false + )) + ORDER BY name", + authed.email, + query.super_admin + ) + .fetch_all(&db) + .await?; + let ids = workspaces.iter().map(|w| w.id.clone()).collect(); + let found = accesses( + &db, + &authed.email, + ids, + SessionAccess::Full, + query.super_admin, + ) + .await?; + // Counted as the owner, who as a superadmin sees more than a connection without those rights. + let owner_is_super_admin = + windmill_common::auth::is_super_admin_email(&db, &authed.email).await?; + let mut out = Vec::with_capacity(workspaces.len()); + for w in workspaces { + let Some(member) = found.get(&w.id) else { + continue; + }; + let runnables = match (&member.limit, &member.username) { + // A role that cannot run is offered none of them. + (Some(McpLimit::Runnables { .. }), _) if !member.can_run => Some(0), + (Some(McpLimit::Runnables { scripts, flows }), Some(username)) + if query.with_counts && !owner_is_super_admin => + { + count_runnables( + &db, + &user_db, + &authed.email, + username, + &w.id, + scripts, + flows, + ) + .await + .ok() + } + _ => None, + }; + out.push(WorkspaceAccessEntry { + access: member.access, + runnables, + restricted: member.restricted, + id: w.id, + name: w.name, + }); + } + Ok(Json(out)) +} + +/// Mounted at /api/w/{workspace}/mcp/runnable_tools. +pub fn runnable_tools_service() -> axum::Router { + axum::Router::new().route("/", axum::routing::get(list_runnable_tools)) +} + +/// GET /api/w/{workspace}/mcp/runnable_tools: the scripts and flows a sign-in bound to the +/// workspace would list where the caller's role offers them as tools, with their arguments. The +/// caller is authenticated in that workspace, holding there only the rights its credential carries. +async fn list_runnable_tools( + Extension(db): Extension, + Extension(user_db): Extension, + Extension(auth_cache): Extension>, + Path(w_id): Path, + authed: ApiAuthed, +) -> JsonResult> { + if authed + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:"))) + { + return Err(Error::NotAuthorized( + "A scope-restricted token cannot list its owner's tools".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, + user_db, + String::new(), + auth_cache, + )); + let tools = runner + .role_runnable_tools(&authed, &w_id) + .await + .map_err(|e| Error::internal_err(e.message.into_owned()))?; + Ok(Json(tools.tools.into_iter().map(Into::into).collect())) +} + +async fn count_runnables( + db: &DB, + user_db: &UserDB, + email: &str, + username: &str, + w_id: &str, + scripts: &[String], + flows: &[String], +) -> windmill_common::error::Result { + let there: ApiAuthed = windmill_common::auth::fetch_authed_from_permissioned_as( + &format!("u/{username}"), + email, + w_id, + db, + ) + .await? + .into(); + let mut count = 0; + for (kind, patterns) in [("script", scripts), ("flow", flows)] { + let filter = Some(PathFilter::Patterns(patterns)); + count += count_items(user_db, &there, w_id, kind, filter) + .await + .map_err(|e| Error::internal_err(e.message.into_owned()))?; + } + Ok(count) +} diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index ff5c16cf35..721797d699 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -288,6 +288,20 @@ pub async fn get_item_paths( Ok(rows.into_iter().map(|(path,)| path).collect()) } +/// How many tools `get_items` would list, its cap included, without fetching them. +pub async fn count_items( + user_db: &UserDB, + authed: &ApiAuthed, + workspace_id: &str, + item_type: &str, + path_filter: Option>, +) -> Result { + let mut sqlb = items_query(authed, workspace_id, "all", item_type, path_filter); + sqlb.distinct().field("o.path").limit(ITEMS_FETCH_MAX_LIMIT); + let rows: Vec<(String,)> = fetch_items(user_db, authed, &sqlb, item_type).await?; + Ok(rows.len()) +} + /// Get scripts from the Hub pub async fn get_scripts_from_hub( db: &DB, diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 92054e9a96..1864aa656c 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -293,7 +293,16 @@ pub trait McpBackend: Send + Sync + Clone + 'static { auth: &Self::Auth, workspaces: &[WorkspaceInfo], access: SessionAccess, - ) -> BackendResult>; + ) -> BackendResult>; + + /// What a session granted `access` gets in `workspace_id`, by `session_in`, or why it gets + /// none. `auth` is the caller's there. Every call and the tool listing go through it. + async fn session_access( + &self, + auth: &Self::Auth, + workspace_id: &str, + access: SessionAccess, + ) -> BackendResult; /// The instructions a client reaching one workspace receives on connecting, built for /// this user and what the token lets them do. diff --git a/backend/windmill-mcp/src/server/mod.rs b/backend/windmill-mcp/src/server/mod.rs index 58fa0ceeeb..ebca5f32a1 100644 --- a/backend/windmill-mcp/src/server/mod.rs +++ b/backend/windmill-mcp/src/server/mod.rs @@ -23,7 +23,7 @@ pub use endpoints::{ list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool, }; pub use runner::{has_endpoint_path_policy, Runner, MAX_TOOL_RESULT_BYTES}; -pub use session::{admits, session_limit, SessionRunner}; +pub use session::{admits, session_in, session_limit, workspace_mcp_url, SessionRunner}; pub use tools::create_tool_from_item; // Re-export rmcp types for convenience diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index aebf89219c..a6a15ddab6 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -819,6 +819,27 @@ impl Runner { .collect()) } + /// What a sign-in bound to `workspace_id` lists where the caller's role offers scripts and + /// flows as tools, for the consent page to show; empty under any other role. `auth` is the + /// caller as a member of that workspace. + pub async fn role_runnable_tools( + &self, + auth: &B::Auth, + workspace_id: &str, + ) -> Result { + let Some(limit @ McpLimit::Runnables { .. }) = + self.backend.mcp_limit(auth, workspace_id).await? + else { + return Ok(ListToolsResult::default()); + }; + let scope_config = parse_mcp_scopes(&["mcp:all".to_string()]) + .map_err(|e| ErrorData::internal_error(e, None))? + .limited_by(&limit); + let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only; + self.list_tools_single(auth, workspace_id, &scope_config, read_only) + .await + } + /// List tools for a single, bound workspace (URL-path or token-bound). async fn list_tools_single( &self, diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index f8624e1ebf..bc358510b8 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -55,13 +55,45 @@ pub fn session_limit(workspace_id: &str, limit: &McpLimit) -> Result, + locked: bool, + can_run: bool, +) -> Result { + let mut access = match limit { + Some(limit) => access.min(session_limit(workspace_id, limit)?), + None => access, + }; + if locked { + access = access.min(SessionAccess::ReadAndRun); + } + if !can_run { + access = SessionAccess::ReadOnly; + } + Ok(access) +} + +/// The MCP URL connecting to this workspace alone. +pub fn workspace_mcp_url(workspace_id: &str) -> String { + format!( + "{}/api/mcp/w/{workspace_id}/mcp", + windmill_common::global_settings::mcp_base_url() + ) +} + /// Says what is allowed there instead, so the model does not retry. pub(super) fn limit_refusal(workspace_id: &str, limit: &McpLimit) -> ErrorData { let allowed = match limit { McpLimit::Off => "your role has no MCP access there".to_string(), McpLimit::Runnables { .. } => format!( "your role is limited there to chosen scripts and flows as tools, which a connection \ - to that workspace's own MCP URL (/api/mcp/w/{workspace_id}/mcp) serves" + to that workspace's own MCP URL, {}, serves", + workspace_mcp_url(workspace_id) ), McpLimit::ReadOnly => "your role is limited there to reading, through /api/mcp".to_string(), McpLimit::ReadAndRun => { @@ -228,14 +260,10 @@ impl SessionRunner { // Connecting succeeds so the client shows why no tool works there. Some(limit @ (McpLimit::Off | McpLimit::Runnables { .. })) => limit_refusal(&only.id, &limit).message.into_owned(), - _ => - self.backend - .session_instructions( - &auth, - &only.id, - access(&auth, &caller.scope), - ) - .await?, + _ => self + .backend + .session_instructions(&auth, &only.id, access(&auth, &caller.scope),) + .await?, } ) } @@ -322,37 +350,29 @@ impl ServerHandler for SessionRunner { if let McpMode::Multi(_) = caller.mode { tools.push(get_workspace_context_tool()); } - let mut access = access(&caller.auth, &caller.scope); - // A bound token's one workspace decides its toolset as it decides its instructions: - // a role there that cannot run gets the read-only tools. - if let McpMode::Single(bound) = &caller.mode { - match self.backend.mcp_limit(&caller.auth, bound).await? { - Some(limit) => match session_limit(bound, &limit) { - Ok(most) => access = access.min(most), - Err(_) => { - return Ok(ListToolsResult::with_all_items(tools) - .with_ttl_ms(LIST_TTL_MS) - .with_cache_scope(LIST_CACHE_SCOPE)) - } - }, - None => {} - } - if access != SessionAccess::ReadOnly - && !self - .backend - .can_run(&caller.auth, bound) - .await - .unwrap_or(true) - { - access = SessionAccess::ReadOnly; + // The highest access a covered workspace gives, as each call there is checked; one giving + // less refuses per call what it does not allow. + let granted = access(&caller.auth, &caller.scope); + let mut listed = None; + for w in self.workspaces(&caller).await? { + let Ok(auth) = self.auth_in(&caller, &w.id).await else { + continue; + }; + if let Ok(got) = self.backend.session_access(&auth, &w.id, granted).await { + listed = listed.max(Some(got)); + if got == granted { + break; + } } } - tools.extend( - self.backend - .session_tools(access) - .into_iter() - .map(with_workspace_id_arg), - ); + if let Some(listed) = listed { + tools.extend( + self.backend + .session_tools(listed) + .into_iter() + .map(with_workspace_id_arg), + ); + } if declines_cards(context.meta.client_capabilities().as_ref()) { tools.retain(|tool| { !tool.meta.as_ref().is_some_and(|m| { @@ -433,7 +453,7 @@ impl ServerHandler for SessionRunner { .map(|w| { let mut entry = serde_json::json!({ "id": w.id, "name": w.name }); if let Some(access) = accesses.get(&w.id) { - entry["access"] = (*access).into(); + entry["access"] = access.as_str().into(); } entry }) diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 2d5c6984b5..24a625b4f8 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -75,6 +75,8 @@ it must not restrict a role, cost a seat or reach an authoring gate. `runnables` gets the tools server whatever the token, and an `mcp:all` token under another limit the session toolset, since endpoint tools are never served under one. Where a connection covers several workspaces the list is one for all, so the limit refuses at call time. +- The connect page and the MCP tab of the home page read `workspace_access`, the same computation + as `list_workspaces`, so a user is shown what they get rather than what they ask for. - A selection intersects with the token's own (`McpScopeConfig::limited_by`). - A lapsed license freezes it as it does roles: it keeps applying and can be removed, not changed. On Community it is ignored and refused at write. diff --git a/frontend/src/lib/components/instanceSettings/McpExternalIdp.svelte b/frontend/src/lib/components/instanceSettings/McpExternalIdp.svelte index 358256947d..0ef685111b 100644 --- a/frontend/src/lib/components/instanceSettings/McpExternalIdp.svelte +++ b/frontend/src/lib/components/instanceSettings/McpExternalIdp.svelte @@ -93,7 +93,7 @@ } const ACCESS_LABELS = { - full: 'Build and run', + full: 'Everything your role allows', read_run: 'Read and run', read: 'Read only' } diff --git a/frontend/src/lib/components/mcp/McpAccessLine.svelte b/frontend/src/lib/components/mcp/McpAccessLine.svelte new file mode 100644 index 0000000000..3293df2870 --- /dev/null +++ b/frontend/src/lib/components/mcp/McpAccessLine.svelte @@ -0,0 +1,41 @@ + + +{#if labelled} +
+ {shown.label} + {#if shown.hint}{shown.hint}{/if} + {@render edit?.()} +
+{/if} +{#if less} +

+ In each workspace, the client can do at most what your role allows there. +

+{/if} diff --git a/frontend/src/lib/components/mcp/McpAccessPicker.svelte b/frontend/src/lib/components/mcp/McpAccessPicker.svelte index 01ccc19246..ff02b3d900 100644 --- a/frontend/src/lib/components/mcp/McpAccessPicker.svelte +++ b/frontend/src/lib/components/mcp/McpAccessPicker.svelte @@ -9,7 +9,7 @@ * tools. Grants nothing, so it is never shown. */ export const MCP_SESSION = 'mcp:session' - const ACCESS_SCOPES: Record, string[]> = { + export const ACCESS_SCOPES: Record, string[]> = { read: ['mcp:all', 'mcp:read_only'], read_run: ['mcp:all', 'mcp:read_run'], full: ['mcp:all', MCP_SESSION] @@ -27,42 +27,54 @@
-
- Access - - {#snippet children({ item })} - - - - - {/snippet} - -
- {#if narrowed.length > 0} - -
    - {#each narrowed as { id, why } (id)} -
  • In {id}, {why}.
  • - {/each} -
-
- {/if} + + pickedWorkspaces[0], (v) => (pickedWorkspaces = v ? [v] : [])} + items={workspaceAccess.filter(isTools).map((w) => ({ value: w.id, label: w.name }))} + bind:value={ + () => pickedWorkspaces[0], + (v) => { + allWorkspaces = false + pickedWorkspaces = v ? [v] : [] + } + } placeholder="Choose a workspace" /> +

+ Your role lets you connect scripts and flows as tools, one workspace per connection. +

+ {:else if toolsAlone} +
+

{covered[0].name}

+
{:else} {:else if !allWorkspaces} + {#if pickedWorkspaces.length === 0} +

Choose at least one workspace.

+ {/if} {/if} {/if} - {#if isSuperAdmin && !superAdmin && (access === 'selected' || !allWorkspaces)} + {#if isSuperAdmin && !superAdmin && !allWorkspaces}

- Showing workspaces you are a member of. Superadmin rights, under Access, opens the - rest. + Showing workspaces you are a member of. Superadmin rights opens the rest.

{/if} + {#if leftOut.length > 0} + + {/if}
{/if} -
+ {#if accessLoadFailed && !isGateway} +

+ Your access could not be loaded. Reload this page. +

+ {/if} + + {#if isSuperAdmin} +
+ superAdmin, setSuperAdmin} + disabled={loadingWorkspaces} + options={{ + right: 'Superadmin rights', + rightTooltip: + 'The token carries your superadmin rights: admin in every workspace of the instance, including ones you are not a member of.' + }} + size="xs" + /> +
+ {/if} + + {#snippet pen()} + {#if editable} +