mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-03 08:10:27 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b9e0e06878
commit
1a43ff8500
+40
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -252,6 +252,21 @@ fn supported_scopes() -> Vec<String> {
|
||||
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<Vec<String>, &'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<String> = 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<String>,
|
||||
created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
/// 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<DB>,
|
||||
_authed: ApiAuthed,
|
||||
Path(client_id): Path<String>,
|
||||
) -> Result<Json<RegisteredClient>> {
|
||||
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::<String>::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() {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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 }[] = []
|
||||
|
||||
@@ -5,13 +5,18 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state'
|
||||
import CenteredModal from '$lib/components/CenteredModal.svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import { Badge, Button } from '$lib/components/common'
|
||||
import MultiSelect from '$lib/components/select/MultiSelect.svelte'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import McpAccessPicker, { type McpAccess } from '$lib/components/mcp/McpAccessPicker.svelte'
|
||||
import { UserService, WorkspaceService } from '$lib/gen'
|
||||
import { listEveryWorkspace } from '$lib/mcpAuth'
|
||||
import {
|
||||
McpOauthService,
|
||||
UserService,
|
||||
WorkspaceService,
|
||||
type GetMcpOauthServerClientResponse
|
||||
} from '$lib/gen'
|
||||
import { listEveryWorkspace, parseScopeParam } from '$lib/mcpAuth'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { copyToClipboard } from '$lib/utils'
|
||||
import Copy from 'lucide-svelte/icons/copy'
|
||||
@@ -21,12 +26,23 @@
|
||||
let isGateway = page.url.searchParams.get('gateway') === 'true'
|
||||
let workspaceId = $state(page.url.searchParams.get('workspace_id') || '')
|
||||
let clientId = page.url.searchParams.get('client_id') || ''
|
||||
let clientName = page.url.searchParams.get('client_name') || 'Unknown Client'
|
||||
let redirectUri = page.url.searchParams.get('redirect_uri') || ''
|
||||
// The name and redirect URIs come from the client's registration, not from the URL: anyone
|
||||
// can link here, and the client picked its own name when it registered itself.
|
||||
let client = $state<GetMcpOauthServerClientResponse>()
|
||||
let clientLookupFailed = $state(false)
|
||||
const clientName = $derived(client?.client_name ?? '')
|
||||
const redirectRegistered = $derived(client?.redirect_uris.includes(redirectUri) ?? false)
|
||||
McpOauthService.getMcpOauthServerClient({ clientId })
|
||||
.then((c) => (client = c))
|
||||
.catch((e) => {
|
||||
// Logged out: the root layout is already sending the browser to the login page.
|
||||
if (e?.status === 401) return
|
||||
clientLookupFailed = true
|
||||
})
|
||||
// What the client asked for seeds the access picker; what is approved is the picker's.
|
||||
const askedScopes = (page.url.searchParams.get('scope') || 'mcp:all')
|
||||
.split(' ')
|
||||
.filter((s) => s.startsWith('mcp:'))
|
||||
const parsedScopes = parseScopeParam(page.url.searchParams.get('scope') || 'mcp:all')
|
||||
const askedScopes = (parsedScopes ?? []).filter((s) => s.startsWith('mcp:'))
|
||||
// Both narrowings at once is a client requesting every scope it was offered, not a choice.
|
||||
const requestedScopes =
|
||||
askedScopes.includes('mcp:all') &&
|
||||
@@ -45,9 +61,20 @@
|
||||
// browser-executable schemes here too — this also neutralizes any client rows
|
||||
// registered before the backend fix.
|
||||
const DISALLOWED_REDIRECT_SCHEMES = ['javascript:', 'data:', 'vbscript:', 'blob:', 'file:']
|
||||
// The code lands on `redirectUri` as a top-level GET, so this instance's own API is no
|
||||
// callback either.
|
||||
function isOwnApiUrl(url: URL): boolean {
|
||||
if (url.origin !== window.location.origin) return false
|
||||
try {
|
||||
return /^\/+api(\/|$)/i.test(decodeURIComponent(url.pathname))
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
function isSafeRedirectUri(uri: string): boolean {
|
||||
try {
|
||||
return !DISALLOWED_REDIRECT_SCHEMES.includes(new URL(uri).protocol.toLowerCase())
|
||||
const url = new URL(uri)
|
||||
return !DISALLOWED_REDIRECT_SCHEMES.includes(url.protocol.toLowerCase()) && !isOwnApiUrl(url)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
@@ -72,7 +99,12 @@
|
||||
}
|
||||
}
|
||||
const loopbackRedirect = redirectUriValid && isLoopbackUri(redirectUri)
|
||||
const redirectOrigin = redirectUriValid ? new URL(redirectUri).origin : ''
|
||||
// Where the code goes. A private-use scheme (vscode://, cursor://) has an opaque origin.
|
||||
function redirectDestination(uri: string): string {
|
||||
const url = new URL(uri)
|
||||
return url.origin !== 'null' ? url.origin : `${url.protocol}//${url.host}`
|
||||
}
|
||||
const redirectOrigin = redirectUriValid ? redirectDestination(redirectUri) : ''
|
||||
|
||||
let loading = $state(false)
|
||||
let success = $state(false)
|
||||
@@ -145,7 +177,7 @@
|
||||
}
|
||||
|
||||
function onDeny() {
|
||||
if (!redirectUriValid) return
|
||||
if (!redirectUriValid || !redirectRegistered) return
|
||||
// Redirect to client with error
|
||||
const params = new URLSearchParams({
|
||||
error: 'access_denied',
|
||||
@@ -158,7 +190,7 @@
|
||||
}
|
||||
|
||||
async function onApprove() {
|
||||
if (!redirectUriValid) return
|
||||
if (!redirectUriValid || !redirectRegistered) return
|
||||
if (!grantsWorkspace) {
|
||||
sendUserToast('Please select a workspace', true)
|
||||
return
|
||||
@@ -223,6 +255,20 @@
|
||||
<CenteredModal title="Authorization Request">
|
||||
<p class="text-center text-sm text-primary"> Error: invalid or unsafe redirect_uri </p>
|
||||
</CenteredModal>
|
||||
{:else if clientLookupFailed || (client && !redirectRegistered)}
|
||||
<CenteredModal title="Authorization Request">
|
||||
<p class="text-center text-sm text-primary">
|
||||
Error: unknown client, or a redirect_uri it did not register
|
||||
</p>
|
||||
</CenteredModal>
|
||||
{:else if !client}
|
||||
<CenteredModal title="Authorization Request">
|
||||
<p class="text-center text-sm text-secondary">Loading...</p>
|
||||
</CenteredModal>
|
||||
{:else if !parsedScopes}
|
||||
<CenteredModal title="Authorization Request">
|
||||
<p class="text-center text-sm text-primary">Error: invalid scope</p>
|
||||
</CenteredModal>
|
||||
{:else if !isGateway && !workspaceId}
|
||||
<CenteredModal title="Authorization Request">
|
||||
<p class="text-center text-sm text-primary">Error: missing workspace_id</p>
|
||||
@@ -276,8 +322,9 @@
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-center text-sm text-primary mb-6">
|
||||
<p class="text-center text-sm text-primary mb-2">
|
||||
<span class="font-semibold text-accent">{clientName}</span>
|
||||
<Badge color="yellow" small>Unverified app</Badge>
|
||||
is requesting access to
|
||||
{#if isGateway}
|
||||
your Windmill workspaces.
|
||||
@@ -287,12 +334,15 @@
|
||||
workspace.
|
||||
{/if}
|
||||
</p>
|
||||
{#if loopbackRedirect}
|
||||
<p class="text-center text-xs text-secondary -mt-4 mb-6">
|
||||
After you approve, {clientName} receives the sign-in at
|
||||
<span class="font-mono">{redirectOrigin}</span>, an address on this computer.
|
||||
</p>
|
||||
{/if}
|
||||
<p class="text-center text-xs text-secondary mb-2">
|
||||
After you approve, the sign-in is sent to
|
||||
<span class="font-mono font-semibold text-emphasis break-all">{redirectOrigin}</span
|
||||
>{#if loopbackRedirect}, an address on this computer{/if}.
|
||||
</p>
|
||||
<p class="text-center text-2xs text-tertiary mb-6">
|
||||
The app registered itself under this name, and Windmill has not checked who runs it. Approve
|
||||
only if you started this sign-in and you recognize the address above.
|
||||
</p>
|
||||
|
||||
{#if isGateway}
|
||||
<div class="mb-6 flex flex-col gap-2">
|
||||
|
||||
Reference in New Issue
Block a user