import { EventEmitter } from 'node:events' import http from 'node:http' import https from 'node:https' import net from 'node:net' import type { AddressInfo } from 'node:net' import { Readable } from 'node:stream' import { afterEach, describe, expect, it, vi } from 'vitest' import { createPublicFetch, isNotPublicAddressError } from './publicFetch.ts' const servers: Array = [] async function serve(host: string, handler: http.RequestListener): Promise { const server = http.createServer(handler) servers.push(server) await new Promise((resolve) => server.listen(0, host, resolve)) return `http://${host}:${(server.address() as AddressInfo).port}` } // Only 127.0.0.2 is blocked, so two loopback servers play a public host and a private one. const onlySecond = new net.BlockList() onlySecond.addAddress('127.0.0.2', 'ipv4') function stubEnv(values: Record): Disposable { for (const [name, value] of Object.entries(values)) vi.stubEnv(name, value) return { [Symbol.dispose]: () => vi.unstubAllEnvs() } } afterEach(async () => { await Promise.all( servers.splice(0).map((server) => { server.closeAllConnections() return new Promise((resolve) => server.close(resolve)) }), ) }) describe('createPublicFetch', () => { it('returns the body of an allowed host', async () => { const url = await serve('127.0.0.1', (_req, res) => res.end('openapi: 3.1.0')) const response = await createPublicFetch({ blocked: onlySecond })(url) expect(response.status).toBe(200) await expect(response.text()).resolves.toBe('openapi: 3.1.0') }) it('refuses a redirect to a blocked address', async () => { const blocked = await serve('127.0.0.2', (_req, res) => res.end('secret')) const url = await serve('127.0.0.1', (_req, res) => res.writeHead(302, { location: blocked }).end()) const error = await createPublicFetch({ blocked: onlySecond })(url).catch((caught: unknown) => caught) expect(error).toMatchObject({ message: expect.stringContaining('not a public address') }) expect(isNotPublicAddressError(new Error('wrapped', { cause: error }))).toBe(true) }) it('recognizes a refusal from another copy of this module by its name', () => { const fromOtherCopy = Object.assign(new Error('10.0.0.1 is not a public address'), { name: 'NotPublicAddressError' }) expect(isNotPublicAddressError({ message: 'wrapped', cause: fromOtherCopy })).toBe(true) expect(isNotPublicAddressError(new Error('wrapped', { cause: new Error('other') }))).toBe(false) }) it('refuses an IP literal and a name that resolves to a private address', async () => { const url = await serve('127.0.0.1', (_req, res) => res.end('secret')) await expect(createPublicFetch()(url)).rejects.toThrow('not a public address') await expect(createPublicFetch()(url.replace('127.0.0.1', 'localhost'))).rejects.toThrow('not a public address') }) it('refuses other schemes, methods, and request objects', async () => { const fetchPublic = createPublicFetch() await expect(fetchPublic('file:///etc/passwd')).rejects.toThrow('http and https') await expect(fetchPublic('https://example.com', { method: 'POST' })).rejects.toThrow('GET') await expect(fetchPublic(new Request('https://example.com'))).rejects.toThrow('not a Request') }) it('stops following redirects after a few hops', async () => { const url = await serve('127.0.0.1', (req, res) => res.writeHead(302, { location: req.url ?? '/' }).end()) await expect(createPublicFetch({ blocked: onlySecond })(url)).rejects.toThrow('redirects') }) it('refuses a redirect from https to http', async () => { const reached = vi.fn() const target = await serve('127.0.0.1', (_req, res) => { reached() res.end('openapi: 3.1.0') }) // A stand-in for an https server that redirects to plain http. using _httpsSpy = vi.spyOn(https, 'request').mockImplementation(((_url: URL, _options: unknown, callback: (res: http.IncomingMessage) => void) => { const req = Object.assign(new EventEmitter(), { setTimeout: () => req, destroy: () => req, end: () => callback(response) }) const response = Object.assign(Readable.from([]), { statusCode: 302, statusMessage: 'Found', headers: { location: target }, }) as unknown as http.IncomingMessage return req }) as unknown as typeof https.request) await expect(createPublicFetch({ blocked: onlySecond })('https://specs.example.com/openapi.yaml')).rejects.toThrow('from https to http') expect(reached).not.toHaveBeenCalled() }) // Node runs socket timeouts and `AbortSignal.timeout` on its own timers, which fake timers do not reach, // so these two tests take the timer callbacks and fire them by hand. it('fails a body that stalls for 30 seconds after the headers', async () => { const url = await serve('127.0.0.1', (_req, res) => res.writeHead(200).write('openapi: ')) const idle: Array<[number, () => void]> = [] using _timeoutSpy = vi.spyOn(http.ClientRequest.prototype, 'setTimeout').mockImplementation(function (this: http.ClientRequest, ms, callback) { idle.push([ms, callback!]) return this }) const response = await createPublicFetch({ blocked: onlySecond })(url) const [[ms, fire] = [0, () => {}]] = idle fire() expect(ms).toBe(30_000) await expect(response.text()).rejects.toThrow('sent nothing for 30 seconds') }) it('fails a body still arriving after 60 seconds in total', async () => { const url = await serve('127.0.0.1', (_req, res) => { res.writeHead(200) const timer = setInterval(() => res.write(' '), 10) res.on('close', () => clearInterval(timer)) }) const deadline = new AbortController() using timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(deadline.signal) const response = await createPublicFetch({ blocked: onlySecond })(url) deadline.abort(new DOMException('The operation timed out.', 'TimeoutError')) expect(timeoutSpy).toHaveBeenCalledWith(60_000) await expect(response.text()).rejects.toMatchObject({ name: 'TimeoutError' }) }) it('stops reading from the host when the body passes 50 MB', async () => { const closed = Promise.withResolvers() const chunk = Buffer.alloc(1024 * 1024) const url = await serve('127.0.0.1', (_req, res) => { res.writeHead(200) // 60 MB, more than the limit, written as fast as the connection takes it. let sent = 0 const send = () => { while (sent < 60 && !res.destroyed) { sent++ if (!res.write(chunk)) return res.once('drain', send) } } send() res.on('close', () => closed.resolve()) }) const response = await createPublicFetch({ blocked: onlySecond })(url) await expect(response.text()).rejects.toThrow('larger than 50 MB') await expect(closed.promise).resolves.toBeUndefined() }) it('closes the connection of a response that has no body', async () => { const closed = Promise.withResolvers() const url = await serve('127.0.0.1', (_req, res) => { // Headers only, never ended: the host would keep the connection open. res.writeHead(204).flushHeaders() res.on('close', () => closed.resolve()) }) const response = await createPublicFetch({ blocked: onlySecond })(url) expect(response.status).toBe(204) expect(response.body).toBeNull() await expect(closed.promise).resolves.toBeUndefined() }) it('rejects a status outside 200 to 599 instead of throwing outside the promise', async () => { const url = await serve('127.0.0.1', (req) => req.socket.end('HTTP/1.1 600 Odd\r\ncontent-length: 0\r\n\r\n')) await expect(createPublicFetch({ blocked: onlySecond })(url)).rejects.toThrow('HTTP 600') }) it('rejects a switch to another protocol', async () => { const url = await serve('127.0.0.1', (req) => req.socket.write('HTTP/1.1 101 Switching Protocols\r\nconnection: upgrade\r\nupgrade: websocket\r\n\r\n')) await expect(createPublicFetch({ blocked: onlySecond })(url)).rejects.toThrow('switched protocols') }) it('rejects a connection that closes before it answers', async () => { const url = await serve('127.0.0.1', (req) => req.socket.destroy()) await expect(createPublicFetch({ blocked: onlySecond })(url)).rejects.toThrow() }) it('checks the address itself when proxy variables are set', async () => { const proxied = vi.fn() const proxy = await serve('127.0.0.1', (_req, res) => { proxied() res.end('openapi: 3.1.0') }) using _proxyEnv = stubEnv({ HTTP_PROXY: proxy, HTTPS_PROXY: proxy, NODE_USE_ENV_PROXY: '1' }) using requestSpy = vi.spyOn(http, 'request') await expect(createPublicFetch()(`${proxy.replace('127.0.0.1', 'localhost')}/openapi.yaml`)).rejects.toThrow('not a public address') expect(requestSpy.mock.calls[0]?.[1]).toMatchObject({ agent: false, lookup: expect.any(Function) }) expect(proxied).not.toHaveBeenCalled() }) it('rethrows the reason of a caller that cancels', async () => { const url = await serve('127.0.0.1', (_req, res) => res.writeHead(200).write('openapi: ')) const controller = new AbortController() const reason = new Error('canceled') const response = await createPublicFetch({ blocked: onlySecond })(url, { signal: controller.signal }) controller.abort(reason) await expect(response.text()).rejects.toBe(reason) }) })