diff --git a/.env.example b/.env.example index 30733a4..e0edfce 100644 --- a/.env.example +++ b/.env.example @@ -6,3 +6,7 @@ GITOPS_API_URL=https://cloud.getgitops.com GITOPS_API_TIMEOUT_MS=10000 # debug | info | warn | error | silent LOG_LEVEL=info +# URL pública del endpoint MCP (opcional); activa la discovery OAuth (Claude.ai). Sin barra final +# MCP_PUBLIC_URL=https://mcp.cloud.getgitops.com/mcp +# Issuer OAuth de GitOps (opcional); por defecto GITOPS_API_URL +# GITOPS_AUTH_SERVER_URL=https://cloud.getgitops.com diff --git a/CLAUDE.md b/CLAUDE.md index 2b44617..980e330 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ Servidor MCP stateless de GitOps (ADR 0005 en el repo `gitops`). Es un cliente d ## Estructura - `src/config.ts`: variables de entorno. `src/log.ts`: logs JSON con campos cerrados (`LogFields`). -- `src/http.ts`: servidor HTTP (`/mcp`, `/healthz`, auth Bearer, un server+transport por petición). `src/server.ts`: crea el `McpServer`. +- `src/http.ts`: servidor HTTP (`/mcp`, `/healthz`, metadata OAuth, un server+transport por petición). `src/auth.ts`: `TokenValidator` (valida contra `/api/whoami` con caché), `WWW-Authenticate`, metadata RFC 9728 y CORS. `src/server.ts`: crea el `McpServer`. - `src/api/client.ts`: `GitOpsApiClient` (`get`, `post`, `fetchAll`), `GitOpsApiError`. `src/api/types.ts`: tipos de las respuestas de la API. - `src/resolve.ts`: `resolveProject`, `resolveService`, `resolveOrganization` (slug o id, caché por petición). - `src/tools/{code-report,cves,monitoring}.ts`: un `registerXTools(server, ctx)` por área. `src/tools/context.ts`: `ToolContext` y `runTool`. `src/tools/result.ts`: `toolResult`, `toolError`. diff --git a/README.md b/README.md index aa19690..149a0f9 100644 --- a/README.md +++ b/README.md @@ -8,10 +8,13 @@ Diseño completo: ADR 0005 (`docs/adr/0005-mcp-server.md` en el repo `gitops`). ``` Claude Code ──MCP (HTTP + Bearer gvs_…)──▶ gitops-mcp ──REST + mismo Bearer──▶ GitOps API ──▶ GitDB - (sin estado) (permisos, auditoría, - vault bloqueado) +Claude.ai ──MCP (HTTP + Bearer OAuth)──▶ (sin estado) (permisos, auditoría, + │ vault bloqueado, + └──── OAuth 2.1 (login + consentimiento) ──────────────────────────────▶ Authorization Server) ``` +- **OAuth (Claude.ai):** gitops-mcp es solo el _Resource Server_. GitOps es el _Authorization Server_ y emite como access token una clave `gvs_…` normal (audience mcp, caduca en 1 h, con refresh). gitops-mcp publica la metadata de recurso protegido (RFC 9728) para que el cliente descubra dónde autenticarse. + - **Sin acceso a GitDB, sin credenciales propias, sin estado.** Cada tool son una o varias llamadas REST a `/api/...` reenviando la cabecera `Authorization` del usuario tal cual. Permisos, auditoría y rate limit viven en la API: el MCP no puede hacer nada que el usuario no pueda hacer en la UI. - **Transporte:** Streamable HTTP en modo stateless (un server + transport nuevo por petición, sin `Mcp-Session-Id`). Cualquier réplica atiende cualquier petición. - **Sin vault:** no hay ninguna tool de secretos ni una tool genérica "llama a cualquier endpoint". @@ -19,18 +22,22 @@ Claude Code ──MCP (HTTP + Bearer gvs_…)──▶ gitops-mcp ──REST + m ## Variables de entorno -| Variable | Por defecto | Descripción | -| ----------------------- | ------------- | ------------------------------------------- | -| `GITOPS_API_URL` | (obligatoria) | URL base de la API de GitOps | -| `PORT` | `3000` | Puerto HTTP | -| `GITOPS_API_TIMEOUT_MS` | `10000` | Timeout de cada petición a la API | -| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` o `silent` | +| Variable | Por defecto | Descripción | +| ------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| `GITOPS_API_URL` | (obligatoria) | URL base de la API de GitOps | +| `PORT` | `3000` | Puerto HTTP | +| `GITOPS_API_TIMEOUT_MS` | `10000` | Timeout de cada petición a la API | +| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` o `silent` | +| `MCP_PUBLIC_URL` | (vacía) | URL pública del endpoint MCP, p. ej. `https://mcp.cloud.getgitops.com/mcp`, sin barra final. Activa la discovery OAuth; sin ella, desactivada | +| `GITOPS_AUTH_SERVER_URL` | `GITOPS_API_URL` | Issuer OAuth de GitOps (Authorization Server) que se anuncia en la metadata | Ver `.env.example`. ## Endpoints -- `POST /mcp`: protocolo MCP. Requiere `Authorization: Bearer gvs_…` (si no, 401 con `WWW-Authenticate: Bearer realm="gitops-mcp"`). +- `POST /mcp`: protocolo MCP. Requiere `Authorization: Bearer gvs_…` (clave MCP manual o access token OAuth). Antes de atender la petición se valida el token con `GET /api/whoami` de GitOps (caché en memoria de 60 s, solo aciertos, clave = sha256 de la cabecera). Si falta o no es válido: HTTP 401 con `WWW-Authenticate: Bearer realm="gitops-mcp", resource_metadata="/.well-known/oauth-protected-resource/mcp"` (sin `MCP_PUBLIC_URL`, solo `Bearer realm="gitops-mcp"`). Si GitOps limita (429) se devuelve 429 con `Retry-After`; si no responde (red/5xx), 503 sin invalidar el token del cliente. +- `OPTIONS /mcp`: preflight CORS (204). `/mcp` responde con `Access-Control-Allow-Origin: *` y expone `WWW-Authenticate` (clientes de navegador como MCP Inspector). +- `GET /.well-known/oauth-protected-resource` y `/.well-known/oauth-protected-resource/mcp`: metadata RFC 9728 (`resource`, `authorization_servers`, `bearer_methods_supported`, `scopes_supported`, `resource_name`) con CORS. Solo con `MCP_PUBLIC_URL`; si no, 404. - `GET /mcp` y `DELETE /mcp`: 405 (modo stateless). - `GET /healthz`: `200 {"ok":true}`. @@ -83,6 +90,18 @@ docker run --rm -p 3000:3000 -e GITOPS_API_URL=https://cloud.getgitops.com gitop 4. Pregunta, por ejemplo: "¿qué proyectos tengo en GitOps?". +## Uso desde Claude.ai (conector OAuth) + +Claude.ai exige OAuth 2.1 para los conectores personalizados (el servidor debe tener `MCP_PUBLIC_URL` configurada): + +1. **Ajustes → Conectores → Añadir conector personalizado**. +2. URL: `https://mcp.cloud.getgitops.com/mcp`. +3. Inicia sesión en GitOps y acepta el consentimiento. + +La conexión aparece en **/profile** como clave MCP "OAuth" y se revoca desde allí. El access token caduca en 1 h y Claude.ai lo refresca solo. + +Claude Code sigue pudiendo usar la clave manual con cabecera `Authorization: Bearer gvs_…` (ver arriba): OAuth se añade, no sustituye. + Las tools aceptan referencias legibles: `org/proyecto`, `proyecto` (si es único) o `org/proyecto/servicio`, además de ids. ## Tools diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..2cf930a --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,122 @@ +import { createHash } from 'node:crypto'; +import type { ServerResponse } from 'node:http'; +import { GitOpsApiClient, GitOpsApiError } from './api/client.js'; +import type { Config } from './config.js'; + +const WHOAMI_PATH = '/api/whoami'; +const CACHE_TTL_MS = 60_000; +const CACHE_MAX_ENTRIES = 1000; + +export const CORS_HEADERS = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Mcp-Protocol-Version', + 'Access-Control-Expose-Headers': 'WWW-Authenticate', + 'Access-Control-Max-Age': '86400', +} as const; + +export const METADATA_CORS_HEADERS = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Mcp-Protocol-Version', + 'Access-Control-Max-Age': '86400', +} as const; + +const WELL_KNOWN = '/.well-known/oauth-protected-resource'; + +/** Path suffix of the public MCP URL ("/mcp"), empty when it has no path. */ +function resourcePathSuffix(mcpPublicUrl: string): string { + const pathname = new URL(mcpPublicUrl).pathname.replace(/\/+$/, ''); + return pathname === '/' ? '' : pathname; +} + +/** Paths that serve the Protected Resource Metadata (RFC 9728), empty if OAuth is disabled. */ +export function metadataPaths(config: Config): string[] { + if (!config.mcpPublicUrl) return []; + const suffix = resourcePathSuffix(config.mcpPublicUrl); + return suffix ? [WELL_KNOWN, WELL_KNOWN + suffix] : [WELL_KNOWN]; +} + +export function protectedResourceMetadata(config: Config): Record { + return { + resource: config.mcpPublicUrl, + authorization_servers: [config.authServerUrl], + bearer_methods_supported: ['header'], + scopes_supported: ['mcp'], + resource_name: 'GitOps', + }; +} + +/** `WWW-Authenticate` challenge, with the metadata pointer when OAuth discovery is enabled. */ +export function wwwAuthenticate(config: Config): string { + const base = 'Bearer realm="gitops-mcp"'; + if (!config.mcpPublicUrl) return base; + const origin = new URL(config.mcpPublicUrl).origin; + const suffix = resourcePathSuffix(config.mcpPublicUrl); + return `${base}, resource_metadata="${origin}${WELL_KNOWN}${suffix}"`; +} + +export type TokenCheck = + { ok: true } | { ok: false; status: 401 | 429 | 503; message: string; retryAfter?: number }; + +/** + * Validates the caller's token against `GET /api/whoami`, so an expired or revoked token fails + * with HTTP 401 (and OAuth clients know they must refresh). Only successes are cached, keyed by + * the sha256 of the Authorization value: neither the token nor its hash is ever logged. + */ +export class TokenValidator { + private readonly cache = new Map(); + + constructor( + private readonly now: () => number = Date.now, + private readonly ttlMs = CACHE_TTL_MS, + private readonly maxEntries = CACHE_MAX_ENTRIES, + ) {} + + async validate(authorization: string, client: GitOpsApiClient): Promise { + const key = createHash('sha256').update(authorization).digest('hex'); + const expires = this.cache.get(key); + if (expires !== undefined) { + if (expires > this.now()) return { ok: true }; + this.cache.delete(key); + } + try { + await client.get(WHOAMI_PATH); + } catch (err) { + if (err instanceof GitOpsApiError) { + if (err.status === 401 || err.status === 403) { + return { + ok: false, + status: 401, + message: 'Unauthorized: invalid, expired or revoked token (GitOps MCP key or OAuth).', + }; + } + if (err.status === 429) { + return { + ok: false, + status: 429, + message: 'Too many requests to the GitOps API. Retry shortly.', + ...(err.retryAfter !== undefined ? { retryAfter: err.retryAfter } : {}), + }; + } + } + return { + ok: false, + status: 503, + message: 'GitOps API is temporarily unavailable. Try again in a moment.', + }; + } + if (this.cache.size >= this.maxEntries) { + const oldest = this.cache.keys().next().value; + if (oldest !== undefined) this.cache.delete(oldest); + } + this.cache.set(key, this.now() + this.ttlMs); + return { ok: true }; + } +} + +export function sendNoContent(res: ServerResponse, headers: Record): void { + if (res.headersSent) return; + res.writeHead(204, headers); + res.end(); +} diff --git a/src/config.ts b/src/config.ts index ff2e231..07abfea 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,6 +4,10 @@ export interface Config { port: number; apiUrl: string; apiTimeoutMs: number; + /** Public URL of the MCP endpoint (OAuth discovery). Undefined = OAuth discovery disabled. */ + mcpPublicUrl?: string; + /** Issuer of the OAuth Authorization Server (GitOps). */ + authServerUrl: string; logLevel: LogLevel; } @@ -16,6 +20,21 @@ function positiveInt(name: string, raw: string | undefined, fallback: number): n return n; } +function optionalUrl(name: string, raw: string | undefined): string | undefined { + const value = raw?.trim(); + if (!value) return undefined; + let parsed: URL; + try { + parsed = new URL(value); + } catch { + throw new Error(`${name} must be a valid URL`); + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new Error(`${name} must be an http(s) URL`); + } + return value.replace(/\/+$/, ''); +} + export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const apiUrl = env.GITOPS_API_URL?.trim(); if (!apiUrl) throw new Error('GITOPS_API_URL is required'); @@ -28,10 +47,14 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { if (!LOG_LEVELS.includes(level)) { throw new Error(`LOG_LEVEL must be one of ${LOG_LEVELS.join(', ')}`); } + const cleanApiUrl = apiUrl.replace(/\/+$/, ''); + const mcpPublicUrl = optionalUrl('MCP_PUBLIC_URL', env.MCP_PUBLIC_URL); return { port: positiveInt('PORT', env.PORT, 3000), - apiUrl: apiUrl.replace(/\/+$/, ''), + apiUrl: cleanApiUrl, apiTimeoutMs: positiveInt('GITOPS_API_TIMEOUT_MS', env.GITOPS_API_TIMEOUT_MS, 10000), + ...(mcpPublicUrl ? { mcpPublicUrl } : {}), + authServerUrl: optionalUrl('GITOPS_AUTH_SERVER_URL', env.GITOPS_AUTH_SERVER_URL) ?? cleanApiUrl, logLevel: level, }; } diff --git a/src/http.ts b/src/http.ts index 8cc2d87..0575a80 100644 --- a/src/http.ts +++ b/src/http.ts @@ -2,6 +2,15 @@ import { randomUUID } from 'node:crypto'; import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; import { GitOpsApiClient } from './api/client.js'; +import { + CORS_HEADERS, + METADATA_CORS_HEADERS, + TokenValidator, + metadataPaths, + protectedResourceMetadata, + sendNoContent, + wwwAuthenticate, +} from './auth.js'; import type { Config } from './config.js'; import type { Logger } from './log.js'; import { createMcpServer } from './server.js'; @@ -41,7 +50,12 @@ async function readJson(req: IncomingMessage): Promise { } export function createHttpServer(config: Config, log: Logger): Server { + const validator = new TokenValidator(); + const resourceMetadataPaths = metadataPaths(config); + async function handleMcp(req: IncomingMessage, res: ServerResponse, requestId: string) { + for (const [name, value] of Object.entries(CORS_HEADERS)) res.setHeader(name, value); + if (req.method === 'OPTIONS') return sendNoContent(res, {}); if (req.method !== 'POST') { return sendJson(res, 405, rpcError(-32000, 'Method not allowed.'), { Allow: 'POST' }); } @@ -51,11 +65,31 @@ export function createHttpServer(config: Config, log: Logger): Server { return sendJson( res, 401, - rpcError(-32001, 'Unauthorized: send "Authorization: Bearer ".'), - { 'WWW-Authenticate': 'Bearer realm="gitops-mcp"' }, + rpcError( + -32001, + 'Unauthorized: send "Authorization: Bearer " or connect through OAuth.', + ), + { 'WWW-Authenticate': wwwAuthenticate(config) }, ); } + const client = new GitOpsApiClient({ + baseUrl: config.apiUrl, + authorization, + timeoutMs: config.apiTimeoutMs, + onCall: ({ path, status, durationMs }) => + log.debug('api call', { requestId, apiPath: path, apiStatus: status, durationMs }), + }); + + const check = await validator.validate(authorization, client); + if (!check.ok) { + const headers: Record = {}; + if (check.status === 401) headers['WWW-Authenticate'] = wwwAuthenticate(config); + if (check.retryAfter !== undefined) headers['Retry-After'] = String(check.retryAfter); + const code = check.status === 401 ? -32001 : check.status === 429 ? -32029 : -32003; + return sendJson(res, check.status, rpcError(code, check.message), headers); + } + let body: unknown; try { body = await readJson(req); @@ -65,13 +99,6 @@ export function createHttpServer(config: Config, log: Logger): Server { : sendJson(res, 400, rpcError(-32700, 'Parse error: invalid JSON.')); } - const client = new GitOpsApiClient({ - baseUrl: config.apiUrl, - authorization, - timeoutMs: config.apiTimeoutMs, - onCall: ({ path, status, durationMs }) => - log.debug('api call', { requestId, apiPath: path, apiStatus: status, durationMs }), - }); const server = createMcpServer({ client, log, requestId }); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, @@ -104,6 +131,15 @@ export function createHttpServer(config: Config, log: Logger): Server { if (path === '/healthz' && (req.method === 'GET' || req.method === 'HEAD')) { return sendJson(res, 200, { ok: true }); } + if (resourceMetadataPaths.includes(path)) { + if (req.method === 'OPTIONS') return sendNoContent(res, METADATA_CORS_HEADERS); + if (req.method === 'GET' || req.method === 'HEAD') { + return sendJson(res, 200, protectedResourceMetadata(config), { + ...METADATA_CORS_HEADERS, + 'Cache-Control': 'public, max-age=300', + }); + } + } if (path === '/mcp') return handleMcp(req, res, requestId); sendJson(res, 404, { error: 'Not found' }); }; diff --git a/test/fake-api.ts b/test/fake-api.ts index 381b7b1..1753d97 100644 --- a/test/fake-api.ts +++ b/test/fake-api.ts @@ -322,6 +322,13 @@ const monitorSummary = (m: FakeDb['monitors'][number]) => ({ export function defaultRoutes(): Route[] { return [ + { + method: 'GET', + pattern: /^\/api\/whoami$/, + handler: () => ({ + body: { type: 'mcp', audience: 'mcp', name: 'Test key', oauth: false }, + }), + }, { method: 'GET', pattern: /^\/api\/projects$/, diff --git a/test/helpers.ts b/test/helpers.ts index b483de1..1295d0f 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -29,6 +29,7 @@ export async function startMcp(api: FakeApi, overrides: Partial = {}): P const config: Config = { port: 0, apiUrl: api.url, + authServerUrl: api.url, apiTimeoutMs: 5000, logLevel: 'debug', ...overrides, diff --git a/test/http.test.ts b/test/http.test.ts index 3603a4d..ad6c9bd 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -120,12 +120,11 @@ describe('e2e with the MCP SDK client', () => { await client.close(); }); - it('a revoked token gives a readable tool error', async () => { - const client = await connect('gvs_revoked'); - const result = await client.callTool({ name: 'list_projects', arguments: {} }); - expect(result.isError).toBe(true); - expect((result.content as { text: string }[])[0]!.text).toMatch(/token inválido o revocado/i); - await client.close(); + it('a revoked token is rejected with HTTP 401, not a tool error', async () => { + const res = await post({ Authorization: 'Bearer gvs_revoked' }); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toContain('Bearer realm="gitops-mcp"'); + await expect(connect('gvs_revoked')).rejects.toThrow(); }); it('never logs the token', () => { diff --git a/test/oauth.test.ts b/test/oauth.test.ts new file mode 100644 index 0000000..6c31039 --- /dev/null +++ b/test/oauth.test.ts @@ -0,0 +1,216 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { loadConfig } from '../src/config.js'; +import { startFakeApi, VALID_TOKEN, type FakeApi } from './fake-api.js'; +import { startMcp, type TestMcp } from './helpers.js'; + +const PUBLIC_URL = 'https://mcp.example.com/mcp'; +const METADATA_URL = 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp'; + +let api: FakeApi; +let mcp: TestMcp; +let plain: TestMcp; +beforeAll(async () => { + api = await startFakeApi({ + validTokens: [VALID_TOKEN, 'gvs_other_token', 'gvs_fresh_429', 'gvs_fresh_500', 'gvs_net'], + }); + mcp = await startMcp(api, { + mcpPublicUrl: PUBLIC_URL, + authServerUrl: 'https://auth.example.com', + }); + plain = await startMcp(api); +}); +afterAll(async () => { + await mcp.close(); + await plain.close(); + await api.close(); +}); +beforeEach(() => api.reset()); + +const initBody = { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-03-26', + capabilities: {}, + clientInfo: { name: 't', version: '1' }, + }, +}; +const post = (base: string, headers: Record) => + fetch(`${base}/mcp`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + ...headers, + }, + body: JSON.stringify(initBody), + }); +const whoamiCalls = () => api.requests.filter((r) => r.path === '/api/whoami').length; + +describe('protected resource metadata', () => { + it.each(['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp'])( + 'serves %s', + async (path) => { + for (const method of ['GET', 'HEAD']) { + const res = await fetch(`${mcp.url}${path}`, { method }); + expect(res.status).toBe(200); + expect(res.headers.get('access-control-allow-origin')).toBe('*'); + if (method === 'GET') { + expect(await res.json()).toEqual({ + resource: PUBLIC_URL, + authorization_servers: ['https://auth.example.com'], + bearer_methods_supported: ['header'], + scopes_supported: ['mcp'], + resource_name: 'GitOps', + }); + } + } + const pre = await fetch(`${mcp.url}${path}`, { method: 'OPTIONS' }); + expect(pre.status).toBe(204); + expect(pre.headers.get('access-control-allow-origin')).toBe('*'); + }, + ); + + it('is 404 without MCP_PUBLIC_URL', async () => { + for (const path of [ + '/.well-known/oauth-protected-resource', + '/.well-known/oauth-protected-resource/mcp', + ]) { + expect((await fetch(`${plain.url}${path}`)).status).toBe(404); + } + }); +}); + +describe('config', () => { + const base = { GITOPS_API_URL: 'https://cloud.example.com/' }; + + it('defaults the auth server to the API URL and disables discovery', () => { + const config = loadConfig(base); + expect(config.authServerUrl).toBe('https://cloud.example.com'); + expect(config.mcpPublicUrl).toBeUndefined(); + }); + + it('strips trailing slashes and validates URLs', () => { + const config = loadConfig({ + ...base, + MCP_PUBLIC_URL: 'https://mcp.example.com/mcp/', + GITOPS_AUTH_SERVER_URL: 'https://auth.example.com/', + }); + expect(config.mcpPublicUrl).toBe('https://mcp.example.com/mcp'); + expect(config.authServerUrl).toBe('https://auth.example.com'); + expect(() => loadConfig({ ...base, MCP_PUBLIC_URL: 'nope' })).toThrow(/MCP_PUBLIC_URL/); + }); +}); + +describe('CORS on /mcp', () => { + it('answers the preflight', async () => { + const res = await fetch(`${mcp.url}/mcp`, { method: 'OPTIONS' }); + expect(res.status).toBe(204); + expect(res.headers.get('access-control-allow-origin')).toBe('*'); + expect(res.headers.get('access-control-allow-headers')).toBe( + 'Authorization, Content-Type, Mcp-Protocol-Version', + ); + expect(res.headers.get('access-control-expose-headers')).toBe('WWW-Authenticate'); + }); + + it('adds CORS headers to real responses too', async () => { + const res = await post(mcp.url, {}); + expect(res.headers.get('access-control-allow-origin')).toBe('*'); + expect(res.headers.get('access-control-expose-headers')).toBe('WWW-Authenticate'); + }); +}); + +describe('401 with discovery', () => { + it('points to the metadata when the Bearer is missing', async () => { + const res = await post(mcp.url, {}); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe( + `Bearer realm="gitops-mcp", resource_metadata="${METADATA_URL}"`, + ); + expect(whoamiCalls()).toBe(0); + }); + + it('is a plain HTTP 401 (not a tool error) when whoami rejects the token', async () => { + const res = await post(mcp.url, { Authorization: 'Bearer gvs_expired' }); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe( + `Bearer realm="gitops-mcp", resource_metadata="${METADATA_URL}"`, + ); + const body = (await res.json()) as { error: { code: number } }; + expect(body.error.code).toBeLessThan(0); + expect(whoamiCalls()).toBe(1); + }); + + it('keeps the old header without MCP_PUBLIC_URL', async () => { + const res = await post(plain.url, {}); + expect(res.headers.get('www-authenticate')).toBe('Bearer realm="gitops-mcp"'); + }); +}); + +describe('token validation', () => { + const authHeader = { Authorization: 'Bearer gvs_other_token' }; + + it('caches successful validations', async () => { + expect((await post(mcp.url, authHeader)).status).toBe(200); + expect((await post(mcp.url, authHeader)).status).toBe(200); + expect(whoamiCalls()).toBe(1); + }); + + it('does not cache failures', async () => { + await post(mcp.url, { Authorization: 'Bearer gvs_bad' }); + await post(mcp.url, { Authorization: 'Bearer gvs_bad' }); + expect(whoamiCalls()).toBe(2); + }); + + it('works end to end with the SDK client', async () => { + const client = new Client({ name: 'test', version: '1' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${mcp.url}/mcp`), { + requestInit: { headers: { Authorization: `Bearer ${VALID_TOKEN}` } }, + }), + ); + const result = await client.callTool({ name: 'list_projects', arguments: {} }); + expect(result.isError).toBeFalsy(); + await client.close(); + }); + + it('answers 429 with Retry-After when whoami is rate limited', async () => { + api.failNext({ status: 429, code: 'rate_limited', headers: { 'Retry-After': '9' } }); + const res = await post(mcp.url, { Authorization: 'Bearer gvs_fresh_429' }); + expect(res.status).toBe(429); + expect(res.headers.get('retry-after')).toBe('9'); + }); + + it('answers 503 (not 401) when whoami fails with 500', async () => { + api.failNext({ status: 500, code: 'internal' }); + const res = await post(mcp.url, { Authorization: 'Bearer gvs_fresh_500' }); + expect(res.status).toBe(503); + expect(res.headers.get('www-authenticate')).toBeNull(); + const body = (await res.json()) as { error: { message: string } }; + expect(body.error.message).toMatch(/unavailable/i); + }); + + it('answers 503 when the API is unreachable', async () => { + const dead = await startMcp(api, { apiUrl: 'http://127.0.0.1:1', apiTimeoutMs: 500 }); + const res = await post(dead.url, { Authorization: 'Bearer gvs_net' }); + expect(res.status).toBe(503); + await dead.close(); + }); + + it('never logs tokens on the new paths', () => { + const all = [...mcp.logs, ...plain.logs].join('\n'); + for (const secret of [ + 'gvs_expired', + 'gvs_bad', + 'gvs_other_token', + 'gvs_fresh_500', + VALID_TOKEN, + ]) { + expect(all).not.toContain(secret); + } + expect(all).not.toMatch(/bearer|authorization/i); + }); +});