diff --git a/v3/@claude-flow/cli/__tests__/http-fetch-dns-pinning.test.ts b/v3/@claude-flow/cli/__tests__/http-fetch-dns-pinning.test.ts new file mode 100644 index 0000000000..1cf327564e --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/http-fetch-dns-pinning.test.ts @@ -0,0 +1,142 @@ +/** + * http_fetch SSRF via DNS: the allowlist checked only the URL's hostname text, and fetch() + * then resolved the name on its own, so a name pointing at (or rebinding to) loopback, + * RFC-1918 or 169.254.169.254 reached it. Now the connection's own DNS lookup refuses any + * private address and the socket connects only to the addresses that lookup checked. + */ +import type * as dns from 'node:dns'; +import * as http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; + +// A scripted DNS answer for the pinnedLookup unit tests; null falls through to the real resolver. +const answer = vi.hoisted(() => ({ next: null as null | Array<{ address: string; family: number }> })); +vi.mock('node:dns', async (importOriginal) => { + const real = await importOriginal(); + const lookup = ((host: string, options: unknown, cb: (...a: unknown[]) => void) => + answer.next ? cb(null, answer.next) : (real.lookup as (...a: unknown[]) => void)(host, options, cb)) as typeof real.lookup; + return { ...real, default: { ...real, lookup }, lookup }; +}); + +import { httpFetchExecute } from '../src/mcp-tools/http-fetch-tools.js'; +import { isPrivateOrLoopback, pinnedLookup, PrivateAddressError } from '../src/mcp-tools/http-fetch-pinned.js'; + +let server: http.Server; +let port: number; +let hits = 0; + +beforeAll(async () => { + server = http.createServer((_req, res) => { + hits++; + res.end('INTERNAL-ONLY-SECRET-DATA'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + port = (server.address() as AddressInfo).port; +}); +afterAll(async () => { + server.closeAllConnections?.(); + await new Promise((resolve) => server.close(() => resolve())); +}); +afterEach(() => { + vi.restoreAllMocks(); + delete process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE; +}); + +describe('a hostname that resolves to loopback is refused on the connection', () => { + // `localhost.` (trailing dot) is not an IP literal and not the text "localhost", so the old + // hostname check passed it; the system resolver maps it to loopback, no network needed. + it('refuses it and the internal server never sees a request', async () => { + const before = hits; + const result = await httpFetchExecute({ url: `http://localhost.:${port}/secret` }); + expect(result.success).toBe(false); + expect(result.errorCode).toBe('PRIVATE_ADDRESS'); + expect(result.error).toMatch(/resolves to (127\.0\.0\.1|::1)/); + expect(result.body).toBe(''); + expect(hits).toBe(before); + }); + + it('a redirect hop to such a name is refused the same way', async () => { + const before = hits; + const redirecting = http.createServer((_req, res) => { + res.writeHead(302, { location: `http://localhost.:${port}/secret` }); + res.end(); + }); + await new Promise((resolve) => redirecting.listen(0, '127.0.0.1', resolve)); + const rport = (redirecting.address() as AddressInfo).port; + try { + // The first hop is an IP literal on loopback, so it needs the opt-in; turn it off for the second hop + // by resolving the second through a lookup that sees the flag unset. + process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1'; + const result = await httpFetchExecute( + { url: `http://127.0.0.1:${rport}/start` }, + { + request: async (url, init) => { + if (new URL(url).hostname === 'localhost.') delete process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE; + const { pinnedRequest } = await import('../src/mcp-tools/http-fetch-pinned.js'); + return pinnedRequest(url, init); + }, + }, + ); + expect(result.success).toBe(false); + expect(result.errorCode).toBe('PRIVATE_ADDRESS'); + expect(hits).toBe(before); + } finally { + redirecting.closeAllConnections?.(); + await new Promise((resolve) => redirecting.close(() => resolve())); + } + }); + + it('with CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 the same name connects (the opt-in still works)', async () => { + process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1'; + const result = await httpFetchExecute({ url: `http://localhost.:${port}/secret` }); + expect(result.success).toBe(true); + expect(result.body).toBe('INTERNAL-ONLY-SECRET-DATA'); + }); +}); + +describe('pinnedLookup checks every resolved address and hands the socket only those', () => { + const fake = (addresses: dns.LookupAddress[]) => { answer.next = addresses; }; + afterEach(() => { answer.next = null; }); + const run = (all: boolean) => + new Promise<{ err: Error | null; result: unknown }>((resolve) => { + pinnedLookup('rebind.example', { all } as never, ((err: Error | null, a: unknown, f?: number) => resolve({ err, result: all ? a : [a, f] })) as never); + }); + + it('refuses a name whose answer mixes a public and a metadata address', async () => { + fake([{ address: '93.184.216.34', family: 4 }, { address: '169.254.169.254', family: 4 }]); + const { err } = await run(true); + expect(err).toBeInstanceOf(PrivateAddressError); + expect(err!.message).toContain('169.254.169.254'); + }); + + it('refuses IPv6 answers that reach private space (mapped, NAT64, ULA)', async () => { + for (const address of ['::ffff:10.0.0.1', '64:ff9b::a9fe:a9fe', 'fd00::1', '::1']) { + fake([{ address, family: 6 }]); + expect((await run(true)).err, address).toBeInstanceOf(PrivateAddressError); + } + }); + + it('passes public answers through unchanged, as a list or as the first address', async () => { + fake([{ address: '93.184.216.34', family: 4 }, { address: '2606:2800:220:1::1', family: 6 }]); + expect(await run(true)).toEqual({ err: null, result: [{ address: '93.184.216.34', family: 4 }, { address: '2606:2800:220:1::1', family: 6 }] }); + expect(await run(false)).toEqual({ err: null, result: ['93.184.216.34', 4] }); + }); + + it('refuses an empty answer', async () => { + fake([]); + expect((await run(true)).err).toBeInstanceOf(PrivateAddressError); + }); +}); + +describe('isPrivateOrLoopback covers the address forms a resolver can return', () => { + it.each([ + '127.0.0.1', '10.1.2.3', '172.16.0.1', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '198.18.0.1', + '224.0.0.1', '255.255.255.255', '::', '::1', '[::1]', '::ffff:127.0.0.1', '[::ffff:7f00:1]', '::7f00:1', + '64:ff9b::7f00:1', '2002:a9fe:a9fe::1', 'fc00::1', 'fd12:3456::1', 'fe80::1', 'febf::1', 'fec0::1', 'ff02::1', + 'localhost', 'api.localhost', + ])('%s is refused', (host) => expect(isPrivateOrLoopback(host)).toBe(true)); + + it.each(['8.8.8.8', '93.184.216.34', '172.32.0.1', '2606:4700::1111', '[2001:db8::1]', '2002:0808:0808::1', 'example.com'])( + '%s is not', (host) => expect(isPrivateOrLoopback(host)).toBe(false), + ); +}); 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 index 78a23da3f9..3020f6ccf5 100644 --- a/v3/@claude-flow/cli/__tests__/http-fetch-redirect-ssrf.test.ts +++ b/v3/@claude-flow/cli/__tests__/http-fetch-redirect-ssrf.test.ts @@ -5,7 +5,7 @@ * 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'; +import { httpFetchExecute, type HttpFetchRequest } from '../src/mcp-tools/http-fetch-tools.js'; function redirect(location: string, status = 302): Response { return new Response(null, { status, headers: { location } }); @@ -25,10 +25,10 @@ afterEach(() => { describe('http_fetch redirect SSRF guard', () => { it('blocks a public -> loopback redirect without issuing the second request', async () => { - const fetchMock = vi.spyOn(globalThis, 'fetch') + const fetchMock = vi.fn() .mockResolvedValueOnce(redirect('http://127.0.0.1:8080/secret')); - const result = await httpFetchExecute({ url: 'https://example.com/start' }); + const result = await httpFetchExecute({ url: 'https://example.com/start' }, { request: fetchMock }); expect(result.success).toBe(false); expect(result.errorCode).toBe('PRIVATE_ADDRESS'); @@ -37,10 +37,10 @@ describe('http_fetch redirect SSRF guard', () => { }); it('blocks a redirect to cloud metadata via an IPv4-mapped IPv6 literal', async () => { - const fetchMock = vi.spyOn(globalThis, 'fetch') + const fetchMock = vi.fn() .mockResolvedValueOnce(redirect('http://[::ffff:169.254.169.254]/latest/meta-data/')); - const result = await httpFetchExecute({ url: 'https://example.com/start' }); + const result = await httpFetchExecute({ url: 'https://example.com/start' }, { request: fetchMock }); expect(result.success).toBe(false); expect(result.errorCode).toBe('PRIVATE_ADDRESS'); @@ -48,10 +48,10 @@ describe('http_fetch redirect SSRF guard', () => { }); it('blocks a redirect that switches to a non-http protocol', async () => { - const fetchMock = vi.spyOn(globalThis, 'fetch') + const fetchMock = vi.fn() .mockResolvedValueOnce(redirect('file:///etc/passwd')); - const result = await httpFetchExecute({ url: 'https://example.com/start' }); + const result = await httpFetchExecute({ url: 'https://example.com/start' }, { request: fetchMock }); expect(result.success).toBe(false); expect(result.errorCode).toBe('FORBIDDEN_PROTOCOL'); @@ -59,11 +59,11 @@ describe('http_fetch redirect SSRF guard', () => { }); it('follows a validated public relative redirect and reports the final URL', async () => { - const fetchMock = vi.spyOn(globalThis, 'fetch') + const fetchMock = vi.fn() .mockResolvedValueOnce(redirect('/final')) .mockResolvedValueOnce(ok('redirected-body')); - const result = await httpFetchExecute({ url: 'https://example.com/start' }); + const result = await httpFetchExecute({ url: 'https://example.com/start' }, { request: fetchMock }); expect(result.success).toBe(true); expect(result.status).toBe(200); @@ -75,26 +75,26 @@ describe('http_fetch redirect SSRF guard', () => { it('drops Authorization when a redirect crosses origins', async () => { process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH = '1'; - const fetchMock = vi.spyOn(globalThis, 'fetch') + const fetchMock = vi.fn() .mockResolvedValueOnce(redirect('https://other.example/final')) .mockResolvedValueOnce(ok()); const result = await httpFetchExecute({ url: 'https://example.com/start', headers: { Authorization: 'Bearer secret' }, - }); + }, { request: fetchMock }); expect(result.success).toBe(true); expect(fetchMock).toHaveBeenCalledTimes(2); - const secondInit = fetchMock.mock.calls[1][1] as RequestInit; + const secondInit = fetchMock.mock.calls[1][1]; expect(secondInit.headers).not.toHaveProperty('Authorization'); }); it('stops at the redirect limit', async () => { - const fetchMock = vi.spyOn(globalThis, 'fetch') + const fetchMock = vi.fn() .mockImplementation(async () => redirect('/again')); - const result = await httpFetchExecute({ url: 'https://example.com/start' }); + const result = await httpFetchExecute({ url: 'https://example.com/start' }, { request: fetchMock }); expect(result.success).toBe(false); expect(result.errorCode).toBe('REDIRECT_LIMIT'); diff --git a/v3/@claude-flow/cli/src/mcp-tools/http-fetch-pinned.ts b/v3/@claude-flow/cli/src/mcp-tools/http-fetch-pinned.ts new file mode 100644 index 0000000000..23a39e0942 --- /dev/null +++ b/v3/@claude-flow/cli/src/mcp-tools/http-fetch-pinned.ts @@ -0,0 +1,149 @@ +/** + * http_fetch's address checks and connection-pinned transport (ADR-164 §5.1.8). + * + * Checking the URL's hostname string is not enough: a public-looking name can resolve to + * loopback, RFC-1918 or cloud metadata (169.254.169.254), and `fetch()` resolves the name + * again on its own, so even a pre-resolution check can be rebound (TTL-0 DNS) between the + * check and the connect. Here the socket's DNS lookup *is* the check: `pinnedLookup` + * resolves the name, refuses it when any address is private, and hands the socket only the + * addresses it checked, so the connection cannot land anywhere else. IP-literal hosts never + * reach a lookup; `validateUrl` checks those by text, with the same `isPrivateOrLoopback`. + * + * @module @claude-flow/cli/mcp-tools/http-fetch-pinned + */ + +import { lookup as dnsLookup, type LookupAddress } from 'node:dns'; +import * as http from 'node:http'; +import * as https from 'node:https'; +import { isIP, type LookupFunction } from 'node:net'; +import { Readable } from 'node:stream'; + +/** Raised when a hostname resolves to an address the allowlist refuses. */ +export class PrivateAddressError extends Error { + readonly code = 'PRIVATE_ADDRESS'; + constructor(host: string, address: string) { + super(`host ${host} resolves to ${address}, which is loopback/private/link-local; set CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 to override`); + this.name = 'PrivateAddressError'; + } +} + +export const allowPrivateAddresses = (): boolean => process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE === '1'; + +/** The 16-bit groups of an IPv6 address (brackets stripped), or null when it is not one. */ +function ipv6Groups(addr: string): number[] | null { + if (isIP(addr) !== 6) return null; + let text = addr.split('%')[0]!; + // A trailing dotted IPv4 (`::ffff:1.2.3.4`) is two groups. + const v4 = text.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); + if (v4) { + const [a, b, c, d] = v4.slice(1).map(Number) as [number, number, number, number]; + text = `${text.slice(0, v4.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; + } + const [head, tail] = text.includes('::') ? text.split('::') as [string, string] : [text, undefined]; + const parse = (s: string) => (s ? s.split(':').map((g) => parseInt(g, 16)) : []); + const h = parse(head); + const t = tail === undefined ? [] : parse(tail); + const groups = tail === undefined ? h : [...h, ...new Array(8 - h.length - t.length).fill(0), ...t]; + return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null; +} + +function privateIPv4(a: number, b: number): boolean { + return a === 0 // 0.0.0.0/8 ("this" network) + || a === 127 // loopback + || a === 10 // RFC 1918 + || (a === 172 && b >= 16 && b <= 31) // RFC 1918 + || (a === 192 && b === 168) // RFC 1918 + || (a === 169 && b === 254) // link-local, cloud metadata + || (a === 100 && b >= 64 && b <= 127) // CGNAT + || (a === 198 && (b === 18 || b === 19)) // benchmarking + || a >= 224; // multicast, reserved, broadcast +} + +/** + * Whether a host (an IP literal, bracketed or not, or `localhost`) is one http_fetch refuses + * by default. A name that is not an IP literal is `false` here: what it resolves to is + * checked at connect time by `pinnedLookup`. + */ +export function isPrivateOrLoopback(host: string): boolean { + const lower = host.toLowerCase(); + if (lower === 'localhost' || lower === 'localhost.localdomain' || lower.endsWith('.localhost')) return true; + const bare = lower.startsWith('[') && lower.endsWith(']') ? lower.slice(1, -1) : lower; + + const v4 = bare.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); + if (v4) return privateIPv4(Number(v4[1]), Number(v4[2])); + + const g = ipv6Groups(bare); + if (!g) return false; + const embedded = (hi: number) => privateIPv4(hi >> 8, hi & 0xff); + if (g.slice(0, 7).every((x) => x === 0) && g[7]! <= 1) return true; // :: and ::1 + if (g.slice(0, 5).every((x) => x === 0) && g[5] === 0xffff) return embedded(g[6]!); // ::ffff:a.b.c.d (IPv4-mapped) + if (g.slice(0, 6).every((x) => x === 0)) return true; // ::a.b.c.d (deprecated IPv4-compatible) + if (g[0] === 0x64 && g[1] === 0xff9b) return true; // 64:ff9b::/96 and /48 NAT64: may wrap any IPv4 + if (g[0] === 0x2002) return embedded(g[1]!); // 6to4 carries an IPv4 + if ((g[0]! & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local + if ((g[0]! & 0xffc0) === 0xfe80 || (g[0]! & 0xffc0) === 0xfec0) return true; // fe80::/10 link-local, fec0::/10 site-local + if ((g[0]! & 0xff00) === 0xff00) return true; // ff00::/8 multicast + return false; +} + +/** + * The socket's DNS lookup: resolve every address, refuse the host when any of them is + * private (unless opted in), and return only those checked addresses to the socket. + */ +export const pinnedLookup: LookupFunction = (hostname, options, callback) => { + dnsLookup(hostname, { ...options, all: true }, (err, addresses) => { + if (err) return (callback as (e: NodeJS.ErrnoException | null, a: LookupAddress[]) => void)(err, []); + const list = addresses as LookupAddress[]; + if (!allowPrivateAddresses()) { + const bad = list.find((a) => isPrivateOrLoopback(a.address)); + if (bad || list.length === 0) { + return (callback as (e: Error | null, a: LookupAddress[]) => void)(new PrivateAddressError(hostname, bad?.address ?? 'no address'), []); + } + } + if ((options as { all?: boolean }).all) return (callback as (e: null, a: LookupAddress[]) => void)(null, list); + (callback as (e: null, a: string, f: number) => void)(null, list[0]!.address, list[0]!.family); + }); +}; + +export interface PinnedInit { + method: string; + headers: Record; + body?: string; + signal: AbortSignal; +} + +/** Statuses whose Response must not carry a body. */ +const NULL_BODY = new Set([101, 103, 204, 205, 304]); + +/** + * One HTTP(S) request whose connection goes only to an address `pinnedLookup` checked, with + * no redirect following and a fresh connection every time (no pooled socket from elsewhere). + * Returns a standard `Response` so the caller reads it as it would a `fetch()` result. + */ +export function pinnedRequest(url: string, init: PinnedInit): Promise { + const target = new URL(url); + const client = target.protocol === 'https:' ? https : http; + const headers: Record = { accept: '*/*', ...init.headers }; + if (init.body !== undefined && !Object.keys(headers).some((k) => k.toLowerCase() === 'content-length')) { + headers['content-length'] = String(Buffer.byteLength(init.body)); + } + return new Promise((resolve, reject) => { + const req = client.request(target, { method: init.method, headers, lookup: pinnedLookup, agent: false, signal: init.signal }, (res) => { + const out = new Headers(); + for (const [key, value] of Object.entries(res.headers)) { + for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) out.append(key, v); + } + const status = res.statusCode ?? 0; + if (status < 200 || status > 599) { + res.destroy(); + reject(new Error(`unsupported HTTP status ${status}`)); + return; + } + const body = NULL_BODY.has(status) || init.method === 'HEAD' ? null : (Readable.toWeb(res) as ReadableStream); + if (body === null) res.resume(); + resolve(new Response(body, { status, statusText: res.statusMessage ?? '', headers: out })); + }); + req.on('error', reject); + req.end(init.body); + }); +} 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 752fe250d5..b6ebcd791d 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 @@ -11,7 +11,10 @@ * AbortController, response truncation, default User-Agent. * * Architectural constraints (load-bearing): - * - DEFAULT-REFUSES private addresses + loopback (CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 opt-in) + * - DEFAULT-REFUSES private addresses + loopback (CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 opt-in): + * IP literals by text here, and every resolved address of a hostname at connect time, on the + * connection itself (http-fetch-pinned.ts), so DNS that points at, or rebinds to, a private + * address is refused too * - 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 @@ -21,6 +24,9 @@ */ import type { MCPTool } from './types.js'; +import { allowPrivateAddresses, isPrivateOrLoopback, pinnedRequest, PrivateAddressError, type PinnedInit } from './http-fetch-pinned.js'; + +export { isPrivateOrLoopback } from './http-fetch-pinned.js'; const DEFAULT_TIMEOUT_MS = 30_000; const MAX_TIMEOUT_MS = 60_000; @@ -60,8 +66,7 @@ export function validateUrl(rawUrl: string): URL { ); } const host = parsed.hostname.toLowerCase(); - const allowPrivate = process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE === '1'; - if (!allowPrivate && isPrivateOrLoopback(host)) { + if (!allowPrivateAddresses() && isPrivateOrLoopback(host)) { throw new HttpFetchValidationError( `host ${host} is loopback/private/link-local; set CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 to override`, 'PRIVATE_ADDRESS', @@ -70,62 +75,6 @@ export function validateUrl(rawUrl: string): URL { return parsed; } -function isPrivateOrLoopback(host: string): boolean { - if (host === 'localhost' || host === 'localhost.localdomain') return true; - - // Node's URL parser keeps brackets in `.hostname` for every IPv6 literal - // (e.g. "[::1]", "[fc00::1]", "[::ffff:7f00:1]"). Strip them once so every - // check below operates on the bare address — without this, the fc00::/7 - // and fe80::/10 checks further down never match anything (they test - // `startsWith('fc'/'fe80:')` against a string starting with "["), and an - // IPv4-mapped-IPv6 literal (`::ffff:a.b.c.d`, which Node normalizes to a - // canonical `::ffff:xxxx:yyyy` hex form) sails through both the IPv4 and - // IPv6 branches untested — a live SSRF bypass (e.g. `::ffff:127.0.0.1` or - // `::ffff:169.254.169.254` reaching loopback / cloud-metadata targets). - const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host; - - if (bare === '::1') return true; // IPv6 loopback - - // IPv4-mapped IPv6 — decode back to dotted-decimal and recurse into the - // IPv4 check below so it inherits every existing private/loopback/ - // link-local/CGNAT rule instead of needing its own copy. - const mappedHex = bare.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/); - if (mappedHex) { - const hi = parseInt(mappedHex[1], 16); - const lo = parseInt(mappedHex[2], 16); - const decoded = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`; - return isPrivateOrLoopback(decoded); - } - const mappedDecimal = bare.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); - if (mappedDecimal) return isPrivateOrLoopback(mappedDecimal[1]); - - // IPv4 numeric checks - const m = bare.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); - if (m) { - const a = Number(m[1]); - const b = Number(m[2]); - if (a === 0) return true; // 0.0.0.0/8 - if (a === 127) return true; // loopback - if (a === 10) return true; // RFC1918 - if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918 - if (a === 192 && b === 168) return true; // RFC1918 - if (a === 169 && b === 254) return true; // link-local - if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT - return false; - } - // IPv6 special forms — be conservative and accept only public-looking - // literals. Reject obvious private/local forms. - if (bare.startsWith('fc') || bare.startsWith('fd')) return true; // fc00::/7 ULA - if (bare.startsWith('fe80:')) return true; // link-local - // KNOWN LIMITATION (pre-existing, not introduced by the bracket-stripping / - // IPv4-mapped-IPv6 fix above; flagged by an independent adversarial review): - // `::` (IPv6 unspecified/"any", the analog of 0.0.0.0, which the IPv4 branch - // above does block), IPv6 multicast (ff00::/8), and NAT64 (64:ff9b::/96) are - // not covered. Left as a follow-up hardening item rather than scope-creeping - // this patch. - return false; -} - export function validateHeaders(headers: Record): Record { const allowAuth = process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH === '1'; const out: Record = {}; @@ -178,12 +127,16 @@ export interface HttpFetchResult { errorCode?: string; } +/** How one request is sent; tests replace it to script responses. The default pins each connection to checked addresses. */ +export type HttpFetchRequest = (url: string, init: PinnedInit) => Promise; + /** * Pure execution path so tests can call it without going through the MCP * dispatcher. Returns a result object (does not throw on validation failure * — it returns success: false with an errorCode). */ -export async function httpFetchExecute(input: Record): Promise { +export async function httpFetchExecute(input: Record, deps: { request?: HttpFetchRequest } = {}): Promise { + const send = deps.request ?? pinnedRequest; const startedAt = Date.now(); const url = String(input.url ?? ''); const method = String(input.method ?? 'GET').toUpperCase(); @@ -277,12 +230,13 @@ export async function httpFetchExecute(input: Record): Promise< // 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(), { + // Never fetch(): it resolves the hostname again on its own, so what it connects to is + // not what was checked. `send` connects only to addresses its DNS lookup checked. + response = await send(currentUrl.toString(), { method: currentMethod, headers, body: currentMethod === 'GET' || currentMethod === 'HEAD' ? undefined : currentBody, signal: controller.signal, - redirect: 'manual', }); if (!REDIRECT_STATUSES.has(response.status)) break; @@ -408,6 +362,12 @@ export async function httpFetchExecute(input: Record): Promise< }; } catch (e) { const msg = e instanceof Error ? e.message : String(e); + if (e instanceof PrivateAddressError) { + return { + success: false, status: 0, statusText: '', headers: {}, body: '', bodyTruncated: false, bytesRead: 0, + durationMs: Date.now() - startedAt, url: parsed.toString(), method, error: msg, errorCode: 'PRIVATE_ADDRESS', + }; + } const aborted = msg.includes('aborted') || (e as { name?: string } | undefined)?.name === 'AbortError'; return { success: false, @@ -431,7 +391,7 @@ export async function httpFetchExecute(input: Record): Promise< export const httpFetchTools: MCPTool[] = [ { name: 'http_fetch', - description: 'ADR-164 §5.1.8 — HTTP probe primitive for business-pod ops benches (synthetic 200/500 endpoint checks, third-party status pages). Default-secure: blocks file://, ftp://, RFC-1918 / loopback / link-local hosts unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1, and rejects Authorization / Cookie / X-Auth-* headers unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1. Hard 30s timeout (60s ceiling), response truncated to 256 KB (1 MB ceiling), default User-Agent ruflo-http-fetch/1.0. Use when a pod or smoke contract needs a guarded HTTP probe — calling Node fetch() directly is wrong because it skips the URL allowlist and header sanitization that ADR-164 mandates for autopilot mode. Pair with the ops-pod bench in plugins/ruflo-business-pods/templates/ops.json (the §4.4 synthetic-endpoint test).', + description: 'ADR-164 §5.1.8 — HTTP probe primitive for business-pod ops benches (synthetic 200/500 endpoint checks, third-party status pages). Default-secure: blocks file://, ftp://, and RFC-1918 / loopback / link-local hosts, whether given as an address or as a name that resolves to one (checked on the connection itself, every redirect hop included), unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1, and rejects Authorization / Cookie / X-Auth-* headers unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1. Hard 30s timeout (60s ceiling), response truncated to 256 KB (1 MB ceiling), default User-Agent ruflo-http-fetch/1.0. Use when a pod or smoke contract needs a guarded HTTP probe — calling Node fetch() directly is wrong because it skips the URL allowlist and header sanitization that ADR-164 mandates for autopilot mode. Pair with the ops-pod bench in plugins/ruflo-business-pods/templates/ops.json (the §4.4 synthetic-endpoint test).', category: 'business-pods', tags: ['business-pods', 'http', 'fetch', 'adr-164', 'security', 'ops-pod'], inputSchema: {