From 7cd18ca4e4f1dfc5942d5afcb45759ddddd5a7f0 Mon Sep 17 00:00:00 2001 From: ordinary being Date: Tue, 27 Oct 2026 21:29:32 +0800 Subject: [PATCH] fix(cli): validate every http_fetch redirect target (#4534) http_fetch validated only the initial URL, then called fetch with its default redirect:'follow'. A public URL could redirect to loopback/RFC1918/cloud-metadata or switch to file:// without ever passing validateUrl(), bypassing the SSRF allowlist. This is the redirect escalation called out as the natural follow-up to #4503/#4504.\n\nFollow redirects manually with redirect:'manual': cap at 10 hops, run validateUrl() on every Location, cancel redirect bodies, drop Authorization/Cookie/Proxy-Authorization on cross-origin hops, and apply fetch's 303/301/302 method rules. The reported URL is the final validated URL. Redirect validation failures return the same error codes as initial-URL failures (PRIVATE_ADDRESS/FORBIDDEN_PROTOCOL), with REDIRECT_LIMIT for the hop cap.\n\nSix regression tests mock fetch: loopback, IPv4-mapped metadata, file:// redirect, public relative redirect + final URL, cross-origin auth stripping, and the redirect limit. Baseline fails all six; candidate passes. Existing 37 http-fetch tests still pass, 43/43 total. tsc reports no errors in the changed file. --- .../http-fetch-redirect-ssrf.test.ts | 103 ++++++++++++++++++ .../cli/src/mcp-tools/http-fetch-tools.ts | 103 ++++++++++++++++-- 2 files changed, 197 insertions(+), 9 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/http-fetch-redirect-ssrf.test.ts diff --git a/v3/@claude-flow/cli/__tests__/http-fetch-redirect-ssrf.test.ts b/v3/@claude-flow/cli/__tests__/http-fetch-redirect-ssrf.test.ts new file mode 100644 index 0000000000..78a23da3f9 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/http-fetch-redirect-ssrf.test.ts @@ -0,0 +1,103 @@ +/** + * #4503 follow-up: http_fetch validated only the initial URL and let fetch + * follow redirects automatically. A public URL could therefore redirect to + * loopback/RFC1918/cloud-metadata (or another protocol) without ever passing + * validateUrl(). Redirects are now followed manually and every hop is checked. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { httpFetchExecute } from '../src/mcp-tools/http-fetch-tools.js'; + +function redirect(location: string, status = 302): Response { + return new Response(null, { status, headers: { location } }); +} + +function ok(body = 'final'): Response { + return new Response(body, { + status: 200, + headers: { 'content-type': 'text/plain' }, + }); +} + +afterEach(() => { + vi.restoreAllMocks(); + delete process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH; +}); + +describe('http_fetch redirect SSRF guard', () => { + it('blocks a public -> loopback redirect without issuing the second request', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(redirect('http://127.0.0.1:8080/secret')); + + const result = await httpFetchExecute({ url: 'https://example.com/start' }); + + expect(result.success).toBe(false); + expect(result.errorCode).toBe('PRIVATE_ADDRESS'); + expect(result.error).toContain('redirect blocked'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('blocks a redirect to cloud metadata via an IPv4-mapped IPv6 literal', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(redirect('http://[::ffff:169.254.169.254]/latest/meta-data/')); + + const result = await httpFetchExecute({ url: 'https://example.com/start' }); + + expect(result.success).toBe(false); + expect(result.errorCode).toBe('PRIVATE_ADDRESS'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('blocks a redirect that switches to a non-http protocol', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(redirect('file:///etc/passwd')); + + const result = await httpFetchExecute({ url: 'https://example.com/start' }); + + expect(result.success).toBe(false); + expect(result.errorCode).toBe('FORBIDDEN_PROTOCOL'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('follows a validated public relative redirect and reports the final URL', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(redirect('/final')) + .mockResolvedValueOnce(ok('redirected-body')); + + const result = await httpFetchExecute({ url: 'https://example.com/start' }); + + expect(result.success).toBe(true); + expect(result.status).toBe(200); + expect(result.body).toBe('redirected-body'); + expect(result.url).toBe('https://example.com/final'); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(fetchMock.mock.calls[1][0]).toBe('https://example.com/final'); + }); + + it('drops Authorization when a redirect crosses origins', async () => { + process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH = '1'; + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(redirect('https://other.example/final')) + .mockResolvedValueOnce(ok()); + + const result = await httpFetchExecute({ + url: 'https://example.com/start', + headers: { Authorization: 'Bearer secret' }, + }); + + expect(result.success).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(2); + const secondInit = fetchMock.mock.calls[1][1] as RequestInit; + expect(secondInit.headers).not.toHaveProperty('Authorization'); + }); + + it('stops at the redirect limit', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch') + .mockImplementation(async () => redirect('/again')); + + const result = await httpFetchExecute({ url: 'https://example.com/start' }); + + expect(result.success).toBe(false); + expect(result.errorCode).toBe('REDIRECT_LIMIT'); + expect(fetchMock).toHaveBeenCalledTimes(11); + }); +}); diff --git a/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts index 9fa3df6ca9..752fe250d5 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts @@ -15,7 +15,7 @@ * - DEFAULT-REFUSES Authorization / Cookie / X-Auth-* (CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1 opt-in) * - hard timeout 30s default, 60s ceiling * - response truncated to 256KB default, 1MB ceiling - * - no redirects auto-followed beyond fetch's default; status reported as-is + * - redirects followed manually, max 10, every hop re-validated by the same allowlist * * @module @claude-flow/cli/mcp-tools/http-fetch */ @@ -26,6 +26,8 @@ const DEFAULT_TIMEOUT_MS = 30_000; const MAX_TIMEOUT_MS = 60_000; const DEFAULT_MAX_RESPONSE_BYTES = 256 * 1024; // 256 KB const MAX_RESPONSE_BYTES = 1024 * 1024; // 1 MB +const MAX_REDIRECTS = 10; +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); const DEFAULT_USER_AGENT = 'ruflo-http-fetch/1.0'; const FORBIDDEN_HEADER_PREFIXES = ['x-auth-', 'x-api-key'] as const; @@ -264,13 +266,96 @@ export async function httpFetchExecute(input: Record): Promise< const timer = setTimeout(() => controller.abort(), timeoutMs); try { - const response = await fetch(parsed.toString(), { - method, - headers, - body: method === 'GET' || method === 'HEAD' ? undefined : body, - signal: controller.signal, - // Keep redirect default ('follow') — caller sees final status/url. - }); + let currentUrl = parsed; + let currentMethod = method; + let currentBody = body; + let response: Response; + let redirects = 0; + + // Do not let fetch follow redirects on its own: only the initial URL was + // validated, so an automatic follow could reach loopback/RFC1918 or switch + // protocols after passing the allowlist. Every hop is validated with the + // same rules; sensitive headers are dropped when the origin changes. + while (true) { + response = await fetch(currentUrl.toString(), { + method: currentMethod, + headers, + body: currentMethod === 'GET' || currentMethod === 'HEAD' ? undefined : currentBody, + signal: controller.signal, + redirect: 'manual', + }); + + if (!REDIRECT_STATUSES.has(response.status)) break; + + const location = response.headers.get('location'); + if (!location) break; + + if (redirects++ >= MAX_REDIRECTS) { + try { await response.body?.cancel(); } catch { /* ignore */ } + return { + success: false, + status: response.status, + statusText: response.statusText, + headers: {}, + body: '', + bodyTruncated: false, + bytesRead: 0, + durationMs: Date.now() - startedAt, + url: currentUrl.toString(), + method, + error: `too many redirects (max ${MAX_REDIRECTS})`, + errorCode: 'REDIRECT_LIMIT', + }; + } + + let nextUrl: URL; + try { + nextUrl = validateUrl(new URL(location, currentUrl).toString()); + } catch (e) { + try { await response.body?.cancel(); } catch { /* ignore */ } + const err = e as HttpFetchValidationError; + return { + success: false, + status: response.status, + statusText: response.statusText, + headers: {}, + body: '', + bodyTruncated: false, + bytesRead: 0, + durationMs: Date.now() - startedAt, + url: currentUrl.toString(), + method, + error: `redirect blocked: ${err.message}`, + errorCode: err.code ?? 'REDIRECT_BLOCKED', + }; + } + + // The redirect response body is not returned; release the connection + // before issuing the next request. A body-less 3xx is also fine. + try { await response.body?.cancel(); } catch { /* ignore */ } + + if (nextUrl.origin !== currentUrl.origin) { + for (const key of Object.keys(headers)) { + const lower = key.toLowerCase(); + if (lower === 'authorization' || lower === 'cookie' || lower === 'proxy-authorization') { + delete headers[key]; + } + } + } + + // Match fetch's redirect method rules: 303 becomes GET except for + // GET/HEAD, while 301/302 only rewrite POST to GET. 307/308 preserve + // both method and body. + if ( + (response.status === 303 && currentMethod !== 'GET' && currentMethod !== 'HEAD') || + ((response.status === 301 || response.status === 302) && currentMethod === 'POST') + ) { + currentMethod = 'GET'; + currentBody = undefined; + } + + currentUrl = nextUrl; + } // Drain the body with byte budget. Use array-buffer first to bound size // deterministically before decoding to UTF-8. @@ -318,7 +403,7 @@ export async function httpFetchExecute(input: Record): Promise< bodyTruncated, bytesRead, durationMs: Date.now() - startedAt, - url: parsed.toString(), + url: currentUrl.toString(), method, }; } catch (e) {