From 1a43ff85005fb972404323decab3bbbf61f8cb2b Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:53:00 +0000 Subject: [PATCH] feat(mcp): show client details on the oauth consent page The consent page shows the registered client name and redirect address; stricter scope parsing. Co-Authored-By: Claude Opus 5.5 --- ...290da9bd333a79aa71f0bc3118381aaeae465.json | 40 ++++++++ backend/windmill-api/openapi.yaml | 41 +++++++++ backend/windmill-api/src/mcp/oauth_server.rs | 91 +++++++++++++++++-- frontend/src/lib/mcpAuth.test.ts | 20 ++++ frontend/src/lib/mcpAuth.ts | 10 ++ .../oauth/mcp_authorize/+page@(root).svelte | 86 ++++++++++++++---- 6 files changed, 260 insertions(+), 28 deletions(-) create mode 100644 backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json create mode 100644 frontend/src/lib/mcpAuth.test.ts diff --git a/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json b/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json new file mode 100644 index 0000000000..06d87660f8 --- /dev/null +++ b/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT client_id, client_name, redirect_uris, created_at FROM mcp_oauth_server_client\n WHERE client_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "client_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "client_name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "redirect_uris", + "type_info": "TextArray" + }, + { + "ordinal": 3, + "name": "created_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465" +} diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 4655b14e18..3f6c014b36 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -29740,6 +29740,47 @@ paths: items: $ref: "#/components/schemas/EndpointTool" + /mcp/gateway/oauth/server/client/{client_id}: + get: + summary: get an MCP client registered with Windmill's OAuth server + description: | + The name and redirect URIs a client registered itself with, for the consent page to + show from the server rather than from the authorization URL. + operationId: getMcpOAuthServerClient + tags: + - mcp_oauth + parameters: + - name: client_id + in: path + required: true + schema: + type: string + responses: + "200": + description: the registered client + content: + application/json: + schema: + type: object + required: + - client_id + - client_name + - redirect_uris + - created_at + properties: + client_id: + type: string + client_name: + type: string + description: The name the client chose when it registered, unverified. + redirect_uris: + type: array + items: + type: string + created_at: + type: string + format: date-time + /mcp/oauth/discover: post: summary: discover MCP server OAuth metadata diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index fdce7b4907..08a58b353f 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -252,6 +252,21 @@ fn supported_scopes() -> Vec { scopes } +/// Splits a requested scope into its scope tokens (RFC 6749 §3.3: separated by spaces). +/// The consent page shows the scopes split on spaces alone, so any other separator or control +/// character is refused: Rust's `split_whitespace` also splits on U+0085 and tabs, which would +/// grant scope tokens the page displayed as part of another one. +fn parse_scope_param(scope: &str) -> std::result::Result, &'static str> { + if scope.bytes().any(|b| !(0x20..=0x7e).contains(&b)) { + return Err("scope may only hold printable ASCII scope tokens separated by spaces"); + } + Ok(scope + .split(' ') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect()) +} + /// GET /.well-known/oauth-authorization-server/api/w/:workspace_id/mcp/oauth/server /// /// `client_base_url` serves what the MCP client calls itself, `base_url` the authorization @@ -786,6 +801,16 @@ async fn oauth_authorize_inner( .into_response(); } + if let Err(e) = parse_scope_param(params.scope.as_deref().unwrap_or_default()) { + return OAuthErrorRedirect::new( + ¶ms.redirect_uri, + "invalid_scope", + Some(e), + params.state.as_deref(), + ) + .into_response(); + } + let code_challenge = match ¶ms.code_challenge { Some(challenge) if !challenge.is_empty() => challenge.as_str(), _ => { @@ -837,7 +862,6 @@ async fn oauth_authorize_inner( serde_urlencoded::to_string(&[ (mode_key, mode_value), ("client_id", params.client_id.as_str()), - ("client_name", client.client_name.as_str()), ("redirect_uri", params.redirect_uri.as_str()), ("scope", params.scope.as_deref().unwrap_or("mcp:all")), ("state", params.state.as_deref().unwrap_or("")), @@ -952,11 +976,8 @@ async fn oauth_approve_inner( let code = format!("mcp-code-{}", rd_string(32)); - let mut scopes: Vec = form - .scope - .split_whitespace() - .map(|s| s.to_string()) - .collect(); + let mut scopes = + parse_scope_param(&form.scope).map_err(|e| Error::BadRequest(e.to_string()))?; if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) { scopes.push(SESSION_SCOPE.to_string()); } @@ -1146,8 +1167,8 @@ pub async fn gateway_oauth_approve( workspace_ids.extend(form.workspace_id); } // A selection of scripts and flows names paths, which only mean something in one workspace. - if !scope.split_whitespace().any(|s| s == "mcp:all") - && (form.all_workspaces || workspace_ids.len() > 1) + let requested = parse_scope_param(&scope).map_err(|e| Error::BadRequest(e.to_string()))?; + if !requested.iter().any(|s| s == "mcp:all") && (form.all_workspaces || workspace_ids.len() > 1) { return Err(Error::BadRequest( "Selected scripts and flows come from one workspace: pick one".to_string(), @@ -1191,6 +1212,33 @@ pub async fn gateway_oauth_approve( .await } +#[derive(Debug, Serialize)] +pub struct RegisteredClient { + client_id: String, + client_name: String, + redirect_uris: Vec, + created_at: chrono::DateTime, +} + +/// GET /api/mcp/gateway/oauth/server/client/:client_id — what the consent page shows: the +/// authorization URL's own copy of the client name is the client's to choose. +pub async fn get_registered_client( + Extension(db): Extension, + _authed: ApiAuthed, + Path(client_id): Path, +) -> Result> { + let client = sqlx::query_as!( + RegisteredClient, + "SELECT client_id, client_name, redirect_uris, created_at FROM mcp_oauth_server_client + WHERE client_id = $1", + client_id + ) + .fetch_optional(&db) + .await? + .ok_or_else(|| Error::NotFound("Unknown client_id".to_string()))?; + Ok(Json(client)) +} + /// Gateway approval form — same as ApprovalForm, plus the workspaces the token reaches: /// one binds the token to it, several are listed in its scopes. #[derive(Debug, Deserialize)] @@ -1245,12 +1293,35 @@ pub fn gateway_unauthed_service() -> Router { /// Gateway OAuth endpoints that require authentication /// Mounted at /api/mcp/gateway/oauth/server (inside authenticated section) pub fn gateway_authed_service() -> Router { - Router::new().route("/approve", post(gateway_oauth_approve)) + Router::new() + .route("/approve", post(gateway_oauth_approve)) + .route("/client/{client_id}", get(get_registered_client)) } #[cfg(test)] mod tests { - use super::{build_oauth_metadata, validate_redirect_uri}; + use super::{build_oauth_metadata, parse_scope_param, validate_redirect_uri}; + + #[test] + fn scope_param_splits_on_spaces_only() { + assert_eq!( + parse_scope_param(" mcp:scripts:f/x/* mcp:runnables_as_tools ").unwrap(), + vec!["mcp:scripts:f/x/*", "mcp:runnables_as_tools"] + ); + assert_eq!(parse_scope_param("").unwrap(), Vec::::new()); + for scope in [ + "mcp:scripts:f/x/*\u{85}mcp:all", + "mcp:scripts:f/x/*\tmcp:all", + "mcp:scripts:f/x/*\nmcp:all", + "mcp:scripts:f/x/*\u{a0}mcp:all", + "mcp:scripts:f/x/*\u{2028}mcp:all", + ] { + assert!( + parse_scope_param(scope).is_err(), + "expected {scope:?} to be refused" + ); + } + } #[test] fn authorization_endpoint_stays_on_base_url() { diff --git a/frontend/src/lib/mcpAuth.test.ts b/frontend/src/lib/mcpAuth.test.ts new file mode 100644 index 0000000000..05be32b3a0 --- /dev/null +++ b/frontend/src/lib/mcpAuth.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('$lib/gen', () => ({ SettingService: {}, WorkspaceService: {} })) + +import { parseScopeParam } from './mcpAuth' + +describe('parseScopeParam', () => { + it('splits on spaces as the server does', () => { + expect(parseScopeParam(' mcp:scripts:f/x/* mcp:runnables_as_tools ')).toEqual([ + 'mcp:scripts:f/x/*', + 'mcp:runnables_as_tools' + ]) + }) + + it('refuses separators the server does not split on', () => { + for (const sep of ['\u0085', '\t', '\n', ' ', '
']) { + expect(parseScopeParam(`mcp:scripts:f/x/*${sep}mcp:all`)).toBeUndefined() + } + }) +}) diff --git a/frontend/src/lib/mcpAuth.ts b/frontend/src/lib/mcpAuth.ts index 69637337cc..02d7949087 100644 --- a/frontend/src/lib/mcpAuth.ts +++ b/frontend/src/lib/mcpAuth.ts @@ -1,5 +1,15 @@ import { SettingService, WorkspaceService } from '$lib/gen' +/** + * The scope tokens of an OAuth `scope` parameter, split on spaces as the server splits them, or + * undefined when it holds anything but printable ASCII: the server refuses those, and a separator + * only one side honours (U+0085, a tab) would let the page show other scopes than the grant's. + */ +export function parseScopeParam(scope: string): string[] | undefined { + if (!/^[\x20-\x7e]*$/.test(scope)) return undefined + return scope.split(' ').filter((s) => s.length > 0) +} + /** Every live workspace of the instance, for a superadmin granting an MCP token their rights. */ export async function listEveryWorkspace(): Promise<{ id: string; name: string }[]> { const all: { id: string; name: string; deleted?: boolean }[] = [] diff --git a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte index aa52c8cc75..b53bdfc135 100644 --- a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte @@ -5,13 +5,18 @@