mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 15:02:02 +00:00
↪️ fix: Block Unsafe MCP OAuth Redirects and Private IPs (#16514)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* ↪️ fix: Block Unsafe MCP OAuth Redirects and Private IPs * ↪️ fix: Keep MCP OAuth Blocked-Address Error Stable --------- Co-authored-by: Lia <lia@librechat.ai>
This commit is contained in:
parent
f995ba17da
commit
4d33d8c2c7
3 changed files with 121 additions and 6 deletions
|
|
@ -8,11 +8,19 @@ type TestServer = {
|
|||
close: () => Promise<void>;
|
||||
};
|
||||
|
||||
async function createLocalServer(): Promise<TestServer> {
|
||||
async function createLocalServer(
|
||||
hostname = 'localhost',
|
||||
redirect?: { status: 302 | 307; target: string },
|
||||
): Promise<TestServer> {
|
||||
let requestCount = 0;
|
||||
const sockets = new Set<Socket>();
|
||||
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<TestServer> {
|
|||
socket.once('close', () => sockets.delete(socket));
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, 'localhost', resolve));
|
||||
await new Promise<void>((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'],
|
||||
|
|
|
|||
|
|
@ -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<typeof isOAuthUrlAllowed>;
|
||||
const mockIsSSRFTarget = isSSRFTarget as jest.MockedFunction<typeof isSSRFTarget>;
|
||||
|
||||
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 () => {
|
||||
|
|
|
|||
|
|
@ -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<Response> => {
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue