Browse Source

refactor(api): address review feedback on MCP OAuth client verification and auth code storage

pull/8478/head
KenTandrian 4 hours ago
parent
commit
28372888e6
  1. 1
      apps/api/src/app/endpoints/oauth/interfaces/oauth-client-metadata.interface.ts
  2. 49
      apps/api/src/app/endpoints/oauth/oauth-client.service.spec.ts
  3. 44
      apps/api/src/app/endpoints/oauth/oauth-client.service.ts
  4. 30
      apps/api/src/app/endpoints/oauth/oauth-storage.service.spec.ts
  5. 4
      apps/api/src/app/endpoints/oauth/oauth-storage.service.ts
  6. 51
      apps/api/src/helper/ssrf-guard.helper.spec.ts
  7. 91
      apps/api/src/helper/ssrf-guard.helper.ts
  8. 8
      apps/api/src/services/redis-cache/redis-cache.service.ts

1
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;
}

49
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')

44
apps/api/src/app/endpoints/oauth/oauth-client.service.ts

@ -22,10 +22,14 @@ export class OAuthClientService {
public async getClient(clientId: string): Promise<OAuthClientMetadata> {
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
};
}

30
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<string, { expiresAt: number; value: string }>;
let redisCacheService: jest.Mocked<
Pick<RedisCacheService, 'get' | 'remove' | 'set'>
Pick<RedisCacheService, 'get' | 'removeIfExists' | 'set'>
>;
let service: OAuthStorageService;
let store: Map<string, { expiresAt: number; value: string }>;
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 () => {

4
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 {

51
apps/api/src/helper/ssrf-guard.helper.spec.ts

@ -14,6 +14,7 @@ jest.mock('node:dns', () => ({
}));
jest.mock('undici', () => ({
...jest.requireActual<typeof import('undici')>('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 () => {

91
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<T>(
rawUrl: string,
maxBytes = 64 * 1024
maxBytes = 5 * 1024
): Promise<T> {
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<T>(
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()}`
);
}
}

8
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
}: {

Loading…
Cancel
Save