diff --git a/examples/servers/typescript/auth-token-audience-server.ts b/examples/servers/typescript/auth-token-audience-server.ts new file mode 100644 index 00000000..8e7d57b1 --- /dev/null +++ b/examples/servers/typescript/auth-token-audience-server.ts @@ -0,0 +1,436 @@ +#!/usr/bin/env node + +/** + * MCP Token Audience Validation Reference & Negative-Test Server + * + * Built on `@modelcontextprotocol/sdk` (`McpServer`, + * `StreamableHTTPServerTransport`, `requireBearerAuth`, `checkResourceAllowed`). + * Validates Bearer JWTs issued by the conformance mock Authorization Server + * either locally via JWKS (default) or via RFC 7662 token introspection + * (`AUTH_MODE=introspect`). + * + * Environment variables: + * PORT Listening port (default: 3014) + * AUTH_SERVER_URL Mock AS issuer URL (default: http://localhost:8091) + * RESOURCE_URL Canonical MCP server URI expected in `aud` + * (default: http://localhost:/mcp) + * AUTH_MODE `jwks` (default) or `introspect` + * TOKEN_AUDIENCE_BREAK Optional defect injection for negative testing: + * - `skip-audience` + * - `allow-missing-audience` + * - `skip-expiration` + * - `no-auth` + * - `reject-all` + * - `wrong-status-403` + */ + +import express from 'express'; +import { createPublicKey, randomUUID, verify, type JsonWebKey } from 'crypto'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js'; +import { + InsufficientScopeError, + InvalidTokenError +} from '@modelcontextprotocol/sdk/server/auth/errors.js'; +import type { OAuthTokenVerifier } from '@modelcontextprotocol/sdk/server/auth/provider.js'; +import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; +import { getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js'; +import { + checkResourceAllowed, + resourceUrlFromServerUrl +} from '@modelcontextprotocol/sdk/shared/auth-utils.js'; + +const ALLOWED_BREAK_MODES = new Set([ + 'skip-audience', + 'allow-missing-audience', + 'skip-expiration', + 'no-auth', + 'reject-all', + 'wrong-status-403' +]); + +const PORT = Number.parseInt(process.env.PORT || '3014', 10); +const AUTH_SERVER_URL = ( + process.env.AUTH_SERVER_URL || 'http://localhost:8091' +).replace(/\/+$/, ''); +const RESOURCE_URL = process.env.RESOURCE_URL || `http://localhost:${PORT}/mcp`; +const AUTH_MODE = (process.env.AUTH_MODE || 'jwks').toLowerCase(); +const BREAK_MODE = process.env.TOKEN_AUDIENCE_BREAK || ''; + +if (BREAK_MODE && !ALLOWED_BREAK_MODES.has(BREAK_MODE)) { + console.error( + `Unknown TOKEN_AUDIENCE_BREAK="${BREAK_MODE}". Allowed: ${Array.from(ALLOWED_BREAK_MODES).join(', ')}` + ); + process.exit(1); +} + +if (AUTH_MODE !== 'jwks' && AUTH_MODE !== 'introspect') { + console.error(`Unknown AUTH_MODE="${AUTH_MODE}". Allowed: jwks, introspect`); + process.exit(1); +} + +const configuredResource = resourceUrlFromServerUrl(RESOURCE_URL); +const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl( + new URL(RESOURCE_URL) +); + +interface AsMetadata { + issuer: string; + jwks_uri?: string; + introspection_endpoint?: string; +} + +interface JwkWithKid extends JsonWebKey { + kid?: string; + alg?: string; + use?: string; +} + +interface JwtHeader { + alg?: string; + kid?: string; +} + +interface JwtPayload { + iss?: string; + sub?: string; + aud?: string | string[]; + exp?: number; + iat?: number; + client_id?: string; + scope?: string; +} + +function decodeBase64UrlJson(segment: string): T { + const raw = Buffer.from(segment, 'base64url').toString('utf8'); + return JSON.parse(raw) as T; +} + +async function fetchAsMetadata(): Promise { + const res = await fetch( + `${AUTH_SERVER_URL}/.well-known/oauth-authorization-server`, + { headers: { Accept: 'application/json' } } + ); + if (!res.ok) { + throw new InvalidTokenError( + `Failed to fetch AS metadata: HTTP ${res.status}` + ); + } + return (await res.json()) as AsMetadata; +} + +function validateAudienceClaim(aud: unknown): URL | undefined { + if (BREAK_MODE === 'skip-audience') { + return configuredResource; + } + + const audiences: string[] = + typeof aud === 'string' + ? [aud] + : Array.isArray(aud) + ? aud.filter((item): item is string => typeof item === 'string') + : []; + + if (audiences.length === 0) { + if (BREAK_MODE === 'allow-missing-audience') { + return configuredResource; + } + throw new InvalidTokenError('Access token is missing required aud claim'); + } + + for (const candidate of audiences) { + try { + const candidateUrl = resourceUrlFromServerUrl(candidate); + if ( + checkResourceAllowed({ + requestedResource: candidateUrl, + configuredResource + }) + ) { + return candidateUrl; + } + } catch { + // Non-URL audience value does not match this server's URI. + } + } + + if (BREAK_MODE === 'wrong-status-403') { + throw new InsufficientScopeError( + 'Deliberately returning 403 for audience mismatch' + ); + } + throw new InvalidTokenError( + `Access token audience does not match ${configuredResource.href}` + ); +} + +async function verifyViaJwks(token: string): Promise { + const parts = token.split('.'); + if (parts.length !== 3) { + throw new InvalidTokenError('Malformed JWT'); + } + const [headerSeg, payloadSeg, signatureSeg] = parts; + + let header: JwtHeader; + let payload: JwtPayload; + try { + header = decodeBase64UrlJson(headerSeg); + payload = decodeBase64UrlJson(payloadSeg); + } catch { + throw new InvalidTokenError('Failed to decode JWT'); + } + + if (header.alg !== 'RS256') { + throw new InvalidTokenError(`Unsupported JWT algorithm: ${header.alg}`); + } + + const metadata = await fetchAsMetadata(); + if (!metadata.jwks_uri) { + throw new InvalidTokenError('AS metadata is missing jwks_uri'); + } + + const jwksRes = await fetch(metadata.jwks_uri, { + headers: { Accept: 'application/json' } + }); + if (!jwksRes.ok) { + throw new InvalidTokenError(`Failed to fetch JWKS: HTTP ${jwksRes.status}`); + } + const jwks = (await jwksRes.json()) as { keys?: JwkWithKid[] }; + const keys = Array.isArray(jwks.keys) ? jwks.keys : []; + const matchingKey = + keys.find((k) => !header.kid || k.kid === header.kid) ?? keys[0]; + if (!matchingKey) { + throw new InvalidTokenError('No matching signing key found in JWKS'); + } + + const publicKey = createPublicKey({ key: matchingKey, format: 'jwk' }); + const signingInput = Buffer.from(`${headerSeg}.${payloadSeg}`, 'utf8'); + const signature = Buffer.from(signatureSeg, 'base64url'); + const signatureValid = verify( + 'RSA-SHA256', + signingInput, + publicKey, + signature + ); + if (!signatureValid) { + throw new InvalidTokenError('Invalid token signature'); + } + + if (payload.iss !== metadata.issuer) { + throw new InvalidTokenError( + `Unexpected issuer "${payload.iss ?? ''}", expected "${metadata.issuer}"` + ); + } + + const now = Math.floor(Date.now() / 1000); + if (BREAK_MODE !== 'skip-expiration') { + if (typeof payload.exp !== 'number' || payload.exp <= now) { + throw new InvalidTokenError('Token has expired'); + } + } + + const validatedResource = validateAudienceClaim(payload.aud); + + return { + token, + clientId: payload.client_id ?? payload.sub ?? 'unknown', + scopes: payload.scope ? payload.scope.split(/\s+/).filter(Boolean) : [], + expiresAt: BREAK_MODE === 'skip-expiration' ? now + 3600 : payload.exp, + resource: validatedResource + }; +} + +async function verifyViaIntrospection(token: string): Promise { + const metadata = await fetchAsMetadata(); + if (!metadata.introspection_endpoint) { + throw new InvalidTokenError( + 'AS metadata is missing introspection_endpoint' + ); + } + + const res = await fetch(metadata.introspection_endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }, + body: new URLSearchParams({ token }).toString() + }); + + if (!res.ok) { + throw new InvalidTokenError(`Introspection failed: HTTP ${res.status}`); + } + + const data = (await res.json()) as { + active?: boolean; + aud?: string | string[]; + exp?: number; + client_id?: string; + sub?: string; + scope?: string; + }; + + if (!data.active) { + throw new InvalidTokenError('Token is not active'); + } + + const validatedResource = validateAudienceClaim(data.aud); + const now = Math.floor(Date.now() / 1000); + + return { + token, + clientId: data.client_id ?? data.sub ?? 'unknown', + scopes: data.scope ? data.scope.split(/\s+/).filter(Boolean) : [], + expiresAt: BREAK_MODE === 'skip-expiration' ? now + 3600 : data.exp, + resource: validatedResource + }; +} + +const verifier: OAuthTokenVerifier = { + async verifyAccessToken(token: string): Promise { + if (BREAK_MODE === 'reject-all') { + throw new InvalidTokenError('Server configured to reject all tokens'); + } + if (AUTH_MODE === 'introspect') { + return verifyViaIntrospection(token); + } + return verifyViaJwks(token); + } +}; + +function createMcpServer(): McpServer { + const server = new McpServer( + { name: 'auth-token-audience-test-server', version: '1.0.0' }, + { capabilities: { tools: {} } } + ); + server.tool('echo', 'Echo a message', {}, async () => ({ + content: [{ type: 'text', text: 'ok' }] + })); + return server; +} + +const app = express(); +app.use(express.json()); + +const prmDocument = { + resource: configuredResource.href, + authorization_servers: [AUTH_SERVER_URL], + bearer_methods_supported: ['header'] +}; + +app.get('/.well-known/oauth-protected-resource/mcp', (_req, res) => { + res.json(prmDocument); +}); + +app.get('/.well-known/oauth-protected-resource', (_req, res) => { + res.json(prmDocument); +}); + +const authMiddleware = + BREAK_MODE === 'no-auth' + ? ( + _req: express.Request, + _res: express.Response, + next: express.NextFunction + ) => next() + : requireBearerAuth({ verifier, resourceMetadataUrl }); + +const transports: Record = {}; +const servers: Record = {}; + +app.post('/mcp', authMiddleware, async (req, res) => { + const body = req.body as { + method?: string; + id?: string | number | null; + params?: { _meta?: Record }; + }; + + // Support stateless SEP-2575 `server/discover` (2026-07-28 draft wire) + if (body?.method === 'server/discover') { + res.status(200).json({ + jsonrpc: '2.0', + id: body.id ?? 1, + result: { + protocolVersion: '2026-07-28', + capabilities: { tools: {} }, + serverInfo: { + name: 'auth-token-audience-test-server', + version: '1.0.0' + } + } + }); + return; + } + + const sessionId = req.headers['mcp-session-id'] as string | undefined; + try { + if (sessionId && transports[sessionId]) { + await transports[sessionId].handleRequest(req, res, req.body); + return; + } + + if (!sessionId && body?.method === 'initialize') { + const mcpServer = createMcpServer(); + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: (newSessionId) => { + transports[newSessionId] = transport; + servers[newSessionId] = mcpServer; + } + }); + + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + delete transports[sid]; + if (servers[sid]) { + void servers[sid].close(); + delete servers[sid]; + } + } + }; + + await mcpServer.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + + res.status(400).json({ + jsonrpc: '2.0', + id: body?.id ?? null, + error: { code: -32000, message: 'Invalid or missing session ID' } + }); + } catch (error) { + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + id: body?.id ?? null, + error: { + code: -32603, + message: error instanceof Error ? error.message : String(error) + } + }); + } + } +}); + +app.delete('/mcp', authMiddleware, async (req, res) => { + const sessionId = req.headers['mcp-session-id'] as string | undefined; + if (!sessionId || !transports[sessionId]) { + res.status(404).send('Session not found'); + return; + } + await transports[sessionId].handleRequest(req, res); +}); + +app.listen(PORT, '127.0.0.1', () => { + console.log( + `MCP Token Audience Test Server running on http://localhost:${PORT}` + ); + console.log(` - MCP endpoint: ${RESOURCE_URL}`); + console.log(` - Auth server: ${AUTH_SERVER_URL} (mode=${AUTH_MODE})`); + if (BREAK_MODE) { + console.log(` - Break mode: ${BREAK_MODE}`); + } +}); diff --git a/src/scenarios/index.ts b/src/scenarios/index.ts index ff377f54..e3bf2001 100644 --- a/src/scenarios/index.ts +++ b/src/scenarios/index.ts @@ -108,6 +108,7 @@ import { HttpHeaderValidationScenario, HttpCustomHeaderServerValidationScenario } from './server/http-standard-headers'; +import { TokenAudienceValidationScenario } from './server/auth/token-audience-validation'; import { authScenariosList, @@ -166,7 +167,13 @@ const pendingClientScenariosList: ClientScenario[] = [ // `npm start -- server --scenario sep-2640-skills-* --url `. new SkillsDirectoryReadScenario(), new SkillsEnumerationScenario(), - new SkillsManifestScenario() + new SkillsManifestScenario(), + + // Server-side OAuth token audience validation (issue #78). Pending because + // the everything-server runs without authentication enabled; targeted runs + // point at an auth-enabled server configured to trust the mock AS via + // `npm start -- server --scenario auth/token-audience-validation --url `. + new TokenAudienceValidationScenario() ]; // All client scenarios @@ -233,6 +240,7 @@ const allClientScenariosList: ClientScenario[] = [ // Security scenarios new DNSRebindingProtectionScenario(), + new TokenAudienceValidationScenario(), // Caching scenarios (SEP-2549) new CachingScenario(), diff --git a/src/scenarios/server/auth/mock-auth-server.ts b/src/scenarios/server/auth/mock-auth-server.ts new file mode 100644 index 00000000..abdb5773 --- /dev/null +++ b/src/scenarios/server/auth/mock-auth-server.ts @@ -0,0 +1,316 @@ +/** + * Local Mock Authorization Server for server-side token validation tests. + * + * Serves OAuth 2.0 Authorization Server Metadata (RFC 8414), a JWKS endpoint + * (RFC 7517), and an RFC 7662 Token Introspection endpoint so MCP servers under + * test can validate signed JWT access tokens either locally via JWKS or via + * introspection. + */ + +import http from 'http'; +import type { AddressInfo } from 'net'; +import { randomUUID } from 'crypto'; +import * as jose from 'jose'; +import type { CryptoKey, JWK } from 'jose'; + +const DEFAULT_ALG = 'RS256'; +const DEFAULT_KID = 'conformance-mock-as-key-1'; + +export interface MockTokenAuthServerOptions { + /** TCP port to listen on. Pass `0` for an ephemeral OS-assigned port. */ + port?: number; + /** Bind address for the HTTP socket. Defaults to `'127.0.0.1'`. */ + host?: string; + /** + * Explicit `issuer` URL advertised in metadata and placed in JWT `iss`. + * Defaults to `http://:`. + */ + issuerUrl?: string; + /** JWS signing algorithm. Defaults to `'RS256'`. */ + alg?: string; + /** Key ID (`kid`) published in JWKS and JWT headers. */ + kid?: string; +} + +export interface MintAccessTokenOptions { + /** `aud` claim value (single URI or array). Ignored when `omitAud` is true. */ + audience?: string | string[]; + /** Omit the `aud` claim entirely. */ + omitAud?: boolean; + /** Issue an already-expired token (`exp` 5 minutes in the past). */ + expired?: boolean; + /** Token lifetime in seconds for non-expired tokens. Defaults to 3600. */ + expiresInSeconds?: number; + /** `sub` claim. Defaults to `'conformance-test-subject'`. */ + subject?: string; + /** `client_id` claim. Defaults to `'conformance-test-client'`. */ + clientId?: string; + /** `scope` claim. Defaults to `'mcp:tools'`. */ + scope?: string; + /** Override `iat` (epoch seconds). Defaults to current time. */ + iat?: number; +} + +export interface MockAuthServerCounters { + metadataRequests: number; + jwksRequests: number; + introspectionRequests: number; +} + +async function readBody(req: http.IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + return Buffer.concat(chunks).toString('utf8'); +} + +function extractIntrospectionToken( + rawBody: string, + contentType: string | undefined +): string | undefined { + if (contentType?.toLowerCase().includes('application/json')) { + try { + const parsed = JSON.parse(rawBody) as { token?: unknown }; + return typeof parsed.token === 'string' ? parsed.token : undefined; + } catch { + return undefined; + } + } + const params = new URLSearchParams(rawBody); + return params.get('token') ?? undefined; +} + +export class MockTokenAuthServer { + private readonly requestedPort: number; + private readonly host: string; + private readonly explicitIssuerUrl?: string; + private readonly alg: string; + private readonly kid: string; + + private server: http.Server | null = null; + private privateKey: CryptoKey | null = null; + private publicKey: CryptoKey | null = null; + private publicJwk: JWK | null = null; + private boundPort: number | null = null; + private resolvedIssuerUrl: string | null = null; + + private counters: MockAuthServerCounters = { + metadataRequests: 0, + jwksRequests: 0, + introspectionRequests: 0 + }; + + constructor(options: MockTokenAuthServerOptions = {}) { + this.requestedPort = options.port ?? 0; + this.host = options.host ?? '127.0.0.1'; + this.explicitIssuerUrl = options.issuerUrl?.replace(/\/+$/, ''); + this.alg = options.alg ?? DEFAULT_ALG; + this.kid = options.kid ?? DEFAULT_KID; + } + + /** Base issuer URL (available after `start()`). */ + get issuerUrl(): string { + if (!this.resolvedIssuerUrl) { + throw new Error('MockTokenAuthServer has not been started'); + } + return this.resolvedIssuerUrl; + } + + /** Bound TCP port (available after `start()`). */ + get port(): number { + if (this.boundPort === null) { + throw new Error('MockTokenAuthServer has not been started'); + } + return this.boundPort; + } + + /** Snapshot of observed requests to the mock AS endpoints. */ + getCounters(): MockAuthServerCounters { + return { ...this.counters }; + } + + async start(): Promise { + if (this.server) return; + + const { publicKey, privateKey } = await jose.generateKeyPair(this.alg, { + extractable: true + }); + const exportedJwk = await jose.exportJWK(publicKey); + this.privateKey = privateKey; + this.publicKey = publicKey; + this.publicJwk = { + ...exportedJwk, + kid: this.kid, + use: 'sig', + alg: this.alg + }; + + const server = http.createServer((req, res) => { + void this.handleRequest(req, res).catch((error) => { + if (!res.headersSent) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + error: 'server_error', + error_description: + error instanceof Error ? error.message : String(error) + }) + ); + } + }); + }); + + await new Promise((resolve, reject) => { + const onError = (err: Error) => reject(err); + server.once('error', onError); + server.listen(this.requestedPort, this.host, () => { + server.off('error', onError); + resolve(); + }); + }); + + const address = server.address() as AddressInfo | null; + if (!address || typeof address === 'string') { + server.close(); + throw new Error('MockTokenAuthServer did not bind to a TCP port'); + } + + this.server = server; + this.boundPort = address.port; + this.resolvedIssuerUrl = + this.explicitIssuerUrl ?? `http://${this.host}:${this.boundPort}`; + } + + async stop(): Promise { + if (!this.server) return; + const srv = this.server; + this.server = null; + srv.closeAllConnections(); + await new Promise((resolve) => srv.close(() => resolve())); + } + + async mintToken(options: MintAccessTokenOptions = {}): Promise { + if (!this.privateKey || !this.resolvedIssuerUrl) { + throw new Error('MockTokenAuthServer must be started before minting'); + } + + const now = options.iat ?? Math.floor(Date.now() / 1000); + const lifetime = options.expiresInSeconds ?? 3600; + const iat = options.expired ? now - 600 : now; + const exp = options.expired ? now - 300 : now + lifetime; + + const payload: Record = { + client_id: options.clientId ?? 'conformance-test-client', + scope: options.scope ?? 'mcp:tools' + }; + + let builder = new jose.SignJWT(payload) + .setProtectedHeader({ + alg: this.alg, + kid: this.kid, + typ: 'at+jwt' + }) + .setIssuer(this.resolvedIssuerUrl) + .setSubject(options.subject ?? 'conformance-test-subject') + .setIssuedAt(iat) + .setExpirationTime(exp) + .setJti(randomUUID()); + + if (!options.omitAud && options.audience !== undefined) { + builder = builder.setAudience(options.audience); + } + + return builder.sign(this.privateKey); + } + + private async handleRequest( + req: http.IncomingMessage, + res: http.ServerResponse + ): Promise { + const method = req.method ?? 'GET'; + const pathname = new URL(req.url ?? '/', 'http://localhost').pathname; + + if ( + method === 'GET' && + (pathname === '/.well-known/oauth-authorization-server' || + pathname === '/.well-known/openid-configuration') + ) { + this.counters.metadataRequests += 1; + const issuer = this.issuerUrl; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + issuer, + jwks_uri: `${issuer}/jwks`, + introspection_endpoint: `${issuer}/introspect`, + token_endpoint: `${issuer}/token`, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'client_credentials'], + id_token_signing_alg_values_supported: [this.alg] + }) + ); + return; + } + + if ( + method === 'GET' && + (pathname === '/jwks' || pathname === '/.well-known/jwks.json') + ) { + this.counters.jwksRequests += 1; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ keys: this.publicJwk ? [this.publicJwk] : [] })); + return; + } + + if (method === 'POST' && pathname === '/introspect') { + this.counters.introspectionRequests += 1; + const rawBody = await readBody(req); + const token = extractIntrospectionToken( + rawBody, + req.headers['content-type'] + ); + + if (!token || !this.publicKey || !this.resolvedIssuerUrl) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ active: false })); + return; + } + + try { + // Verify signature, issuer, and expiration without filtering on `aud`: + // per RFC 7662, introspection reports the token's `aud` so the resource + // server performs audience validation. + const { payload } = await jose.jwtVerify(token, this.publicKey, { + issuer: this.resolvedIssuerUrl, + algorithms: [this.alg] + }); + + const response: Record = { + active: true, + iss: payload.iss, + sub: payload.sub, + exp: payload.exp, + iat: payload.iat, + jti: payload.jti, + client_id: payload.client_id, + scope: payload.scope, + token_type: 'Bearer' + }; + if (payload.aud !== undefined) { + response.aud = payload.aud; + } + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(response)); + } catch { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ active: false })); + } + return; + } + + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'not_found' })); + } +} diff --git a/src/scenarios/server/auth/token-audience-validation.test.ts b/src/scenarios/server/auth/token-audience-validation.test.ts new file mode 100644 index 00000000..5590ab3d --- /dev/null +++ b/src/scenarios/server/auth/token-audience-validation.test.ts @@ -0,0 +1,499 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { spawn, type ChildProcess } from 'child_process'; +import { createServer as createNetServer } from 'net'; +import path from 'path'; +import * as jose from 'jose'; +import { testContext } from '../../../connection/testing'; +import { + DRAFT_PROTOCOL_VERSION, + LATEST_SPEC_VERSION, + type ConformanceCheck +} from '../../../types'; +import { + getClientScenario, + listActiveClientScenarios, + listClientScenariosForSpec, + listPendingClientScenarios +} from '../../index'; +import { MockTokenAuthServer } from './mock-auth-server'; +import { TokenAudienceValidationScenario } from './token-audience-validation'; + +const EXAMPLE_SERVER_PATH = path.join( + process.cwd(), + 'examples/servers/typescript/auth-token-audience-server.ts' +); + +function getFreePort(): Promise { + return new Promise((resolve, reject) => { + const srv = createNetServer(); + srv.once('error', reject); + srv.listen(0, '127.0.0.1', () => { + const addr = srv.address(); + if (!addr || typeof addr === 'string') { + srv.close(); + reject(new Error('Failed to allocate free port')); + return; + } + const port = addr.port; + srv.close(() => resolve(port)); + }); + }); +} + +function startExampleServer(options: { + port: number; + authServerUrl: string; + authMode?: 'jwks' | 'introspect'; + breakMode?: string; +}): Promise { + return new Promise((resolve, reject) => { + const isWindows = process.platform === 'win32'; + const env: NodeJS.ProcessEnv = { + ...process.env, + PORT: String(options.port), + AUTH_SERVER_URL: options.authServerUrl, + RESOURCE_URL: `http://localhost:${options.port}/mcp`, + AUTH_MODE: options.authMode ?? 'jwks' + }; + if (options.breakMode) { + env.TOKEN_AUDIENCE_BREAK = options.breakMode; + } else { + delete env.TOKEN_AUDIENCE_BREAK; + } + + const proc = spawn('npx', ['tsx', EXAMPLE_SERVER_PATH], { + env, + stdio: ['ignore', 'pipe', 'pipe'], + shell: isWindows + }); + + let stderr = ''; + proc.stderr?.on('data', (chunk) => { + stderr += chunk.toString(); + }); + + const timer = setTimeout(() => { + proc.kill('SIGKILL'); + reject( + new Error(`Example server did not start within 25s. STDERR: ${stderr}`) + ); + }, 25_000); + + let settled = false; + proc.stdout?.on('data', (chunk) => { + if (!settled && chunk.toString().includes('running on')) { + settled = true; + clearTimeout(timer); + resolve(proc); + } + }); + proc.once('error', (err) => { + if (!settled) { + settled = true; + clearTimeout(timer); + reject(err); + } + }); + proc.once('exit', (code) => { + if (!settled) { + settled = true; + clearTimeout(timer); + reject( + new Error( + `Example server exited prematurely (code=${code}). STDERR: ${stderr}` + ) + ); + } + }); + }); +} + +function stopProcess(proc: ChildProcess | null): Promise { + return new Promise((resolve) => { + if (!proc || proc.killed || proc.exitCode !== null) { + resolve(); + return; + } + const timer = setTimeout(() => { + if (!proc.killed) proc.kill('SIGKILL'); + resolve(); + }, 5_000); + proc.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + proc.kill('SIGTERM'); + }); +} + +function checkById(checks: ConformanceCheck[], id: string): ConformanceCheck { + const found = checks.find((c) => c.id === id); + expect(found, `Expected check "${id}" to be emitted`).toBeDefined(); + return found!; +} + +describe('MockTokenAuthServer', () => { + let mockAs: MockTokenAuthServer | null = null; + + afterEach(async () => { + await mockAs?.stop(); + mockAs = null; + }); + + it('serves AS metadata, JWKS, and verifies minted tokens', async () => { + mockAs = new MockTokenAuthServer({ port: 0, host: '127.0.0.1' }); + await mockAs.start(); + + const metaRes = await fetch( + `${mockAs.issuerUrl}/.well-known/oauth-authorization-server` + ); + expect(metaRes.status).toBe(200); + const meta = (await metaRes.json()) as { + issuer: string; + jwks_uri: string; + introspection_endpoint: string; + }; + expect(meta.issuer).toBe(mockAs.issuerUrl); + expect(meta.jwks_uri).toBe(`${mockAs.issuerUrl}/jwks`); + expect(meta.introspection_endpoint).toBe(`${mockAs.issuerUrl}/introspect`); + + const jwks = jose.createRemoteJWKSet(new URL(meta.jwks_uri)); + const token = await mockAs.mintToken({ + audience: 'http://localhost:3014/mcp' + }); + const { payload } = await jose.jwtVerify(token, jwks, { + issuer: meta.issuer, + audience: 'http://localhost:3014/mcp' + }); + expect(payload.aud).toBe('http://localhost:3014/mcp'); + + const noAudToken = await mockAs.mintToken({ omitAud: true }); + expect(jose.decodeJwt(noAudToken).aud).toBeUndefined(); + + const expiredToken = await mockAs.mintToken({ + audience: 'http://localhost:3014/mcp', + expired: true + }); + await expect( + jose.jwtVerify(expiredToken, jwks, { issuer: meta.issuer }) + ).rejects.toThrow(); + + expect(mockAs.getCounters()).toEqual({ + metadataRequests: 1, + jwksRequests: 1, + introspectionRequests: 0 + }); + }); + + it('serves RFC 7662 token introspection with aud claim and active status', async () => { + mockAs = new MockTokenAuthServer({ port: 0, host: '127.0.0.1' }); + await mockAs.start(); + + const validToken = await mockAs.mintToken({ + audience: 'http://localhost:3014/mcp' + }); + const validRes = await fetch(`${mockAs.issuerUrl}/introspect`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ token: validToken }).toString() + }); + expect(validRes.status).toBe(200); + const validBody = (await validRes.json()) as { + active: boolean; + aud?: string; + }; + expect(validBody.active).toBe(true); + expect(validBody.aud).toBe('http://localhost:3014/mcp'); + + const missingAudToken = await mockAs.mintToken({ omitAud: true }); + const missingAudRes = await fetch(`${mockAs.issuerUrl}/introspect`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ token: missingAudToken }).toString() + }); + const missingAudBody = (await missingAudRes.json()) as { + active: boolean; + aud?: string; + }; + expect(missingAudBody.active).toBe(true); + expect(missingAudBody.aud).toBeUndefined(); + + const expiredToken = await mockAs.mintToken({ + audience: 'http://localhost:3014/mcp', + expired: true + }); + const expiredRes = await fetch(`${mockAs.issuerUrl}/introspect`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ token: expiredToken }).toString() + }); + const expiredBody = (await expiredRes.json()) as { active: boolean }; + expect(expiredBody.active).toBe(false); + }); +}); + +describe('TokenAudienceValidationScenario registry', () => { + it('is registered in pending suite and scoped to 2025-06-18+', () => { + const scenario = getClientScenario('auth/token-audience-validation'); + expect(scenario).toBeDefined(); + expect(scenario?.source).toEqual({ introducedIn: '2025-06-18' }); + + expect(listPendingClientScenarios()).toContain( + 'auth/token-audience-validation' + ); + expect(listActiveClientScenarios()).not.toContain( + 'auth/token-audience-validation' + ); + + expect(listClientScenariosForSpec('2025-03-26')).not.toContain( + 'auth/token-audience-validation' + ); + expect(listClientScenariosForSpec('2025-06-18')).toContain( + 'auth/token-audience-validation' + ); + expect(listClientScenariosForSpec('2025-11-25')).toContain( + 'auth/token-audience-validation' + ); + expect(listClientScenariosForSpec(DRAFT_PROTOCOL_VERSION)).toContain( + 'auth/token-audience-validation' + ); + }); +}); + +describe('TokenAudienceValidationScenario end-to-end', () => { + let mockAs: MockTokenAuthServer | null = null; + let serverProc: ChildProcess | null = null; + + afterEach(async () => { + await stopProcess(serverProc); + serverProc = null; + await mockAs?.stop(); + mockAs = null; + }); + + async function runAgainstExampleServer( + options: { + authMode?: 'jwks' | 'introspect'; + breakMode?: string; + specVersion?: '2025-06-18' | '2025-11-25' | typeof DRAFT_PROTOCOL_VERSION; + } = {} + ): Promise { + mockAs = new MockTokenAuthServer({ port: 0, host: '127.0.0.1' }); + await mockAs.start(); + + const serverPort = await getFreePort(); + serverProc = await startExampleServer({ + port: serverPort, + authServerUrl: mockAs.issuerUrl, + authMode: options.authMode, + breakMode: options.breakMode + }); + + const scenario = new TokenAudienceValidationScenario({ + mockAuthServer: mockAs + }); + return scenario.run( + testContext( + `http://localhost:${serverPort}/mcp`, + options.specVersion ?? LATEST_SPEC_VERSION + ) + ); + } + + it('passes all 4 checks against a compliant JWKS server (2025-11-25)', async () => { + const checks = await runAgainstExampleServer({ + authMode: 'jwks', + specVersion: '2025-11-25' + }); + + expect(checks).toHaveLength(4); + expect(checkById(checks, 'server-token-valid-accepted').status).toBe( + 'SUCCESS' + ); + expect(checkById(checks, 'server-token-audience-validation').status).toBe( + 'SUCCESS' + ); + expect( + checkById(checks, 'server-token-missing-audience-rejected').status + ).toBe('SUCCESS'); + expect(checkById(checks, 'server-token-expired-rejected').status).toBe( + 'SUCCESS' + ); + expect(mockAs!.getCounters().jwksRequests).toBeGreaterThan(0); + }, 30_000); + + it('passes all 4 checks on 2025-06-18 and 2026-07-28 (stateless) wire versions', async () => { + mockAs = new MockTokenAuthServer({ port: 0, host: '127.0.0.1' }); + await mockAs.start(); + const serverPort = await getFreePort(); + serverProc = await startExampleServer({ + port: serverPort, + authServerUrl: mockAs.issuerUrl + }); + + const scenario = new TokenAudienceValidationScenario({ + mockAuthServer: mockAs + }); + const url = `http://localhost:${serverPort}/mcp`; + + for (const version of ['2025-06-18', DRAFT_PROTOCOL_VERSION] as const) { + const checks = await scenario.run(testContext(url, version)); + expect(checks.map((c) => c.status)).toEqual([ + 'SUCCESS', + 'SUCCESS', + 'SUCCESS', + 'SUCCESS' + ]); + } + }, 30_000); + + it('passes all 4 checks against a compliant RFC 7662 introspection server', async () => { + const checks = await runAgainstExampleServer({ + authMode: 'introspect', + specVersion: '2025-11-25' + }); + + expect(checks.map((c) => c.status)).toEqual([ + 'SUCCESS', + 'SUCCESS', + 'SUCCESS', + 'SUCCESS' + ]); + expect(mockAs!.getCounters().introspectionRequests).toBeGreaterThan(0); + }, 30_000); + + it('auto-binds its own mock AS to a loopback port advertised in server PRM', async () => { + const freeAsPort = await getFreePort(); + const serverPort = await getFreePort(); + + // Start the server BEFORE the mock AS exists — it advertises + // http://localhost: in /.well-known/oauth-protected-resource. + serverProc = await startExampleServer({ + port: serverPort, + authServerUrl: `http://localhost:${freeAsPort}` + }); + + const scenario = new TokenAudienceValidationScenario(); + const checks = await scenario.run( + testContext(`http://localhost:${serverPort}/mcp`, '2025-11-25') + ); + + expect(checks.map((c) => c.status)).toEqual([ + 'SUCCESS', + 'SUCCESS', + 'SUCCESS', + 'SUCCESS' + ]); + }, 30_000); + + it('fails wrong-aud and missing-aud checks when server skips audience validation', async () => { + const checks = await runAgainstExampleServer({ + breakMode: 'skip-audience' + }); + + expect(checkById(checks, 'server-token-valid-accepted').status).toBe( + 'SUCCESS' + ); + expect(checkById(checks, 'server-token-audience-validation').status).toBe( + 'FAILURE' + ); + expect( + checkById(checks, 'server-token-missing-audience-rejected').status + ).toBe('FAILURE'); + expect(checkById(checks, 'server-token-expired-rejected').status).toBe( + 'SUCCESS' + ); + }, 30_000); + + it('fails only missing-aud check when server allows tokens without aud claim', async () => { + const checks = await runAgainstExampleServer({ + breakMode: 'allow-missing-audience' + }); + + expect(checkById(checks, 'server-token-valid-accepted').status).toBe( + 'SUCCESS' + ); + expect(checkById(checks, 'server-token-audience-validation').status).toBe( + 'SUCCESS' + ); + expect( + checkById(checks, 'server-token-missing-audience-rejected').status + ).toBe('FAILURE'); + expect(checkById(checks, 'server-token-expired-rejected').status).toBe( + 'SUCCESS' + ); + }, 30_000); + + it('fails expired-token check when server skips expiration validation', async () => { + const checks = await runAgainstExampleServer({ + breakMode: 'skip-expiration' + }); + + expect(checkById(checks, 'server-token-valid-accepted').status).toBe( + 'SUCCESS' + ); + expect(checkById(checks, 'server-token-audience-validation').status).toBe( + 'SUCCESS' + ); + expect( + checkById(checks, 'server-token-missing-audience-rejected').status + ).toBe('SUCCESS'); + expect(checkById(checks, 'server-token-expired-rejected').status).toBe( + 'FAILURE' + ); + }, 30_000); + + it('fails all checks without false positives against an unauthenticated server', async () => { + const checks = await runAgainstExampleServer({ breakMode: 'no-auth' }); + + const valid = checkById(checks, 'server-token-valid-accepted'); + expect(valid.status).toBe('FAILURE'); + expect(valid.details?.untestable).toBe(true); + expect(checkById(checks, 'server-token-audience-validation').status).toBe( + 'FAILURE' + ); + expect( + checkById(checks, 'server-token-missing-audience-rejected').status + ).toBe('FAILURE'); + expect(checkById(checks, 'server-token-expired-rejected').status).toBe( + 'FAILURE' + ); + }, 30_000); + + it('marks negative checks untestable (not SUCCESS) against a reject-all server', async () => { + const checks = await runAgainstExampleServer({ breakMode: 'reject-all' }); + + expect(checkById(checks, 'server-token-valid-accepted').status).toBe( + 'FAILURE' + ); + for (const id of [ + 'server-token-audience-validation', + 'server-token-missing-audience-rejected', + 'server-token-expired-rejected' + ]) { + const check = checkById(checks, id); + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBe(true); + } + }, 30_000); + + it('fails audience validation when server returns HTTP 403 instead of 401', async () => { + const checks = await runAgainstExampleServer({ + breakMode: 'wrong-status-403' + }); + + expect(checkById(checks, 'server-token-valid-accepted').status).toBe( + 'SUCCESS' + ); + const audCheck = checkById(checks, 'server-token-audience-validation'); + expect(audCheck.status).toBe('FAILURE'); + expect(audCheck.errorMessage).toContain('Expected HTTP 401'); + expect(audCheck.errorMessage).toContain('403'); + expect( + checkById(checks, 'server-token-missing-audience-rejected').status + ).toBe('SUCCESS'); + expect(checkById(checks, 'server-token-expired-rejected').status).toBe( + 'SUCCESS' + ); + }, 30_000); +}); diff --git a/src/scenarios/server/auth/token-audience-validation.ts b/src/scenarios/server/auth/token-audience-validation.ts new file mode 100644 index 00000000..32573c36 --- /dev/null +++ b/src/scenarios/server/auth/token-audience-validation.ts @@ -0,0 +1,751 @@ +/** + * Server-side Token Audience Validation conformance scenario (issue #78). + * + * Verifies that an MCP server acting as an OAuth 2.1 resource server validates + * presented JWT access tokens against its own intended audience (RFC 8707) and + * expiration time: + * 1. Valid token with `aud` matching the server URI -> accepted (HTTP 2xx) + * 2. Token with `aud` for a different server -> rejected (HTTP 401) + * 3. Token missing the `aud` claim -> rejected (HTTP 401) + * 4. Expired token -> rejected (HTTP 401) + * + * Runs a local mock Authorization Server serving RFC 8414 metadata + * (`/.well-known/oauth-authorization-server`), JWKS (`/jwks`), and RFC 7662 + * token introspection (`/introspect`), so servers validating via either JWKS + * or introspection can integrate without external infrastructure. + */ + +import { request } from 'undici'; +import { + ClientScenario, + ConformanceCheck, + DRAFT_PROTOCOL_VERSION, + SpecReference +} from '../../../types'; +import { + buildStandardHeaders, + withRequestMeta, + type RunContext +} from '../../../connection'; +import { untestableCheck } from '../../untestable'; +import { MockTokenAuthServer } from './mock-auth-server'; + +export const DEFAULT_MOCK_AS_PORT = 8091; + +const REQUEST_TIMEOUT_MS = 10_000; +const DISCOVERY_TIMEOUT_MS = 5_000; +const BODY_READ_TIMEOUT_MS = 2_000; + +const WRONG_AUDIENCE_PRIMARY = 'https://other-mcp-server.example.com/mcp'; +const WRONG_AUDIENCE_FALLBACK = 'https://different-mcp-server.example.com/mcp'; + +const SPEC_REF_TOKEN_HANDLING: SpecReference = { + id: 'MCP-Token-Handling', + url: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#token-handling' +}; + +const SPEC_REF_AUDIENCE_VALIDATION: SpecReference = { + id: 'MCP-Token-Audience-Validation', + url: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#token-audience-binding-and-validation' +}; + +const SPEC_REF_PRIVILEGE_RESTRICTION: SpecReference = { + id: 'MCP-Access-Token-Privilege-Restriction', + url: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#access-token-privilege-restriction' +}; + +const SPEC_REF_RFC_8707: SpecReference = { + id: 'RFC-8707-Resource-Indicators', + url: 'https://www.rfc-editor.org/rfc/rfc8707.html#section-2' +}; + +const VALID_ACCEPTED_REFS: SpecReference[] = [ + SPEC_REF_TOKEN_HANDLING, + SPEC_REF_AUDIENCE_VALIDATION +]; + +const AUDIENCE_VALIDATION_REFS: SpecReference[] = [ + SPEC_REF_TOKEN_HANDLING, + SPEC_REF_AUDIENCE_VALIDATION, + SPEC_REF_PRIVILEGE_RESTRICTION, + SPEC_REF_RFC_8707 +]; + +const EXPIRED_TOKEN_REFS: SpecReference[] = [SPEC_REF_TOKEN_HANDLING]; + +export interface TokenAudienceValidationOptions { + /** + * Optional pre-started mock Authorization Server (useful in automated tests + * where the server under test is started after binding an ephemeral AS port). + * When supplied, the caller owns its lifecycle and this scenario will not + * stop it. + */ + mockAuthServer?: MockTokenAuthServer; + /** Explicit TCP port for the scenario-managed mock AS. */ + mockAsPort?: number; + /** Explicit issuer URL for the scenario-managed mock AS. */ + mockAsIssuerUrl?: string; +} + +interface ProbePayload { + jsonrpc: '2.0'; + id: number; + method: string; + params: Record; +} + +interface ProbeResponse { + statusCode: number; + wwwAuthenticate?: string; + sessionId?: string; + bodySnippet?: string; +} + +interface LoopbackAsConfig { + host: string; + port: number; + issuerUrl: string; +} + +/** + * Strip any fragment from the server URL per RFC 8707 §2 to form the canonical + * resource identifier expected in the `aud` claim. + */ +function canonicalResourceUri(serverUrl: string): string { + const url = new URL(serverUrl); + url.hash = ''; + return url.href; +} + +/** + * Build a version-appropriate MCP JSON-RPC probe body: + * - 2025-x (stateful): `initialize` + * - 2026-07-28 / draft (stateless): `server/discover` with `_meta` envelope + */ +function buildProbeBody(specVersion: string): ProbePayload { + if (specVersion === DRAFT_PROTOCOL_VERSION) { + return { + jsonrpc: '2.0', + id: 1, + method: 'server/discover', + params: withRequestMeta({}, specVersion) + }; + } + return { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: specVersion, + capabilities: {}, + clientInfo: { + name: 'conformance-token-audience-test', + version: '1.0.0' + } + } + }; +} + +function getHeader( + headers: Record, + name: string +): string | undefined { + const value = headers[name.toLowerCase()]; + if (typeof value === 'string') return value; + if (Array.isArray(value) && value.length > 0) return value.join(', '); + return undefined; +} + +function isAcceptedStatus(statusCode: number): boolean { + return statusCode >= 200 && statusCode < 300; +} + +/** + * Abort and release an undici response body without surfacing an unhandled + * `UND_ERR_ABORTED` error event on the stream. + */ +function discardResponseBody( + body: Awaited>['body'] +): void { + body.on('error', () => {}); + body.destroy(); +} + +/** + * Safely read a short diagnostic body snippet without hanging on open SSE + * streams. Always consumes or destroys the response body to release sockets. + */ +async function readBoundedBodySnippet( + response: Awaited> +): Promise { + const contentType = + getHeader(response.headers, 'content-type')?.toLowerCase() ?? ''; + if (contentType.includes('text/event-stream')) { + discardResponseBody(response.body); + return undefined; + } + + let timer: NodeJS.Timeout | undefined; + try { + const text = await Promise.race([ + response.body.text(), + new Promise((resolve) => { + timer = setTimeout(() => { + discardResponseBody(response.body); + resolve(undefined); + }, BODY_READ_TIMEOUT_MS); + }) + ]); + if (text === undefined) return undefined; + return text.length > 300 ? `${text.slice(0, 300)}...` : text; + } catch { + discardResponseBody(response.body); + return undefined; + } finally { + if (timer) clearTimeout(timer); + } +} + +async function sendMcpProbe( + serverUrl: string, + specVersion: string, + bearerToken?: string +): Promise { + const probe = buildProbeBody(specVersion); + const extraHeaders: Record = { + 'MCP-Protocol-Version': specVersion + }; + if (bearerToken !== undefined) { + extraHeaders.Authorization = `Bearer ${bearerToken}`; + } + + const response = await request(serverUrl, { + method: 'POST', + headers: buildStandardHeaders(probe.method, probe.params, { + headers: extraHeaders + }), + body: JSON.stringify(probe), + headersTimeout: REQUEST_TIMEOUT_MS, + bodyTimeout: REQUEST_TIMEOUT_MS, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) + }); + + const bodySnippet = await readBoundedBodySnippet(response); + + return { + statusCode: response.statusCode, + wwwAuthenticate: getHeader(response.headers, 'www-authenticate'), + sessionId: getHeader(response.headers, 'mcp-session-id'), + bodySnippet + }; +} + +/** + * Best-effort cleanup for stateful sessions created during the valid-token + * probe so we don't leave open sessions on the server under test. + */ +async function closeStatefulSession( + serverUrl: string, + specVersion: string, + sessionId: string, + bearerToken: string +): Promise { + try { + const response = await request(serverUrl, { + method: 'DELETE', + headers: { + 'MCP-Protocol-Version': specVersion, + 'Mcp-Session-Id': sessionId, + Authorization: `Bearer ${bearerToken}` + }, + headersTimeout: DISCOVERY_TIMEOUT_MS, + bodyTimeout: DISCOVERY_TIMEOUT_MS, + signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS) + }); + discardResponseBody(response.body); + } catch { + // Best-effort cleanup only. + } +} + +/** + * Extract `resource_metadata` URL from a `WWW-Authenticate` header (RFC 9728). + */ +function extractResourceMetadataUrl( + wwwAuthenticate: string | undefined +): string | undefined { + if (!wwwAuthenticate) return undefined; + const quoted = /resource_metadata\s*=\s*"([^"]+)"/i.exec(wwwAuthenticate); + if (quoted?.[1]) return quoted[1]; + const unquoted = /resource_metadata\s*=\s*([^\s,]+)/i.exec(wwwAuthenticate); + return unquoted?.[1]; +} + +function parseLoopbackAuthServerUrl( + candidate: string +): LoopbackAsConfig | undefined { + try { + const parsed = new URL(candidate); + if (parsed.protocol !== 'http:') return undefined; + const hostname = parsed.hostname.toLowerCase(); + if (hostname !== 'localhost' && hostname !== '127.0.0.1') { + return undefined; + } + if (!parsed.port) return undefined; + if (parsed.pathname !== '' && parsed.pathname !== '/') return undefined; + const port = Number.parseInt(parsed.port, 10); + if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined; + return { + host: '127.0.0.1', + port, + issuerUrl: `${parsed.protocol}//${parsed.host}` + }; + } catch { + return undefined; + } +} + +/** + * Attempt to discover a loopback Authorization Server URL from the server's + * RFC 9728 Protected Resource Metadata so an operator who pointed their server + * at a local mock AS port needs no extra CLI/env configuration. + */ +async function discoverLoopbackAuthServerFromPrm( + serverUrl: string, + wwwAuthenticate: string | undefined +): Promise { + const parsedServer = new URL(serverUrl); + const candidates: string[] = []; + + const fromHeader = extractResourceMetadataUrl(wwwAuthenticate); + if (fromHeader) candidates.push(fromHeader); + + const normalizedPath = parsedServer.pathname.replace(/\/+$/, ''); + if (normalizedPath && normalizedPath !== '/') { + candidates.push( + `${parsedServer.origin}/.well-known/oauth-protected-resource${normalizedPath}` + ); + } + candidates.push( + `${parsedServer.origin}/.well-known/oauth-protected-resource` + ); + + const seen = new Set(); + for (const url of candidates) { + if (seen.has(url)) continue; + seen.add(url); + try { + const res = await request(url, { + method: 'GET', + headers: { Accept: 'application/json' }, + headersTimeout: DISCOVERY_TIMEOUT_MS, + bodyTimeout: DISCOVERY_TIMEOUT_MS, + signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS) + }); + if (res.statusCode !== 200) { + discardResponseBody(res.body); + continue; + } + const data = (await res.body.json()) as { + authorization_servers?: unknown; + }; + if (Array.isArray(data?.authorization_servers)) { + for (const entry of data.authorization_servers) { + if (typeof entry === 'string') { + const loopback = parseLoopbackAuthServerUrl(entry); + if (loopback) return loopback; + } + } + } + } catch { + // PRM discovery is best-effort for auto-configuring the mock AS port. + } + } + return undefined; +} + +function resolveEnvMockAsConfig(): LoopbackAsConfig | undefined { + const rawPort = process.env.MCP_CONFORMANCE_MOCK_AS_PORT; + if (!rawPort) return undefined; + const port = Number.parseInt(rawPort, 10); + if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined; + const issuerUrl = + process.env.MCP_CONFORMANCE_MOCK_AS_ISSUER?.replace(/\/+$/, '') || + `http://localhost:${port}`; + return { host: '127.0.0.1', port, issuerUrl }; +} + +export class TokenAudienceValidationScenario implements ClientScenario { + name = 'auth/token-audience-validation'; + readonly source = { introducedIn: '2025-06-18' } as const; + description = `Test server-side OAuth access token audience validation (RFC 8707 / OAuth 2.1). + +**Requirements:** +- Server **MUST** validate access tokens as an OAuth 2.1 resource server +- Server **MUST** accept valid tokens whose \`aud\` claim matches the server URI +- Server **MUST** validate that access tokens were issued specifically for it as the intended audience and reject tokens with a mismatched \`aud\` claim (HTTP 401) +- Server **MUST** reject tokens missing an \`aud\` claim (HTTP 401) +- Server **MUST** reject expired tokens (HTTP 401) + +**Server Setup:** +The scenario starts a local mock Authorization Server exposing: +- \`/.well-known/oauth-authorization-server\` (RFC 8414 metadata with \`jwks_uri\` and \`introspection_endpoint\`) +- \`/jwks\` (RS256 public key in JWKS format) +- \`/introspect\` (RFC 7662 token introspection) + +Configure the server under test to trust this mock AS (either via JWKS or token introspection) and validate \`aud\` against its own \`--url\`. The mock AS port is selected in order: +1. \`MCP_CONFORMANCE_MOCK_AS_PORT\` env var (optional \`MCP_CONFORMANCE_MOCK_AS_ISSUER\`) +2. Loopback URL advertised in the server's Protected Resource Metadata (\`authorization_servers[0]\`) +3. Default: \`http://localhost:${DEFAULT_MOCK_AS_PORT}\``; + + private readonly options: TokenAudienceValidationOptions; + + constructor(options: TokenAudienceValidationOptions = {}) { + this.options = options; + } + + async run(ctx: RunContext): Promise { + const { serverUrl, specVersion } = ctx; + const checks: ConformanceCheck[] = []; + const timestamp = new Date().toISOString(); + + const validAudience = canonicalResourceUri(serverUrl); + const wrongAudience = + validAudience === WRONG_AUDIENCE_PRIMARY + ? WRONG_AUDIENCE_FALLBACK + : WRONG_AUDIENCE_PRIMARY; + + // Step 0: Unauthenticated probe to detect servers without auth and to + // read WWW-Authenticate / PRM metadata for automatic mock AS port binding. + let unauthenticatedAccepted = false; + let unauthStatusCode: number | undefined; + let unauthWwwAuthenticate: string | undefined; + + try { + const unauthRes = await sendMcpProbe(serverUrl, specVersion); + unauthStatusCode = unauthRes.statusCode; + unauthWwwAuthenticate = unauthRes.wwwAuthenticate; + unauthenticatedAccepted = isAcceptedStatus(unauthRes.statusCode); + if ( + unauthenticatedAccepted && + specVersion !== DRAFT_PROTOCOL_VERSION && + unauthRes.sessionId + ) { + await closeStatefulSession( + serverUrl, + specVersion, + unauthRes.sessionId, + '' + ); + } + } catch { + // Connection/timeout errors will be surfaced cleanly by the checks below. + } + + // Step 1: Resolve or start the local mock Authorization Server. + let mockAs: MockTokenAuthServer; + let ownsMockAs = false; + + if (this.options.mockAuthServer) { + mockAs = this.options.mockAuthServer; + } else { + let config: LoopbackAsConfig; + if (this.options.mockAsPort !== undefined) { + const port = this.options.mockAsPort; + config = { + host: '127.0.0.1', + port, + issuerUrl: + this.options.mockAsIssuerUrl?.replace(/\/+$/, '') || + `http://localhost:${port}` + }; + } else { + const fromEnv = resolveEnvMockAsConfig(); + const fromPrm = + fromEnv ?? + (await discoverLoopbackAuthServerFromPrm( + serverUrl, + unauthWwwAuthenticate + )); + config = fromPrm ?? { + host: '127.0.0.1', + port: DEFAULT_MOCK_AS_PORT, + issuerUrl: + process.env.MCP_CONFORMANCE_MOCK_AS_ISSUER?.replace(/\/+$/, '') || + `http://localhost:${DEFAULT_MOCK_AS_PORT}` + }; + } + + mockAs = new MockTokenAuthServer({ + host: config.host, + port: config.port, + issuerUrl: config.issuerUrl + }); + + try { + await mockAs.start(); + ownsMockAs = true; + } catch (error) { + const reason = `Failed to start mock authorization server on ${config.host}:${config.port}: ${error instanceof Error ? error.message : String(error)}`; + return [ + untestableCheck( + 'server-token-valid-accepted', + 'TokenValidAccepted', + 'Server accepts a valid access token whose aud claim matches its own URI', + reason, + VALID_ACCEPTED_REFS + ), + untestableCheck( + 'server-token-audience-validation', + 'TokenAudienceValidation', + 'Server rejects an access token issued for a different audience with HTTP 401', + reason, + AUDIENCE_VALIDATION_REFS + ), + untestableCheck( + 'server-token-missing-audience-rejected', + 'TokenMissingAudienceRejected', + 'Server rejects an access token missing the aud claim with HTTP 401', + reason, + AUDIENCE_VALIDATION_REFS + ), + untestableCheck( + 'server-token-expired-rejected', + 'TokenExpiredRejected', + 'Server rejects an expired access token with HTTP 401', + reason, + EXPIRED_TOKEN_REFS + ) + ]; + } + } + + try { + const issuerUrl = mockAs.issuerUrl; + let validTokenAccepted = false; + + // Check 1: Valid token with `aud` matching this server's URI -> accepted + if (unauthenticatedAccepted) { + checks.push( + untestableCheck( + 'server-token-valid-accepted', + 'TokenValidAccepted', + 'Server accepts a valid access token whose aud claim matches its own URI', + `Server accepted an unauthenticated request (HTTP ${unauthStatusCode}); authentication does not appear to be enforced`, + VALID_ACCEPTED_REFS + ) + ); + } else { + try { + const validToken = await mockAs.mintToken({ + audience: validAudience + }); + const res = await sendMcpProbe(serverUrl, specVersion, validToken); + const accepted = isAcceptedStatus(res.statusCode); + validTokenAccepted = accepted; + + if ( + accepted && + specVersion !== DRAFT_PROTOCOL_VERSION && + res.sessionId + ) { + await closeStatefulSession( + serverUrl, + specVersion, + res.sessionId, + validToken + ); + } + + checks.push({ + id: 'server-token-valid-accepted', + name: 'TokenValidAccepted', + description: + 'Server accepts a valid access token whose aud claim matches its own URI', + status: accepted ? 'SUCCESS' : 'FAILURE', + timestamp, + specReferences: VALID_ACCEPTED_REFS, + errorMessage: accepted + ? undefined + : `Expected HTTP 2xx for valid token with aud="${validAudience}", got ${res.statusCode}. Ensure the server is configured to trust the mock authorization server at ${issuerUrl}.`, + details: { + issuer: issuerUrl, + audience: validAudience, + statusCode: res.statusCode, + wwwAuthenticate: res.wwwAuthenticate, + mockAsRequests: mockAs.getCounters() + } + }); + } catch (error) { + checks.push({ + id: 'server-token-valid-accepted', + name: 'TokenValidAccepted', + description: + 'Server accepts a valid access token whose aud claim matches its own URI', + status: 'FAILURE', + timestamp, + specReferences: VALID_ACCEPTED_REFS, + errorMessage: `Request failed: ${error instanceof Error ? error.message : String(error)}`, + details: { + issuer: issuerUrl, + audience: validAudience + } + }); + } + } + + // Helper for the three negative token checks (wrong aud, missing aud, expired). + // A 401 only proves the server enforced the specific claim when the + // positive valid-token probe succeeded; otherwise a reject-all server or + // misconfigured AS would falsely score green (#248 / #483). + const runNegativeProbe = async (params: { + id: string; + name: string; + description: string; + token: string; + caseLabel: string; + specReferences: SpecReference[]; + extraDetails: Record; + }): Promise => { + try { + const res = await sendMcpProbe(serverUrl, specVersion, params.token); + const rejectedWith401 = res.statusCode === 401; + + if ( + isAcceptedStatus(res.statusCode) && + specVersion !== DRAFT_PROTOCOL_VERSION && + res.sessionId + ) { + await closeStatefulSession( + serverUrl, + specVersion, + res.sessionId, + params.token + ); + } + + if (!rejectedWith401) { + checks.push({ + id: params.id, + name: params.name, + description: params.description, + status: 'FAILURE', + timestamp, + specReferences: params.specReferences, + errorMessage: `Expected HTTP 401 for ${params.caseLabel}, got ${res.statusCode}`, + details: { + issuer: issuerUrl, + statusCode: res.statusCode, + wwwAuthenticate: res.wwwAuthenticate, + ...params.extraDetails + } + }); + return; + } + + if (!validTokenAccepted) { + checks.push( + untestableCheck( + params.id, + params.name, + params.description, + `Server returned HTTP 401 for ${params.caseLabel}, but did not accept the valid token with matching audience (aud="${validAudience}"), so rejection cannot be attributed to ${params.caseLabel} validation`, + params.specReferences + ) + ); + return; + } + + checks.push({ + id: params.id, + name: params.name, + description: params.description, + status: 'SUCCESS', + timestamp, + specReferences: params.specReferences, + details: { + issuer: issuerUrl, + statusCode: res.statusCode, + wwwAuthenticate: res.wwwAuthenticate, + ...params.extraDetails + } + }); + } catch (error) { + checks.push({ + id: params.id, + name: params.name, + description: params.description, + status: 'FAILURE', + timestamp, + specReferences: params.specReferences, + errorMessage: `Request failed: ${error instanceof Error ? error.message : String(error)}`, + details: { + issuer: issuerUrl, + ...params.extraDetails + } + }); + } + }; + + // Check 2: Token with `aud` for a different server -> rejected (401) + const wrongAudToken = await mockAs.mintToken({ + audience: wrongAudience + }); + await runNegativeProbe({ + id: 'server-token-audience-validation', + name: 'TokenAudienceValidation', + description: + 'Server rejects an access token issued for a different audience with HTTP 401', + token: wrongAudToken, + caseLabel: `token with wrong aud claim ("${wrongAudience}")`, + specReferences: AUDIENCE_VALIDATION_REFS, + extraDetails: { + expectedAudience: validAudience, + sentAudience: wrongAudience + } + }); + + // Check 3: Token with missing `aud` claim -> rejected (401) + const missingAudToken = await mockAs.mintToken({ + omitAud: true + }); + await runNegativeProbe({ + id: 'server-token-missing-audience-rejected', + name: 'TokenMissingAudienceRejected', + description: + 'Server rejects an access token missing the aud claim with HTTP 401', + token: missingAudToken, + caseLabel: 'token with missing aud claim', + specReferences: AUDIENCE_VALIDATION_REFS, + extraDetails: { + expectedAudience: validAudience, + sentAudience: null + } + }); + + // Check 4: Expired token (with matching `aud`) -> rejected (401) + const expiredToken = await mockAs.mintToken({ + audience: validAudience, + expired: true + }); + await runNegativeProbe({ + id: 'server-token-expired-rejected', + name: 'TokenExpiredRejected', + description: 'Server rejects an expired access token with HTTP 401', + token: expiredToken, + caseLabel: 'expired token', + specReferences: EXPIRED_TOKEN_REFS, + extraDetails: { + audience: validAudience, + expired: true + } + }); + + return checks; + } finally { + if (ownsMockAs) { + await mockAs.stop(); + } + } + } +}