diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 6c8f59c20..35703bdb5 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1697,11 +1697,26 @@ reference: the Spec 132 contracts. - `GET /api/v1/oauth/authorizations`, `GET /api/v1/oauth/authorizations/{id}`: pending sign-in requests and the data the consent view needs. One uniform `404` - for an unknown, expired, decided or cancelled id. + for an unknown, expired, decided or cancelled id. On the generic address the view + may carry `suggested_client` (`{id, matched}`, `matched` is `id`, `display_name` or + `known_name`): present only when the sanitised reported name (trimmed, any case; a + trailing parenthesised suffix is also tried without it) equals exactly one existing + client's id, display name or known client name, absent otherwise and never on a + per-client address. It is advice for the page, computed on read and never stored: preview + without a `client` answers `200 {"complete": false}` (no `access`, no `guard`) and + approve without one answers `422 client_required`. `previous_login` is + `{grant_id, client_id, approved_at}`: `client_id` is the client that owns that + login (the newest live login of this registration overall). `previous_logins` lists + the newest live login of this registration under each client, so the page can offer + replacement for whichever client is selected on the generic address. Names a client + reports are stripped of Unicode format characters (bidi controls, zero-width + characters) at registration and in a new client's display name. Preview and approve refuse (`422`, field `replace_grant`) a `replace_grant` + that is a live login of this registration owned by another client than the one + chosen; the page offers replacement only for the owning client. - `POST /api/v1/oauth/authorizations/{id}/preview`: read-only verdict for a proposed client, profile and mode. `POST .../approve` and `POST .../deny` answer `{redirect_url}`; approve refuses with `409 already_decided`, `409 binding_changed`, - `409 binding_bypassable_without_auth`, `422 profile_required`, `client_fixed`, + `409 binding_bypassable_without_auth`, `422 client_required`, `profile_required`, `client_fixed`, `identity_exists`, `reserved_identity` and `404 profile_not_found`. - `GET /api/v1/clients` and `GET /api/v1/clients/{client}` gain `credentials[]` (the API key and each browser login: `kind`, `prefix`, `grant_id`, `state`, diff --git a/docs/development/release-gate.md b/docs/development/release-gate.md index 109133c5b..95b103d87 100644 --- a/docs/development/release-gate.md +++ b/docs/development/release-gate.md @@ -138,6 +138,11 @@ page disagree): 900 px: the header status pill names servers awaiting review, a secret-like Manual-add value is masked with a Show toggle, and profile Try it is readable and labels unsaved edits. +- `client-oauth-consent.spec.ts` (spec 132): the browser-login consent page. + The sweep core runs with `MCPPROXY_MCP_OAUTH_ENABLED=true`; a scripted public + client registers and authorizes, then the page is approved on the per-client + and generic addresses (name suggestion, new client), denied, opened without + an API key, shown a markup-shaped client name, and checked for frame headers. - `skills-tab.spec.ts` (spec 125): the Skills tab of Server Detail, run by its own launcher [`scripts/run-skills-tab-sweep.sh`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/scripts/run-skills-tab-sweep.sh) as a second step of the same job (it needs `enable_skills` and a diff --git a/docs/development/web-ui-verification.md b/docs/development/web-ui-verification.md index 4eb32e138..a05258445 100644 --- a/docs/development/web-ui-verification.md +++ b/docs/development/web-ui-verification.md @@ -32,6 +32,8 @@ Alongside it, [`e2e/web-ui-sweep/visual-a11y-sweep.spec.ts`](https://github.com/ [`e2e/web-ui-sweep/usertest-web-fixes.spec.ts`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/e2e/web-ui-sweep/usertest-web-fixes.spec.ts) guards three findings of the first-run user test (Spec 109 T202 and T201, Spec 108 T169) at 1440x900 and 900x900: the header status pill says "awaiting review" for the sweep's quarantined server (compact form keeps the text in its title, no sideways scroll), a secret-like Manual-add env value is a password input with a Show toggle (never submitted), and profile Try it shows no `[object Object]`, says it uses unsaved edits, and the tool counts read "Saved profile:" while a Deny toggle is unsaved. The wizard import flow is covered by vitest and live QA, because the smoke core uses the real HOME for client paths. +[`e2e/web-ui-sweep/client-oauth-consent.spec.ts`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/e2e/web-ui-sweep/client-oauth-consent.spec.ts) guards the browser-login consent page (`specs/132-client-oauth-login`, PR-2a). The launcher starts the sweep core with `MCPPROXY_MCP_OAUTH_ENABLED=true`; against a core with browser login off the spec skips with a reason. A scripted public client registers, authorizes with PKCE and follows the redirect to `/ui/authorize?request=`; the API key reaches the page through localStorage, never a URL. It checks the per-client address (fixed client, "All servers", approve, code and state returned, `tools/list` with the token), the generic address (a reported name of "Cursor" pre-selects the existing `cursor` client, switching to "New client" pre-fills id and name and leaves `cursor` unchanged, an unknown name selects "New client"), deny returning `access_denied` with the original state, the page without an API key (no detail request until a key is set), a markup-shaped client name shown as text, and that the page is never framed. + [`e2e/web-ui-sweep/skills-tab.spec.ts`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/e2e/web-ui-sweep/skills-tab.spec.ts) guards the Skills tab of Server Detail (`specs/125-skills-over-mcp`, PR-4a). It needs `enable_skills` and a skills-capable upstream, so it has its own launcher, [`scripts/run-skills-tab-sweep.sh`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/scripts/run-skills-tab-sweep.sh): ```bash diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index 5d95a384b..e7c37f3f2 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -96,6 +96,29 @@ are checked again. (The client's registration was already stored when it registe request with `access_denied`; `.../preview` shows the guard verdict without writing. Full contract: [REST API](../api/rest-api.md). +### The consent page + +The request opens in the Web UI at `/ui/authorize?request=` (the page is never framed: +`frame-ancestors 'none'` and `X-Frame-Options: DENY`). It shows the name the app reports, +labelled as unverified, where the browser returns to, and one sentence on whose access is being +handed over. Everything the app reports is shown as plain text. + +- **Per-client address**: the client is fixed. A client that has a profile binding shows it, + without asking; a client with none and configured profiles needs a profile chosen before + Approve is enabled. "Replace the previous browser login" appears only when this same + registration signed in before. +- **Generic address**: the page opens with a client selected and you can change it. When the + reported name equals exactly one existing client's id, display name or known client name + (`Claude Code (my-server)` is also tried as `Claude Code`), that client is pre-selected with + the note `Suggested because the app calls itself "". MCPProxy cannot verify that.` + Otherwise "New client" is selected, with an editable id and name filled from the reported name. + The suggestion decides nothing: approval carries the client the page sent, and a request with + no client is refused (`client_required`). +- The binding guard's verdict is fetched through the preview call whenever the choice is + complete or changes; a refusal is shown with its fixes and Approve stays disabled. +- Without the admin API key in this browser the page asks you to open the request from the + MCPProxy tray or paste the key, and makes no request until then. + ## Seeing and revoking logins `GET /api/v1/clients` and `GET /api/v1/clients/` list each login under `credentials` diff --git a/e2e/web-ui-sweep/client-oauth-consent.spec.ts b/e2e/web-ui-sweep/client-oauth-consent.spec.ts new file mode 100644 index 000000000..0eb2f51b5 --- /dev/null +++ b/e2e/web-ui-sweep/client-oauth-consent.spec.ts @@ -0,0 +1,270 @@ +import { test, expect, type Page } from '@playwright/test' +import { createHash, randomBytes } from 'node:crypto' +import { mkdirSync } from 'node:fs' +import { join } from 'node:path' + +// Spec 132 (issue #1971) consent page, driven in a real browser against a core +// started with MCPPROXY_MCP_OAUTH_ENABLED=true (no profiles configured, so a +// client's profile is "All servers"). A scripted public client does register -> +// authorize and follows the 302 to /ui/authorize?request=; the admin API key +// reaches the page through localStorage, never a URL. +// +// Environment (exported by the launcher / by hand): +// MCPPROXY_BASE_URL e.g. http://127.0.0.1:19700 (must be the 127.0.0.1 origin) +// MCPPROXY_API_KEY the admin API key +// SWEEP_SCREENSHOT_DIR optional: keep a PNG of every step there +const BASE = process.env.MCPPROXY_BASE_URL || '' +const KEY = process.env.MCPPROXY_API_KEY || '' +const REDIRECT = 'http://127.0.0.1:54321/callback' +const shotDir = process.env.SWEEP_SCREENSHOT_DIR || '' + +test.describe.configure({ mode: 'serial' }) +test.skip(!BASE || !KEY, 'MCPPROXY_BASE_URL and MCPPROXY_API_KEY are required (core with MCPPROXY_MCP_OAUTH_ENABLED=true)') + +// The standing sweep runs against a core with browser login off (the default): +// skip loudly there instead of failing. +let oauthServed = false +test.beforeAll(async () => { + try { + oauthServed = (await fetch(`${BASE}/.well-known/oauth-authorization-server`)).status === 200 + } catch { + oauthServed = false + } +}) +test.beforeEach(() => { + test.skip(!oauthServed, 'browser login is not served by this core (start it with MCPPROXY_MCP_OAUTH_ENABLED=true)') +}) + +const t = (page: Page, id: string) => page.locator(`[data-test="${id}"]`) + +async function shot(page: Page, name: string) { + if (!shotDir) return + mkdirSync(shotDir, { recursive: true }) + await page.screenshot({ path: join(shotDir, `${name}.png`), fullPage: true }) +} + +async function sleep(ms: number) { + await new Promise((r) => setTimeout(r, ms)) +} + +// fetch that waits out the public endpoints' 429 (the limiter is not under test). +async function fetchRetry(url: string, init: RequestInit = {}): Promise { + for (let i = 0; i < 5; i++) { + const res = await fetch(url, { ...init, redirect: 'manual' }) + if (res.status !== 429) return res + await sleep((Number(res.headers.get('retry-after')) || 3) * 1000) + } + throw new Error(`still rate limited: ${url}`) +} + +const admin = (path: string, init: RequestInit = {}) => + fetch(`${BASE}/api/v1${path}`, { ...init, headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json', ...(init.headers || {}) } }) + +interface Pending { clientId: string; verifier: string; requestUrl: string; resource: string } + +async function startSignIn(clientName: string, clientPath: string, state: string): Promise { + const reg = await fetchRetry(`${BASE}/oauth/register`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ redirect_uris: [REDIRECT], client_name: clientName }), + }) + expect(reg.status).toBe(201) + const clientId = (await reg.json()).client_id as string + const verifier = randomBytes(48).toString('base64url') + const challenge = createHash('sha256').update(verifier).digest('base64url') + const resource = `${BASE}${clientPath}` + const q = new URLSearchParams({ + response_type: 'code', client_id: clientId, redirect_uri: REDIRECT, code_challenge: challenge, + code_challenge_method: 'S256', resource, state, + }) + const auth = await fetchRetry(`${BASE}/oauth/authorize?${q}`) + expect(auth.status).toBe(302) + const location = auth.headers.get('location') || '' + expect(location).toContain('/ui/authorize?request=') + return { clientId, verifier, requestUrl: location, resource } +} + +async function exchange(p: Pending, code: string) { + const res = await fetchRetry(`${BASE}/oauth/token`, { + method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', code, redirect_uri: REDIRECT, client_id: p.clientId, + code_verifier: p.verifier, resource: p.resource, + }), + }) + expect(res.status).toBe(200) + return (await res.json()) as { access_token: string } +} + +// The client's redirect URI has no listener: answer it so the navigation lands. +async function catchCallback(page: Page) { + await page.route('http://127.0.0.1:54321/**', (route) => route.fulfill({ status: 200, contentType: 'text/html', body: '

client callback

' })) +} + +async function withKey(page: Page) { + await page.addInitScript((k) => localStorage.setItem('mcpproxy-api-key', k), KEY) +} + +async function loginCount(client: string): Promise { + const res = await admin(`/clients/${client}`) + if (res.status !== 200) return 0 + const body = await res.json() + return ((body.data?.credentials as any[]) || []).filter((c) => c.kind === 'browser_login' && c.state === 'active').length +} + +test('a. per-client address: fixed client, All servers, approve, code + state, tools/list', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-a') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-fixed')).toContainText('Cursor') + await expect(t(page, 'authorize-reported')).toContainText('MCPProxy cannot verify that.') + await expect(t(page, 'authorize-client-select')).toHaveCount(0) + await expect(t(page, 'authorize-profile-select')).toHaveValue('__all__') + await expect(t(page, 'authorize-access')).toContainText('All servers') + await shot(page, 'a-per-client') + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + const back = new URL(page.url()) + expect(back.searchParams.get('state')).toBe('state-a') + const code = back.searchParams.get('code') || '' + expect(code).not.toBe('') + const tok = await exchange(p, code) + + const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${tok.access_token}` } + const init = await fetch(`${BASE}/mcp/oauth/cursor`, { + method: 'POST', headers, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'cursor', version: '1' } } }), + }) + expect(init.status).toBe(200) + const sid = init.headers.get('mcp-session-id') || '' + const list = await fetch(`${BASE}/mcp/oauth/cursor`, { + method: 'POST', headers: { ...headers, ...(sid ? { 'Mcp-Session-Id': sid } : {}) }, + body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }), + }) + expect(list.status).toBe(200) + expect(await list.text()).toContain('"tools"') +}) + +test('b. generic address: "Cursor" pre-selects the existing cursor client, approve unchanged', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const before = await loginCount('cursor') + const p = await startSignIn('Cursor', '/mcp/oauth', 'state-b') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-select')).toHaveValue('cursor') + await expect(t(page, 'authorize-suggestion-note')).toHaveText('Suggested because the app calls itself "cursor". MCPProxy cannot verify that.') + await expect(t(page, 'authorize-access')).toContainText('the same access as') + await shot(page, 'b-suggested') + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + const back = new URL(page.url()) + expect(back.searchParams.get('state')).toBe('state-b') + await exchange(p, back.searchParams.get('code') || '') + expect(await loginCount('cursor')).toBeGreaterThan(before) +}) + +test('c. generic address: switching to "New client" pre-fills id and name; cursor is unchanged', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const before = await loginCount('cursor') + const p = await startSignIn('Cursor', '/mcp/oauth', 'state-c') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-select')).toHaveValue('cursor') + await t(page, 'authorize-client-select').selectOption('__new__') + await expect(t(page, 'authorize-suggestion-note')).toHaveCount(0) + const newId = await t(page, 'authorize-new-id').inputValue() + expect(newId).not.toBe('') + expect(newId).not.toBe('cursor') + expect(await t(page, 'authorize-new-name').inputValue()).not.toBe('') + await expect(t(page, 'authorize-approve')).toBeEnabled() + await shot(page, 'c-new-client') + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + await exchange(p, new URL(page.url()).searchParams.get('code') || '') + expect((await admin(`/clients/${newId}`)).status).toBe(200) + expect(await loginCount(newId)).toBe(1) + expect(await loginCount('cursor')).toBe(before) +}) + +test('d. generic address, unknown name: "New client" is selected', async ({ page }) => { + await withKey(page) + const p = await startSignIn('Totally Unknown App', '/mcp/oauth', 'state-d') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-select')).toHaveValue('__new__') + await expect(t(page, 'authorize-suggestion-note')).toHaveCount(0) + expect(await t(page, 'authorize-new-id').inputValue()).toBe('totally-unknown-app') + await shot(page, 'd-unknown') +}) + +test('e. deny: access_denied and the original state', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-e') + await page.goto(p.requestUrl) + await t(page, 'authorize-deny').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + const back = new URL(page.url()) + expect(back.searchParams.get('error')).toBe('access_denied') + expect(back.searchParams.get('state')).toBe('state-e') + expect(back.searchParams.get('code')).toBeNull() +}) + +// With no key the app shell also opens its own "Authentication Required" dialog +// (every page does). The consent page makes no request until a key is set, by +// either door: the dialog's field, or the page's own paste field once the dialog +// is dismissed. +test('f1. no API key: only the open-from-tray text and no detail request; the app dialog sets the key', async ({ page }) => { + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-f1') + const detailRequests: string[] = [] + page.on('request', (r) => { if (r.url().includes('/api/v1/oauth/authorizations')) detailRequests.push(r.url()) }) + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-no-key')).toContainText('Open this request from the MCPProxy tray, or paste the API key') + await expect(t(page, 'authorize-approve')).toHaveCount(0) + await expect(t(page, 'authorize-deny')).toHaveCount(0) + await expect(page.getByText('Authentication Required')).toBeVisible() + await shot(page, 'f1-no-key') + expect(detailRequests).toEqual([]) + await page.getByPlaceholder('Enter your API key...').fill(KEY) + await page.getByRole('button', { name: 'Set Key' }).click() + await expect(t(page, 'authorize-client-fixed')).toContainText('Cursor') + expect(detailRequests.length).toBeGreaterThan(0) + await shot(page, 'f1-key-set') +}) + +test("f2. no API key: the page's own paste field works once the app dialog is dismissed", async ({ page }) => { + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-f2') + const detailRequests: string[] = [] + page.on('request', (r) => { if (r.url().includes('/api/v1/oauth/authorizations')) detailRequests.push(r.url()) }) + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-no-key')).toBeVisible() + await page.getByText('Dismiss (pages stay empty)').click() + expect(detailRequests).toEqual([]) + await t(page, 'authorize-key-input').fill(KEY) + await t(page, 'authorize-key-submit').click() + await expect(t(page, 'authorize-client-fixed')).toContainText('Cursor') + expect(detailRequests.length).toBeGreaterThan(0) + await shot(page, 'f2-key-pasted') +}) + +test('g. a markup-shaped client name is shown as text: no element, no dialog', async ({ page }) => { + await withKey(page) + let dialog = '' + page.on('dialog', async (d) => { dialog = d.message(); await d.dismiss() }) + const p = await startSignIn('', '/mcp/oauth', 'state-g') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-reported')).toBeVisible() + await page.waitForTimeout(500) + expect(dialog).toBe('') + await expect(page.locator('img[src="x"]')).toHaveCount(0) + await expect(t(page, 'authorize-reported')).toContainText('cannot verify') + await shot(page, 'g-markup-name') +}) + +test('h. the consent page is never framed (any case)', async ({ request }) => { + for (const path of ['/ui/authorize?request=x', '/ui/Authorize?request=x']) { + const res = await request.get(`${BASE}${path}`) + expect(res.status(), path).toBe(200) + expect(res.headers()['content-security-policy'], path).toContain("frame-ancestors 'none'") + expect(res.headers()['x-frame-options'], path).toBe('DENY') + } +}) diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 2cfb7d855..bc885b3a5 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -35,6 +35,8 @@ const router = createRouter({ title: 'Usage Analytics', }, }, + // Spec 132: consent page for a browser sign-in request (`?request=`). + { path: '/authorize', name: 'authorize', component: () => import('@/views/AuthorizeRequest.vue'), meta: { title: 'Sign-in request' } }, { path: '/clients', name: 'clients', component: () => import('@/views/Clients.vue'), meta: { title: 'Clients' } }, // Spec 108-i I4: two SIBLING top-level routes. The Spec 109-i gate on the // sidebar item, the Add menu item and the palette action compares diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 3fb553725..5362b8c42 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -1,5 +1,5 @@ import type { APIResponse, Server, Tool, ToolApproval, SearchResult, StatusUpdate, StatusResponse, SecretRef, MigrationAnalysis, ConfigSecretsResponse, GetToolCallsResponse, GetToolCallDetailResponse, GetServerToolCallsResponse, GetConfigResponse, ValidateConfigResponse, ConfigApplyResult, ServerTokenMetrics, GetRegistriesResponse, SearchRegistryServersResponse, RegistrySummary, CatalogSearchResponse, GetSessionsResponse, GetSessionDetailResponse, InfoResponse, ActivityListResponse, ActivityDetailResponse, ActivityRecord, ActivitySummaryResponse, ImportResponse, AgentTokenInfo, CreateAgentTokenRequest, CreateAgentTokenResponse, RoutingInfo, ConnectStatusResponse, ClientStatus, ConnectResult, ConnectPreview, OnboardingStateResponse, OnboardingMarkRequest, DiagnosticFixResponse, GlobalToolsResponse, UsageAggregateResponse, UsageWindow, UsageSort, UsageStatus, AttentionResponse, ReviewQueueResponse, ServerReviewResponse } from '@/types' -import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' +import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions, OAuthAuthorization, OAuthApprovalBody, OAuthPreview, OAuthDecision, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' import { joinHoldEvidence, type HoldEvidenceSource } from '@/utils/holdEvidence' @@ -1530,6 +1530,24 @@ class APIService { return this.data(`/api/v1/clients/${encodeURIComponent(id)}${queryString({ disconnect: opts.disconnect ? 'true' : undefined })}`, { method: 'DELETE' }) } + // Spec 132 sign-in requests (administrator only). All throw an ApiError whose + // `status` and `code` the consent page branches on. + getOAuthAuthorization(id: string): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}`) + } + + previewOAuthAuthorization(id: string, body: OAuthApprovalBody): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}/preview`, { method: 'POST', body: JSON.stringify(body) }) + } + + approveOAuthAuthorization(id: string, body: OAuthApprovalBody): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}/approve`, { method: 'POST', body: JSON.stringify(body) }) + } + + denyOAuthAuthorization(id: string): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}/deny`, { method: 'POST', body: '{}' }) + } + upgradeAdminKeyHolders(body: { profile?: string; mode?: 'locked' | 'switchable'; apply?: boolean; precondition_token?: string } = {}): Promise { return this.data('/api/v1/clients/upgrade-admin-key-holders', { method: 'POST', body: JSON.stringify(body) }) } diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index 2aa4c8a12..a5557b781 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -1569,6 +1569,63 @@ export interface BindingRef { client_id: string; token_name: string; profile: st /** One fix of a binding-guard refusal (`require_mcp_auth` | `set_anonymous_profile`). */ export interface GuardFix { kind: string; target?: string } +// --- Spec 132: browser login for MCP clients (consent page) ---------------------- +// Everything named by the app (`reported_name`, `suggested_new_client`) is +// untrusted text: render it with mustaches, never as HTML. + +export interface OAuthBindingView { profile: string; mode: string; revision: string } + +export interface OAuthAuthorizationClient { + id: string + display_name: string + exists: boolean + has_api_key: boolean + logins: number + binding?: OAuthBindingView +} + +export interface OAuthExistingClient { id: string; display_name: string; binding?: OAuthBindingView } + +export interface OAuthGuardVerdict { code: string; bindings: BindingRef[]; fixes: GuardFix[] } + +export interface OAuthAuthorization { + id: string + status: string + expires_at: string + reported_name: string + redirect_uri: string + resource: string + address_kind: 'client' | 'generic' + client?: OAuthAuthorizationClient + existing_clients?: OAuthExistingClient[] + suggested_new_client?: { id: string; display_name: string } + /** Advice only; present on the generic address when the reported name equals exactly one existing client. */ + suggested_client?: { id: string; matched: 'id' | 'display_name' | 'known_name' } + profiles: Array<{ name: string }> + profile_required: boolean + previous_login?: { grant_id: string; client_id: string; approved_at: string } + /** The newest live login of this registration under each client. */ + previous_logins?: Array<{ grant_id: string; client_id: string; approved_at: string }> + guard: OAuthGuardVerdict | null +} + +export interface OAuthApprovalBody { + client?: { id?: string; new?: { id: string; display_name?: string } } + /** Omitted = not chosen; '' = All servers. */ + profile?: string + mode?: 'locked' | 'switchable' + binding_revision?: string + replace_grant?: string +} + +export interface OAuthPreview { + complete: boolean + access?: { client: string; profile: string; mode: string; same_access_as_existing_client: boolean } + guard: OAuthGuardVerdict | null +} + +export interface OAuthDecision { redirect_url: string } + export interface BulkAssignResponse { moved: string[] skipped: Array<{ client_id: string; code: string; error?: string }> diff --git a/frontend/src/utils/navigate.ts b/frontend/src/utils/navigate.ts new file mode 100644 index 000000000..c32eacd67 --- /dev/null +++ b/frontend/src/utils/navigate.ts @@ -0,0 +1,5 @@ +// A seam for leaving the app: the consent page hands the browser back to the +// client's redirect URI, which tests replace with a spy. +export function navigateTo(url: string): void { + window.location.assign(url) +} diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue new file mode 100644 index 000000000..a4aec555c --- /dev/null +++ b/frontend/src/views/AuthorizeRequest.vue @@ -0,0 +1,486 @@ + + + diff --git a/frontend/tests/unit/authorize-request-nokey.spec.ts b/frontend/tests/unit/authorize-request-nokey.spec.ts new file mode 100644 index 000000000..5a20b9854 --- /dev/null +++ b/frontend/tests/unit/authorize-request-nokey.spec.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api from '@/services/api' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => false), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any + +describe('AuthorizeRequest without an API key in storage', () => { + beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(false) + }) + + it('shows only the open-from-tray message, makes no request, and continues after a pasted key', async () => { + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + + expect(w.text()).toContain('Open this request from the MCPProxy tray, or paste the API key') + expect(w.find('[data-test="authorize-approve"]').exists()).toBe(false) + expect(w.find('[data-test="authorize-deny"]').exists()).toBe(false) + expect(A.getOAuthAuthorization).not.toHaveBeenCalled() + expect(A.previewOAuthAuthorization).not.toHaveBeenCalled() + + A.getOAuthAuthorization.mockResolvedValue({ + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor', + redirect_uri: 'http://127.0.0.1:1/cb', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: false, logins: 0, binding: { profile: '', mode: 'switchable', revision: 'r' } }, + profiles: [], profile_required: false, guard: null, + }) + A.previewOAuthAuthorization.mockResolvedValue({ complete: true, access: { client: 'cursor', profile: '', mode: 'switchable', same_access_as_existing_client: true }, guard: null }) + + await w.find('[data-test="authorize-key-input"]').setValue(' the-admin-key ') + await w.find('[data-test="authorize-key-submit"]').trigger('click') + await flushPromises() + + expect(A.setAPIKey).toHaveBeenCalledWith('the-admin-key') + expect(A.getOAuthAuthorization).toHaveBeenCalledWith('r1') + expect(w.find('[data-test="authorize-approve"]').exists()).toBe(true) + }) + + it('does not call the API when the request id is missing', async () => { + A.hasAPIKey.mockReturnValue(true) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + expect(A.getOAuthAuthorization).not.toHaveBeenCalled() + expect(w.find('[data-test="authorize-gone"]').exists()).toBe(true) + }) +}) diff --git a/frontend/tests/unit/authorize-request-race.spec.ts b/frontend/tests/unit/authorize-request-race.spec.ts new file mode 100644 index 000000000..03fe82907 --- /dev/null +++ b/frontend/tests/unit/authorize-request-race.spec.ts @@ -0,0 +1,269 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const bound = { profile: 'dev-readonly', mode: 'locked', revision: 'rev1' } +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function detail(id: string, over: Record = {}) { + return { + id, status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor IDE', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: bound }, + profiles: [{ name: 'dev-readonly' }, { name: 'ops' }], profile_required: false, guard: null, ...over, + } +} + +function generic(id: string, over: Record = {}) { + return detail(id, { + address_kind: 'generic', client: undefined, resource: 'http://127.0.0.1:8080/mcp/oauth', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: bound }, + ], + suggested_new_client: { id: 'acme-agent', display_name: 'Acme Agent' }, + profile_required: true, ...over, + }) +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? 'dev-readonly', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountAt(details: Record, query = '?request=r1') { + A.getOAuthAuthorization.mockImplementation(async (id: string) => details[id]) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }, { path: '/settings', component: { template: '
' } }] }) + await router.push('/authorize' + query) + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return { w, router } +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('AuthorizeRequest: request id changes in the same component', () => { + it('drops r1 at once, shows r2 and binds both decisions to the displayed request', async () => { + const slow = deferred() + const { w, router } = await mountAt({ r1: detail('r1', { reported_name: 'First App' }), r2: detail('r2', { reported_name: 'Second App' }) }) + expect(t(w, 'authorize-reported').text()).toContain('First App') + + A.getOAuthAuthorization.mockImplementation((id: string) => (id === 'r2' ? slow.promise : Promise.resolve(detail(id)))) + await router.push('/authorize?request=r2') + await flushPromises() + // r2 is still loading: r1 must not be on screen or decidable. + expect(w.text()).not.toContain('First App') + expect(t(w, 'authorize-approve').exists()).toBe(false) + expect(t(w, 'authorize-deny').exists()).toBe(false) + + slow.resolve(detail('r2', { reported_name: 'Second App' })) + await flushPromises() + expect(t(w, 'authorize-reported').text()).toContain('Second App') + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r2', expect.anything()) + expect(A.approveOAuthAuthorization).not.toHaveBeenCalledWith('r1', expect.anything()) + }) + + it('ignores a late answer for the request that was left', async () => { + const late = deferred() + A.getOAuthAuthorization.mockImplementation((id: string) => (id === 'r1' ? late.promise : Promise.resolve(detail(id, { reported_name: 'Second App' })))) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + await router.push('/authorize?request=r2') + await flushPromises() + late.resolve(detail('r1', { reported_name: 'First App' })) + await flushPromises() + expect(t(w, 'authorize-reported').text()).toContain('Second App') + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(A.denyOAuthAuthorization).toHaveBeenCalledWith('r2') + }) +}) + +describe('AuthorizeRequest: Approve needs a complete, current preview', () => { + it('stays disabled on {complete:false} and while the preview is pending', async () => { + const first = deferred() + A.previewOAuthAuthorization.mockImplementation(() => first.promise) + const { w } = await mountAt({ r1: detail('r1') }) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + first.resolve({ complete: false, guard: null }) + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-access').exists()).toBe(false) + }) + + it('ignores an out-of-order preview and sends the body the accepted preview was for', async () => { + const p1 = deferred() + const p2 = deferred() + const pending: Array<[any, ReturnType>]> = [] + A.previewOAuthAuthorization.mockImplementation((_id: string, body: any) => { + const d = pending.length === 0 ? p1 : p2 + pending.push([body, d]) + return d.promise + }) + const { w } = await mountAt({ r1: generic('r1') }) + // First preview (new client acme-agent, no profile yet) is not even asked: incomplete. Choose ops. + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(pending).toHaveLength(1) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(pending).toHaveLength(2) + // The newer preview (codex) answers first; the stale one (acme-agent) arrives late. + p2.resolve(complete(pending[1][0])) + await flushPromises() + p1.resolve(complete(pending[0][0])) + await flushPromises() + expect(t(w, 'authorize-access').text()).toContain('Codex') + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', pending[1][0]) + }) + + it('disables Approve again as soon as the choice changes, until its preview answers', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + const next = deferred() + A.previewOAuthAuthorization.mockImplementation(() => next.promise) + await t(w, 'authorize-client-select').setValue('codex') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-access').exists()).toBe(false) + next.resolve(complete({ client: { id: 'codex' }, binding_revision: 'rc' })) + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('AuthorizeRequest: replacing the previous login', () => { + const prev = { grant_id: 'gc', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + + it('offers it only for the client that owns it, and sends the exact body', async () => { + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + expect(t(w, 'authorize-replace').exists()).toBe(true) + + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(false) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { client: { id: 'codex' }, binding_revision: 'rc' }) + }) + + it('does not show or send it for a new client, and brings it back for the owner', async () => { + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + await t(w, 'authorize-client-select').setValue('__new__') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(false) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(A.previewOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBeUndefined() + await t(w, 'authorize-client-select').setValue('cursor') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(true) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { client: { id: 'cursor' }, binding_revision: 'rev1', replace_grant: 'gc' }) + }) +}) + +describe('AuthorizeRequest: new-client draft', () => { + it('is populated from suggested_new_client when the page opened on a suggested client', async () => { + const { w } = await mountAt({ r1: generic('r1', { suggested_client: { id: 'cursor', matched: 'id' } }) }) + expect(t(w, 'authorize-new-id').exists()).toBe(false) + await t(w, 'authorize-client-select').setValue('__new__') + await flushPromises() + expect((t(w, 'authorize-new-id').element as HTMLInputElement).value).toBe('acme-agent') + expect((t(w, 'authorize-new-name').element as HTMLInputElement).value).toBe('Acme Agent') + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { + client: { new: { id: 'acme-agent', display_name: 'Acme Agent' } }, profile: 'ops', mode: 'locked', + }) + }) +}) + +describe('AuthorizeRequest: one decision per request', () => { + it('ignores repeated and mixed clicks while a decision is in flight, and stays decided after success', async () => { + const d = deferred() + const { w } = await mountAt({ r1: detail('r1') }) + A.approveOAuthAuthorization.mockImplementation(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + await t(w, 'authorize-approve').trigger('click') + await t(w, 'authorize-deny').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(1) + expect(A.denyOAuthAuthorization).not.toHaveBeenCalled() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await flushPromises() + expect(navigateTo).toHaveBeenCalledTimes(1) + // Terminal: the buttons stay disabled and no second decision is possible. + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeDefined() + await t(w, 'authorize-approve').trigger('click') + await t(w, 'authorize-deny').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(1) + expect(A.denyOAuthAuthorization).not.toHaveBeenCalled() + }) + + it('guards Deny too, and releases the buttons after a recoverable failure', async () => { + const d = deferred() + const { w } = await mountAt({ r1: detail('r1') }) + A.denyOAuthAuthorization.mockImplementation(() => d.promise) + await t(w, 'authorize-deny').trigger('click') + await t(w, 'authorize-deny').trigger('click') + await t(w, 'authorize-approve').trigger('click') + expect(A.denyOAuthAuthorization).toHaveBeenCalledTimes(1) + expect(A.approveOAuthAuthorization).not.toHaveBeenCalled() + d.reject(new Error('network down')) + await flushPromises() + expect(t(w, 'authorize-error').text()).toContain('network down') + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(navigateTo).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/tests/unit/authorize-request-round2.spec.ts b/frontend/tests/unit/authorize-request-round2.spec.ts new file mode 100644 index 000000000..a26264cb5 --- /dev/null +++ b/frontend/tests/unit/authorize-request-round2.spec.ts @@ -0,0 +1,169 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function detail(id: string, over: Record = {}) { + return { + id, status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: `App ${id}`, + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: { profile: 'dev', mode: 'locked', revision: 'rev1' } }, + profiles: [{ name: 'dev' }], profile_required: false, guard: null, ...over, + } +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? 'dev', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountAt(details: Record, query = '?request=r1') { + A.getOAuthAuthorization.mockImplementation(async (id: string) => details[id]) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize' + query) + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return { w, router } +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('obsolete decision responses are ignored', () => { + async function pendingApproveThenNavigate() { + const d = deferred() + const ctx = await mountAt({ r1: detail('r1'), r2: detail('r2') }) + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(ctx.w, 'authorize-approve').trigger('click') + await ctx.router.push('/authorize?request=r2') + await flushPromises() + return { ...ctx, d } + } + + it('a successful r1 answer neither navigates nor disables r2', async () => { + const { w, d } = await pendingApproveThenNavigate() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=r1' }) + await flushPromises() + expect(navigateTo).not.toHaveBeenCalled() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + }) + + it('an already_decided / 404 answer for r1 does not hide r2', async () => { + const { w, d } = await pendingApproveThenNavigate() + d.reject(new ApiError(409, { code: 'already_decided', error: 'decided' }, 'x')) + await flushPromises() + expect(t(w, 'authorize-decided').exists()).toBe(false) + expect(t(w, 'authorize-gone').exists()).toBe(false) + expect(t(w, 'authorize-approve').exists()).toBe(true) + }) + + it("a failure of r1 does not release r2's own pending decision", async () => { + const { w, d } = await pendingApproveThenNavigate() + const d2 = deferred() + A.approveOAuthAuthorization.mockImplementationOnce(() => d2.promise) + await t(w, 'authorize-approve').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(2) + d.reject(new Error('network down')) + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + await t(w, 'authorize-approve').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(2) + expect(t(w, 'authorize-error').exists()).toBe(false) + }) + + it('a deny answer for r1 is ignored after navigating to r2', async () => { + const d = deferred() + const { w, router } = await mountAt({ r1: detail('r1'), r2: detail('r2') }) + A.denyOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-deny').trigger('click') + await router.push('/authorize?request=r2') + await flushPromises() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?error=access_denied' }) + await flushPromises() + expect(navigateTo).not.toHaveBeenCalled() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + }) + + it('an answer that arrives after the component is unmounted does nothing', async () => { + const d = deferred() + const { w } = await mountAt({ r1: detail('r1') }) + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + w.unmount() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=late' }) + await flushPromises() + expect(navigateTo).not.toHaveBeenCalled() + }) +}) + +describe('binding_changed from the preview call', () => { + it('on a generic page: a refused preview reloads with the new revision', async () => { + const generic = (rev: string) => detail('r1', { + address_kind: 'generic', client: undefined, + existing_clients: [{ id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: rev } }], + suggested_new_client: { id: 'acme', display_name: 'Acme' }, profile_required: true, + }) + const { w } = await mountAt({ r1: generic('rc1') }) + A.getOAuthAuthorization.mockImplementation(async () => generic('rc2')) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => { + if (body.binding_revision === 'rc1') throw new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x') + return complete(body) + }) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-changed').exists()).toBe(true) + expect(A.previewOAuthAuthorization.mock.calls.at(-1)![1].binding_revision).toBe('rc2') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('unbound client with no profiles configured', () => { + it('shows "All servers" selected and submits the empty profile', async () => { + const d = detail('r1', { + profiles: [], profile_required: false, + client: { id: 'cursor', display_name: 'Cursor', exists: false, has_api_key: false, logins: 0 }, + }) + const { w } = await mountAt({ r1: d }) + const select = t(w, 'authorize-profile-select') + expect((select.element as HTMLSelectElement).value).toBe('__all__') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', { client: { id: 'cursor' }, profile: '' }) + }) +}) diff --git a/frontend/tests/unit/authorize-request-round3.spec.ts b/frontend/tests/unit/authorize-request-round3.spec.ts new file mode 100644 index 000000000..4b8afcb28 --- /dev/null +++ b/frontend/tests/unit/authorize-request-round3.spec.ts @@ -0,0 +1,189 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function generic(id: string, over: Record = {}) { + return { + id, status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: `App ${id}`, + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth', + address_kind: 'generic', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: { profile: 'dev', mode: 'locked', revision: 'rv' } }, + ], + suggested_new_client: { id: 'acme', display_name: 'Acme' }, + profiles: [{ name: 'ops' }, { name: 'dev' }], profile_required: true, guard: null, ...over, + } +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? '', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountAt(details: Record) { + A.getOAuthAuthorization.mockImplementation(async (id: string) => details[id]) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return { w, router } +} + +const changed = () => new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x') + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('review-again reload validates what it keeps', () => { + it('a kept named profile that no profiles remain for becomes All servers (select and body agree)', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + // The next preview is refused; the reload finds that every profile was deleted. + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { profiles: [], profile_required: false })) + await t(w, 'authorize-new-id').setValue('acme2') + await t(w, 'authorize-new-id').trigger('change') + await flushPromises() + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__all__') + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].profile).toBe('') + }) + + it('a kept unset choice with no profiles left becomes All servers', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__unset__') + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { profiles: [], profile_required: false })) + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + await t(w, 'authorize-client-select').setValue('__new__') + await flushPromises() + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__all__') + }) + + it('a kept named profile that was deleted (others remain) goes back to unset and Approve stays disabled', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { profiles: [{ name: 'dev' }] })) + await t(w, 'authorize-new-id').setValue('acme2') + await t(w, 'authorize-new-id').trigger('change') + await flushPromises() + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__unset__') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) + + it('re-checks replace for a previous login that changed (g1 -> g2) and sends the new grant', async () => { + const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + // Unchecking changes the choice; its preview is refused and the reload finds a newer login. + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { previous_login: { ...prev, grant_id: 'g2' }, suggested_client: { id: 'cursor', matched: 'id' } })) + await t(w, 'authorize-replace').setValue(false) + await flushPromises() + const box = t(w, 'authorize-replace') + expect(box.exists()).toBe(true) + expect((box.element as HTMLInputElement).checked).toBe(true) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBe('g2') + }) +}) + +describe('choice controls are frozen while a decision is pending or done', () => { + const controls = ['authorize-client-select', 'authorize-profile-select'] + + it('disables every choice control, and a late answer lands on the choice that was approved', async () => { + const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + const d = deferred() + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + for (const id of ['authorize-client-select', 'authorize-replace']) { + expect(t(w, id).attributes('disabled'), id).toBeDefined() + } + const calls = A.previewOAuthAuthorization.mock.calls.length + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(A.previewOAuthAuthorization.mock.calls.length).toBe(calls) + expect(t(w, 'authorize-access').text()).toContain('Cursor') + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await flushPromises() + expect(navigateTo).toHaveBeenCalledTimes(1) + // Terminal: still frozen. + expect(t(w, 'authorize-client-select').attributes('disabled')).toBeDefined() + }) + + it('freezes the new-client fields, the profile and the lock', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + const d = deferred() + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + for (const id of [...controls, 'authorize-new-id', 'authorize-new-name', 'authorize-lock']) { + expect(t(w, id).attributes('disabled'), id).toBeDefined() + } + d.reject(new Error('network down')) + await flushPromises() + for (const id of controls) expect(t(w, id).attributes('disabled'), id).toBeUndefined() + }) +}) + +describe('the review-again notice belongs to the request that was reloaded', () => { + it('is not shown on r2 when the page navigated during the reload', async () => { + const { w, router } = await mountAt({ r1: generic('r1'), r2: generic('r2') }) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + const reload = deferred() + A.approveOAuthAuthorization.mockRejectedValueOnce(changed()) + A.getOAuthAuthorization.mockImplementation((id: string) => (id === 'r1' ? reload.promise : Promise.resolve(generic(id)))) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + await router.push('/authorize?request=r2') + await flushPromises() + reload.resolve(generic('r1')) + await flushPromises() + expect(t(w, 'authorize-changed').exists()).toBe(false) + expect(t(w, 'authorize-reported').text()).toContain('App r2') + }) +}) diff --git a/frontend/tests/unit/authorize-request-round4.spec.ts b/frontend/tests/unit/authorize-request-round4.spec.ts new file mode 100644 index 000000000..1c740746e --- /dev/null +++ b/frontend/tests/unit/authorize-request-round4.spec.ts @@ -0,0 +1,123 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +const detail = () => ({ + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'App', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: { profile: 'dev', mode: 'locked', revision: 'rev1' } }, + profiles: [{ name: 'dev' }], profile_required: false, guard: null, +}) + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id, profile: 'dev', mode: 'locked', same_access_as_existing_client: true }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountPage() { + A.getOAuthAuthorization.mockImplementation(async () => detail()) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('Deny does not depend on the preview', () => { + it('a pending preview that later answers binding_changed does not drop the Deny redirect', async () => { + const pv = deferred() + A.previewOAuthAuthorization.mockImplementationOnce(() => pv.promise) + const w = await mountPage() + const deny = deferred() + A.denyOAuthAuthorization.mockImplementationOnce(() => deny.promise) + await t(w, 'authorize-deny').trigger('click') + const loads = A.getOAuthAuthorization.mock.calls.length + pv.reject(new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x')) + await flushPromises() + expect(A.getOAuthAuthorization.mock.calls.length).toBe(loads) // no reload while deciding + expect(t(w, 'authorize-deny').attributes('disabled')).toBeDefined() + deny.resolve({ redirect_url: 'http://127.0.0.1:54321/callback?error=access_denied' }) + await flushPromises() + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?error=access_denied') + }) + + it.each([ + ['failed', async () => { throw new Error('boom') }], + ['incomplete', async () => ({ complete: false, guard: null })], + ])('works with a %s preview', async (_n, impl) => { + A.previewOAuthAuthorization.mockImplementation(impl) + const w = await mountPage() + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(navigateTo).toHaveBeenCalledTimes(1) + }) + + it('restarts the preview after a recoverable decision failure', async () => { + const pv = deferred() + A.previewOAuthAuthorization.mockImplementationOnce(() => pv.promise) + const w = await mountPage() + const deny = deferred() + A.denyOAuthAuthorization.mockImplementationOnce(() => deny.promise) + await t(w, 'authorize-deny').trigger('click') + pv.resolve(complete({ client: { id: 'cursor' } })) // obsolete: a decision is pending + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + const calls = A.previewOAuthAuthorization.mock.calls.length + deny.reject(new Error('network down')) + await flushPromises() + expect(A.previewOAuthAuthorization.mock.calls.length).toBe(calls + 1) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('a failed preview can be retried', () => { + it('shows Check again, and Approve enables after a successful retry without remount', async () => { + A.previewOAuthAuthorization.mockRejectedValueOnce(new Error('HTTP 503')) + const w = await mountPage() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-retry').exists()).toBe(true) + await t(w, 'authorize-retry').trigger('click') + await flushPromises() + expect(t(w, 'authorize-retry').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-access').exists()).toBe(true) + }) +}) diff --git a/frontend/tests/unit/authorize-request-round5.spec.ts b/frontend/tests/unit/authorize-request-round5.spec.ts new file mode 100644 index 000000000..78333827a --- /dev/null +++ b/frontend/tests/unit/authorize-request-round5.spec.ts @@ -0,0 +1,109 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +const detail = () => ({ + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'App', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: { profile: 'dev', mode: 'locked', revision: 'rev1' } }, + profiles: [{ name: 'dev' }], profile_required: false, guard: null, +}) + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id, profile: 'dev', mode: 'locked', same_access_as_existing_client: true }, + guard: null, +}) + +const changed = () => new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x') + +async function mountPage() { + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.getOAuthAuthorization.mockImplementation(async () => detail()) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('binding_changed from preview reloads at most once', () => { + it('stops after one automatic reload, keeps Deny, shows the notice and offers Check again', async () => { + A.previewOAuthAuthorization.mockRejectedValue(changed()) + const w = await mountPage() + // initial GET + one automatic reload; initial preview + the reload's preview. + expect(A.getOAuthAuthorization).toHaveBeenCalledTimes(2) + expect(A.previewOAuthAuthorization).toHaveBeenCalledTimes(2) + expect(t(w, 'authorize-changed').exists()).toBe(true) + expect(t(w, 'authorize-retry').exists()).toBe(true) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?error=access_denied') + expect(A.getOAuthAuthorization).toHaveBeenCalledTimes(2) + }) + + it('Check again is an explicit user action that can recover', async () => { + A.previewOAuthAuthorization.mockRejectedValueOnce(changed()).mockRejectedValueOnce(changed()) + const w = await mountPage() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + await t(w, 'authorize-retry').trigger('click') + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('a failed review-again reload can be retried', () => { + it('shows Try again for a transient failure (not for an expired request) and recovers', async () => { + const w = await mountPage() + A.approveOAuthAuthorization.mockRejectedValueOnce(changed()) + A.getOAuthAuthorization.mockRejectedValueOnce(new ApiError(503, { error: 'unavailable' }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-load-error').exists()).toBe(true) + expect(t(w, 'authorize-load-retry').exists()).toBe(true) + await t(w, 'authorize-load-retry').trigger('click') + await flushPromises() + expect(t(w, 'authorize-load-error').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-deny').exists()).toBe(true) + }) + + it('an expired request (404) has no retry', async () => { + A.getOAuthAuthorization.mockRejectedValue(new ApiError(404, { error: 'not found' }, 'x')) + const w = await mountPage() + expect(t(w, 'authorize-gone').exists()).toBe(true) + expect(t(w, 'authorize-load-retry').exists()).toBe(false) + }) +}) diff --git a/frontend/tests/unit/authorize-request-round7.spec.ts b/frontend/tests/unit/authorize-request-round7.spec.ts new file mode 100644 index 000000000..55cdb94c7 --- /dev/null +++ b/frontend/tests/unit/authorize-request-round7.spec.ts @@ -0,0 +1,151 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function generic(over: Record = {}) { + return { + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth', + address_kind: 'generic', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: { profile: 'dev', mode: 'locked', revision: 'rv' } }, + { id: 'cursor-2', display_name: 'Cursor', binding: { profile: 'dev', mode: 'locked', revision: 'r2' } }, + ], + suggested_new_client: { id: 'acme', display_name: 'Acme' }, + profiles: [{ name: 'ops' }, { name: 'dev' }], profile_required: true, guard: null, ...over, + } +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? '', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +async function mountWith(detail: any) { + A.getOAuthAuthorization.mockImplementation(async () => detail) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('untrusted names are isolated from the page copy', () => { + it('puts the reported name in its own bdi with the disclaimer as the sibling after it', async () => { + const name = 'cursor (official". verified by the mcpproxy tray. "x)' + const w = await mountWith(generic({ reported_name: name, suggested_client: { id: 'cursor', matched: 'id' } })) + const p = t(w, 'authorize-reported').element as HTMLElement + const bdi = p.querySelector('bdi')! + expect(bdi).not.toBeNull() + expect(bdi.textContent).toBe(name) + expect(bdi.nextSibling!.textContent).toBe('". MCPProxy cannot verify that.') + expect(p.firstChild!.textContent).toBe('The app calls itself "') + + const note = t(w, 'authorize-suggestion-note').element as HTMLElement + const nb = note.querySelector('bdi')! + expect(nb.textContent).toBe(name) + expect(nb.nextSibling!.textContent).toBe('". MCPProxy cannot verify that.') + }) + + it('also isolates the new-client name in the access sentence and the return address', async () => { + const w = await mountWith(generic()) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + const access = t(w, 'authorize-access').element as HTMLElement + const bdis = access.querySelectorAll('bdi') + expect(bdis[bdis.length - 1].textContent).toBe('Acme') + expect((t(w, 'authorize-returns-to').element as HTMLElement).querySelector('bdi')!.textContent).toBe('http://127.0.0.1:54321/callback') + }) +}) + +describe('client options', () => { + it('show the id next to the display name so two clients never look identical', async () => { + const w = await mountWith(generic()) + const labels = t(w, 'authorize-client-select').findAll('option').map((o: any) => o.text()) + expect(labels).toContain('Cursor (cursor)') + expect(labels).toContain('Cursor (cursor-2)') + expect(labels).toContain('Codex (codex)') + }) +}) + +describe('previous logins per client', () => { + it('offers replacement for the selected client, whichever login is newest overall', async () => { + const prevCodex = { grant_id: 'gx', client_id: 'codex', approved_at: '2026-11-20T10:00:00Z' } + const prevCursor = { grant_id: 'gc', client_id: 'cursor', approved_at: '2026-11-10T10:00:00Z' } + const w = await mountWith(generic({ previous_login: prevCodex, previous_logins: [prevCodex, prevCursor] })) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + + await t(w, 'authorize-client-select').setValue('cursor') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(true) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { client: { id: 'cursor' }, binding_revision: 'rv', replace_grant: 'gc' }) + + const w2 = await mountWith(generic({ previous_login: prevCodex, previous_logins: [prevCodex, prevCursor] })) + await t(w2, 'authorize-client-select').setValue('codex') + await flushPromises() + await t(w2, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { client: { id: 'codex' }, binding_revision: 'rc', replace_grant: 'gx' }) + + // A client with no login of its own gets no Replace option. + const w3 = await mountWith(generic({ previous_login: prevCodex, previous_logins: [prevCodex, prevCursor] })) + await t(w3, 'authorize-client-select').setValue('cursor-2') + await flushPromises() + expect(t(w3, 'authorize-replace').exists()).toBe(false) + }) +}) + +describe('client_not_found is an error on the choice, not an expired request', () => { + it('from approve', async () => { + const w = await mountWith(generic({ suggested_client: { id: 'cursor', matched: 'id' } })) + A.approveOAuthAuthorization.mockRejectedValue(new ApiError(404, { code: 'client_not_found', error: 'unknown client' }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-gone').exists()).toBe(false) + expect(t(w, 'authorize-error').text()).toContain('unknown client') + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + // Another choice can still be made. + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) + + it('from preview', async () => { + A.previewOAuthAuthorization.mockRejectedValue(new ApiError(404, { code: 'client_not_found', error: 'unknown client' }, 'x')) + const w = await mountWith(generic({ suggested_client: { id: 'cursor', matched: 'id' } })) + expect(t(w, 'authorize-gone').exists()).toBe(false) + expect(t(w, 'authorize-error').text()).toContain('unknown client') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) +}) diff --git a/frontend/tests/unit/authorize-request.spec.ts b/frontend/tests/unit/authorize-request.spec.ts new file mode 100644 index 000000000..ae32c32b4 --- /dev/null +++ b/frontend/tests/unit/authorize-request.spec.ts @@ -0,0 +1,285 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any + +const bound = { profile: 'dev-readonly', mode: 'locked', revision: 'rev1' } + +function base(over: Record = {}) { + return { + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor IDE', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: bound }, + profiles: [{ name: 'dev-readonly' }, { name: 'ops' }], profile_required: false, guard: null, + ...over, + } +} + +function generic(over: Record = {}) { + return base({ + address_kind: 'generic', client: undefined, resource: 'http://127.0.0.1:8080/mcp/oauth', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: bound }, + ], + suggested_new_client: { id: 'acme-agent', display_name: 'Acme Agent' }, + profile_required: true, + ...over, + }) +} + +async function mountPage(detail: any, query = '?request=r1') { + A.getOAuthAuthorization.mockResolvedValue(detail) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => { + const client = body.client?.id ?? body.client?.new?.id + if (!client) return { complete: false, guard: null } + const existing = !!body.binding_revision + return { + complete: true, + access: { client, profile: body.profile ?? 'dev-readonly', mode: body.mode ?? 'locked', same_access_as_existing_client: existing }, + guard: null, + } + }) + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/authorize', name: 'authorize', component: AuthorizeRequest }, + { path: '/settings', name: 'settings', component: { template: '
' } }, + ], + }) + await router.push('/authorize' + query) + await router.isReady() + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +describe('AuthorizeRequest: per-client address', () => { + beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + }) + + it('fixes the client, labels the reported name as unverified and states the access', async () => { + const w = await mountPage(base()) + expect(t(w, 'authorize-reported').text()).toContain('The app calls itself "Cursor IDE". MCPProxy cannot verify that.') + expect(t(w, 'authorize-client-fixed').text()).toContain('Cursor') + expect(t(w, 'authorize-client-select').exists()).toBe(false) + expect(t(w, 'authorize-binding').text()).toContain('dev-readonly') + expect(t(w, 'authorize-binding').text()).toContain('locked') + expect(t(w, 'authorize-profile-select').exists()).toBe(false) + expect(t(w, 'authorize-access').text()).toContain('the same access as Cursor') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) + + it('never renders reported text as HTML', async () => { + const w = await mountPage(base({ reported_name: '' })) + expect(w.find('img').exists()).toBe(false) + expect(t(w, 'authorize-reported').text()).toContain('') + }) + + it('disables Approve until a profile is chosen when profile_required', async () => { + const detail = base({ + profile_required: true, + client: { id: 'cursor', display_name: 'Cursor', exists: false, has_api_key: false, logins: 0 }, + }) + const w = await mountPage(detail) + expect(t(w, 'authorize-binding').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(A.previewOAuthAuthorization).toHaveBeenLastCalledWith('r1', expect.objectContaining({ client: { id: 'cursor' }, profile: 'ops', mode: 'locked' })) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) + + it('offers the replace-login checkbox only with previous_login, pre-checked, and sends it', async () => { + const without = await mountPage(base()) + expect(t(without, 'authorize-replace').exists()).toBe(false) + + const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + const w = await mountPage(base({ previous_login: prev })) + const box = t(w, 'authorize-replace') + expect(box.exists()).toBe(true) + expect((box.element as HTMLInputElement).checked).toBe(true) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?code=c&state=s' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', expect.objectContaining({ + client: { id: 'cursor' }, binding_revision: 'rev1', replace_grant: 'g1', + })) + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?code=c&state=s') + + // A fresh page with the box unchecked sends no replace_grant. + const w2 = await mountPage(base({ previous_login: prev })) + await t(w2, 'authorize-replace').setValue(false) + await flushPromises() + A.approveOAuthAuthorization.mockClear() + await t(w2, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBeUndefined() + }) + + it('fetches the guard verdict through preview, shows the refusal with its fixes and keeps Approve disabled', async () => { + const detail = base() + A.getOAuthAuthorization.mockResolvedValue(detail) + A.previewOAuthAuthorization.mockResolvedValue({ + complete: true, + access: { client: 'cursor', profile: 'dev-readonly', mode: 'locked', same_access_as_existing_client: true }, + guard: { code: 'binding_bypassable_without_auth', bindings: [{ client_id: 'cursor', token_name: 'client-cursor', profile: 'dev-readonly', mode: 'locked' }], fixes: [{ kind: 'require_mcp_auth' }] }, + }) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }, { path: '/settings', component: { template: '
' } }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + expect(A.previewOAuthAuthorization).toHaveBeenCalled() + expect(w.find('[data-test="guard-refusal"]').exists()).toBe(true) + expect(w.find('[data-test="guard-fix-require_mcp_auth"]').exists()).toBe(true) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) + + it('shows the refusal when approve itself answers binding_bypassable_without_auth', async () => { + const w = await mountPage(base()) + A.approveOAuthAuthorization.mockRejectedValue(new ApiError(409, { + code: 'binding_bypassable_without_auth', error: 'would leave a client reachable without authentication', + bindings: [], fixes: [{ kind: 'require_mcp_auth' }], + }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(w.find('[data-test="guard-refusal"]').exists()).toBe(true) + expect(navigateTo).not.toHaveBeenCalled() + }) + + it('handles already_decided, binding_changed and 404', async () => { + const w = await mountPage(base()) + A.approveOAuthAuthorization.mockRejectedValueOnce(new ApiError(409, { code: 'already_decided', error: 'decided' }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-decided').exists()).toBe(true) + expect(t(w, 'authorize-approve').exists()).toBe(false) + + const w2 = await mountPage(base()) + const calls = A.getOAuthAuthorization.mock.calls.length + A.approveOAuthAuthorization.mockRejectedValueOnce(new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x')) + await t(w2, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.getOAuthAuthorization.mock.calls.length).toBe(calls + 1) + expect(t(w2, 'authorize-changed').exists()).toBe(true) + expect(navigateTo).not.toHaveBeenCalled() + + A.getOAuthAuthorization.mockRejectedValueOnce(new ApiError(404, { error: 'not found' }, 'x')) + const w3 = await mountPage(base()) + expect(t(w3, 'authorize-gone').exists()).toBe(true) + expect(t(w3, 'authorize-approve').exists()).toBe(false) + }) + + it('deny navigates to the returned redirect', async () => { + const w = await mountPage(base()) + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(A.denyOAuthAuthorization).toHaveBeenCalledWith('r1') + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?error=access_denied') + }) +}) + +describe('AuthorizeRequest: generic address', () => { + beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + }) + + it('selects "New client" with the id and name filled from the reported name when nothing is suggested', async () => { + const w = await mountPage(generic()) + expect((t(w, 'authorize-client-select').element as HTMLSelectElement).value).toBe('__new__') + expect((t(w, 'authorize-new-id').element as HTMLInputElement).value).toBe('acme-agent') + expect((t(w, 'authorize-new-name').element as HTMLInputElement).value).toBe('Acme Agent') + expect(t(w, 'authorize-suggestion-note').exists()).toBe(false) + // Profiles exist and the client is new: nothing pre-selected, Approve disabled. + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) + + it('opens with the suggested client selected and says why', async () => { + const w = await mountPage(generic({ reported_name: 'Cursor', suggested_client: { id: 'cursor', matched: 'display_name' } })) + expect((t(w, 'authorize-client-select').element as HTMLSelectElement).value).toBe('cursor') + expect(t(w, 'authorize-suggestion-note').text()).toBe('Suggested because the app calls itself "Cursor". MCPProxy cannot verify that.') + expect(t(w, 'authorize-new-id').exists()).toBe(false) + expect(t(w, 'authorize-access').text()).toContain('the same access as Cursor') + expect(A.previewOAuthAuthorization).toHaveBeenLastCalledWith('r1', expect.objectContaining({ client: { id: 'cursor' }, binding_revision: 'rev1' })) + }) + + it('sends the client the user changed to, not the suggestion', async () => { + const w = await mountPage(generic({ reported_name: 'Cursor', suggested_client: { id: 'cursor', matched: 'id' } })) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-suggestion-note').exists()).toBe(false) + expect(A.previewOAuthAuthorization).toHaveBeenLastCalledWith('r1', expect.objectContaining({ client: { id: 'codex' }, binding_revision: 'rc' })) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', expect.objectContaining({ client: { id: 'codex' }, binding_revision: 'rc' })) + }) + + it('creates a new client with the edited id and name', async () => { + const w = await mountPage(generic()) + const id = t(w, 'authorize-new-id') + await id.setValue('my-agent') + await id.trigger('change') + const name = t(w, 'authorize-new-name') + await name.setValue('My Agent') + await name.trigger('change') + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', expect.objectContaining({ + client: { new: { id: 'my-agent', display_name: 'My Agent' } }, profile: 'ops', mode: 'locked', + })) + }) + + it.each([ + ['identity_exists', 'A client with this id already exists'], + ['reserved_identity', 'This id belongs to a supported client'], + ])('shows %s next to the id and does not navigate', async (code, text) => { + const w = await mountPage(generic()) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.approveOAuthAuthorization.mockRejectedValue(new ApiError(422, { code, error: text }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-error').text()).toContain(text) + expect(navigateTo).not.toHaveBeenCalled() + }) + + it('shows a profile-bound existing client without asking for a profile', async () => { + const w = await mountPage(generic()) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-binding').text()).toContain('ops') + expect(t(w, 'authorize-profile-select').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) diff --git a/internal/httpapi/oauth_login_test.go b/internal/httpapi/oauth_login_test.go index 87028a502..718dc5648 100644 --- a/internal/httpapi/oauth_login_test.go +++ b/internal/httpapi/oauth_login_test.go @@ -249,6 +249,53 @@ func TestOAuthLoginREST_GenericAddress(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code, w.Body.String()) } +// T049a: the generic address carries suggested_client when the reported name +// equals exactly one existing client; the server never applies it. +func TestOAuthLoginREST_SuggestedClient(t *testing.T) { + h := newOAuthHarness(t, true) + h.mint("cursor", "ro") + h.mint("codex", "ro") + begin := func(name, client string) string { + reg, rerr, err := h.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: name}) + require.NoError(t, err) + require.Nil(t, rerr) + regID, _ := reg["client_id"].(string) + sum := sha256.Sum256([]byte(strings.Repeat("v", 43))) + id, aerr := h.svc.BeginAuthorization(internalRuntime.AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "st", + CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]), Method: "S256", + Resource: oauthTestOrigin + mcplogin.ResourcePath(client), ResponseType: "code", + }) + require.Nil(t, aerr) + return id + } + + id := begin("Cursor (my-server)", "") + w := h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+id, "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + d := dataOf(t, w) + sc, _ := d["suggested_client"].(map[string]interface{}) + require.NotNil(t, sc, w.Body.String()) + assert.Equal(t, "cursor", sc["id"]) + assert.Equal(t, "id", sc["matched"]) + + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/preview", `{}`, bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + pv := dataOf(t, w) + assert.Equal(t, false, pv["complete"]) + assert.NotContains(t, pv, "access") + assert.Nil(t, pv["guard"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"profile":"ro"}`, bindingAdminKey) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "client_required", decodeBody(t, w)["code"]) + + // No match: absent. Per-client address: absent. + d = dataOf(t, h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+begin("Something Else", ""), "", bindingAdminKey)) + assert.NotContains(t, d, "suggested_client") + d = dataOf(t, h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+begin("codex", "cursor"), "", bindingAdminKey)) + assert.NotContains(t, d, "suggested_client") +} + // T042: client payloads and the per-credential revokes. func TestOAuthLoginREST_ClientCredentialsPayloadAndRevokes(t *testing.T) { h := newOAuthHarness(t, true) diff --git a/internal/mcplogin/format_chars_test.go b/internal/mcplogin/format_chars_test.go new file mode 100644 index 000000000..8b64e0940 --- /dev/null +++ b/internal/mcplogin/format_chars_test.go @@ -0,0 +1,50 @@ +package mcplogin + +import "testing" + +// The format characters are built from code points so the source stays readable. +var ( + rlo = string(rune(0x202e)) // right-to-left override + pdf = string(rune(0x202c)) + lri = string(rune(0x2066)) + pdi = string(rune(0x2069)) + zwsp = string(rune(0x200b)) + zwj = string(rune(0x200d)) + lrm = string(rune(0x200e)) + rlm = string(rune(0x200f)) + wj = string(rune(0x2060)) + bom = string(rune(0xfeff)) +) + +// Unicode format characters (category Cf: bidi overrides and isolates, +// zero-width characters, BOM) are dropped from every name the client reports, +// so a name cannot reorder or hide the text the consent page puts around it. +func TestValidateRegistrationDropsFormatCharacters(t *testing.T) { + cases := []struct{ in, want string }{ + {"cursor (" + rlo + "x)", "cursor (x)"}, + {"cur" + zwsp + "sor", "cursor"}, + {"a" + lri + "b" + pdi + "c", "abc"}, + {bom + "name" + rlm, "name"}, + {"x" + wj + "y" + zwj + lrm + "z", "xyz"}, + {"plain éü ok", "plain éü ok"}, + {"cursor (" + rlo + pdf + "x)", "cursor (x)"}, + } + for _, c := range cases { + reg, rerr := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}, ClientName: c.in, SoftwareID: c.in}) + if rerr != nil { + t.Fatal(rerr) + } + if reg.ClientName != c.want || reg.SoftwareID != c.want { + t.Errorf("%q -> name %q software_id %q, want %q", c.in, reg.ClientName, reg.SoftwareID, c.want) + } + } +} + +func TestStripFormat(t *testing.T) { + if got := StripFormat("a" + rlo + "b" + zwsp + "c"); got != "abc" { + t.Fatalf("%q", got) + } + if got := StripFormat("plain"); got != "plain" { + t.Fatalf("%q", got) + } +} diff --git a/internal/mcplogin/registration.go b/internal/mcplogin/registration.go index 9936c6ac3..a7c11e2b7 100644 --- a/internal/mcplogin/registration.go +++ b/internal/mcplogin/registration.go @@ -1,7 +1,9 @@ package mcplogin import ( + "strings" "time" + "unicode" "unicode/utf8" "github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity" @@ -67,8 +69,22 @@ func truncateUTF8(s string, max int) string { return s } +// StripFormat drops every Unicode format character (category Cf: bidi +// overrides and isolates, zero-width characters, the byte order mark). A name a +// client reports is shown between the consent page's own words; with these +// controls it could reorder or hide them. Kept here, not in the shared +// clientidentity.SanitizeDisplay, so other callers keep their stored names. +func StripFormat(s string) string { + return strings.Map(func(r rune) rune { + if unicode.Is(unicode.Cf, r) { + return -1 + } + return r + }, s) +} + func sanitize(s string, max int) string { - return truncateUTF8(clientidentity.SanitizeDisplay(s), max) + return truncateUTF8(clientidentity.SanitizeDisplay(StripFormat(s)), max) } // ValidateRegistration checks a request and returns the registration with the diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 93e9f10f8..f6b32e99a 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -213,6 +213,15 @@ type SuggestedClient struct { DisplayName string `json:"display_name"` } +// SuggestedExisting is the page's advice for the generic address: the one +// existing client the reported name equals. Matched is the first field that +// matched: "id", "display_name" or "known_name". Advice only: the server never +// applies it (preview and approve take the client from their own body). +type SuggestedExisting struct { + ID string `json:"id"` + Matched string `json:"matched"` +} + // ProfileChoice names a profile the page may offer. type ProfileChoice struct { Name string `json:"name"` @@ -221,6 +230,7 @@ type ProfileChoice struct { // PreviousLogin is a live login of THIS registration. type PreviousLogin struct { GrantID string `json:"grant_id"` + ClientID string `json:"client_id"` // the client that owns the login ApprovedAt time.Time `json:"approved_at"` } @@ -251,10 +261,14 @@ type AuthorizationView struct { Client *AuthorizationClientView `json:"client,omitempty"` ExistingClients []ExistingClientView `json:"existing_clients,omitempty"` SuggestedNewClient *SuggestedClient `json:"suggested_new_client,omitempty"` + SuggestedClient *SuggestedExisting `json:"suggested_client,omitempty"` Profiles []ProfileChoice `json:"profiles"` ProfileRequired bool `json:"profile_required"` PreviousLogin *PreviousLogin `json:"previous_login,omitempty"` - Guard *GuardVerdict `json:"guard"` + // PreviousLogins is the newest live login of THIS registration under each + // client (generic address: the page picks the one for the selected client). + PreviousLogins []PreviousLogin `json:"previous_logins,omitempty"` + Guard *GuardVerdict `json:"guard"` } // PreviewAccess is the access sentence of a proposed choice. @@ -333,16 +347,28 @@ func (s *OAuthLoginService) Describe(ctx context.Context, requestID string) (*Au RedirectURI: req.RedirectURI, Resource: req.Resource, Profiles: profileChoices(cfg), } liveByClient := map[string]int{} + newestByClient := map[string]PreviousLogin{} for i := range grants { g := &grants[i] if !g.Revoked && g.RefreshExpiresAt.After(now) { liveByClient[g.Client]++ + if g.RegistrationID == reg.ClientID && (req.PathClient == "" || g.Client == req.PathClient) { + if cur, ok := newestByClient[g.Client]; !ok || g.ApprovedAt.After(cur.ApprovedAt) { + newestByClient[g.Client] = PreviousLogin{GrantID: g.GrantID, ClientID: g.Client, ApprovedAt: g.ApprovedAt} + } + } if g.RegistrationID == reg.ClientID && (req.PathClient == "" || g.Client == req.PathClient) && (v.PreviousLogin == nil || g.ApprovedAt.After(v.PreviousLogin.ApprovedAt)) { - v.PreviousLogin = &PreviousLogin{GrantID: g.GrantID, ApprovedAt: g.ApprovedAt} + v.PreviousLogin = &PreviousLogin{GrantID: g.GrantID, ClientID: g.Client, ApprovedAt: g.ApprovedAt} } } } + defer func() { + for _, pl := range newestByClient { + v.PreviousLogins = append(v.PreviousLogins, pl) + } + sort.Slice(v.PreviousLogins, func(i, j int) bool { return v.PreviousLogins[i].ClientID < v.PreviousLogins[j].ClientID }) + }() bindingOf := func(id string) (*BindingView, bool) { pin, mode, found, err := s.store.CurrentClientBinding(id) if err != nil || !found { @@ -402,6 +428,7 @@ func (s *OAuthLoginService) Describe(ctx context.Context, requestID string) (*Au } v.ProfileRequired = len(v.Profiles) > 0 v.SuggestedNewClient = s.suggestNewClient(reg.ReportedName, ids) + v.SuggestedClient = suggestExistingClient(reg.ReportedName, v.ExistingClients) } return v, nil } @@ -434,6 +461,88 @@ func (s *OAuthLoginService) displayNameOf(id string, all []auth.AgentToken, bind return id } +// stripTrailingGroup removes one balanced trailing parenthesised group +// ("Claude Code (my (dev) server)" -> "Claude Code") and returns the trimmed +// text before it. ok is false when the text does not end with a balanced group +// or nothing is left before it. +func stripTrailingGroup(s string) (string, bool) { + s = strings.TrimSpace(s) + if !strings.HasSuffix(s, ")") { + return "", false + } + depth := 0 + for i := len(s) - 1; i >= 0; i-- { + switch s[i] { + case ')': + depth++ + case '(': + depth-- + if depth == 0 { + base := strings.TrimSpace(s[:i]) + return base, base != "" + } + } + } + return "", false +} + +// suggestExistingClient compares the sanitised reported name, trimmed and +// without regard to case, with each offered client's id, display name and (for +// a connect-registry client) known client names. The whole name is tried and, +// when it ends with a parenthesised suffix, also the part before it. Matches +// are counted by distinct client id: exactly one client yields a suggestion, +// none or several yield nil. Pure advice, computed on read, never stored. +func suggestExistingClient(reported string, clients []ExistingClientView) *SuggestedExisting { + name := strings.TrimSpace(reported) + if name == "" { + return nil + } + forms := []string{name} + if base, ok := stripTrailingGroup(name); ok { + forms = append(forms, base) + } + eq := func(candidate string) bool { + c := strings.TrimSpace(candidate) + if c == "" { + return false + } + for _, f := range forms { + if strings.EqualFold(f, c) { + return true + } + } + return false + } + var found *SuggestedExisting + for i := range clients { + c := &clients[i] + matched := "" + switch { + case eq(c.ID): + matched = "id" + case eq(c.DisplayName): + matched = "display_name" + default: + if def := connect.FindClient(c.ID); def != nil { + for _, n := range def.ClientInfoNames { + if eq(n) { + matched = "known_name" + break + } + } + } + } + if matched == "" { + continue + } + if found != nil { + return nil // several distinct clients + } + found = &SuggestedExisting{ID: c.ID, Matched: matched} + } + return found +} + // suggestNewClient derives an id from the reported name: lower-case slug of // letters, digits, '-' and '_', at most 56 characters, made unique against the // registry and the existing clients ("-2", "-3", ...). It only SUGGESTS: the @@ -594,7 +703,8 @@ func (s *OAuthLoginService) resolveChoice(req mcplogin.Request, c ApprovalChoice if c.Client.ID != "" { return nil, &ValidationError{Field: "client", Message: "choose an existing client or a new one, not both"} } - n := c.Client.New + n := *c.Client.New + n.DisplayName = mcplogin.StripFormat(n.DisplayName) if !auth.ValidClientID(n.ID) { return nil, &ValidationError{Field: "client_new_id", Message: fmt.Sprintf( "invalid client id %q: must be lower-case letters, digits, '-' or '_', start with a letter or digit, and be at most 56 characters", n.ID)} @@ -664,10 +774,15 @@ func (s *OAuthLoginService) resolveChoice(req mcplogin.Request, c ApprovalChoice } // 3. Replace the previous login: only a live login of THIS registration - // and of this client; anything else is ignored, never revoked. + // and of this client; anything else is ignored, never revoked. A live login + // of this registration that belongs to ANOTHER client is refused: the page + // asked to replace a login of a client it is not signing in. if c.ReplaceGrant != "" { - if g, err := s.store.GetOAuthGrant(c.ReplaceGrant); err == nil && g != nil && g.Client == rc.clientID && + if g, err := s.store.GetOAuthGrant(c.ReplaceGrant); err == nil && g != nil && !g.Revoked && g.RefreshExpiresAt.After(s.now()) && g.RegistrationID == req.RegistrationID { + if g.Client != rc.clientID { + return nil, &ValidationError{Field: "replace_grant", Message: "that login belongs to another client"} + } rc.replace = g.GrantID } } diff --git a/internal/runtime/oauth_login_observed_name_test.go b/internal/runtime/oauth_login_observed_name_test.go new file mode 100644 index 000000000..4bfe02297 --- /dev/null +++ b/internal/runtime/oauth_login_observed_name_test.go @@ -0,0 +1,47 @@ +package runtime + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" +) + +// The name sent at initialize goes through the same normalisation as the name +// sent at registration: an app that registers and initializes as the same +// Cf-containing name is not flagged, and no Cf character is stored or listed. +func TestOAuthTouch_ObservedNameLosesFormatCharacters(t *testing.T) { + zwsp := string(rune(0x200b)) + rlo := string(rune(0x202e)) + name := "Ac" + zwsp + "me" + + fx := newOAuthFx(t) + fx.mintClient("acme", "ro", auth.ProfileModeLocked) + resp, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: name}) + require.NoError(t, err) + require.Nil(t, rerr) + reg := resp["client_id"].(string) + id := fx.authorize(reg, "acme") + rev, _ := fx.sm.ClientBindingRevision("acme") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + grant := fx.grants()[0] + + fx.svc.Touch(grant.GrantID, name) + require.Eventually(t, func() bool { return fx.grants()[0].ObservedClientName != "" }, 2*time.Second, 10*time.Millisecond) + observed := fx.grants()[0].ObservedClientName + assert.Equal(t, "acme", observed, "no format character is stored") + assert.False(t, OAuthNameMismatch(observed, "acme", "acme"), "the same identity is not flagged") + + // Already-stored or direct input is normalised too, and a bidi override + // cannot make an unchanged name look different. + assert.False(t, OAuthNameMismatch(name, "acme", "acme")) + assert.False(t, OAuthNameMismatch("ac"+rlo+"me", "acme", "acme")) + assert.True(t, OAuthNameMismatch("other"+zwsp, "acme", "acme")) +} diff --git a/internal/runtime/oauth_login_replace_owner_test.go b/internal/runtime/oauth_login_replace_owner_test.go new file mode 100644 index 000000000..a7155781f --- /dev/null +++ b/internal/runtime/oauth_login_replace_owner_test.go @@ -0,0 +1,44 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// A login of this registration that belongs to ANOTHER client is never +// replaced by approving a different client: the choice is refused and the +// request stays pending. +func TestOAuthApprove_ReplaceGrantOfAnotherClientIsRefused(t *testing.T) { + fx := newOAuthFx(t) + reg, _ := fx.loginNew("cursor", "ro") + cursorGrant := fx.grants()[0] + fx.mintClient("codex", "rw", auth.ProfileModeSwitchable) + + id := fx.authorize(reg, "") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.PreviousLogin) + assert.Equal(t, "cursor", v.PreviousLogin.ClientID, "the view says which client owns the previous login") + + rev, _ := fx.sm.ClientBindingRevision("codex") + body := ApprovalChoice{Client: ClientChoice{ID: "codex"}, BindingRevision: rev, ReplaceGrant: cursorGrant.GrantID} + _, err = fx.svc.Approve(fx.ctx(), id, body) + var ve *ValidationError + require.ErrorAs(t, err, &ve) + assert.Equal(t, "replace_grant", ve.Field) + _, err = fx.svc.Preview(fx.ctx(), id, body) + assert.ErrorAs(t, err, &ve) + assert.Len(t, fx.svc.ListPending(), 1, "refused, still pending") + for _, g := range fx.grants() { + assert.False(t, g.Revoked) + } + + // The owner may replace it. + cursorRev, _ := fx.sm.ClientBindingRevision("cursor") + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: "cursor"}, BindingRevision: cursorRev, ReplaceGrant: cursorGrant.GrantID}) + assert.NoError(t, err) +} diff --git a/internal/runtime/oauth_login_round_sec_test.go b/internal/runtime/oauth_login_round_sec_test.go new file mode 100644 index 000000000..7f4196e57 --- /dev/null +++ b/internal/runtime/oauth_login_round_sec_test.go @@ -0,0 +1,93 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" +) + +func TestOAuthDescribe_FormatCharactersNeverReachThePage(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("cursor", "ro", auth.ProfileModeLocked) + + // Bidi override inside the suffix: the control is gone; the suffix strip still + // yields "cursor", so the real cursor is suggested (advice only, and the page + // shows the stripped name between its own quotes). + v := fx.suggestFor("cursor ("+string(rune(0x202e))+"x)", "") + assert.NotContains(t, v.ReportedName, string(rune(0x202e))) + assert.Equal(t, "cursor (x)", v.ReportedName) + require.NotNil(t, v.SuggestedClient) + assert.Equal(t, "cursor", v.SuggestedClient.ID) + assert.NotContains(t, v.SuggestedNewClient.DisplayName, string(rune(0x202e))) + + // A zero-width character inside the name is removed at registration, so the + // name IS "cursor": it suggests cursor (the suggestion is only advice), and a + // new client with that id is still refused as reserved_identity. + v = fx.suggestFor("cur"+string(rune(0x200b))+"sor", "") + assert.Equal(t, "cursor", v.ReportedName) + require.NotNil(t, v.SuggestedClient) + assert.Equal(t, "cursor", v.SuggestedClient.ID) + assert.NotContains(t, v.SuggestedNewClient.ID, string(rune(0x200b))) + _, err := fx.svc.Approve(fx.ctx(), v.ID, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "cursor"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthReservedIdentity) +} + +func TestOAuthApprove_NewClientDisplayNameLosesFormatCharacters(t *testing.T) { + fx := newOAuthFx(t) + v := fx.suggestFor("Acme", "") + req, _, err := fx.svc.pendingRequest(v.ID) + require.NoError(t, err) + rc, err := fx.svc.resolveChoice(req, ApprovalChoice{ + Client: ClientChoice{New: &NewClientChoice{ID: "acme-x", DisplayName: "Ac" + string(rune(0x202e)) + "me" + string(rune(0x200b)) + " " + string(rune(0x2066)) + "Agent" + string(rune(0x2069))}}, + Profile: oauthStrp("ro"), + }) + require.NoError(t, err) + assert.Equal(t, "Acme Agent", rc.display) +} + +// With logins of one registration under two clients, every client's own newest +// live login is offered, not only the newest overall. +func TestOAuthDescribe_PreviousLoginsPerClient(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("cursor", "ro", auth.ProfileModeLocked) + fx.mintClient("codex", "rw", auth.ProfileModeSwitchable) + reg := fx.register() + login := func(client string) { + t.Helper() + fx.clock.Advance(1_000_000_000) + id := fx.authorize(reg, client) + rev, _ := fx.sm.ClientBindingRevision(client) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + } + login("cursor") // older + login("codex") // newer + + id := fx.authorize(reg, "") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.PreviousLogin) + assert.Equal(t, "codex", v.PreviousLogin.ClientID, "previous_login stays the newest overall") + byClient := map[string]string{} + for _, p := range v.PreviousLogins { + byClient[p.ClientID] = p.GrantID + } + assert.Len(t, byClient, 2) + assert.NotEmpty(t, byClient["cursor"]) + assert.NotEmpty(t, byClient["codex"]) + assert.NotEqual(t, byClient["cursor"], byClient["codex"]) + + // A per-client address lists only that client's login. + id = fx.authorize(reg, "cursor") + v, err = fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.Len(t, v.PreviousLogins, 1) + assert.Equal(t, "cursor", v.PreviousLogins[0].ClientID) + _ = mcplogin.ResourcePath +} diff --git a/internal/runtime/oauth_login_suggest_round1_test.go b/internal/runtime/oauth_login_suggest_round1_test.go new file mode 100644 index 000000000..135731c61 --- /dev/null +++ b/internal/runtime/oauth_login_suggest_round1_test.go @@ -0,0 +1,86 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func (fx *oauthFx) addCustom(id, display string) { + fx.t.Helper() + _, _, err := fx.clients.Add(fx.ctx(), fx.actor(), AddRequest{ID: id, DisplayName: display, Profile: "ro"}) + require.NoError(fx.t, err) +} + +func TestOAuthDescribe_SuggestedClient_DisplayName(t *testing.T) { + fx := newOAuthFx(t) + fx.addCustom("acme", "Acme Agent") + for _, name := range []string{"Acme Agent", " acme agent "} { + s := fx.suggestFor(name, "").SuggestedClient + require.NotNil(t, s, name) + assert.Equal(t, "acme", s.ID) + assert.Equal(t, "display_name", s.Matched) + } +} + +func TestOAuthDescribe_SuggestedClient_DisplayNameBeatsKnownName(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("claude-desktop", "ro", auth.ProfileModeLocked) + // Registry display name "Claude Desktop"; "Claude" and "claude-ai" are known names. + s := fx.suggestFor("Claude Desktop", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "display_name", s.Matched) + s = fx.suggestFor("Claude", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "known_name", s.Matched) +} + +func TestOAuthDescribe_SuggestedClient_UnicodeFolding(t *testing.T) { + fx := newOAuthFx(t) + fx.addCustom("sig-a", "Σ") + s := fx.suggestFor("σ", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "sig-a", s.ID) + fx.addCustom("sig-b", "ς") + assert.Nil(t, fx.suggestFor("σ", "").SuggestedClient, "Σ and ς fold to the same letter as σ: two clients") +} + +func TestOAuthDescribe_SuggestedClient_Suffix(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + s := fx.suggestFor("Codex (my (dev) server)", "").SuggestedClient + require.NotNil(t, s, "one balanced trailing group is stripped, nested parentheses included") + assert.Equal(t, "codex", s.ID) + + fx.addCustom("acme", "Acme (prod)") + s = fx.suggestFor("Acme (prod)", "").SuggestedClient + require.NotNil(t, s, "whole-name match") + assert.Equal(t, "acme", s.ID) + + // Whole name matches one client, the stripped name another: no suggestion. + fx.addCustom("other", "Codex (x)") + assert.Nil(t, fx.suggestFor("Codex (x)", "").SuggestedClient) +} + +func TestSuggestExistingClient_StripTrailingGroup(t *testing.T) { + cases := map[string]struct { + in, base string + ok bool + }{ + "plain": {"a (b)", "a", true}, + "nested": {"a (b (c) d)", "a", true}, + "unbalanced": {"a (b", "", false}, + "only group": {"(b)", "", false}, + "no group": {"abc", "", false}, + "not trailing": {"a (b) c", "", false}, + "close first": {"a )b(", "", false}, + } + for name, c := range cases { + base, ok := stripTrailingGroup(c.in) + assert.Equal(t, c.ok, ok, name) + assert.Equal(t, c.base, base, name) + } +} diff --git a/internal/runtime/oauth_login_suggest_test.go b/internal/runtime/oauth_login_suggest_test.go new file mode 100644 index 000000000..4dbc6273d --- /dev/null +++ b/internal/runtime/oauth_login_suggest_test.go @@ -0,0 +1,96 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" +) + +// suggestFor registers a client reporting `name`, starts an authorization on the +// given address ("" = generic) and returns the described view. +func (fx *oauthFx) suggestFor(name, client string) *AuthorizationView { + fx.t.Helper() + resp, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: name}) + require.NoError(fx.t, err) + require.Nil(fx.t, rerr) + id := fx.authorize(resp["client_id"].(string), client) + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(fx.t, err) + return v +} + +func TestOAuthDescribe_SuggestedClient(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("cursor", "ro", auth.ProfileModeLocked) + fx.mintClient("codex", "rw", auth.ProfileModeSwitchable) + + t.Run("no match", func(t *testing.T) { + assert.Nil(t, fx.suggestFor("Totally Different", "").SuggestedClient) + }) + t.Run("id match, case and whitespace", func(t *testing.T) { + s := fx.suggestFor(" CODEX ", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "codex", s.ID) + assert.Equal(t, "id", s.Matched) + }) + t.Run("one client on several fields is one match, id wins", func(t *testing.T) { + // "cursor" is the id, the registry display name "Cursor" and a known name. + s := fx.suggestFor("cursor", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "cursor", s.ID) + assert.Equal(t, "id", s.Matched) + }) + t.Run("display name of a registry client", func(t *testing.T) { + // "Cursor" registry display name differs from the id only by case; use the + // alias path below for a distinct spelling. + s := fx.suggestFor("Cursor", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "cursor", s.ID) + }) + t.Run("registry alias", func(t *testing.T) { + s := fx.suggestFor("Cursor-VSCode", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "cursor", s.ID) + assert.Equal(t, "known_name", s.Matched) + }) + t.Run("parenthesised suffix", func(t *testing.T) { + s := fx.suggestFor("Codex (my-server)", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "codex", s.ID) + assert.Equal(t, "id", s.Matched) + }) + t.Run("name equal to one client's id and another's display name is ambiguous", func(t *testing.T) { + fx.mintClient("zed", "ro", auth.ProfileModeLocked) + _, _, err := fx.clients.Add(fx.ctx(), fx.actor(), AddRequest{ID: "acme", DisplayName: "Zed", Profile: "ro"}) + require.NoError(t, err) + assert.Nil(t, fx.suggestFor("zed", "").SuggestedClient) + // Either one alone is fine. + s := fx.suggestFor("Acme (x)", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "acme", s.ID) + }) + t.Run("never on a per-client address", func(t *testing.T) { + v := fx.suggestFor("codex", "cursor") + assert.Equal(t, "client", v.AddressKind) + assert.Nil(t, v.SuggestedClient) + }) + t.Run("the server never applies the suggestion", func(t *testing.T) { + v := fx.suggestFor("codex", "") + require.NotNil(t, v.SuggestedClient) + pv, err := fx.svc.Preview(fx.ctx(), v.ID, ApprovalChoice{}) + require.NoError(t, err) + assert.False(t, pv.Complete) + assert.Nil(t, pv.Access) + assert.Nil(t, pv.Guard) + _, err = fx.svc.Approve(fx.ctx(), v.ID, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientRequired) + code, status, ok := OAuthErrorStatus(ErrOAuthClientRequired) + assert.True(t, ok) + assert.Equal(t, "client_required", code) + assert.Equal(t, 422, status) + }) +} diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go index bbd5f5747..0260da6b3 100644 --- a/internal/runtime/oauth_login_tokens.go +++ b/internal/runtime/oauth_login_tokens.go @@ -185,7 +185,7 @@ func (s *OAuthLoginService) Touch(grantID, observedName string) { if grantID == "" { return } - observed := clientidentity.SanitizeDisplay(observedName) + observed := clientidentity.SanitizeDisplay(mcplogin.StripFormat(observedName)) now := s.now() s.touchMu.Lock() last, seen := s.lastTouch[grantID] @@ -358,6 +358,7 @@ func (s *OAuthLoginService) recheckGuard(cfg *config.Config, d mcplogin.Decision // observed name never mismatches. It takes no part in selection or // authorization. func OAuthNameMismatch(observed, reportedName, clientID string) bool { + observed = mcplogin.StripFormat(observed) // same normalisation as the registered name norm := clientidentity.NormalizeRaw(observed) if norm == "" { return false diff --git a/internal/server/oauth_login_http_test.go b/internal/server/oauth_login_http_test.go index dfbf04718..ae7214d07 100644 --- a/internal/server/oauth_login_http_test.go +++ b/internal/server/oauth_login_http_test.go @@ -4,6 +4,7 @@ package server import ( "net/http" + "net/http/httptest" "net/url" "strings" "testing" @@ -58,6 +59,33 @@ func TestOAuthLoginHTTP_MetadataAndChallenge(t *testing.T) { } } +// T053: the consent page is never framed. The headers are set before the SPA +// handler runs, on the page and anything under it, and on no other UI path. +func TestOAuthLoginHTTP_AuthorizePageIsNeverFramed(t *testing.T) { + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("spa")) }) + h := (&Server{}).createSelectiveWebUIProtectedHandler(inner) + for _, path := range []string{ + "/ui/authorize", "/ui/authorize?request=abc", "/ui/authorize/", "/ui/authorize/x", + "/ui/Authorize?request=abc", "/ui/AUTHORIZE/", "/ui/Authorize/X", "/ui//authorize", "/ui/./authorize", "/ui/x/../authorize", + } { + rec := httptestGet(h, path) + assert.Equal(t, "frame-ancestors 'none'", rec.Header().Get("Content-Security-Policy"), path) + assert.Equal(t, "DENY", rec.Header().Get("X-Frame-Options"), path) + assert.Equal(t, "spa", rec.Body.String(), path) + } + for _, path := range []string{"/ui/", "/ui/clients", "/ui/authorized"} { + rec := httptestGet(h, path) + assert.Empty(t, rec.Header().Get("Content-Security-Policy"), path) + assert.Empty(t, rec.Header().Get("X-Frame-Options"), path) + } +} + +func httptestGet(h http.Handler, target string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, nil)) + return rec +} + // T034: register. func TestOAuthLoginHTTP_Register(t *testing.T) { f := newOAuthFlow(t, nil) diff --git a/internal/server/server.go b/internal/server/server.go index 73b629481..7e0be4f49 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -10,6 +10,7 @@ import ( "net/http" httppprof "net/http/pprof" "os" + "path" "path/filepath" gruntime "runtime" "strings" @@ -809,9 +810,18 @@ func credentialKindContext(ac *auth.AuthContext, kind auth.CredentialKind) *auth // that should be served without authentication to allow the SPA to work properly. // API endpoints are protected separately by the httpAPIServer middleware. func (s *Server) createSelectiveWebUIProtectedHandler(handler http.Handler) http.Handler { - // Simply pass through all requests without authentication - // The handler is only mounted on /ui/* so it won't receive API requests - return handler + // No authentication here; the handler is only mounted on /ui/* so it won't + // receive API requests. The one addition: the sign-in consent page (Spec 132) + // is never framed, so a hostile page cannot overlay its Approve button. + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Vue Router matches case-insensitively and the SPA answers unknown + // paths, so compare the cleaned path without regard to case. + if p := strings.ToLower(path.Clean("/" + r.URL.Path)); p == "/ui/authorize" || strings.HasPrefix(p, "/ui/authorize/") { + w.Header().Set("Content-Security-Policy", "frame-ancestors 'none'") + w.Header().Set("X-Frame-Options", "DENY") + } + handler.ServeHTTP(w, r) + }) } // GetStatus returns the current server status diff --git a/scripts/run-web-smoke.sh b/scripts/run-web-smoke.sh index deebcf98d..03dd0ff18 100755 --- a/scripts/run-web-smoke.sh +++ b/scripts/run-web-smoke.sh @@ -239,7 +239,10 @@ JSON # developer with their own key exported would otherwise leave the server # demanding that key while the sweep probes with this one — a 46s readiness # timeout with nothing but 401s in the log. -HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_API_KEY="$API_KEY" "$BINARY_PATH" serve \ +# MCPPROXY_MCP_OAUTH_ENABLED: browser login (Spec 132) is off by default; the +# sweep turns it on so client-oauth-consent.spec.ts drives the consent page +# instead of skipping. +HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_API_KEY="$API_KEY" MCPPROXY_MCP_OAUTH_ENABLED=true "$BINARY_PATH" serve \ --config "$CONFIG_PATH" --listen "$LISTEN" >"$LOG_PATH" 2>&1 & SERVER_PID=$! @@ -344,7 +347,7 @@ set +e MCPPROXY_API_KEY="$API_KEY" \ SWEEP_SERVER_NAME="$SWEEP_SERVER_NAME" \ SWEEP_REPORT_DIR="$REPORT_DIR" \ - "$PLAYWRIGHT_BIN" test web-ui-sweep.spec.ts visual-a11y-sweep.spec.ts navigation-consistency.spec.ts profiles-clients.spec.ts profiles-scope.spec.ts profiles-unhide.spec.ts demo-ux-fixes.spec.ts usertest-web-fixes.spec.ts + "$PLAYWRIGHT_BIN" test client-oauth-consent.spec.ts web-ui-sweep.spec.ts visual-a11y-sweep.spec.ts navigation-consistency.spec.ts profiles-clients.spec.ts profiles-scope.spec.ts profiles-unhide.spec.ts demo-ux-fixes.spec.ts usertest-web-fixes.spec.ts ) PLAYWRIGHT_STATUS=$? set -e