From cc6f4f32205982da1a1b05e28a52aa2a6764873f Mon Sep 17 00:00:00 2001 From: KenTandrian Date: Fri, 27 Nov 2026 21:08:19 +0700 Subject: [PATCH] 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 + } +});