From 4d33d8c2c71ad497fdfaa2c4334b0a2293bcbd67 Mon Sep 17 00:00:00 2001 From: "lia-by-librechat[bot]" <328778573+lia-by-librechat[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 14:07:25 -0400 Subject: [PATCH] =?UTF-8?q?=E2=86=AA=EF=B8=8F=20fix:=20Block=20Unsafe=20MC?= =?UTF-8?q?P=20OAuth=20Redirects=20and=20Private=20IPs=20(#16514)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ↪️ fix: Block Unsafe MCP OAuth Redirects and Private IPs * ↪️ fix: Keep MCP OAuth Blocked-Address Error Stable --------- Co-authored-by: Lia --- .../mcp/oauth/hardenedFetch.behavior.test.ts | 61 ++++++++++++++++++- .../api/src/mcp/oauth/hardenedFetch.test.ts | 53 +++++++++++++++- packages/api/src/mcp/oauth/hardenedFetch.ts | 13 +++- 3 files changed, 121 insertions(+), 6 deletions(-) diff --git a/packages/api/src/mcp/oauth/hardenedFetch.behavior.test.ts b/packages/api/src/mcp/oauth/hardenedFetch.behavior.test.ts index 206616fdd0..24c42c662e 100644 --- a/packages/api/src/mcp/oauth/hardenedFetch.behavior.test.ts +++ b/packages/api/src/mcp/oauth/hardenedFetch.behavior.test.ts @@ -8,11 +8,19 @@ type TestServer = { close: () => Promise; }; -async function createLocalServer(): Promise { +async function createLocalServer( + hostname = 'localhost', + redirect?: { status: 302 | 307; target: string }, +): Promise { let requestCount = 0; const sockets = new Set(); const server = http.createServer((_req, res) => { requestCount += 1; + if (redirect) { + res.writeHead(redirect.status, { Location: redirect.target }); + res.end(); + return; + } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); }); @@ -22,7 +30,7 @@ async function createLocalServer(): Promise { socket.once('close', () => sockets.delete(socket)); }); - await new Promise((resolve) => server.listen(0, 'localhost', resolve)); + await new Promise((resolve) => server.listen(0, hostname, resolve)); const address = server.address() as AddressInfo; return { @@ -63,6 +71,31 @@ describe('createHardenedOAuthFetch request policy', () => { expect(server.requestCount()).toBe(0); }); + it('blocks private IP literals even when the DNS lookup is bypassed', async () => { + const target = await createLocalServer('127.0.0.1'); + try { + await expect( + createHardenedOAuthFetch()(`http://127.0.0.1:${target.port}/token`), + ).rejects.toThrow('OAuth endpoint targets a blocked address'); + expect(target.requestCount()).toBe(0); + } finally { + await target.close(); + } + }); + + it('permits an explicitly exempted private IP and port', async () => { + const target = await createLocalServer('127.0.0.1'); + try { + const response = await createHardenedOAuthFetch({ + allowedAddresses: [`127.0.0.1:${target.port}`], + })(`http://127.0.0.1:${target.port}/token`); + await expect(response.json()).resolves.toEqual({ ok: true }); + expect(target.requestCount()).toBe(1); + } finally { + await target.close(); + } + }); + it('allows explicitly trusted local OAuth endpoints', async () => { const oauthFetch = createHardenedOAuthFetch({ allowedDomains: ['localhost'] }); @@ -74,6 +107,30 @@ describe('createHardenedOAuthFetch request policy', () => { expect(server.requestCount()).toBe(1); }); + it.each([302, 307] as const)( + 'does not follow a %i from an allowlisted OAuth endpoint to a private IP', + async (status) => { + const target = await createLocalServer('127.0.0.1'); + const redirector = await createLocalServer('localhost', { + status, + target: `http://127.0.0.1:${target.port}/internal`, + }); + try { + await expect( + createHardenedOAuthFetch({ allowedDomains: ['localhost'] })( + `http://localhost:${redirector.port}/token`, + { method: 'POST', body: 'grant_type=refresh_token', redirect: 'follow' }, + ), + ).rejects.toThrow(); + expect(redirector.requestCount()).toBe(1); + expect(target.requestCount()).toBe(0); + } finally { + await redirector.close(); + await target.close(); + } + }, + ); + it('does not use address exemptions when domain policy is active but unmatched', async () => { const oauthFetch = createHardenedOAuthFetch({ allowedDomains: ['trusted.example.com'], diff --git a/packages/api/src/mcp/oauth/hardenedFetch.test.ts b/packages/api/src/mcp/oauth/hardenedFetch.test.ts index 5e9f5bb082..b0570ad46e 100644 --- a/packages/api/src/mcp/oauth/hardenedFetch.test.ts +++ b/packages/api/src/mcp/oauth/hardenedFetch.test.ts @@ -1,15 +1,17 @@ -import { createSSRFSafeUndiciConnect, isOAuthUrlAllowed } from '~/auth'; import { createHardenedOAuthFetch, resetHardenedOAuthFetchDispatchers } from './hardenedFetch'; +import { createSSRFSafeUndiciConnect, isOAuthUrlAllowed, isSSRFTarget } from '~/auth'; jest.mock('~/auth', () => ({ createSSRFSafeUndiciConnect: jest.fn(() => ({ lookup: jest.fn() })), isOAuthUrlAllowed: jest.fn(() => false), + isSSRFTarget: jest.fn(() => false), })); const mockCreateSSRFSafeUndiciConnect = createSSRFSafeUndiciConnect as jest.MockedFunction< typeof createSSRFSafeUndiciConnect >; const mockIsOAuthUrlAllowed = isOAuthUrlAllowed as jest.MockedFunction; +const mockIsSSRFTarget = isSSRFTarget as jest.MockedFunction; describe('createHardenedOAuthFetch', () => { const originalFetch = global.fetch; @@ -20,6 +22,7 @@ describe('createHardenedOAuthFetch', () => { global.fetch = mockFetch; mockFetch.mockResolvedValue({ ok: true } as Response); mockIsOAuthUrlAllowed.mockReturnValue(false); + mockIsSSRFTarget.mockReturnValue(false); }); afterEach(() => { @@ -41,6 +44,7 @@ describe('createHardenedOAuthFetch', () => { expect.objectContaining({ method: 'POST', dispatcher: expect.any(Object), + redirect: 'error', }), ); }); @@ -66,6 +70,53 @@ describe('createHardenedOAuthFetch', () => { expect(mockCreateSSRFSafeUndiciConnect).not.toHaveBeenCalled(); expect(mockFetch.mock.calls[0][1]).not.toHaveProperty('dispatcher'); + expect(mockFetch.mock.calls[0][1]).toEqual(expect.objectContaining({ redirect: 'error' })); + }); + + it('rejects an IPv6 literal before the Undici lookup can be bypassed', async () => { + mockIsSSRFTarget.mockReturnValueOnce(true); + + await expect(createHardenedOAuthFetch()('http://[::1]:9443/token')).rejects.toThrow(); + + expect(mockIsSSRFTarget).toHaveBeenCalledWith('::1', undefined, '9443'); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('checks private IPs before reusing a dispatcher cached for the same port', async () => { + await createHardenedOAuthFetch()('https://auth.example.com:9443/token'); + mockIsSSRFTarget.mockReturnValueOnce(true); + + await expect(createHardenedOAuthFetch()('http://127.0.0.1:9443/token')).rejects.toThrow( + 'OAuth endpoint targets a blocked address', + ); + + expect(mockIsSSRFTarget).toHaveBeenCalledWith('127.0.0.1', undefined, '9443'); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it('normalizes alternate IPv4 spellings before checking the literal', async () => { + mockIsSSRFTarget.mockReturnValueOnce(true); + + await expect(createHardenedOAuthFetch()('http://0x7f000001:9443/token')).rejects.toThrow( + 'OAuth endpoint targets a blocked address', + ); + + expect(mockIsSSRFTarget).toHaveBeenCalledWith('127.0.0.1', undefined, '9443'); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('does not apply address exemptions to an IP when domain policy is active but unmatched', async () => { + mockIsSSRFTarget.mockReturnValueOnce(true); + + await expect( + createHardenedOAuthFetch({ + allowedDomains: ['trusted.example.com'], + allowedAddresses: ['127.0.0.1:9443'], + })('http://127.0.0.1:9443/token'), + ).rejects.toThrow(); + + expect(mockIsSSRFTarget).toHaveBeenCalledWith('127.0.0.1', null, '9443'); + expect(mockFetch).not.toHaveBeenCalled(); }); it('normalizes allowedAddresses before caching dispatchers', async () => { diff --git a/packages/api/src/mcp/oauth/hardenedFetch.ts b/packages/api/src/mcp/oauth/hardenedFetch.ts index 18988af0c7..8cd317547d 100644 --- a/packages/api/src/mcp/oauth/hardenedFetch.ts +++ b/packages/api/src/mcp/oauth/hardenedFetch.ts @@ -1,7 +1,8 @@ import { Agent } from 'undici'; -import type { Dispatcher } from 'undici'; +import { isIP } from 'node:net'; import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport'; -import { createSSRFSafeUndiciConnect, isOAuthUrlAllowed } from '~/auth'; +import type { Dispatcher } from 'undici'; +import { createSSRFSafeUndiciConnect, isOAuthUrlAllowed, isSSRFTarget } from '~/auth'; import { getOAuthUrlPort } from './url'; type FetchInitWithDispatcher = RequestInit & { @@ -50,6 +51,10 @@ function getOAuthDispatcher( const port = getOAuthUrlPort(parsedUrl); const effectiveAddresses = Array.isArray(allowedDomains) && allowedDomains.length > 0 ? null : allowedAddresses; + const literalHost = parsedUrl.hostname.replace(/^\[|\]$/g, ''); + if (isIP(literalHost) && isSSRFTarget(literalHost, effectiveAddresses, port)) { + throw new Error('OAuth endpoint targets a blocked address'); + } const cacheKey = getDispatcherCacheKey(port, effectiveAddresses); const cached = oauthDispatchers.get(cacheKey); if (cached) { @@ -79,7 +84,9 @@ export function createHardenedOAuthFetch({ return async (url: string | URL, init?: RequestInit): Promise => { const dispatcher = getOAuthDispatcher(url, allowedDomains, allowedAddresses); const fetchInit: FetchInitWithDispatcher = - dispatcher != null ? { ...init, dispatcher } : { ...init }; + dispatcher != null + ? { ...init, dispatcher, redirect: 'error' } + : { ...init, redirect: 'error' }; return fetch(url, fetchInit); }; }