|
| 1 | +import { execFile } from 'node:child_process' |
| 2 | +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' |
| 3 | +import { createServer as httpServer } from 'node:http' |
| 4 | +import { createServer as httpsServer } from 'node:https' |
| 5 | +import { type AddressInfo, connect, type Socket } from 'node:net' |
| 6 | +import { tmpdir } from 'node:os' |
| 7 | +import { join } from 'node:path' |
| 8 | +import { getCACertificates, setDefaultCACertificates } from 'node:tls' |
| 9 | +import { fileURLToPath } from 'node:url' |
| 10 | +import { promisify } from 'node:util' |
| 11 | +import { networkConfigMock } from '@sim/testing/mocks/network-config.mock' |
| 12 | +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' |
| 13 | + |
| 14 | +vi.mock('@/lib/core/network/config.server', () => networkConfigMock) |
| 15 | +vi.mock('@sim/security/dns', async (importOriginal) => { |
| 16 | + const actual = await importOriginal<typeof import('@sim/security/dns')>() |
| 17 | + const records: Record<string, string> = { |
| 18 | + 'origin.invalid': '1.1.1.1', |
| 19 | + 'internal.invalid': '10.0.0.5', |
| 20 | + } |
| 21 | + return { |
| 22 | + ...actual, |
| 23 | + resolveHostAddresses: async (host: string) => { |
| 24 | + const address = records[host] |
| 25 | + if (!address) throw new Error(`No addresses for ${host}`) |
| 26 | + return { addresses: [address], preferred: address } |
| 27 | + }, |
| 28 | + } |
| 29 | +}) |
| 30 | + |
| 31 | +import { |
| 32 | + createPinnedFetchWithDispatcher, |
| 33 | + createSsrfGuardedFetchWithDispatcher, |
| 34 | + secureFetchWithPinnedIP, |
| 35 | + secureFetchWithValidation, |
| 36 | +} from '@/lib/core/security/input-validation.server' |
| 37 | + |
| 38 | +const certificateDirectory = mkdtempSync(join(tmpdir(), 'environment-proxy-tls-')) |
| 39 | +const certificatePath = join(certificateDirectory, 'cert.pem') |
| 40 | +const keyPath = join(certificateDirectory, 'key.pem') |
| 41 | +const sockets = new Set<Socket>() |
| 42 | +const tunnels: Array<{ authority: string | undefined; authorization: string | undefined }> = [] |
| 43 | +const forwarded: Array<{ url: string | undefined; authorization: string | undefined }> = [] |
| 44 | +const proxiedPorts = new Set<number>() |
| 45 | +let originHeaders: Record<string, unknown> = {} |
| 46 | + |
| 47 | +const secureOrigin = httpsServer((req, res) => { |
| 48 | + originHeaders = req.headers |
| 49 | + res.setHeader('x-via-proxy', proxiedPorts.has(req.socket.remotePort ?? 0) ? 'yes' : 'no') |
| 50 | + if (req.url === '/to-internal') { |
| 51 | + res.writeHead(302, { location: 'https://internal.invalid/' }) |
| 52 | + res.end() |
| 53 | + return |
| 54 | + } |
| 55 | + res.end('tls reached') |
| 56 | +}) |
| 57 | + |
| 58 | +/** A plain forward proxy: CONNECT tunnels reach the TLS origin, absolute-form requests are answered here. */ |
| 59 | +const proxy = httpServer((req, res) => { |
| 60 | + forwarded.push({ url: req.url, authorization: req.headers['proxy-authorization'] }) |
| 61 | + res.end('forwarded') |
| 62 | +}) |
| 63 | +proxy.on('connect', (req, socket, head) => { |
| 64 | + socket.on('error', () => {}) |
| 65 | + tunnels.push({ authority: req.url, authorization: req.headers['proxy-authorization'] }) |
| 66 | + const upstream = connect(securePort, '127.0.0.1', () => { |
| 67 | + if (upstream.localPort) proxiedPorts.add(upstream.localPort) |
| 68 | + socket.write('HTTP/1.1 200 Connection Established\r\n\r\n') |
| 69 | + if (head.length) upstream.write(head) |
| 70 | + socket.pipe(upstream).pipe(socket) |
| 71 | + }) |
| 72 | + upstream.on('error', () => socket.destroy()) |
| 73 | + socket.on('close', () => upstream.destroy()) |
| 74 | + sockets.add(upstream) |
| 75 | + upstream.on('close', () => sockets.delete(upstream)) |
| 76 | +}) |
| 77 | + |
| 78 | +let securePort = 0 |
| 79 | +let proxyUrl = '' |
| 80 | +const trust = getCACertificates('default') |
| 81 | +const PROXY_ENV = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'NO_PROXY', 'no_proxy'] |
| 82 | +const options = { profile: 'contentFetch' as const, timeout: 10_000 } |
| 83 | + |
| 84 | +beforeAll(async () => { |
| 85 | + await promisify(execFile)('openssl', [ |
| 86 | + 'req', |
| 87 | + '-x509', |
| 88 | + '-newkey', |
| 89 | + 'rsa:2048', |
| 90 | + '-sha256', |
| 91 | + '-nodes', |
| 92 | + '-keyout', |
| 93 | + keyPath, |
| 94 | + '-out', |
| 95 | + certificatePath, |
| 96 | + '-days', |
| 97 | + '2', |
| 98 | + '-subj', |
| 99 | + '/CN=origin.invalid', |
| 100 | + '-addext', |
| 101 | + 'subjectAltName=DNS:origin.invalid,IP:1.1.1.1', |
| 102 | + '-addext', |
| 103 | + 'extendedKeyUsage=serverAuth', |
| 104 | + ]) |
| 105 | + const cert = readFileSync(certificatePath, 'utf8') |
| 106 | + secureOrigin.setSecureContext({ cert, key: readFileSync(keyPath, 'utf8') }) |
| 107 | + setDefaultCACertificates([...trust, cert]) |
| 108 | + for (const server of [secureOrigin, proxy]) { |
| 109 | + server.on('connection', (socket) => { |
| 110 | + sockets.add(socket) |
| 111 | + socket.on('close', () => sockets.delete(socket)) |
| 112 | + }) |
| 113 | + await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve)) |
| 114 | + } |
| 115 | + securePort = (secureOrigin.address() as AddressInfo).port |
| 116 | + proxyUrl = `http://sim:proxy-secret@127.0.0.1:${(proxy.address() as AddressInfo).port}` |
| 117 | +}) |
| 118 | + |
| 119 | +beforeEach(() => { |
| 120 | + for (const name of PROXY_ENV) vi.stubEnv(name, '') |
| 121 | + vi.stubEnv('HTTPS_PROXY', proxyUrl) |
| 122 | + vi.stubEnv('HTTP_PROXY', proxyUrl) |
| 123 | + tunnels.length = 0 |
| 124 | + forwarded.length = 0 |
| 125 | + originHeaders = {} |
| 126 | +}) |
| 127 | + |
| 128 | +afterEach(() => { |
| 129 | + vi.unstubAllEnvs() |
| 130 | +}) |
| 131 | + |
| 132 | +afterAll(async () => { |
| 133 | + for (const socket of sockets) socket.destroy() |
| 134 | + await Promise.all( |
| 135 | + [secureOrigin, proxy].map( |
| 136 | + (server) => new Promise<void>((resolve) => server.close(() => resolve())) |
| 137 | + ) |
| 138 | + ) |
| 139 | + setDefaultCACertificates(trust) |
| 140 | + rmSync(certificateDirectory, { recursive: true, force: true }) |
| 141 | +}) |
| 142 | + |
| 143 | +const PROXY_AUTHORIZATION = `Basic ${Buffer.from('sim:proxy-secret').toString('base64')}` |
| 144 | + |
| 145 | +describe('guarded requests under HTTPS_PROXY', () => { |
| 146 | + it('tunnels a validated request by hostname and keeps proxy credentials off the origin', async () => { |
| 147 | + const response = await secureFetchWithValidation('https://origin.invalid/discovery', { |
| 148 | + ...options, |
| 149 | + headers: { 'Proxy-Authorization': 'must-not-reach-origin' }, |
| 150 | + }) |
| 151 | + expect(await response.text()).toBe('tls reached') |
| 152 | + expect(response.headers.get('x-via-proxy')).toBe('yes') |
| 153 | + expect(tunnels).toEqual([ |
| 154 | + { authority: 'origin.invalid:443', authorization: PROXY_AUTHORIZATION }, |
| 155 | + ]) |
| 156 | + expect(originHeaders['proxy-authorization']).toBeUndefined() |
| 157 | + expect(originHeaders.host).toBe('origin.invalid') |
| 158 | + }) |
| 159 | + |
| 160 | + it('tunnels pinned and DNS-guarded fetches', async () => { |
| 161 | + const pinned = createPinnedFetchWithDispatcher('1.1.1.1', options) |
| 162 | + const guarded = createSsrfGuardedFetchWithDispatcher(options) |
| 163 | + try { |
| 164 | + expect(await (await pinned.fetch('https://origin.invalid/')).text()).toBe('tls reached') |
| 165 | + expect(await (await guarded.fetch('https://origin.invalid/')).text()).toBe('tls reached') |
| 166 | + expect(tunnels.map((tunnel) => tunnel.authority)).toEqual([ |
| 167 | + 'origin.invalid:443', |
| 168 | + 'origin.invalid:443', |
| 169 | + ]) |
| 170 | + } finally { |
| 171 | + await Promise.all([pinned.dispatcher.destroy(), guarded.dispatcher.destroy()]) |
| 172 | + } |
| 173 | + }) |
| 174 | + |
| 175 | + it('forwards plain-http destinations in absolute form instead of tunneling', async () => { |
| 176 | + const response = await secureFetchWithPinnedIP('http://origin.invalid/plain', '1.1.1.1', { |
| 177 | + ...options, |
| 178 | + profile: 'selfHostedService', |
| 179 | + }) |
| 180 | + expect(await response.text()).toBe('forwarded') |
| 181 | + expect(tunnels).toEqual([]) |
| 182 | + expect(forwarded).toEqual([ |
| 183 | + { url: 'http://origin.invalid/plain', authorization: PROXY_AUTHORIZATION }, |
| 184 | + ]) |
| 185 | + }) |
| 186 | + |
| 187 | + it('connects directly, still pinned, when NO_PROXY names the host', async () => { |
| 188 | + vi.stubEnv('NO_PROXY', 'localhost,.invalid') |
| 189 | + const response = await secureFetchWithPinnedIP( |
| 190 | + `https://origin.invalid:${securePort}/`, |
| 191 | + '127.0.0.1', |
| 192 | + options |
| 193 | + ) |
| 194 | + expect(await response.text()).toBe('tls reached') |
| 195 | + expect(response.headers.get('x-via-proxy')).toBe('no') |
| 196 | + expect(tunnels).toEqual([]) |
| 197 | + }) |
| 198 | + |
| 199 | + it('refuses a destination that resolves to a blocked address without asking the proxy', async () => { |
| 200 | + const guarded = createSsrfGuardedFetchWithDispatcher(options) |
| 201 | + try { |
| 202 | + await expect(guarded.fetch('https://internal.invalid/')).rejects.toThrow(/private|blocked/i) |
| 203 | + await expect( |
| 204 | + secureFetchWithPinnedIP('https://internal.invalid/', '1.1.1.1', options) |
| 205 | + ).rejects.toThrow(/private|blocked/i) |
| 206 | + } finally { |
| 207 | + await guarded.dispatcher.destroy() |
| 208 | + } |
| 209 | + expect(tunnels).toEqual([]) |
| 210 | + }) |
| 211 | + |
| 212 | + it('judges each redirect hop again before proxying it', async () => { |
| 213 | + const pinned = createPinnedFetchWithDispatcher('1.1.1.1', options) |
| 214 | + try { |
| 215 | + await expect(pinned.fetch('https://origin.invalid/to-internal')).rejects.toThrow( |
| 216 | + /private|blocked/i |
| 217 | + ) |
| 218 | + await expect( |
| 219 | + secureFetchWithPinnedIP('https://origin.invalid/to-internal', '1.1.1.1', options) |
| 220 | + ).rejects.toThrow(/private|blocked/i) |
| 221 | + } finally { |
| 222 | + await pinned.dispatcher.destroy() |
| 223 | + } |
| 224 | + expect(tunnels.map((tunnel) => tunnel.authority)).toEqual([ |
| 225 | + 'origin.invalid:443', |
| 226 | + 'origin.invalid:443', |
| 227 | + ]) |
| 228 | + }) |
| 229 | + |
| 230 | + it('tunnels through the proxy under the actual Bun runtime', async () => { |
| 231 | + await promisify(execFile)( |
| 232 | + 'bun', |
| 233 | + [ |
| 234 | + '--no-env-file', |
| 235 | + 'run', |
| 236 | + fileURLToPath(new URL('./fixtures/environment-proxy-runtime.fixture.ts', import.meta.url)), |
| 237 | + ], |
| 238 | + { |
| 239 | + timeout: 15_000, |
| 240 | + env: { |
| 241 | + ...process.env, |
| 242 | + NEXT_PUBLIC_APP_URL: 'http://localhost:3000', |
| 243 | + NEXT_PUBLIC_FORCE_HOSTED: 'false', |
| 244 | + NODE_EXTRA_CA_CERTS: certificatePath, |
| 245 | + HTTPS_PROXY: proxyUrl, |
| 246 | + https_proxy: '', |
| 247 | + NO_PROXY: '', |
| 248 | + no_proxy: '', |
| 249 | + }, |
| 250 | + } |
| 251 | + ) |
| 252 | + expect(tunnels).toEqual([{ authority: '1.1.1.1:443', authorization: PROXY_AUTHORIZATION }]) |
| 253 | + }) |
| 254 | +}) |
0 commit comments