diff --git a/backend/.sqlx/query-223fbd972728d5b3ec5b1708e3f2e1f4901b0382fca50704c9544cdec5f9352c.json b/backend/.sqlx/query-223fbd972728d5b3ec5b1708e3f2e1f4901b0382fca50704c9544cdec5f9352c.json deleted file mode 100644 index 8595b12ec6..0000000000 --- a/backend/.sqlx/query-223fbd972728d5b3ec5b1708e3f2e1f4901b0382fca50704c9544cdec5f9352c.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id)\n SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar\n WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Varchar", - "Varchar", - "Varchar", - "Varchar", - "Text", - "TextArray", - "Varchar" - ] - }, - "nullable": [] - }, - "hash": "223fbd972728d5b3ec5b1708e3f2e1f4901b0382fca50704c9544cdec5f9352c" -} diff --git a/backend/.sqlx/query-be303445868662af7b7475f19dc630668a2776fc7a253a6e747653338d10dbd0.json b/backend/.sqlx/query-2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3.json similarity index 54% rename from backend/.sqlx/query-be303445868662af7b7475f19dc630668a2776fc7a253a6e747653338d10dbd0.json rename to backend/.sqlx/query-2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3.json index fefd006379..4524f105bc 100644 --- a/backend/.sqlx/query-be303445868662af7b7475f19dc630668a2776fc7a253a6e747653338d10dbd0.json +++ b/backend/.sqlx/query-2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session'", + "query": "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session'\n AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", "describe": { "columns": [], "parameters": { @@ -11,5 +11,5 @@ }, "nullable": [] }, - "hash": "be303445868662af7b7475f19dc630668a2776fc7a253a6e747653338d10dbd0" + "hash": "2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3" } diff --git a/backend/.sqlx/query-dd8c63ac04e33e2863ff3712fc6a5209e1ff2c235df1e39ddc3dd21f60f66ef4.json b/backend/.sqlx/query-4c49df940de08769d751c5dc161fb50d961e71cc4bb1680788fccca8d30d5464.json similarity index 61% rename from backend/.sqlx/query-dd8c63ac04e33e2863ff3712fc6a5209e1ff2c235df1e39ddc3dd21f60f66ef4.json rename to backend/.sqlx/query-4c49df940de08769d751c5dc161fb50d961e71cc4bb1680788fccca8d30d5464.json index 37055880ae..160d4a5e4b 100644 --- a/backend/.sqlx/query-dd8c63ac04e33e2863ff3712fc6a5209e1ff2c235df1e39ddc3dd21f60f66ef4.json +++ b/backend/.sqlx/query-4c49df940de08769d751c5dc161fb50d961e71cc4bb1680788fccca8d30d5464.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO mcp_oauth_refresh_token\n (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval)", + "query": "INSERT INTO mcp_oauth_refresh_token\n (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at, super_admin)\n VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval, $9)", "describe": { "columns": [], "parameters": { @@ -12,10 +12,11 @@ "Varchar", "TextArray", "Uuid", - "Text" + "Text", + "Bool" ] }, "nullable": [] }, - "hash": "dd8c63ac04e33e2863ff3712fc6a5209e1ff2c235df1e39ddc3dd21f60f66ef4" + "hash": "4c49df940de08769d751c5dc161fb50d961e71cc4bb1680788fccca8d30d5464" } diff --git a/backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json b/backend/.sqlx/query-5505878870e3991ef0d3cf0249e9776432991d9c4420e61f321cb1d28b17d490.json similarity index 89% rename from backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json rename to backend/.sqlx/query-5505878870e3991ef0d3cf0249e9776432991d9c4420e61f321cb1d28b17d490.json index 5791e1ca31..84e90b4cd0 100644 --- a/backend/.sqlx/query-c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da.json +++ b/backend/.sqlx/query-5505878870e3991ef0d3cf0249e9776432991d9c4420e61f321cb1d28b17d490.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE mcp_oauth_refresh_token\n SET used_at = now()\n WHERE refresh_token = $1\n AND client_id = $2\n AND used_at IS NULL\n AND NOT revoked\n AND expires_at > now()\n RETURNING id, refresh_token, access_token_hash, client_id, user_email, workspace_id,\n scopes, token_family, created_at, expires_at, used_at, revoked", + "query": "UPDATE mcp_oauth_refresh_token\n SET used_at = now()\n WHERE refresh_token = $1\n AND client_id = $2\n AND used_at IS NULL\n AND NOT revoked\n AND expires_at > now()\n RETURNING id, refresh_token, access_token_hash, client_id, user_email, workspace_id,\n scopes, token_family, created_at, expires_at, used_at, revoked, super_admin", "describe": { "columns": [ { @@ -62,6 +62,11 @@ "ordinal": 11, "name": "revoked", "type_info": "Bool" + }, + { + "ordinal": 12, + "name": "super_admin", + "type_info": "Bool" } ], "parameters": { @@ -82,8 +87,9 @@ false, false, true, + false, false ] }, - "hash": "c2efefded4eaea858c41c32ef20e2c11ed88327cf033e1abfd7c0458b71f53da" + "hash": "5505878870e3991ef0d3cf0249e9776432991d9c4420e61f321cb1d28b17d490" } diff --git a/backend/.sqlx/query-1b4f7485c015338536d781838448c96ce686fce217be21ec15a8900b772f02a3.json b/backend/.sqlx/query-b721e00cebacc41f9177a5b5f1d7f4ad6bc4c758a873917f5b76443d4399d0d8.json similarity index 65% rename from backend/.sqlx/query-1b4f7485c015338536d781838448c96ce686fce217be21ec15a8900b772f02a3.json rename to backend/.sqlx/query-b721e00cebacc41f9177a5b5f1d7f4ad6bc4c758a873917f5b76443d4399d0d8.json index 8dacf0b647..9b9967f602 100644 --- a/backend/.sqlx/query-1b4f7485c015338536d781838448c96ce686fce217be21ec15a8900b772f02a3.json +++ b/backend/.sqlx/query-b721e00cebacc41f9177a5b5f1d7f4ad6bc4c758a873917f5b76443d4399d0d8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO mcp_oauth_server_code\n (code, client_id, user_email, workspace_id, scopes, redirect_uri, code_challenge, code_challenge_method)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + "query": "INSERT INTO mcp_oauth_server_code\n (code, client_id, user_email, workspace_id, scopes, redirect_uri, code_challenge, code_challenge_method, super_admin)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", "describe": { "columns": [], "parameters": { @@ -12,10 +12,11 @@ "TextArray", "Text", "Varchar", - "Varchar" + "Varchar", + "Bool" ] }, "nullable": [] }, - "hash": "1b4f7485c015338536d781838448c96ce686fce217be21ec15a8900b772f02a3" + "hash": "b721e00cebacc41f9177a5b5f1d7f4ad6bc4c758a873917f5b76443d4399d0d8" } diff --git a/backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json b/backend/.sqlx/query-cd975d30860a63ef97bcbe32f55c680ab88cb8740e41249c76d261c29386e55c.json similarity index 82% rename from backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json rename to backend/.sqlx/query-cd975d30860a63ef97bcbe32f55c680ab88cb8740e41249c76d261c29386e55c.json index 20689e1f0a..895eeec7c4 100644 --- a/backend/.sqlx/query-369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4.json +++ b/backend/.sqlx/query-cd975d30860a63ef97bcbe32f55c680ab88cb8740e41249c76d261c29386e55c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM mcp_oauth_server_code\n WHERE code = $1 AND expires_at > now()\n RETURNING code, client_id, user_email, workspace_id, scopes, redirect_uri,\n code_challenge, code_challenge_method", + "query": "DELETE FROM mcp_oauth_server_code\n WHERE code = $1 AND expires_at > now()\n RETURNING code, client_id, user_email, workspace_id, scopes, redirect_uri,\n code_challenge, code_challenge_method, super_admin", "describe": { "columns": [ { @@ -42,6 +42,11 @@ "ordinal": 7, "name": "code_challenge_method", "type_info": "Varchar" + }, + { + "ordinal": 8, + "name": "super_admin", + "type_info": "Bool" } ], "parameters": { @@ -57,8 +62,9 @@ false, false, true, - true + true, + false ] }, - "hash": "369f8ecde50af034f06d339ecef8fc55a0113b4156274d03d5af643c3da73fa4" + "hash": "cd975d30860a63ef97bcbe32f55c680ab88cb8740e41249c76d261c29386e55c" } diff --git a/backend/.sqlx/query-f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468.json b/backend/.sqlx/query-f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468.json new file mode 100644 index 0000000000..819a8e73b7 --- /dev/null +++ b/backend/.sqlx/query-f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin)\n SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar,\n $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false)\n WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Text", + "TextArray", + "Varchar", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468" +} diff --git a/backend/migrations/20261106093758_mcp_oauth_super_admin.down.sql b/backend/migrations/20261106093758_mcp_oauth_super_admin.down.sql new file mode 100644 index 0000000000..a2b58b83e0 --- /dev/null +++ b/backend/migrations/20261106093758_mcp_oauth_super_admin.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE mcp_oauth_refresh_token DROP COLUMN IF EXISTS super_admin; +ALTER TABLE mcp_oauth_server_code DROP COLUMN IF EXISTS super_admin; diff --git a/backend/migrations/20261106093758_mcp_oauth_super_admin.up.sql b/backend/migrations/20261106093758_mcp_oauth_super_admin.up.sql new file mode 100644 index 0000000000..e86d74caae --- /dev/null +++ b/backend/migrations/20261106093758_mcp_oauth_super_admin.up.sql @@ -0,0 +1,2 @@ +ALTER TABLE mcp_oauth_server_code ADD COLUMN IF NOT EXISTS super_admin BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE mcp_oauth_refresh_token ADD COLUMN IF NOT EXISTS super_admin BOOLEAN NOT NULL DEFAULT false; diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 5af255dad7..afddad0a6c 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -1197,6 +1197,9 @@ pub struct NewToken { pub workspace_id: Option, #[serde(default)] pub read_only: Option, + /// An MCP token carries its owner's superadmin rights (every workspace) only when asked. + #[serde(default)] + pub super_admin: Option, } impl NewToken { @@ -1208,7 +1211,15 @@ impl NewToken { workspace_id: Option, read_only: Option, ) -> Self { - Self { label, expiration, impersonate_email, scopes, workspace_id, read_only } + Self { + label, + expiration, + impersonate_email, + scopes, + workspace_id, + read_only, + super_admin: None, + } } } @@ -1252,6 +1263,11 @@ pub async fn create_token_internal( .fetch_optional(&mut *tx) .await? .unwrap_or(false); + let is_mcp = token_config + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:"))); + let is_super_admin = is_super_admin && (!is_mcp || token_config.super_admin == Some(true)); if *CLOUD_HOSTED { let nb_tokens = sqlx::query_scalar!("SELECT COUNT(*) FROM token WHERE email = $1", &authed.email) diff --git a/backend/windmill-api-groups/src/groups.rs b/backend/windmill-api-groups/src/groups.rs index 63944a9f36..22667e5660 100644 --- a/backend/windmill-api-groups/src/groups.rs +++ b/backend/windmill-api-groups/src/groups.rs @@ -448,9 +448,11 @@ pub async fn apply_instance_role( .execute(&mut **tx) .await?; - // Update super_admin flag on non-session tokens + // Update super_admin flag on non-session tokens. A promotion leaves MCP tokens alone: they + // carry superadmin access only when minted with it (`create_token_internal`). sqlx::query!( - "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session'", + "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session' + AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", new_super_admin, email ) diff --git a/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs b/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs new file mode 100644 index 0000000000..61a9e3130a --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs @@ -0,0 +1,132 @@ +//! A superadmin's MCP token carries their superadmin rights (every workspace) only when asked, +//! and the OAuth consent path and the token-create path agree on it. +#![cfg(feature = "mcp")] + +use serde_json::json; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +const VERIFIER: &str = "e2e-pkce-verifier-0123456789-0123456789-abcdef"; +const CHALLENGE: &str = "q9x8Sam6B6iSaQRwyLQdPrK3Ob2wfH1sNsUhYehHwh8"; +const REDIRECT: &str = "http://localhost:9/cb"; + +async fn token_is_super_admin(db: &Pool, token: &str) -> anyhow::Result { + Ok(sqlx::query_scalar( + "SELECT super_admin FROM token WHERE token_hash = encode(sha256($1::bytea), 'hex')", + ) + .bind(token.as_bytes()) + .fetch_one(db) + .await?) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_mcp_token_super_admin_is_opt_in(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start_mcp(db.clone()).await?; + let base = format!("http://localhost:{}/api", server.addr.port()); + let http = reqwest::Client::new(); + + let client_id = http + .post(format!("{base}/mcp/oauth/server/register")) + .json(&json!({ "client_name": "test", "redirect_uris": [REDIRECT] })) + .send() + .await? + .json::() + .await?["client_id"] + .as_str() + .unwrap() + .to_string(); + let approve = |bearer: &str, super_admin: bool| { + http.post(format!("{base}/mcp/gateway/oauth/server/approve")) + .bearer_auth(bearer) + .json(&json!({ + "client_id": client_id, "redirect_uri": REDIRECT, "scope": "mcp:all", "state": "", + "code_challenge": CHALLENGE, "code_challenge_method": "S256", + "all_workspaces": true, "super_admin": super_admin, + })) + .send() + }; + + for super_admin in [false, true] { + let code = approve("SECRET_TOKEN", super_admin) + .await? + .json::() + .await?["code"] + .as_str() + .unwrap() + .to_string(); + let issued = http + .post(format!("{base}/mcp/gateway/oauth/server/token")) + .form(&[ + ("grant_type", "authorization_code"), + ("code", &code), + ("client_id", &client_id), + ("redirect_uri", REDIRECT), + ("code_verifier", VERIFIER), + ]) + .send() + .await? + .json::() + .await?; + let oauth_token = issued["access_token"].as_str().expect(&issued.to_string()); + assert_eq!(token_is_super_admin(&db, oauth_token).await?, super_admin); + + let refreshed = http + .post(format!("{base}/mcp/gateway/oauth/server/token")) + .form(&[ + ("grant_type", "refresh_token"), + ("refresh_token", issued["refresh_token"].as_str().unwrap()), + ("client_id", &client_id), + ]) + .send() + .await? + .json::() + .await?; + let refreshed = refreshed["access_token"].as_str().unwrap(); + assert_eq!(token_is_super_admin(&db, refreshed).await?, super_admin); + + let user_token = http + .post(format!("{base}/users/tokens/create")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ "label": "mcp", "scopes": ["mcp:all"], "super_admin": super_admin })) + .send() + .await? + .text() + .await?; + assert_eq!(token_is_super_admin(&db, &user_token).await?, super_admin); + } + + assert_eq!( + approve("SECRET_TOKEN_2", true).await?.status(), + 401, + "only a superadmin may grant superadmin rights" + ); + + let opted_out = http + .post(format!("{base}/users/tokens/create")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ "label": "mcp", "scopes": ["mcp:all"] })) + .send() + .await? + .text() + .await?; + assert_eq!( + approve(&opted_out, true).await?.status(), + 401, + "an MCP token without superadmin access cannot approve one that has it" + ); + + http.post(format!("{base}/users/update/test@windmill.dev")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ "is_super_admin": true })) + .send() + .await? + .error_for_status()?; + assert!( + !token_is_super_admin(&db, &opted_out).await?, + "a promotion must not hand superadmin access to an MCP token minted without it" + ); + Ok(()) +} diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 1599afec49..57b0fe2393 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -1590,7 +1590,8 @@ async fn update_user( .await?; // Update super_admin flag on non-session tokens (webhooks, API tokens, etc.) sqlx::query!( - "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session'", + "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session' + AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", sa, &email_to_update ) @@ -1655,7 +1656,8 @@ async fn update_user( .execute(&mut *tx) .await?; sqlx::query!( - "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session'", + "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session' + AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", sa, &email_to_update ) @@ -3295,6 +3297,17 @@ async fn create_token( } windmill_api_auth::ensure_scopes_within_caller(&authed, token_config.scopes.as_deref())?; + // Mirrors the MCP OAuth approve: a scoped token cannot mint superadmin access it may lack. + if token_config.super_admin == Some(true) + && authed + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:"))) + { + return Err(Error::NotAuthorized( + "Only an unscoped token can grant superadmin access".to_string(), + )); + } token_config.expiration = cap_token_expiration( &db, diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index b684b7e69b..4f2cce0485 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -33183,6 +33183,12 @@ components: If true, the token is restricted to read-only HTTP methods (GET/HEAD/OPTIONS). Mutating endpoints and job-run actions are rejected with 403, regardless of the scopes attached. + super_admin: + type: boolean + description: | + For an MCP token (an `mcp:` scope) owned by a superadmin: carry the owner's + superadmin rights, reaching every workspace rather than only their + memberships. Ignored for other tokens, which always carry them. NewTokenImpersonate: type: object diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index b7a7a06a47..ee9c796841 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -160,6 +160,9 @@ pub struct ApprovalForm { pub state: String, pub code_challenge: String, pub code_challenge_method: String, + /// The token carries the approver's superadmin rights: every workspace, members or not. + #[serde(default)] + pub super_admin: bool, } #[derive(Debug, Deserialize)] @@ -207,6 +210,7 @@ struct AuthorizationCode { redirect_uri: String, code_challenge: Option, code_challenge_method: Option, + super_admin: bool, } #[allow(dead_code)] @@ -224,6 +228,7 @@ struct RefreshTokenRow { expires_at: chrono::DateTime, used_at: Option>, revoked: bool, + super_admin: bool, } /// The scopes that grant access. A protected resource advertises only these: MCP clients @@ -456,7 +461,7 @@ async fn handle_authorization_code_grant( "DELETE FROM mcp_oauth_server_code WHERE code = $1 AND expires_at > now() RETURNING code, client_id, user_email, workspace_id, scopes, redirect_uri, - code_challenge, code_challenge_method", + code_challenge, code_challenge_method, super_admin", req.code ) .fetch_optional(&mut *tx) @@ -518,8 +523,9 @@ async fn handle_authorization_code_grant( // Create access token (rejects archived workspaces inline) let rows = sqlx::query!( - "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id) - SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar + "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin) + SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar, + $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false) WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", access_token_hash, access_token_prefix, @@ -529,6 +535,7 @@ async fn handle_authorization_code_grant( MCP_OAUTH_TOKEN_EXPIRATION_SECS.to_string(), &scopes, auth_code.workspace_id, + auth_code.super_admin, ) .execute(&mut *tx) .await @@ -545,8 +552,8 @@ async fn handle_authorization_code_grant( // Create refresh token — store the hash of the access token so we can delete it later sqlx::query!( "INSERT INTO mcp_oauth_refresh_token - (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval)", + (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at, super_admin) + VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval, $9)", refresh_token, access_token_hash, auth_code.client_id, @@ -555,6 +562,7 @@ async fn handle_authorization_code_grant( &scopes, token_family, MCP_OAUTH_REFRESH_TOKEN_EXPIRATION_SECS.to_string(), + auth_code.super_admin, ) .execute(&mut *tx) .await @@ -597,7 +605,7 @@ async fn handle_refresh_token_grant( AND NOT revoked AND expires_at > now() RETURNING id, refresh_token, access_token_hash, client_id, user_email, workspace_id, - scopes, token_family, created_at, expires_at, used_at, revoked", + scopes, token_family, created_at, expires_at, used_at, revoked, super_admin", refresh_token_value, req.client_id ) @@ -661,8 +669,9 @@ async fn handle_refresh_token_grant( // Create new access token (rejects archived workspaces inline) let rows = sqlx::query!( - "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id) - SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar + "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin) + SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar, + $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false) WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", new_access_token_hash, new_access_token_prefix, @@ -672,6 +681,7 @@ async fn handle_refresh_token_grant( MCP_OAUTH_TOKEN_EXPIRATION_SECS.to_string(), &scopes, token_row.workspace_id, + token_row.super_admin, ) .execute(&mut *tx) .await @@ -688,8 +698,8 @@ async fn handle_refresh_token_grant( // Create new refresh token (same token family for tracking) — store hash of access token sqlx::query!( "INSERT INTO mcp_oauth_refresh_token - (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval)", + (refresh_token, access_token_hash, client_id, user_email, workspace_id, scopes, token_family, expires_at, super_admin) + VALUES ($1, $2, $3, $4, $5, $6, $7, now() + ($8 || ' seconds')::interval, $9)", new_refresh_token, new_access_token_hash, token_row.client_id, @@ -698,6 +708,7 @@ async fn handle_refresh_token_grant( &scopes, token_row.token_family, MCP_OAUTH_REFRESH_TOKEN_EXPIRATION_SECS.to_string(), + token_row.super_admin, ) .execute(&mut *tx) .await @@ -860,7 +871,20 @@ async fn oauth_approve_inner( // the gateway approve route reach the exchange through here. forbid_elevated_job_token(db, &authed.email, authed.job_id).await?; - if let Some(workspace_id) = workspace_id { + let caller_restricted = authed + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:"))); + if form.super_admin { + windmill_api_auth::require_super_admin(db, authed).await?; + // The owner's role is not the credential's: an MCP token minted without superadmin + // access may approve a narrower token, never one carrying that access. + if caller_restricted { + return Err(Error::NotAuthorized( + "Only an interactive session can grant superadmin access".to_string(), + )); + } + } else if let Some(workspace_id) = workspace_id { ensure_member(db, workspace_id, &authed.email).await?; } @@ -916,10 +940,6 @@ async fn oauth_approve_inner( // which is the normal consent flow. This is the legitimate MCP-narrowing // path, so it uses MCP-pattern containment rather than the byte-identical // rule ensure_scopes_within_caller applies on the generic token endpoints. - let caller_restricted = authed - .scopes - .as_deref() - .is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:"))); if caller_restricted { // An empty grant would mint a token the auth layer treats as unscoped // (full privileges), so a restricted approver must not produce one. @@ -946,8 +966,8 @@ async fn oauth_approve_inner( sqlx::query!( "INSERT INTO mcp_oauth_server_code - (code, client_id, user_email, workspace_id, scopes, redirect_uri, code_challenge, code_challenge_method) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + (code, client_id, user_email, workspace_id, scopes, redirect_uri, code_challenge, code_challenge_method, super_admin) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", code, form.client_id, authed.email, @@ -956,6 +976,7 @@ async fn oauth_approve_inner( form.redirect_uri, &form.code_challenge, &form.code_challenge_method, + form.super_admin, ) .execute(db) .await @@ -1116,8 +1137,10 @@ pub async fn gateway_oauth_approve( } [only] => Some(only.as_str()), several => { - for workspace_id in several { - ensure_member(&db, workspace_id, &authed.email).await?; + if !form.super_admin { + for workspace_id in several { + ensure_member(&db, workspace_id, &authed.email).await?; + } } scope.push_str(&format!(" mcp:workspaces:{}", several.join(","))); None @@ -1135,6 +1158,7 @@ pub async fn gateway_oauth_approve( state: form.state, code_challenge: form.code_challenge, code_challenge_method: form.code_challenge_method, + super_admin: form.super_admin, }, ) .await @@ -1158,6 +1182,8 @@ pub struct GatewayApprovalForm { /// Every workspace the user is a member of, including ones they join later. #[serde(default)] pub all_workspaces: bool, + #[serde(default)] + pub super_admin: bool, } // ── Router constructors ── diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 5932b8979a..81b2109303 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -49,6 +49,12 @@ Symbols, not line numbers, are cited: they drift less. `ephemeral-` prefix needs no other change (keep it clear of `is_server_minted_label` if minted through `tokens/create`); a new prefix also goes into the SQL and Svelte mirrors that function's doc lists. +- **A token's `super_admin` column is what lets it into a workspace its owner is not a member + of**, and makes a workspace-less MCP token list every workspace. `create_token_internal` copies + it from `password` for every token except an MCP one (an `mcp:` scope), which carries it only + when the request sets `super_admin`; the MCP OAuth approve stores the same request on its code + and refresh rows, and each exchange re-checks `password`. A new path minting an MCP token must + ask the same question, or it reaches a different set of workspaces than the other two. - **Every superadmin route refuses a job token**: `require_super_admin` (`windmill-api-auth/src/lib.rs`) errors on `authed.job_id.is_some()`. A script that needs `users/create`, `tokens/impersonate`, `set_login_type`, … must use a dedicated superadmin user diff --git a/frontend/src/lib/components/mcp/McpAccessPicker.svelte b/frontend/src/lib/components/mcp/McpAccessPicker.svelte index 8ee94571c7..ca9d294a2e 100644 --- a/frontend/src/lib/components/mcp/McpAccessPicker.svelte +++ b/frontend/src/lib/components/mcp/McpAccessPicker.svelte @@ -33,6 +33,7 @@ import { Badge } from '$lib/components/common' import Section from '$lib/components/Section.svelte' import { SvelteMap } from 'svelte/reactivity' + import type { Snippet } from 'svelte' interface Props { /** The workspace the selection picker browses. */ @@ -41,13 +42,16 @@ scopes?: string[] access?: McpAccess initialScopes?: string[] + /** Rendered between the access choice and the tool list. */ + afterAccess?: Snippet } let { workspaceId, scopes = $bindable(), access = $bindable(), - initialScopes = [] + initialScopes = [], + afterAccess }: Props = $props() const initialAccess = mcpAccessOf(initialScopes) @@ -116,6 +120,7 @@ {/snippet} + {@render afterAccess?.()} {#if toolsetAccess}
diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index 561beec734..20b97d9b87 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -1,11 +1,11 @@