From cc6f4f32205982da1a1b05e28a52aa2a6764873f Mon Sep 17 00:00:00 2001 From: KenTandrian Date: Fri, 27 Nov 2026 21:08:19 +0700 Subject: [PATCH 1/3] feat(api): add MCP OAuth CIMD verification, SSRF guard, and auth code storage Implement SSRF-protected client metadata resolution, RFC 8252 loopback redirect URI validation, and single-use Redis-backed authorization code storage. --- .../oauth-authorization-code.interface.ts | 9 + .../oauth-client-metadata.interface.ts | 8 + .../oauth/oauth-client.service.spec.ts | 228 +++++++++++++ .../endpoints/oauth/oauth-client.service.ts | 214 ++++++++++++ .../oauth/oauth-storage.service.spec.ts | 108 ++++++ .../endpoints/oauth/oauth-storage.service.ts | 49 +++ .../src/app/endpoints/oauth/oauth.module.ts | 7 +- apps/api/src/helper/ssrf-guard.helper.spec.ts | 310 ++++++++++++++++++ apps/api/src/helper/ssrf-guard.helper.ts | 190 +++++++++++ 9 files changed, 1122 insertions(+), 1 deletion(-) create mode 100644 apps/api/src/app/endpoints/oauth/interfaces/oauth-authorization-code.interface.ts create mode 100644 apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts create mode 100644 apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts create mode 100644 apps/api/src/app/endpoints/oauth/oauth-client.service.ts create mode 100644 apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts create mode 100644 apps/api/src/app/endpoints/oauth/oauth-storage.service.ts create mode 100644 apps/api/src/helper/ssrf-guard.helper.spec.ts create mode 100644 apps/api/src/helper/ssrf-guard.helper.ts diff --git a/apps/api/src/app/endpoints/oauth/interfaces/oauth-authorization-code.interface.ts b/apps/api/src/app/endpoints/oauth/interfaces/oauth-authorization-code.interface.ts new file mode 100644 index 0000000000..d46a4ac3d3 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/interfaces/oauth-authorization-code.interface.ts @@ -0,0 +1,9 @@ +export interface OAuthAuthorizationCode { + clientId: string; + codeChallenge: string; + codeChallengeMethod: 'S256'; + redirectUri: string; + resource: string; + scope?: string; + userId: string; +} diff --git a/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts b/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts new file mode 100644 index 0000000000..920bf8e10b --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts @@ -0,0 +1,8 @@ +export interface OAuthClientMetadata { + client_id: string; + client_name: string; + grant_types: string[]; + redirect_uris: string[]; + response_types: string[]; + token_endpoint_auth_method?: string; +} diff --git a/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts b/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts new file mode 100644 index 0000000000..1729f47a65 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts @@ -0,0 +1,228 @@ +import * as ssrfGuardHelper from '@ghostfolio/api/helper/ssrf-guard.helper'; +import { RedisCacheService } from '@ghostfolio/api/services/redis-cache/redis-cache.service'; + +import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'; +import ms from 'ms'; + +import { OAuthClientMetadata } from './interfaces/oauth-client-metadata.interface'; +import { OAuthClientService } from './oauth-client.service'; + +describe('OAuthClientService', () => { + let redisCacheService: jest.Mocked< + Pick + >; + let service: OAuthClientService; + + const clientId = 'https://client.example.com/oauth/client.json'; + + const validMetadataResponse = { + client_id: clientId, + client_name: 'Example MCP Client', + redirect_uris: [ + 'https://client.example.com/callback', + 'http://127.0.0.1/callback', + 'http://localhost/callback' + ] + }; + + beforeEach(() => { + jest.restoreAllMocks(); + + redisCacheService = { + get: jest.fn().mockResolvedValue(undefined), + remove: jest.fn().mockResolvedValue(true), + set: jest.fn().mockResolvedValue(undefined) + }; + + service = new OAuthClientService( + redisCacheService as unknown as RedisCacheService + ); + }); + + describe('getClient', () => { + it('fetches, validates, applies defaults, and caches client metadata', async () => { + const fetchSpy = jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockResolvedValueOnce(validMetadataResponse); + + const client = await service.getClient(clientId); + + expect(client).toEqual({ + client_id: clientId, + client_name: 'Example MCP Client', + grant_types: ['authorization_code'], + redirect_uris: validMetadataResponse.redirect_uris, + response_types: ['code'] + }); + expect(fetchSpy).toHaveBeenCalledWith(clientId); + expect(redisCacheService.set).toHaveBeenCalledWith( + `oauth:client:${clientId}`, + JSON.stringify(client), + ms('1 hour') + ); + }); + + it('returns cached client metadata without fetching externally', async () => { + const cachedClient: OAuthClientMetadata = { + client_id: clientId, + client_name: 'Cached Client', + grant_types: ['authorization_code'], + redirect_uris: ['https://client.example.com/callback'], + response_types: ['code'] + }; + redisCacheService.get.mockResolvedValueOnce(JSON.stringify(cachedClient)); + const fetchSpy = jest.spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard'); + + const client = await service.getClient(clientId); + + expect(client).toEqual(cachedClient); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('rejects client_id with non-HTTPS scheme or blocked IP before cache lookup', async () => { + await expect( + service.getClient('http://client.example.com/client.json') + ).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + expect(redisCacheService.get).not.toHaveBeenCalled(); + }); + + it('rejects client_id containing a URL fragment', async () => { + await expect( + service.getClient(`${clientId}#section`) + ).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + expect(redisCacheService.get).not.toHaveBeenCalled(); + }); + + it('throws invalid_client_metadata when document client_id does not match URL', async () => { + jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockResolvedValueOnce({ + ...validMetadataResponse, + client_id: 'https://other.example.com/client.json' + }); + + await expect(service.getClient(clientId)).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + expect(redisCacheService.set).not.toHaveBeenCalled(); + }); + + it('throws invalid_client_metadata when client_name is missing or empty', async () => { + jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockResolvedValueOnce({ + ...validMetadataResponse, + client_name: ' ' + }); + + await expect(service.getClient(clientId)).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + }); + + it('throws invalid_client_metadata when redirect_uris is empty or invalid', async () => { + jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockResolvedValueOnce({ + ...validMetadataResponse, + redirect_uris: ['not-a-valid-uri'] + }); + + await expect(service.getClient(clientId)).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + }); + + it('propagates timeout errors from fetchJsonWithSsrfGuard as OAuthError', async () => { + jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockRejectedValueOnce( + new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Failed to fetch JSON from ${clientId}` + ) + ); + + await expect(service.getClient(clientId)).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + }); + }); + + describe('validateRedirectUri', () => { + const client: OAuthClientMetadata = { + client_id: clientId, + client_name: 'Example MCP Client', + grant_types: ['authorization_code'], + redirect_uris: [ + 'https://client.example.com/callback', + 'http://127.0.0.1/callback', + 'http://[::1]/callback', + 'http://localhost/callback' + ], + response_types: ['code'] + }; + + it('accepts exact redirect_uri matches', () => { + expect( + service.validateRedirectUri( + client, + 'https://client.example.com/callback' + ) + ).toBe(true); + }); + + it('rejects unregistered redirect_uris', () => { + expect( + service.validateRedirectUri(client, 'https://evil.example.com/callback') + ).toBe(false); + expect( + service.validateRedirectUri( + client, + 'https://client.example.com/other-path' + ) + ).toBe(false); + }); + + it('allows arbitrary ports on registered loopback redirect_uris (RFC 8252 ยง7.3)', () => { + expect( + service.validateRedirectUri(client, 'http://127.0.0.1:54321/callback') + ).toBe(true); + expect( + service.validateRedirectUri(client, 'http://[::1]:54321/callback') + ).toBe(true); + expect( + service.validateRedirectUri(client, 'http://localhost:8080/callback') + ).toBe(true); + }); + + it('rejects loopback redirect_uris with mismatched path, query, or scheme', () => { + expect( + service.validateRedirectUri(client, 'http://127.0.0.1:54321/other') + ).toBe(false); + expect( + service.validateRedirectUri( + client, + 'http://127.0.0.1:54321/callback?extra=1' + ) + ).toBe(false); + expect( + service.validateRedirectUri(client, 'https://127.0.0.1:54321/callback') + ).toBe(false); + }); + + it('rejects malformed redirect_uris and URIs containing fragments', () => { + expect(service.validateRedirectUri(client, 'not-a-uri')).toBe(false); + expect( + service.validateRedirectUri( + client, + 'https://client.example.com/callback#frag' + ) + ).toBe(false); + }); + }); +}); diff --git a/apps/api/src/app/endpoints/oauth/oauth-client.service.ts b/apps/api/src/app/endpoints/oauth/oauth-client.service.ts new file mode 100644 index 0000000000..fface1d564 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-client.service.ts @@ -0,0 +1,214 @@ +import { + assertSafeExternalUrl, + fetchJsonWithSsrfGuard +} from '@ghostfolio/api/helper/ssrf-guard.helper'; +import { RedisCacheService } from '@ghostfolio/api/services/redis-cache/redis-cache.service'; + +import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'; +import { Injectable } from '@nestjs/common'; +import ms from 'ms'; + +import { OAuthClientMetadata } from './interfaces/oauth-client-metadata.interface'; + +const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', '[::1]', 'localhost']); + +@Injectable() +export class OAuthClientService { + private static readonly CACHE_KEY_PREFIX = 'oauth:client:'; + private static readonly CACHE_TTL_MS = ms('1 hour'); + + public constructor(private readonly redisCacheService: RedisCacheService) {} + + public async getClient(clientId: string): Promise { + const parsedClientUrl = assertSafeExternalUrl(clientId); + + if (parsedClientUrl.hash) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client ID URL must not contain a fragment' + ); + } + + const cacheKey = `${OAuthClientService.CACHE_KEY_PREFIX}${clientId}`; + const cached = await this.redisCacheService.get(cacheKey); + + if (cached) { + try { + return JSON.parse(cached) as OAuthClientMetadata; + } catch { + // Ignore corrupted cache entry and refetch + } + } + + const rawMetadata = await fetchJsonWithSsrfGuard(clientId); + const metadata = this.parseClientMetadata(rawMetadata, clientId); + + await this.redisCacheService.set( + cacheKey, + JSON.stringify(metadata), + OAuthClientService.CACHE_TTL_MS + ); + + return metadata; + } + + public validateRedirectUri( + client: OAuthClientMetadata, + redirectUri: string + ): boolean { + let requestedUrl: URL; + + try { + requestedUrl = new URL(redirectUri); + } catch { + return false; + } + + if (requestedUrl.hash) { + return false; + } + + return client.redirect_uris.some((registeredUri) => { + if (registeredUri === redirectUri) { + return true; + } + + return this.matchesLoopbackRedirectUri(registeredUri, requestedUrl); + }); + } + + private matchesLoopbackRedirectUri( + registeredUri: string, + requestedUrl: URL + ): boolean { + if ( + requestedUrl.protocol !== 'http:' || + !LOOPBACK_HOSTNAMES.has(requestedUrl.hostname) + ) { + return false; + } + + let registeredUrl: URL; + + try { + registeredUrl = new URL(registeredUri); + } catch { + return false; + } + + return ( + registeredUrl.protocol === 'http:' && + !registeredUrl.hash && + registeredUrl.hostname === requestedUrl.hostname && + registeredUrl.pathname === requestedUrl.pathname && + registeredUrl.search === requestedUrl.search + ); + } + + private parseClientMetadata( + raw: unknown, + expectedClientId: string + ): OAuthClientMetadata { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata must be a JSON object' + ); + } + + const data = raw as Record; + + if (data.client_id !== expectedClientId) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata client_id does not match requested client_id' + ); + } + + if ( + typeof data.client_name !== 'string' || + data.client_name.trim().length === 0 + ) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata must include a non-empty client_name' + ); + } + + if ( + !Array.isArray(data.redirect_uris) || + data.redirect_uris.length === 0 || + !data.redirect_uris.every((uri) => this.isValidRedirectUri(uri)) + ) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata must include a non-empty array of valid redirect_uris' + ); + } + + const grantTypes = + data.grant_types === undefined + ? ['authorization_code'] + : this.parseStringArray(data.grant_types, 'grant_types'); + + const responseTypes = + data.response_types === undefined + ? ['code'] + : this.parseStringArray(data.response_types, 'response_types'); + + let tokenEndpointAuthMethod: string | undefined; + + if (data.token_endpoint_auth_method !== undefined) { + if ( + typeof data.token_endpoint_auth_method !== 'string' || + data.token_endpoint_auth_method.trim().length === 0 + ) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata token_endpoint_auth_method must be a non-empty string' + ); + } + + tokenEndpointAuthMethod = data.token_endpoint_auth_method; + } + + return { + client_id: data.client_id, + client_name: data.client_name, + grant_types: grantTypes, + redirect_uris: data.redirect_uris, + response_types: responseTypes, + ...(tokenEndpointAuthMethod !== undefined + ? { token_endpoint_auth_method: tokenEndpointAuthMethod } + : {}) + }; + } + + private isValidRedirectUri(uri: unknown): uri is string { + if (typeof uri !== 'string') { + return false; + } + + try { + const parsed = new URL(uri); + return !parsed.hash; + } catch { + return false; + } + } + + private parseStringArray(value: unknown, fieldName: string): string[] { + if ( + !Array.isArray(value) || + value.length === 0 || + !value.every((item) => typeof item === 'string' && item.trim().length > 0) + ) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Client metadata ${fieldName} must be a non-empty array of strings` + ); + } + + return value as string[]; + } +} diff --git a/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts b/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts new file mode 100644 index 0000000000..0f1ddce5a2 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts @@ -0,0 +1,108 @@ +import { RedisCacheService } from '@ghostfolio/api/services/redis-cache/redis-cache.service'; + +import ms from 'ms'; + +import { OAuthAuthorizationCode } from './interfaces/oauth-authorization-code.interface'; +import { OAuthStorageService } from './oauth-storage.service'; + +describe('OAuthStorageService', () => { + let store: Map; + let redisCacheService: jest.Mocked< + Pick + >; + let service: OAuthStorageService; + + const sampleAuthCode: OAuthAuthorizationCode = { + clientId: 'https://client.example.com/client.json', + codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + codeChallengeMethod: 'S256', + redirectUri: 'https://client.example.com/callback', + resource: 'https://ghostfol.io/mcp', + scope: 'mcp:read', + userId: 'user-123' + }; + + beforeEach(() => { + store = new Map(); + + redisCacheService = { + get: jest.fn((key: string) => { + const entry = store.get(key); + + if (!entry) { + return Promise.resolve(undefined); + } + + if (Date.now() >= entry.expiresAt) { + store.delete(key); + return Promise.resolve(undefined); + } + + return Promise.resolve(entry.value); + }), + remove: jest.fn((key: string) => { + return Promise.resolve(store.delete(key)); + }), + set: jest.fn((key: string, value: string, ttl?: number) => { + store.set(key, { + expiresAt: Date.now() + (ttl ?? ms('5 minutes')), + value + }); + return Promise.resolve(value); + }) + }; + + service = new OAuthStorageService( + redisCacheService as unknown as RedisCacheService + ); + }); + + it('stores authorization code with oauth:code: prefix and default 5-minute TTL', async () => { + await service.storeAuthorizationCode('abc123', sampleAuthCode); + + expect(redisCacheService.set).toHaveBeenCalledWith( + 'oauth:code:abc123', + JSON.stringify(sampleAuthCode), + ms('5 minutes') + ); + }); + + it('consumes authorization code once and returns null on second consumption', async () => { + await service.storeAuthorizationCode('single-use-code', sampleAuthCode); + + const first = await service.consumeAuthorizationCode('single-use-code'); + const second = await service.consumeAuthorizationCode('single-use-code'); + + expect(first).toEqual(sampleAuthCode); + expect(second).toBeNull(); + expect(redisCacheService.remove).toHaveBeenCalledWith( + 'oauth:code:single-use-code' + ); + }); + + it('returns null when consuming a non-existent code', async () => { + const result = await service.consumeAuthorizationCode('missing-code'); + + expect(result).toBeNull(); + expect(redisCacheService.remove).not.toHaveBeenCalled(); + }); + + it('returns null after the authorization code TTL expires', async () => { + jest.useFakeTimers(); + + try { + await service.storeAuthorizationCode( + 'expiring-code', + sampleAuthCode, + 1000 + ); + + jest.advanceTimersByTime(1001); + + const result = await service.consumeAuthorizationCode('expiring-code'); + expect(result).toBeNull(); + } finally { + jest.useRealTimers(); + } + }); +}); diff --git a/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts b/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts new file mode 100644 index 0000000000..59490061ba --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts @@ -0,0 +1,49 @@ +import { RedisCacheService } from '@ghostfolio/api/services/redis-cache/redis-cache.service'; + +import { Injectable } from '@nestjs/common'; +import ms from 'ms'; + +import { OAuthAuthorizationCode } from './interfaces/oauth-authorization-code.interface'; + +@Injectable() +export class OAuthStorageService { + private static readonly CODE_KEY_PREFIX = 'oauth:code:'; + private static readonly DEFAULT_TTL_MS = ms('5 minutes'); + + public constructor(private readonly redisCacheService: RedisCacheService) {} + + public async storeAuthorizationCode( + code: string, + data: OAuthAuthorizationCode, + ttlMs: number = OAuthStorageService.DEFAULT_TTL_MS + ): Promise { + await this.redisCacheService.set( + this.getCodeKey(code), + JSON.stringify(data), + ttlMs + ); + } + + public async consumeAuthorizationCode( + code: string + ): Promise { + const key = this.getCodeKey(code); + const raw = await this.redisCacheService.get(key); + + if (!raw) { + return null; + } + + await this.redisCacheService.remove(key); + + try { + return JSON.parse(raw) as OAuthAuthorizationCode; + } catch { + return null; + } + } + + private getCodeKey(code: string): string { + return `${OAuthStorageService.CODE_KEY_PREFIX}${code}`; + } +} diff --git a/apps/api/src/app/endpoints/oauth/oauth.module.ts b/apps/api/src/app/endpoints/oauth/oauth.module.ts index b025ac5c45..9a6d329a39 100644 --- a/apps/api/src/app/endpoints/oauth/oauth.module.ts +++ b/apps/api/src/app/endpoints/oauth/oauth.module.ts @@ -1,11 +1,16 @@ import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; +import { RedisCacheModule } from '@ghostfolio/api/services/redis-cache/redis-cache.module'; import { Module } from '@nestjs/common'; +import { OAuthClientService } from './oauth-client.service'; import { OAuthMetadataController } from './oauth-metadata.controller'; +import { OAuthStorageService } from './oauth-storage.service'; @Module({ controllers: [OAuthMetadataController], - imports: [ConfigurationModule] + exports: [OAuthClientService, OAuthStorageService], + imports: [ConfigurationModule, RedisCacheModule], + providers: [OAuthClientService, OAuthStorageService] }) export class OAuthModule {} diff --git a/apps/api/src/helper/ssrf-guard.helper.spec.ts b/apps/api/src/helper/ssrf-guard.helper.spec.ts new file mode 100644 index 0000000000..36bc84be4b --- /dev/null +++ b/apps/api/src/helper/ssrf-guard.helper.spec.ts @@ -0,0 +1,310 @@ +import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'; +import { lookup as dnsLookup } from 'node:dns'; +import { LookupFunction } from 'node:net'; +import { Agent, fetch as undiciFetch, Response } from 'undici'; + +import { + assertSafeExternalUrl, + fetchJsonWithSsrfGuard, + isBlockedIp +} from './ssrf-guard.helper'; + +jest.mock('node:dns', () => ({ + lookup: jest.fn() +})); + +jest.mock('undici', () => ({ + Agent: jest.fn().mockImplementation(() => ({})), + fetch: jest.fn() +})); + +const agentOptions = jest.mocked(Agent).mock.calls[0]?.[0] as { + connect?: { lookup?: LookupFunction }; +}; +const capturedLookup = agentOptions.connect.lookup; + +const dnsLookupMock = dnsLookup as unknown as jest.Mock< + void, + [ + string, + unknown, + ( + err: NodeJS.ErrnoException | null, + address: string | { address: string; family: number }[], + family?: number + ) => void + ] +>; + +function createMockResponse(bodyText: string, ok = true, status = 200) { + const cancel = jest.fn(); + let consumed = false; + + const body = { + cancel, + [Symbol.asyncIterator]() { + return { + next() { + if (consumed) { + return Promise.resolve({ done: true as const, value: undefined }); + } + + consumed = true; + + return Promise.resolve({ + done: false as const, + value: Buffer.from(bodyText, 'utf8') + }); + } + }; + } + }; + + return { + cancel, + response: { + body, + ok, + status, + statusText: ok ? 'OK' : 'Bad Request' + } as unknown as Response + }; +} + +describe('isBlockedIp', () => { + it('allows public IPv4 addresses', () => { + expect(isBlockedIp('8.8.8.8')).toBe(false); + expect(isBlockedIp('1.1.1.1')).toBe(false); + expect(isBlockedIp('93.184.216.34')).toBe(false); + }); + + it('allows public IPv6 addresses', () => { + expect(isBlockedIp('2606:4700:4700::1111')).toBe(false); + expect(isBlockedIp('2001:4860:4860::8888')).toBe(false); + }); + + it('blocks private IPv4 ranges (RFC 1918)', () => { + expect(isBlockedIp('10.0.0.1')).toBe(true); + expect(isBlockedIp('10.255.255.255')).toBe(true); + expect(isBlockedIp('172.16.0.1')).toBe(true); + expect(isBlockedIp('172.31.255.255')).toBe(true); + expect(isBlockedIp('192.168.0.1')).toBe(true); + expect(isBlockedIp('192.168.255.255')).toBe(true); + }); + + it('blocks loopback, link-local, cloud metadata, and CGNAT IPv4 ranges', () => { + expect(isBlockedIp('0.0.0.0')).toBe(true); + expect(isBlockedIp('127.0.0.1')).toBe(true); + expect(isBlockedIp('127.0.0.2')).toBe(true); + expect(isBlockedIp('169.254.169.254')).toBe(true); + expect(isBlockedIp('169.254.0.1')).toBe(true); + expect(isBlockedIp('100.64.0.1')).toBe(true); + expect(isBlockedIp('100.127.255.254')).toBe(true); + expect(isBlockedIp('224.0.0.1')).toBe(true); + expect(isBlockedIp('240.0.0.1')).toBe(true); + }); + + it('blocks loopback, ULA, link-local, and multicast IPv6 ranges', () => { + expect(isBlockedIp('::')).toBe(true); + expect(isBlockedIp('::1')).toBe(true); + expect(isBlockedIp('fc00::1')).toBe(true); + expect(isBlockedIp('fd12:3456:789a::1')).toBe(true); + expect(isBlockedIp('fe80::1')).toBe(true); + expect(isBlockedIp('ff02::1')).toBe(true); + }); + + it('blocks invalid IP strings', () => { + expect(isBlockedIp('')).toBe(true); + expect(isBlockedIp('example.com')).toBe(true); + expect(isBlockedIp('999.999.999.999')).toBe(true); + }); +}); + +describe('assertSafeExternalUrl', () => { + it('allows a valid HTTPS URL', () => { + const url = assertSafeExternalUrl('https://example.com'); + expect(url).toEqual(new URL('https://example.com')); + }); + + it('rejects malformed URLs', () => { + expect(() => assertSafeExternalUrl('not-a-url')).toThrow(OAuthError); + }); + + it('rejects non-HTTPS schemes', () => { + expect(() => + assertSafeExternalUrl('http://example.com/client.json') + ).toThrow(OAuthError); + expect(() => assertSafeExternalUrl('file:///etc/passwd')).toThrow( + OAuthError + ); + }); + + it('rejects URLs containing credentials', () => { + expect(() => + assertSafeExternalUrl('https://user:pass@example.com/client.json') + ).toThrow(OAuthError); + }); + + it('rejects blocked IP literals', () => { + expect(() => + assertSafeExternalUrl('https://127.0.0.1/client.json') + ).toThrow(OAuthError); + expect(() => assertSafeExternalUrl('https://10.0.0.1/client.json')).toThrow( + OAuthError + ); + expect(() => + assertSafeExternalUrl('https://192.168.1.1/client.json') + ).toThrow(OAuthError); + expect(() => + assertSafeExternalUrl('https://169.254.169.254/latest') + ).toThrow(OAuthError); + expect(() => assertSafeExternalUrl('https://[::1]/client.json')).toThrow( + OAuthError + ); + }); + + it('allows public IP literals', () => { + const url = assertSafeExternalUrl('https://8.8.8.8/client.json'); + expect(url).toEqual(new URL('https://8.8.8.8/client.json')); + }); +}); + +describe('ssrfSafeLookup', () => { + beforeEach(() => { + dnsLookupMock.mockReset(); + }); + + it('allows hostnames resolving to public IPs', (done) => { + dnsLookupMock.mockImplementationOnce((_hostname, _options, callback) => { + callback(null, '8.8.8.8', 4); + }); + + capturedLookup('example.com', {}, (err, address, family) => { + expect(err).toBeNull(); + expect(address).toBe('8.8.8.8'); + expect(family).toBe(4); + done(); + }); + }); + + it('blocks hostnames resolving to private or metadata IPs', (done) => { + dnsLookupMock.mockImplementationOnce((_hostname, _options, callback) => { + callback(null, '169.254.169.254', 4); + }); + + capturedLookup('evil.example.com', {}, (err) => { + expect(err).toBeInstanceOf(OAuthError); + expect((err as unknown as OAuthError).code).toBe( + OAuthErrorCode.InvalidClientMetadata + ); + done(); + }); + }); + + it('blocks when any resolved address in an array is blocked', (done) => { + dnsLookupMock.mockImplementationOnce((_hostname, _options, callback) => { + callback( + null, + [ + { address: '8.8.8.8', family: 4 }, + { address: '10.0.0.5', family: 4 } + ], + undefined + ); + }); + + capturedLookup('rebind.example.com', { all: true }, (err) => { + expect(err).toBeInstanceOf(OAuthError); + done(); + }); + }); + + it('propagates DNS lookup errors', (done) => { + const dnsError = new Error('ENOTFOUND'); + dnsLookupMock.mockImplementationOnce((_hostname, _options, callback) => { + callback(dnsError, '', 4); + }); + + capturedLookup('nonexistent.invalid', {}, (err) => { + expect(err).toBe(dnsError); + done(); + }); + }); +}); + +describe('fetchJsonWithSsrfGuard', () => { + beforeEach(() => { + dnsLookupMock.mockReset(); + jest.mocked(undiciFetch).mockReset(); + }); + + it('parses and returns JSON on 200 OK', async () => { + const { response } = createMockResponse('{"key": "value"}'); + jest.mocked(undiciFetch).mockResolvedValueOnce(response); + + const result = await fetchJsonWithSsrfGuard('https://8.8.8.8/client.json'); + expect(result).toEqual({ key: 'value' }); + expect(undiciFetch).toHaveBeenCalledWith( + new URL('https://8.8.8.8/client.json'), + expect.objectContaining({ + headers: { Accept: 'application/json' }, + redirect: 'error' + }) + ); + }); + + it('throws OAuthError and cancels body on non-OK HTTP status', async () => { + const { cancel, response } = createMockResponse('Not Found', false, 404); + jest.mocked(undiciFetch).mockResolvedValueOnce(response); + + await expect( + fetchJsonWithSsrfGuard('https://example.com/client.json') + ).rejects.toThrow(OAuthError); + expect(cancel).toHaveBeenCalled(); + }); + + it('throws OAuthError and cancels body when payload exceeds maxBytes', async () => { + const oversizedBody = JSON.stringify({ data: 'a'.repeat(200) }); + const { cancel, response } = createMockResponse(oversizedBody); + jest.mocked(undiciFetch).mockResolvedValueOnce(response); + + await expect( + fetchJsonWithSsrfGuard('https://example.com/client.json', 64) + ).rejects.toThrow(OAuthError); + expect(cancel).toHaveBeenCalled(); + }); + + it('throws OAuthError on invalid JSON response', async () => { + const { response } = createMockResponse('not-valid-json'); + jest.mocked(undiciFetch).mockResolvedValueOnce(response); + + await expect( + fetchJsonWithSsrfGuard('https://example.com/client.json') + ).rejects.toThrow(OAuthError); + }); + + it('wraps network or timeout errors in OAuthError', async () => { + jest + .mocked(undiciFetch) + .mockRejectedValueOnce(new DOMException('Timeout', 'TimeoutError')); + + await expect( + fetchJsonWithSsrfGuard('https://example.com/client.json') + ).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + }); + + it('unwraps and rethrows OAuthError from fetch error cause', async () => { + const ssrfError = new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata URL resolves to a blocked IP address' + ); + const fetchError = new Error('fetch failed', { cause: ssrfError }); + jest.mocked(undiciFetch).mockRejectedValueOnce(fetchError); + + await expect( + fetchJsonWithSsrfGuard('https://example.com/client.json') + ).rejects.toBe(ssrfError); + }); +}); diff --git a/apps/api/src/helper/ssrf-guard.helper.ts b/apps/api/src/helper/ssrf-guard.helper.ts new file mode 100644 index 0000000000..59f5862ab1 --- /dev/null +++ b/apps/api/src/helper/ssrf-guard.helper.ts @@ -0,0 +1,190 @@ +import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'; +import { lookup as dnsLookup } from 'node:dns'; +import { BlockList, isIP, LookupFunction } from 'node:net'; +import { Agent, fetch as undiciFetch, Response } from 'undici'; + +const BLOCKED_IP_RANGES = new BlockList(); + +// IPv4 reserved / private / metadata ranges +BLOCKED_IP_RANGES.addSubnet('0.0.0.0', 8, 'ipv4'); // "This" network +BLOCKED_IP_RANGES.addSubnet('10.0.0.0', 8, 'ipv4'); // RFC 1918 private +BLOCKED_IP_RANGES.addSubnet('100.64.0.0', 10, 'ipv4'); // Carrier-grade NAT +BLOCKED_IP_RANGES.addSubnet('127.0.0.0', 8, 'ipv4'); // Loopback +BLOCKED_IP_RANGES.addSubnet('169.254.0.0', 16, 'ipv4'); // Link-local & cloud metadata (169.254.169.254) +BLOCKED_IP_RANGES.addSubnet('172.16.0.0', 12, 'ipv4'); // RFC 1918 private +BLOCKED_IP_RANGES.addSubnet('192.168.0.0', 16, 'ipv4'); // RFC 1918 private +BLOCKED_IP_RANGES.addSubnet('224.0.0.0', 4, 'ipv4'); // Multicast +BLOCKED_IP_RANGES.addSubnet('240.0.0.0', 4, 'ipv4'); + +// IPv6 reserved / private / loopback ranges +BLOCKED_IP_RANGES.addAddress('::', 'ipv6'); // Unspecified +BLOCKED_IP_RANGES.addAddress('::1', 'ipv6'); // Loopback +BLOCKED_IP_RANGES.addSubnet('fc00::', 7, 'ipv6'); // Unique local (ULA) +BLOCKED_IP_RANGES.addSubnet('fe80::', 10, 'ipv6'); // Link-local +BLOCKED_IP_RANGES.addSubnet('ff00::', 8, 'ipv6'); // Multicast + +/** + * Validates a raw URL string to ensure it is safe for external use. + * + * @param rawUrl The raw URL string to validate + * @returns The validated URL object + */ +export function assertSafeExternalUrl(rawUrl: string): URL { + let url: URL; + + try { + url = new URL(rawUrl); + } catch { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Invalid URL provided' + ); + } + + if (url.protocol !== 'https:') { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Only HTTPS URLs are allowed' + ); + } + + if (url.username || url.password) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'URLs with credentials are not allowed' + ); + } + + const host = url.hostname.replace(/^\[|\]$/g, ''); + + if (isIP(host) && isBlockedIp(host)) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'URLs pointing to blocked IP addresses are not allowed' + ); + } + + return url; +} + +/** + * Fetches JSON from a URL with SSRF protection + * + * @param rawUrl The URL to fetch JSON from + * @param maxBytes The maximum number of bytes to allow + * @returns A promise resolving to the fetched JSON data + */ +export async function fetchJsonWithSsrfGuard( + rawUrl: string, + maxBytes = 64 * 1024 +): Promise { + let response: Response; + const url = assertSafeExternalUrl(rawUrl); + + try { + response = await undiciFetch(url, { + dispatcher: ssrfSafeAgent, + headers: { + Accept: 'application/json' + }, + redirect: 'error', + signal: AbortSignal.timeout(5000) + }); + } catch (error) { + if (error instanceof OAuthError) { + throw error; + } + + if (error instanceof Error && error.cause instanceof OAuthError) { + throw error.cause; + } + + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Failed to fetch JSON from ${url.toString()}` + ); + } + + if (!response.ok) { + await response.body?.cancel(); + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Failed to fetch JSON from ${url.toString()}: ${response.status} ${response.statusText}` + ); + } + + const chunks: Uint8Array[] = []; + let totalBytes = 0; + + if (response.body) { + for await (const chunk of response.body) { + totalBytes += (chunk as Uint8Array).byteLength; + + if (totalBytes > maxBytes) { + await response.body.cancel(); + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Response from ${url.toString()} exceeds maximum allowed size of ${maxBytes} bytes` + ); + } + + chunks.push(chunk as Uint8Array); + } + } + + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8')) as T; + } catch { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Invalid JSON response' + ); + } +} + +/** + * Checks if an IP address is blocked + * + * @param ip The IP address to check + * @returns True if the IP address is blocked, false otherwise + */ +export function isBlockedIp(ip: string): boolean { + const version = isIP(ip); + + if (version === 0) { + return true; + } + + return BLOCKED_IP_RANGES.check(ip, version === 4 ? 'ipv4' : 'ipv6'); +} + +const ssrfSafeLookup: LookupFunction = (hostname, options, callback) => { + dnsLookup(hostname, options, (err, address, family) => { + if (err) { + return callback(err, address, family); + } + + const addresses = Array.isArray(address) + ? address.map((entry) => entry.address) + : [address]; + + if (addresses.some((ip) => isBlockedIp(ip))) { + return callback( + new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata URL resolves to a blocked IP address' + ), + address, + family + ); + } + + return callback(null, address, family); + }); +}; + +const ssrfSafeAgent = new Agent({ + connect: { + lookup: ssrfSafeLookup + } +}); From f7a4c2c14333517004e825f30f3d18a34d720866 Mon Sep 17 00:00:00 2001 From: KenTandrian Date: Fri, 27 Nov 2026 21:13:27 +0700 Subject: [PATCH 2/3] fix(api): reorder methods --- .../endpoints/oauth/oauth-client.service.ts | 26 +++++++++---------- .../endpoints/oauth/oauth-storage.service.ts | 24 ++++++++--------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/apps/api/src/app/endpoints/oauth/oauth-client.service.ts b/apps/api/src/app/endpoints/oauth/oauth-client.service.ts index fface1d564..76d5529e9b 100644 --- a/apps/api/src/app/endpoints/oauth/oauth-client.service.ts +++ b/apps/api/src/app/endpoints/oauth/oauth-client.service.ts @@ -77,6 +77,19 @@ export class OAuthClientService { }); } + private isValidRedirectUri(uri: unknown): uri is string { + if (typeof uri !== 'string') { + return false; + } + + try { + const parsed = new URL(uri); + return !parsed.hash; + } catch { + return false; + } + } + private matchesLoopbackRedirectUri( registeredUri: string, requestedUrl: URL @@ -184,19 +197,6 @@ export class OAuthClientService { }; } - private isValidRedirectUri(uri: unknown): uri is string { - if (typeof uri !== 'string') { - return false; - } - - try { - const parsed = new URL(uri); - return !parsed.hash; - } catch { - return false; - } - } - private parseStringArray(value: unknown, fieldName: string): string[] { if ( !Array.isArray(value) || diff --git a/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts b/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts index 59490061ba..0311b0bbd3 100644 --- a/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts +++ b/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts @@ -12,18 +12,6 @@ export class OAuthStorageService { public constructor(private readonly redisCacheService: RedisCacheService) {} - public async storeAuthorizationCode( - code: string, - data: OAuthAuthorizationCode, - ttlMs: number = OAuthStorageService.DEFAULT_TTL_MS - ): Promise { - await this.redisCacheService.set( - this.getCodeKey(code), - JSON.stringify(data), - ttlMs - ); - } - public async consumeAuthorizationCode( code: string ): Promise { @@ -43,6 +31,18 @@ export class OAuthStorageService { } } + public async storeAuthorizationCode( + code: string, + data: OAuthAuthorizationCode, + ttlMs: number = OAuthStorageService.DEFAULT_TTL_MS + ): Promise { + await this.redisCacheService.set( + this.getCodeKey(code), + JSON.stringify(data), + ttlMs + ); + } + private getCodeKey(code: string): string { return `${OAuthStorageService.CODE_KEY_PREFIX}${code}`; } From 28372888e6d288a7750492173caaf110c7a44f62 Mon Sep 17 00:00:00 2001 From: KenTandrian Date: Sun, 29 Nov 2026 06:59:14 +0000 Subject: [PATCH 3/3] refactor(api): address review feedback on MCP OAuth client verification and auth code storage --- .../oauth-client-metadata.interface.ts | 1 - .../oauth/oauth-client.service.spec.ts | 49 ++++++++-- .../endpoints/oauth/oauth-client.service.ts | 44 ++++----- .../oauth/oauth-storage.service.spec.ts | 30 +++++- .../endpoints/oauth/oauth-storage.service.ts | 4 +- apps/api/src/helper/ssrf-guard.helper.spec.ts | 51 +++++++++-- apps/api/src/helper/ssrf-guard.helper.ts | 91 ++++++++++--------- .../redis-cache/redis-cache.service.ts | 8 ++ 8 files changed, 192 insertions(+), 86 deletions(-) diff --git a/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts b/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts index 920bf8e10b..018b256df6 100644 --- a/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts +++ b/apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts @@ -4,5 +4,4 @@ export interface OAuthClientMetadata { grant_types: string[]; redirect_uris: string[]; response_types: string[]; - token_endpoint_auth_method?: string; } diff --git a/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts b/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts index 1729f47a65..bafcff05c0 100644 --- a/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts +++ b/apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts @@ -88,10 +88,13 @@ describe('OAuthClientService', () => { expect(redisCacheService.get).not.toHaveBeenCalled(); }); - it('rejects client_id containing a URL fragment', async () => { - await expect( - service.getClient(`${clientId}#section`) - ).rejects.toMatchObject({ + it.each([ + 'https://client.example.com', + 'https://client.example.com/a/../client.json', + `${clientId}#`, + `${clientId}#section` + ])('rejects client_id %s', async (invalidClientId) => { + await expect(service.getClient(invalidClientId)).rejects.toMatchObject({ code: OAuthErrorCode.InvalidClientMetadata }); expect(redisCacheService.get).not.toHaveBeenCalled(); @@ -124,12 +127,12 @@ describe('OAuthClientService', () => { }); }); - it('throws invalid_client_metadata when redirect_uris is empty or invalid', async () => { + it('throws invalid_client_metadata when redirect_uris is empty', async () => { jest .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') .mockResolvedValueOnce({ ...validMetadataResponse, - redirect_uris: ['not-a-valid-uri'] + redirect_uris: [] }); await expect(service.getClient(clientId)).rejects.toMatchObject({ @@ -137,6 +140,40 @@ describe('OAuthClientService', () => { }); }); + it.each([ + 'data:text/html,x', + 'http://client.example.com/callback', + 'javascript:alert(1)', + 'not-a-valid-uri' + ])('throws invalid_client_metadata for redirect_uri %s', async (uri) => { + jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockResolvedValueOnce({ + ...validMetadataResponse, + redirect_uris: [uri] + }); + + await expect(service.getClient(clientId)).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + }); + + it.each(['client_secret_basic', 'private_key_jwt'])( + 'throws invalid_client_metadata for token_endpoint_auth_method %s', + async (tokenEndpointAuthMethod) => { + jest + .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') + .mockResolvedValueOnce({ + ...validMetadataResponse, + token_endpoint_auth_method: tokenEndpointAuthMethod + }); + + await expect(service.getClient(clientId)).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + } + ); + it('propagates timeout errors from fetchJsonWithSsrfGuard as OAuthError', async () => { jest .spyOn(ssrfGuardHelper, 'fetchJsonWithSsrfGuard') diff --git a/apps/api/src/app/endpoints/oauth/oauth-client.service.ts b/apps/api/src/app/endpoints/oauth/oauth-client.service.ts index 76d5529e9b..43ce333405 100644 --- a/apps/api/src/app/endpoints/oauth/oauth-client.service.ts +++ b/apps/api/src/app/endpoints/oauth/oauth-client.service.ts @@ -22,10 +22,14 @@ export class OAuthClientService { public async getClient(clientId: string): Promise { const parsedClientUrl = assertSafeExternalUrl(clientId); - if (parsedClientUrl.hash) { + if ( + clientId.includes('#') || + parsedClientUrl.href !== clientId || + parsedClientUrl.pathname === '/' + ) { throw new OAuthError( OAuthErrorCode.InvalidClientMetadata, - 'Client ID URL must not contain a fragment' + 'Client ID URL must be normalized and contain a path, but no fragment' ); } @@ -83,8 +87,13 @@ export class OAuthClientService { } try { - const parsed = new URL(uri); - return !parsed.hash; + const { hash, hostname, protocol } = new URL(uri); + + return ( + !hash && + (protocol === 'https:' || + (protocol === 'http:' && LOOPBACK_HOSTNAMES.has(hostname))) + ); } catch { return false; } @@ -169,20 +178,14 @@ export class OAuthClientService { ? ['code'] : this.parseStringArray(data.response_types, 'response_types'); - let tokenEndpointAuthMethod: string | undefined; - - if (data.token_endpoint_auth_method !== undefined) { - if ( - typeof data.token_endpoint_auth_method !== 'string' || - data.token_endpoint_auth_method.trim().length === 0 - ) { - throw new OAuthError( - OAuthErrorCode.InvalidClientMetadata, - 'Client metadata token_endpoint_auth_method must be a non-empty string' - ); - } - - tokenEndpointAuthMethod = data.token_endpoint_auth_method; + if ( + data.token_endpoint_auth_method !== undefined && + data.token_endpoint_auth_method !== 'none' + ) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + 'Client metadata token_endpoint_auth_method must be none' + ); } return { @@ -190,10 +193,7 @@ export class OAuthClientService { client_name: data.client_name, grant_types: grantTypes, redirect_uris: data.redirect_uris, - response_types: responseTypes, - ...(tokenEndpointAuthMethod !== undefined - ? { token_endpoint_auth_method: tokenEndpointAuthMethod } - : {}) + response_types: responseTypes }; } diff --git a/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts b/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts index 0f1ddce5a2..77f2a8afa9 100644 --- a/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts +++ b/apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts @@ -6,11 +6,11 @@ import { OAuthAuthorizationCode } from './interfaces/oauth-authorization-code.in import { OAuthStorageService } from './oauth-storage.service'; describe('OAuthStorageService', () => { - let store: Map; let redisCacheService: jest.Mocked< - Pick + Pick >; let service: OAuthStorageService; + let store: Map; const sampleAuthCode: OAuthAuthorizationCode = { clientId: 'https://client.example.com/client.json', @@ -40,7 +40,7 @@ describe('OAuthStorageService', () => { return Promise.resolve(entry.value); }), - remove: jest.fn((key: string) => { + removeIfExists: jest.fn((key: string) => { return Promise.resolve(store.delete(key)); }), set: jest.fn((key: string, value: string, ttl?: number) => { @@ -75,16 +75,36 @@ describe('OAuthStorageService', () => { expect(first).toEqual(sampleAuthCode); expect(second).toBeNull(); - expect(redisCacheService.remove).toHaveBeenCalledWith( + expect(redisCacheService.removeIfExists).toHaveBeenCalledWith( 'oauth:code:single-use-code' ); }); + it('gives the authorization code to only one of several parallel calls', async () => { + await service.storeAuthorizationCode('parallel-code', sampleAuthCode); + + const results = await Promise.all([ + service.consumeAuthorizationCode('parallel-code'), + service.consumeAuthorizationCode('parallel-code') + ]); + + expect(results).toEqual([sampleAuthCode, null]); + }); + + it('returns null if the authorization code cannot be removed', async () => { + await service.storeAuthorizationCode('locked-code', sampleAuthCode); + redisCacheService.removeIfExists.mockResolvedValueOnce(false); + + const result = await service.consumeAuthorizationCode('locked-code'); + + expect(result).toBeNull(); + }); + it('returns null when consuming a non-existent code', async () => { const result = await service.consumeAuthorizationCode('missing-code'); expect(result).toBeNull(); - expect(redisCacheService.remove).not.toHaveBeenCalled(); + expect(redisCacheService.removeIfExists).not.toHaveBeenCalled(); }); it('returns null after the authorization code TTL expires', async () => { diff --git a/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts b/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts index 0311b0bbd3..5759007aec 100644 --- a/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts +++ b/apps/api/src/app/endpoints/oauth/oauth-storage.service.ts @@ -18,12 +18,10 @@ export class OAuthStorageService { const key = this.getCodeKey(code); const raw = await this.redisCacheService.get(key); - if (!raw) { + if (!raw || !(await this.redisCacheService.removeIfExists(key))) { return null; } - await this.redisCacheService.remove(key); - try { return JSON.parse(raw) as OAuthAuthorizationCode; } catch { diff --git a/apps/api/src/helper/ssrf-guard.helper.spec.ts b/apps/api/src/helper/ssrf-guard.helper.spec.ts index 36bc84be4b..3c95e723df 100644 --- a/apps/api/src/helper/ssrf-guard.helper.spec.ts +++ b/apps/api/src/helper/ssrf-guard.helper.spec.ts @@ -14,6 +14,7 @@ jest.mock('node:dns', () => ({ })); jest.mock('undici', () => ({ + ...jest.requireActual('undici'), Agent: jest.fn().mockImplementation(() => ({})), fetch: jest.fn() })); @@ -113,6 +114,26 @@ describe('isBlockedIp', () => { expect(isBlockedIp('ff02::1')).toBe(true); }); + it.each([ + '192.0.0.192', + '192.0.2.1', + '192.88.99.1', + '198.18.0.1', + '198.51.100.1', + '203.0.113.1', + '::10.0.0.1', + '::ffff:0:10.0.0.1', + '64:ff9b::a00:1', + '64:ff9b:1::a00:1', + '100::1', + '2001::1', + '2001:db8::1', + '2002:a00:1::', + 'fec0::1' + ])('blocks special-use address %s (RFC 6890)', (ip) => { + expect(isBlockedIp(ip)).toBe(true); + }); + it('blocks invalid IP strings', () => { expect(isBlockedIp('')).toBe(true); expect(isBlockedIp('example.com')).toBe(true); @@ -263,15 +284,33 @@ describe('fetchJsonWithSsrfGuard', () => { expect(cancel).toHaveBeenCalled(); }); - it('throws OAuthError and cancels body when payload exceeds maxBytes', async () => { - const oversizedBody = JSON.stringify({ data: 'a'.repeat(200) }); - const { cancel, response } = createMockResponse(oversizedBody); - jest.mocked(undiciFetch).mockResolvedValueOnce(response); + it('throws OAuthError when payload exceeds maxBytes', async () => { + jest + .mocked(undiciFetch) + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: 'a'.repeat(200) })) + ); await expect( fetchJsonWithSsrfGuard('https://example.com/client.json', 64) - ).rejects.toThrow(OAuthError); - expect(cancel).toHaveBeenCalled(); + ).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); + }); + + it('wraps errors of the response body in OAuthError', async () => { + const body = new ReadableStream({ + pull(controller) { + controller.error(new TypeError('terminated')); + } + }); + jest.mocked(undiciFetch).mockResolvedValueOnce(new Response(body)); + + await expect( + fetchJsonWithSsrfGuard('https://example.com/client.json') + ).rejects.toMatchObject({ + code: OAuthErrorCode.InvalidClientMetadata + }); }); it('throws OAuthError on invalid JSON response', async () => { diff --git a/apps/api/src/helper/ssrf-guard.helper.ts b/apps/api/src/helper/ssrf-guard.helper.ts index 59f5862ab1..9576dba318 100644 --- a/apps/api/src/helper/ssrf-guard.helper.ts +++ b/apps/api/src/helper/ssrf-guard.helper.ts @@ -1,7 +1,7 @@ import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'; import { lookup as dnsLookup } from 'node:dns'; import { BlockList, isIP, LookupFunction } from 'node:net'; -import { Agent, fetch as undiciFetch, Response } from 'undici'; +import { Agent, fetch as undiciFetch } from 'undici'; const BLOCKED_IP_RANGES = new BlockList(); @@ -12,15 +12,28 @@ BLOCKED_IP_RANGES.addSubnet('100.64.0.0', 10, 'ipv4'); // Carrier-grade NAT BLOCKED_IP_RANGES.addSubnet('127.0.0.0', 8, 'ipv4'); // Loopback BLOCKED_IP_RANGES.addSubnet('169.254.0.0', 16, 'ipv4'); // Link-local & cloud metadata (169.254.169.254) BLOCKED_IP_RANGES.addSubnet('172.16.0.0', 12, 'ipv4'); // RFC 1918 private +BLOCKED_IP_RANGES.addSubnet('192.0.0.0', 24, 'ipv4'); // IETF protocol assignments +BLOCKED_IP_RANGES.addSubnet('192.0.2.0', 24, 'ipv4'); // Documentation +BLOCKED_IP_RANGES.addSubnet('192.88.99.0', 24, 'ipv4'); // 6to4 relay anycast BLOCKED_IP_RANGES.addSubnet('192.168.0.0', 16, 'ipv4'); // RFC 1918 private +BLOCKED_IP_RANGES.addSubnet('198.18.0.0', 15, 'ipv4'); // Benchmarking +BLOCKED_IP_RANGES.addSubnet('198.51.100.0', 24, 'ipv4'); // Documentation +BLOCKED_IP_RANGES.addSubnet('203.0.113.0', 24, 'ipv4'); // Documentation BLOCKED_IP_RANGES.addSubnet('224.0.0.0', 4, 'ipv4'); // Multicast -BLOCKED_IP_RANGES.addSubnet('240.0.0.0', 4, 'ipv4'); +BLOCKED_IP_RANGES.addSubnet('240.0.0.0', 4, 'ipv4'); // Reserved // IPv6 reserved / private / loopback ranges -BLOCKED_IP_RANGES.addAddress('::', 'ipv6'); // Unspecified -BLOCKED_IP_RANGES.addAddress('::1', 'ipv6'); // Loopback +BLOCKED_IP_RANGES.addSubnet('::', 96, 'ipv6'); // Unspecified, loopback & IPv4-compatible +BLOCKED_IP_RANGES.addSubnet('::ffff:0:0:0', 96, 'ipv6'); // IPv4-translated +BLOCKED_IP_RANGES.addSubnet('64:ff9b::', 96, 'ipv6'); // NAT64 +BLOCKED_IP_RANGES.addSubnet('64:ff9b:1::', 48, 'ipv6'); // Local-use NAT64 +BLOCKED_IP_RANGES.addSubnet('100::', 64, 'ipv6'); // Discard-only +BLOCKED_IP_RANGES.addSubnet('2001::', 23, 'ipv6'); // IETF protocol assignments & Teredo +BLOCKED_IP_RANGES.addSubnet('2001:db8::', 32, 'ipv6'); // Documentation +BLOCKED_IP_RANGES.addSubnet('2002::', 16, 'ipv6'); // 6to4 BLOCKED_IP_RANGES.addSubnet('fc00::', 7, 'ipv6'); // Unique local (ULA) BLOCKED_IP_RANGES.addSubnet('fe80::', 10, 'ipv6'); // Link-local +BLOCKED_IP_RANGES.addSubnet('fec0::', 10, 'ipv6'); // Site-local BLOCKED_IP_RANGES.addSubnet('ff00::', 8, 'ipv6'); // Multicast /** @@ -76,13 +89,12 @@ export function assertSafeExternalUrl(rawUrl: string): URL { */ export async function fetchJsonWithSsrfGuard( rawUrl: string, - maxBytes = 64 * 1024 + maxBytes = 5 * 1024 ): Promise { - let response: Response; const url = assertSafeExternalUrl(rawUrl); try { - response = await undiciFetch(url, { + const response = await undiciFetch(url, { dispatcher: ssrfSafeAgent, headers: { Accept: 'application/json' @@ -90,54 +102,47 @@ export async function fetchJsonWithSsrfGuard( redirect: 'error', signal: AbortSignal.timeout(5000) }); - } catch (error) { - if (error instanceof OAuthError) { - throw error; - } - if (error instanceof Error && error.cause instanceof OAuthError) { - throw error.cause; + if (response.status !== 200) { + await response.body?.cancel(); + + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Failed to fetch JSON from ${url.toString()}: ${response.status}` + ); } - throw new OAuthError( - OAuthErrorCode.InvalidClientMetadata, - `Failed to fetch JSON from ${url.toString()}` - ); - } + const chunks: Uint8Array[] = []; + let totalBytes = 0; - if (!response.ok) { - await response.body?.cancel(); - throw new OAuthError( - OAuthErrorCode.InvalidClientMetadata, - `Failed to fetch JSON from ${url.toString()}: ${response.status} ${response.statusText}` - ); - } + if (response.body) { + for await (const chunk of response.body) { + totalBytes += (chunk as Uint8Array).byteLength; - const chunks: Uint8Array[] = []; - let totalBytes = 0; + if (totalBytes > maxBytes) { + throw new OAuthError( + OAuthErrorCode.InvalidClientMetadata, + `Response from ${url.toString()} exceeds maximum allowed size of ${maxBytes} bytes` + ); + } - if (response.body) { - for await (const chunk of response.body) { - totalBytes += (chunk as Uint8Array).byteLength; - - if (totalBytes > maxBytes) { - await response.body.cancel(); - throw new OAuthError( - OAuthErrorCode.InvalidClientMetadata, - `Response from ${url.toString()} exceeds maximum allowed size of ${maxBytes} bytes` - ); + chunks.push(chunk as Uint8Array); } - - chunks.push(chunk as Uint8Array); } - } - try { return JSON.parse(Buffer.concat(chunks).toString('utf8')) as T; - } catch { + } catch (error) { + if (error instanceof OAuthError) { + throw error; + } + + if (error instanceof Error && error.cause instanceof OAuthError) { + throw error.cause; + } + throw new OAuthError( OAuthErrorCode.InvalidClientMetadata, - 'Invalid JSON response' + `Failed to fetch JSON from ${url.toString()}` ); } } diff --git a/apps/api/src/services/redis-cache/redis-cache.service.ts b/apps/api/src/services/redis-cache/redis-cache.service.ts index 5e64f5a635..378c9b5a3e 100644 --- a/apps/api/src/services/redis-cache/redis-cache.service.ts +++ b/apps/api/src/services/redis-cache/redis-cache.service.ts @@ -121,6 +121,14 @@ export class RedisCacheService { return this.cache.del(key); } + /** + * Removes a key and tells if it was there. Of several parallel calls, only + * one gets `true`. + */ + public async removeIfExists(key: string) { + return this.client.delete(key); + } + public async removePortfolioSnapshotsByUserId({ userId }: {