Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔌 fix: Follow 307/308 redirects in MCP streamable HTTP transport (#12850)

Nick Haffie-Emslie3758380c615f
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts
index b4eb58dbef..f365f166e4 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionSSRF.test.ts
@@ -3,21 +3,31 @@
*
* These tests spin up real in-process HTTP servers and verify that MCPConnection:
*
- * 1. Does NOT follow HTTP redirects from SSE/StreamableHTTP transports
+ * 1. Does NOT follow 301/302 redirects from SSE/StreamableHTTP transports
* (redirect: 'manual' prevents SSRF via server-controlled 301/302)
- * 2. Blocks WebSocket connections to hosts that DNS-resolve to private IPs,
+ * 2. DOES follow 307/308 redirects (method-preserving) with a depth limit of 5,
+ * as required by servers like Coda that route doc-scoped tool calls via 308
+ * 3. Blocks WebSocket connections to hosts that DNS-resolve to private IPs,
* regardless of whether useSSRFProtection is enabled (allowlist scenario)
*/
import * as net from 'net';
import * as http from 'http';
import { randomUUID } from 'crypto';
+import { Request as UndiciRequest } from 'undici';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+import type {
+ RequestInfo as UndiciRequestInfo,
+ RequestInit as UndiciRequestInit,
+ Response as UndiciResponse,
+} from 'undici';
import type { Socket } from 'net';
import { MCPConnection } from '~/mcp/connection';
import { resolveHostnameSSRF } from '~/auth';
+type CustomFetch = (input: UndiciRequestInfo, init?: UndiciRequestInit) => Promise<UndiciResponse>;
+
jest.mock('@librechat/data-schemas', () => ({
logger: {
info: jest.fn(),
@@ -122,18 +132,22 @@ async function createRedirectingServer(redirectTarget: string): Promise<TestServ
}
/**
- * Creates a real StreamableHTTP MCP server for baseline connectivity tests.
+ * Builds an HTTP request handler that routes incoming requests to (per-session)
+ * `StreamableHTTPServerTransport` instances backed by an `McpServer`. Sessions
+ * are stored in the caller-provided `sessions` Map so the caller can drain them
+ * during teardown.
*/
-async function createStreamableServer(): Promise<Omit<TestServer, 'redirectHit'>> {
- const sessions = new Map<string, StreamableHTTPServerTransport>();
-
- const httpServer = http.createServer(async (req, res) => {
+function createMCPRequestHandler(
+ sessions: Map<string, StreamableHTTPServerTransport>,
+ serverName: string,
+): http.RequestListener {
+ return async (req, res) => {
const sid = req.headers['mcp-session-id'] as string | undefined;
let transport = sid ? sessions.get(sid) : undefined;
if (!transport) {
transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
- const mcp = new McpServer({ name: 'test-ssrf', version: '0.0.1' });
+ const mcp = new McpServer({ name: serverName, version: '0.0.1' });
await mcp.connect(transport);
}
@@ -143,7 +157,23 @@ async function createStreamableServer(): Promise<Omit<TestServer, 'redirectHit'>
sessions.set(transport.sessionId, transport);
transport.onclose = () => sessions.delete(transport!.sessionId!);
}
- });
+ };
+}
+
+async function closeMCPSessions(
+ sessions: Map<string, StreamableHTTPServerTransport>,
+): Promise<void> {
+ const closing = [...sessions.values()].map((t) => t.close().catch(() => undefined));
+ sessions.clear();
+ await Promise.all(closing);
+}
+
+/**
+ * Creates a real StreamableHTTP MCP server for baseline connectivity tests.
+ */
+async function createStreamableServer(): Promise<Omit<TestServer, 'redirectHit'>> {
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
+ const httpServer = http.createServer(createMCPRequestHandler(sessions, 'test-ssrf'));
const destroySockets = trackSockets(httpServer);
const port = await getFreePort();
@@ -152,9 +182,7 @@ async function createStreamableServer(): Promise<Omit<TestServer, 'redirectHit'>
return {
url: `http://127.0.0.1:${port}/`,
close: async () => {
- const closing = [...sessions.values()].map((t) => t.close().catch(() => undefined));
- sessions.clear();
- await Promise.all(closing);
+ await closeMCPSessions(sessions);
await destroySockets();
},
};
@@ -223,6 +251,637 @@ describe('MCP SSRF protection – redirect blocking', () => {
});
});
+/**
+ * Creates a single HTTP server that 307/308-redirects from the root path to
+ * `/mcp`, where a real MCP server is mounted. The redirect stays on the same
+ * origin (Coda-style doc-scoped routing), so credential-bearing headers like
+ * `mcp-session-id` survive the cross-path hop and the MCP session keeps state.
+ */
+async function createRedirectingMCPServer(
+ statusCode: 307 | 308,
+): Promise<TestServer & { close: () => Promise<void> }> {
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
+ const state = { redirectHit: false };
+ const mcpPath = '/mcp';
+ const port = await getFreePort();
+ const mcpHandler = createMCPRequestHandler(sessions, 'redirect-target');
+
+ const server = http.createServer(async (req, res) => {
+ if ((req.url ?? '').startsWith(mcpPath)) {
+ state.redirectHit = true;
+ await mcpHandler(req, res);
+ return;
+ }
+
+ res.writeHead(statusCode, { Location: `http://127.0.0.1:${port}${mcpPath}` });
+ res.end();
+ });
+
+ const destroySockets = trackSockets(server);
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+
+ return {
+ url: `http://127.0.0.1:${port}/`,
+ get redirectHit() {
+ return state.redirectHit;
+ },
+ close: async () => {
+ await closeMCPSessions(sessions);
+ await destroySockets();
+ },
+ };
+}
+
+/**
+ * Creates a single HTTP server with `depth` chained 307/308 redirects on
+ * `/hop/N → /hop/N-1 → … → /hop/0`, where `/hop/0` returns a plain 200.
+ * Same-origin throughout, so the chain exercises only redirect-depth limits
+ * (not cross-origin header behavior).
+ */
+async function createRedirectChain(depth: number, statusCode: 307 | 308): Promise<TestServer> {
+ const state = { redirectHit: false };
+ const port = await getFreePort();
+
+ const server = http.createServer((req, res) => {
+ const match = (req.url ?? '/').match(/^\/hop\/(\d+)/);
+ const n = match ? parseInt(match[1], 10) : -1;
+ if (n > 0) {
+ res.writeHead(statusCode, {
+ Location: `http://127.0.0.1:${port}/hop/${n - 1}`,
+ });
+ res.end();
+ return;
+ }
+ state.redirectHit = true;
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('final');
+ });
+
+ const destroySockets = trackSockets(server);
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+
+ return {
+ url: `http://127.0.0.1:${port}/hop/${depth}`,
+ get redirectHit() {
+ return state.redirectHit;
+ },
+ close: destroySockets,
+ };
+}
+
+/**
+ * Same-origin redirect chain ending at a real MCP server at `/mcp`. URL
+ * `/hop/N-1` redirects through N hops total, with the final hop landing on
+ * `/mcp`. Used to verify MCP traffic survives the maximum allowed redirect
+ * depth.
+ */
+async function createRedirectChainToMCP(depth: number, statusCode: 307 | 308): Promise<TestServer> {
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
+ const state = { redirectHit: false };
+ const mcpPath = '/mcp';
+ const port = await getFreePort();
+ const mcpHandler = createMCPRequestHandler(sessions, 'mcp-via-chain');
+
+ const server = http.createServer(async (req, res) => {
+ const url = req.url ?? '/';
+
+ if (url.startsWith(mcpPath)) {
+ state.redirectHit = true;
+ await mcpHandler(req, res);
+ return;
+ }
+
+ const match = url.match(/^\/hop\/(\d+)/);
+ const n = match ? parseInt(match[1], 10) : 0;
+ const nextLocation =
+ n > 0 ? `http://127.0.0.1:${port}/hop/${n - 1}` : `http://127.0.0.1:${port}${mcpPath}`;
+ res.writeHead(statusCode, { Location: nextLocation });
+ res.end();
+ });
+
+ const destroySockets = trackSockets(server);
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+
+ return {
+ url: `http://127.0.0.1:${port}/hop/${depth - 1}`,
+ get redirectHit() {
+ return state.redirectHit;
+ },
+ close: async () => {
+ await closeMCPSessions(sessions);
+ await destroySockets();
+ },
+ };
+}
+
+interface CapturedRequest {
+ method: string;
+ headers: http.IncomingHttpHeaders;
+ body: string;
+}
+
+interface HeaderCaptureServer {
+ url: string;
+ receivedHeaders: http.IncomingHttpHeaders[];
+ receivedRequests: CapturedRequest[];
+ close: () => Promise<void>;
+}
+
+/**
+ * Captures every incoming request's headers, method, and body, then replies
+ * with a benign 200 so tests can assert what actually crossed a redirect
+ * boundary (header stripping, 307/308 method preservation, payload survival).
+ */
+async function createHeaderCaptureServer(): Promise<HeaderCaptureServer> {
+ const headers: http.IncomingHttpHeaders[] = [];
+ const requests: CapturedRequest[] = [];
+ const server = http.createServer((req, res) => {
+ headers.push({ ...req.headers });
+ const chunks: Buffer[] = [];
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
+ req.on('end', () => {
+ requests.push({
+ method: req.method ?? '',
+ headers: { ...req.headers },
+ body: Buffer.concat(chunks).toString('utf8'),
+ });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end('{}');
+ });
+ });
+ const destroySockets = trackSockets(server);
+ const port = await getFreePort();
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+ return {
+ url: `http://127.0.0.1:${port}/`,
+ receivedHeaders: headers,
+ receivedRequests: requests,
+ close: destroySockets,
+ };
+}
+
+/**
+ * Issues a single 307/308 redirect to `redirectTarget` (which lives on a
+ * different port and is therefore a different origin). Used to verify
+ * cross-origin credential-stripping behavior.
+ */
+async function createCrossOriginRedirectingServer(
+ redirectTarget: string,
+ statusCode: 307 | 308,
+): Promise<TestServer> {
+ const state = { redirectHit: false };
+ const server = http.createServer((_req, res) => {
+ state.redirectHit = true;
+ res.writeHead(statusCode, { Location: redirectTarget });
+ res.end();
+ });
+ const destroySockets = trackSockets(server);
+ const port = await getFreePort();
+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));
+ return {
+ url: `http://127.0.0.1:${port}/`,
+ get redirectHit() {
+ return state.redirectHit;
+ },
+ close: destroySockets,
+ };
+}
+
+describe('MCP SSRF protection – 307/308 redirect following', () => {
+ let server: TestServer | undefined;
+ let conn: MCPConnection | null;
+
+ afterEach(async () => {
+ await safeDisconnect(conn);
+ conn = null;
+ if (server) {
+ await server.close();
+ server = undefined;
+ }
+ jest.restoreAllMocks();
+ });
+
+ it('should follow a 308 redirect and connect to the target MCP server', async () => {
+ server = await createRedirectingMCPServer(308);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-308',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ await conn.connect();
+ const tools = await conn.fetchTools();
+ expect(tools).toBeDefined();
+ expect(server.redirectHit).toBe(true);
+ });
+
+ it('should follow a 307 redirect and connect to the target MCP server', async () => {
+ server = await createRedirectingMCPServer(307);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-307',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ await conn.connect();
+ const tools = await conn.fetchTools();
+ expect(tools).toBeDefined();
+ expect(server.redirectHit).toBe(true);
+ });
+
+ it('should stop following redirects after 5 hops', async () => {
+ server = await createRedirectChain(6, 308);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-too-deep',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ await expect(conn.connect()).rejects.toThrow();
+ expect(server.redirectHit).toBe(false);
+ });
+
+ it('should reach the target after exactly 5 redirect hops (at the limit)', async () => {
+ server = await createRedirectChain(5, 308);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-at-limit',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ await expect(conn.connect()).rejects.toThrow();
+ expect(server.redirectHit).toBe(true);
+ });
+
+ it('should complete an MCP request through 5 same-origin redirect hops', async () => {
+ server = await createRedirectChainToMCP(5, 308);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-chain-mcp',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ await conn.connect();
+ const tools = await conn.fetchTools();
+ expect(tools).toBeDefined();
+ expect(server.redirectHit).toBe(true);
+ });
+});
+
+describe('MCP SSRF protection – 307/308 redirect to private IP', () => {
+ let server: TestServer | undefined;
+ let conn: MCPConnection | null;
+
+ afterEach(async () => {
+ await safeDisconnect(conn);
+ conn = null;
+ if (server) {
+ await server.close();
+ server = undefined;
+ }
+ jest.restoreAllMocks();
+ });
+
+ it('should block a 308 redirect whose target resolves to a private IP (allowlist scenario)', async () => {
+ const capture = await createHeaderCaptureServer();
+ try {
+ server = await createCrossOriginRedirectingServer(capture.url, 308);
+ mockedResolveHostnameSSRF.mockResolvedValueOnce(true);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-ssrf-block',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ await expect(conn.connect()).rejects.toThrow();
+ expect(server.redirectHit).toBe(true);
+ expect(capture.receivedHeaders).toHaveLength(0);
+ } finally {
+ await capture.close();
+ }
+ });
+
+ it('should block a 307 redirect whose target resolves to a private IP (SSRF protection on)', async () => {
+ const capture = await createHeaderCaptureServer();
+ try {
+ server = await createCrossOriginRedirectingServer(capture.url, 307);
+ mockedResolveHostnameSSRF.mockResolvedValueOnce(true);
+
+ conn = new MCPConnection({
+ serverName: 'redirect-ssrf-block-on',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: true,
+ });
+
+ await expect(conn.connect()).rejects.toThrow();
+ expect(server.redirectHit).toBe(true);
+ expect(capture.receivedHeaders).toHaveLength(0);
+ } finally {
+ await capture.close();
+ }
+ });
+});
+
+describe('MCP SSRF protection – cross-origin credential stripping on redirect', () => {
+ let server: TestServer | undefined;
+ let conn: MCPConnection | null;
+
+ afterEach(async () => {
+ await safeDisconnect(conn);
+ conn = null;
+ if (server) {
+ await server.close();
+ server = undefined;
+ }
+ jest.restoreAllMocks();
+ });
+
+ it('should strip Authorization, runtime headers, and config headers when 308-redirecting cross-origin', async () => {
+ const capture = await createHeaderCaptureServer();
+ try {
+ server = await createCrossOriginRedirectingServer(capture.url, 308);
+
+ conn = new MCPConnection({
+ serverName: 'cross-origin-strip',
+ serverConfig: {
+ type: 'streamable-http',
+ url: server.url,
+ headers: {
+ 'X-Config-Api-Key': 'config-level-secret',
+ 'X-Internal-Token': 'config-internal-token',
+ },
+ },
+ oauthTokens: {
+ access_token: 'super-secret-bearer-token',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ },
+ useSSRFProtection: false,
+ });
+ conn.setRequestHeaders({ 'X-Runtime-Api-Key': 'runtime-private-api-key' });
+
+ await expect(conn.connect()).rejects.toThrow();
+ expect(server.redirectHit).toBe(true);
+ expect(capture.receivedHeaders.length).toBeGreaterThan(0);
+
+ for (const headers of capture.receivedHeaders) {
+ expect(headers['authorization']).toBeUndefined();
+ expect(headers['x-runtime-api-key']).toBeUndefined();
+ expect(headers['x-config-api-key']).toBeUndefined();
+ expect(headers['x-internal-token']).toBeUndefined();
+ expect(headers['mcp-session-id']).toBeUndefined();
+ expect(headers['cookie']).toBeUndefined();
+ /** Non-credential protocol headers must survive — guards against a
+ * regression that strips everything indiscriminately. */
+ expect(headers['accept']).toBeDefined();
+ expect(headers['content-type']).toBeDefined();
+ }
+ } finally {
+ await capture.close();
+ }
+ });
+
+ it('should preserve credential headers on same-origin 308 redirects (Coda-style flow)', async () => {
+ server = await createRedirectingMCPServer(308);
+
+ conn = new MCPConnection({
+ serverName: 'same-origin-preserve',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ oauthTokens: {
+ access_token: 'preserved-bearer',
+ token_type: 'Bearer',
+ obtained_at: Date.now(),
+ },
+ useSSRFProtection: false,
+ });
+
+ /** Same-origin redirect → MCP session continuity must hold across hops. */
+ await conn.connect();
+ const tools = await conn.fetchTools();
+ expect(tools).toBeDefined();
+ });
+
+ it('treats a protocol downgrade as cross-origin (URL.origin contract)', () => {
+ /**
+ * The cross-origin strip path keys off `targetUrl.origin !== originalOrigin`.
+ * `URL.origin` is defined as `scheme + "://" + host + ":" + port`, so a
+ * same-host `https → http` redirect produces a different origin and trips
+ * the strip path through the existing logic — no separate code path is
+ * needed for protocol downgrade. Pin the URL contract here instead of
+ * standing up a TLS fixture just to re-prove the spec.
+ */
+ expect(new URL('https://example.com/a').origin).not.toBe(
+ new URL('http://example.com/a').origin,
+ );
+ expect(new URL('https://example.com:443/a').origin).not.toBe(
+ new URL('http://example.com:80/a').origin,
+ );
+ });
+});
+
+describe('MCP SSRF protection – customFetch input shapes', () => {
+ let target: Omit<TestServer, 'redirectHit'> | undefined;
+ let conn: MCPConnection | null;
+
+ afterEach(async () => {
+ await safeDisconnect(conn);
+ conn = null;
+ if (target) {
+ await target.close();
+ target = undefined;
+ }
+ jest.restoreAllMocks();
+ });
+
+ /**
+ * Reach into the private fetch factory to exercise it with each
+ * `RequestInfo` shape undici accepts. `Request.toString()` returns
+ * `"[object Request]"`, so a naive `new URL(input.toString())` for origin
+ * derivation would throw before any network call — this test pins that
+ * regression.
+ */
+ function getCustomFetch(connection: MCPConnection): CustomFetch {
+ const factory = (
+ connection as unknown as {
+ createFetchFunction: (
+ getHeaders: () => Record<string, string> | null | undefined,
+ ) => CustomFetch;
+ }
+ ).createFetchFunction;
+ return factory.call(connection, () => null);
+ }
+
+ it.each<['string' | 'URL' | 'Request']>([['string'], ['URL'], ['Request']])(
+ 'should accept a %s input without throwing on URL derivation',
+ async (shape) => {
+ target = await createStreamableServer();
+
+ conn = new MCPConnection({
+ serverName: `customfetch-${shape.toLowerCase()}`,
+ serverConfig: { type: 'streamable-http', url: target.url },
+ useSSRFProtection: false,
+ });
+
+ const customFetch = getCustomFetch(conn);
+ const inputs: Record<typeof shape, () => UndiciRequestInfo> = {
+ string: () => target!.url,
+ URL: () => new URL(target!.url),
+ Request: () => new UndiciRequest(target!.url, { method: 'GET' }),
+ };
+
+ const response = await customFetch(inputs[shape]());
+ expect(response.status).toBeGreaterThanOrEqual(200);
+ await response.body?.cancel().catch(() => undefined);
+ },
+ );
+
+ it('should preserve headers carried on a Request input when no override headers are supplied', async () => {
+ /**
+ * Pre-fix regression: `buildFetchInit` unconditionally set `headers: {}`
+ * when neither `init.headers` nor runtime headers contributed anything.
+ * That overrode the headers attached to the `Request` itself, dropping
+ * Authorization / mcp-session-id / protocol negotiation headers that
+ * wrappers commonly bake onto the `Request` object directly.
+ */
+ const capture = await createHeaderCaptureServer();
+ try {
+ conn = new MCPConnection({
+ serverName: 'customfetch-request-headers',
+ serverConfig: { type: 'streamable-http', url: capture.url },
+ useSSRFProtection: false,
+ });
+
+ const customFetch = getCustomFetch(conn);
+ const request = new UndiciRequest(capture.url, {
+ method: 'GET',
+ headers: {
+ Authorization: 'Bearer request-input-token',
+ 'X-Wrapper-Header': 'wrapper-supplied',
+ },
+ });
+
+ const response = await customFetch(request);
+ expect(response.status).toBe(200);
+ await response.body?.cancel().catch(() => undefined);
+
+ expect(capture.receivedHeaders.length).toBeGreaterThan(0);
+ const headers = capture.receivedHeaders[0];
+ expect(headers['authorization']).toBe('Bearer request-input-token');
+ expect(headers['x-wrapper-header']).toBe('wrapper-supplied');
+ } finally {
+ await capture.close();
+ }
+ });
+
+ it('should preserve POST method and body across a 308 redirect when input is a Request', async () => {
+ /**
+ * Pre-fix regression: switching `url` to the `Location` string on
+ * redirect dropped the original `Request`'s method and body, so a
+ * redirected POST silently became a GET with no payload — the exact
+ * thing 307/308 are designed to forbid.
+ */
+ const capture = await createHeaderCaptureServer();
+ let server: TestServer | undefined;
+ try {
+ server = await createCrossOriginRedirectingServer(capture.url, 308);
+
+ conn = new MCPConnection({
+ serverName: 'customfetch-request-redirect-post',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ const customFetch = getCustomFetch(conn);
+ const payload = JSON.stringify({ jsonrpc: '2.0', method: 'ping', id: 1 });
+ const request = new UndiciRequest(server.url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: payload,
+ });
+
+ const response = await customFetch(request);
+ expect(response.status).toBe(200);
+ await response.body?.cancel().catch(() => undefined);
+
+ expect(server.redirectHit).toBe(true);
+ expect(capture.receivedRequests.length).toBeGreaterThan(0);
+ const last = capture.receivedRequests[capture.receivedRequests.length - 1];
+ expect(last.method).toBe('POST');
+ expect(last.body).toBe(payload);
+ } finally {
+ await capture.close();
+ if (server) {
+ await server.close();
+ }
+ }
+ });
+
+ it("should honor the Request's AbortController.signal even after Request -> (string, init) normalization", async () => {
+ /**
+ * Pre-fix regression: `resolveFetchInput` copied method/body/headers
+ * out of a `Request` input but dropped `Request.signal`. Callers that
+ * wired an `AbortController` onto the `Request` for cancellation or
+ * timeouts lost that wiring on entry to the redirect loop, so an abort
+ * after the request started had no effect.
+ */
+ target = await createStreamableServer();
+ conn = new MCPConnection({
+ serverName: 'customfetch-request-signal',
+ serverConfig: { type: 'streamable-http', url: target.url },
+ useSSRFProtection: false,
+ });
+
+ const customFetch = getCustomFetch(conn);
+ const controller = new AbortController();
+ const request = new UndiciRequest(target.url, {
+ method: 'GET',
+ signal: controller.signal,
+ });
+ /** Abort before the fetch lands so we don't race the real socket. */
+ controller.abort();
+
+ await expect(customFetch(request)).rejects.toThrow();
+ });
+
+ it('should not crash on a cross-origin redirect when no headers are present', async () => {
+ /**
+ * Pre-fix regression: `buildFetchInit` skips setting `headers` when
+ * nothing contributes any, but the cross-origin strip path read
+ * `currentInit.headers` unconditionally and called `Object.entries`
+ * on `undefined`, throwing `TypeError`. Guarded so a no-headers
+ * cross-origin hop returns the response cleanly.
+ */
+ const capture = await createHeaderCaptureServer();
+ let server: TestServer | undefined;
+ try {
+ server = await createCrossOriginRedirectingServer(capture.url, 307);
+
+ conn = new MCPConnection({
+ serverName: 'customfetch-redirect-no-headers',
+ serverConfig: { type: 'streamable-http', url: server.url },
+ useSSRFProtection: false,
+ });
+
+ const customFetch = getCustomFetch(conn);
+ const response = await customFetch(server.url);
+ expect(response.status).toBe(200);
+ await response.body?.cancel().catch(() => undefined);
+ expect(server.redirectHit).toBe(true);
+ } finally {
+ await capture.close();
+ if (server) {
+ await server.close();
+ }
+ }
+ });
+});
+
describe('MCP SSRF protection – WebSocket DNS resolution', () => {
let conn: MCPConnection | null;
diff --git a/packages/api/src/mcp/connection.ts b/packages/api/src/mcp/connection.ts
index 8dc857cd3b..904a24f155 100644
--- a/packages/api/src/mcp/connection.ts
+++ b/packages/api/src/mcp/connection.ts
@@ -72,6 +72,144 @@ const DEFAULT_TIMEOUT = 60000;
/** SSE connections through proxies may need longer initial handshake time */
const SSE_CONNECT_TIMEOUT = 120000;
const DEFAULT_INIT_TIMEOUT = 30000;
+/** Max 307/308 redirects to follow per request (prevents redirect loops) */
+const MAX_REDIRECTS = 5;
+
+/**
+ * Headers stripped before forwarding a request across an origin boundary on
+ * 307/308 redirects, mirroring browser/Fetch-spec behavior. These headers can
+ * carry credentials (OAuth bearer, MCP session, cookies) that an attacker
+ * controlling a redirecting MCP endpoint could otherwise exfiltrate by sending
+ * a `Location` to a host they own.
+ */
+const CROSS_ORIGIN_FORBIDDEN_HEADERS = new Set([
+ 'authorization',
+ 'proxy-authorization',
+ 'cookie',
+ 'mcp-session-id',
+]);
+
+/**
+ * Normalizes a fetch input + init pair so the redirect loop only ever has
+ * to deal with `(string, init)`. When `input` is a `Request`, its method,
+ * headers, and body are baked into the returned init — explicit init values
+ * win (matching Fetch-spec semantics) and the body is buffered with
+ * `arrayBuffer()` so 307/308 retries can replay it on the new URL. Without
+ * this, switching `url` to a `Location` string on redirect would silently
+ * drop the original POST method and request payload.
+ */
+async function resolveFetchInput(
+ input: UndiciRequestInfo,
+ init: UndiciRequestInit | undefined,
+): Promise<{ urlString: string; resolvedInit: UndiciRequestInit | undefined }> {
+ if (typeof input === 'string') {
+ return { urlString: input, resolvedInit: init };
+ }
+ if (input instanceof URL) {
+ return { urlString: input.href, resolvedInit: init };
+ }
+ /**
+ * Treat anything else as a `Request`. Duck-typed instead of
+ * `instanceof undici.Request` because requests handed to a generic fetch
+ * wrapper can come from a different undici realm and fail the prototype
+ * check while still implementing the same shape. The `as unknown as` cast
+ * is needed because undici's `Headers` and DOM's `Headers` have
+ * incompatible declared shapes even though they are interchangeable at
+ * runtime for the methods we use.
+ */
+ const req = input as unknown as {
+ url: string;
+ method: string;
+ headers: { entries: () => Iterable<[string, string]> };
+ body: unknown;
+ signal: AbortSignal | null;
+ arrayBuffer: () => Promise<ArrayBuffer>;
+ };
+ const reqHeaders = Object.fromEntries(req.headers.entries());
+ const initHeaders = normalizeInitHeaders(init);
+ const mergedHeaders = { ...reqHeaders, ...initHeaders };
+ /** Body must be buffered before we hand it off — the original stream is
+ * single-shot, so a redirect retry with the same stream would crash with
+ * `body has been read`. Empty/no-body Requests skip the read entirely. */
+ const reqBody = req.body ? await req.arrayBuffer() : undefined;
+ /** Forward the `Request`'s abort signal so callers that wired up an
+ * `AbortController` (for timeout / user-cancellation) keep working after
+ * we re-shape the input into `(string, init)`. Explicit `init.signal`
+ * still wins per Fetch-spec semantics. */
+ const signal = init?.signal ?? req.signal ?? undefined;
+ return {
+ urlString: req.url,
+ resolvedInit: {
+ ...init,
+ method: init?.method ?? req.method,
+ body: init?.body ?? (reqBody as unknown as UndiciRequestInit['body']),
+ headers: mergedHeaders,
+ signal,
+ },
+ };
+}
+
+function normalizeInitHeaders(init: UndiciRequestInit | undefined): Record<string, string> {
+ if (!init?.headers) {
+ return {};
+ }
+ if (init.headers instanceof Headers) {
+ return Object.fromEntries(init.headers.entries());
+ }
+ if (Array.isArray(init.headers)) {
+ return Object.fromEntries(init.headers);
+ }
+ return init.headers as Record<string, string>;
+}
+
+function buildFetchInit(
+ init: UndiciRequestInit | undefined,
+ dispatcher: Agent,
+ requestHeaders: Record<string, string> | null | undefined,
+): UndiciRequestInit {
+ const hasInitHeaders = init?.headers != null;
+ const hasRuntimeHeaders = requestHeaders != null && Object.keys(requestHeaders).length > 0;
+ /**
+ * If neither `init.headers` nor runtime headers contribute anything, leave
+ * `headers` off the returned init entirely. Setting `headers: {}` would
+ * blow away the headers carried on a `Request` input — auth/session tokens
+ * and protocol negotiation headers — even when no redirect is involved.
+ */
+ if (!hasInitHeaders && !hasRuntimeHeaders) {
+ return { ...init, redirect: 'manual', dispatcher };
+ }
+ const initHeaders = normalizeInitHeaders(init);
+ const headers = hasRuntimeHeaders ? { ...initHeaders, ...requestHeaders } : initHeaders;
+ return {
+ ...init,
+ redirect: 'manual',
+ headers,
+ dispatcher,
+ };
+}
+
+/**
+ * Drops credential-bearing headers when a 307/308 redirect crosses an origin
+ * boundary. Removes the always-forbidden set plus any caller-supplied secret
+ * headers (runtime `setRequestHeaders` values and config-level API keys).
+ */
+function stripCrossOriginHeaders(
+ headers: Record<string, string>,
+ secretHeaderKeys: ReadonlySet<string>,
+): Record<string, string> {
+ const stripped: Record<string, string> = {};
+ for (const [key, value] of Object.entries(headers)) {
+ const lowered = key.toLowerCase();
+ if (CROSS_ORIGIN_FORBIDDEN_HEADERS.has(lowered)) {
+ continue;
+ }
+ if (secretHeaderKeys.has(lowered)) {
+ continue;
+ }
+ stripped[key] = value;
+ }
+ return stripped;
+}
interface CircuitBreakerState {
cycleCount: number;
@@ -428,6 +566,7 @@ export class MCPConnection extends EventEmitter {
getHeaders: () => Record<string, string> | null | undefined,
timeout?: number,
sseBodyTimeout?: number,
+ configuredSecretHeaderKeys?: ReadonlySet<string>,
): (input: UndiciRequestInfo, init?: UndiciRequestInit) => Promise<UndiciResponse> {
const ssrfConnect = this.useSSRFProtection ? createSSRFSafeUndiciConnect() : undefined;
const connectOpts = ssrfConnect != null ? { connect: ssrfConnect } : {};
@@ -449,38 +588,81 @@ export class MCPConnection extends EventEmitter {
this.agents.push(getAgent);
}
- return function customFetch(
+ return async function customFetch(
input: UndiciRequestInfo,
init?: UndiciRequestInit,
): Promise<UndiciResponse> {
- const isGet = (init?.method ?? 'GET').toUpperCase() === 'GET';
- const dispatcher = isGet && getAgent ? getAgent : postAgent;
+ /**
+ * Resolve the input shape upfront so the redirect loop can work with a
+ * (string url, init) pair uniformly. When `input` is a `Request`, we
+ * pull its method, headers, and body into the init — the body is
+ * buffered because `Request.body` is a one-shot stream that can't be
+ * replayed across redirect hops, and switching `url` to the new
+ * `Location` would otherwise drop the original method/body and turn a
+ * redirected POST into a GET with no payload.
+ */
+ const { urlString, resolvedInit } = await resolveFetchInput(input, init);
+ const isGet = (resolvedInit?.method ?? 'GET').toUpperCase() === 'GET';
+ const dispatcher = isGet && getAgent ? getAgent : postAgent;
const requestHeaders = getHeaders();
- if (!requestHeaders) {
- return undiciFetch(input, { ...init, redirect: 'manual', dispatcher });
- }
+ /**
+ * Headers that originated from user/server configuration — runtime
+ * `setRequestHeaders` plus any keys baked into the transport at
+ * construction time (e.g. `serverConfig.headers` API keys). All are
+ * treated as credentials and stripped on cross-origin redirect.
+ */
+ const secretHeaderKeys: ReadonlySet<string> = new Set([
+ ...Object.keys(requestHeaders ?? {}).map((key) => key.toLowerCase()),
+ ...(configuredSecretHeaderKeys ?? []),
+ ]);
- let initHeaders: Record<string, string> = {};
- if (init?.headers) {
- if (init.headers instanceof Headers) {
- initHeaders = Object.fromEntries(init.headers.entries());
- } else if (Array.isArray(init.headers)) {
- initHeaders = Object.fromEntries(init.headers);
- } else {
- initHeaders = init.headers as Record<string, string>;
+ let currentInit = buildFetchInit(resolvedInit, dispatcher, requestHeaders);
+ let currentUrlString = urlString;
+ const originalOrigin = new URL(currentUrlString).origin;
+
+ for (let redirects = 0; ; redirects++) {
+ const response = await undiciFetch(currentUrlString, currentInit);
+ const isMethodPreservingRedirect = response.status === 307 || response.status === 308;
+
+ if (!isMethodPreservingRedirect || redirects >= MAX_REDIRECTS) {
+ return response;
}
- }
- return undiciFetch(input, {
- ...init,
- redirect: 'manual',
- headers: {
- ...initHeaders,
- ...requestHeaders,
- },
- dispatcher,
- });
+ const location = response.headers.get('location');
+ if (!location) {
+ return response;
+ }
+
+ const targetUrl = new URL(location, currentUrlString);
+
+ /**
+ * Defense-in-depth SSRF check on every redirect hop. The dispatcher's
+ * connect-time `lookup` only fires when `useSSRFProtection` is true;
+ * allowlist deployments disable it, and the allowlist only covers the
+ * originally-configured URL — not server-controlled redirect targets.
+ */
+ if (await resolveHostnameSSRF(targetUrl.hostname)) {
+ logger.warn(
+ `[MCP] Blocked redirect to private/reserved address: ${sanitizeUrlForLogging(targetUrl)}`,
+ );
+ return response;
+ }
+
+ await response.body?.cancel().catch(() => undefined);
+
+ if (targetUrl.origin !== originalOrigin && currentInit.headers != null) {
+ currentInit = {
+ ...currentInit,
+ headers: stripCrossOriginHeaders(
+ currentInit.headers as Record<string, string>,
+ secretHeaderKeys,
+ ),
+ };
+ }
+
+ currentUrlString = targetUrl.href;
+ }
};
}
@@ -575,6 +757,9 @@ export class MCPConnection extends EventEmitter {
...(ssrfConnect != null ? { connect: ssrfConnect } : {}),
});
this.agents.push(sseAgent);
+ const sseConfiguredSecretHeaderKeys: ReadonlySet<string> = new Set(
+ Object.keys(headers).map((key) => key.toLowerCase()),
+ );
const transport = new SSEClientTransport(url, {
requestInit: {
/** User/OAuth headers override SSE defaults */
@@ -598,6 +783,8 @@ export class MCPConnection extends EventEmitter {
fetch: this.createFetchFunction(
this.getRequestHeaders.bind(this),
sseTimeout,
+ undefined,
+ sseConfiguredSecretHeaderKeys,
) as unknown as FetchLike,
});
@@ -627,6 +814,9 @@ export class MCPConnection extends EventEmitter {
headers['Authorization'] = `Bearer ${this.oauthTokens.access_token}`;
}
+ const httpConfiguredSecretHeaderKeys: ReadonlySet<string> = new Set(
+ Object.keys(headers).map((key) => key.toLowerCase()),
+ );
const transport = new StreamableHTTPClientTransport(url, {
requestInit: {
headers,
@@ -636,6 +826,7 @@ export class MCPConnection extends EventEmitter {
this.getRequestHeaders.bind(this),
this.timeout,
this.sseReadTimeout || DEFAULT_SSE_READ_TIMEOUT,
+ httpConfiguredSecretHeaderKeys,
) as unknown as FetchLike,
});