|
| 1 | +/** |
| 2 | + * A real TLS CONNECT gateway and the HTTPS origin behind it, on loopback, for the gateway suites. |
| 3 | + * One self-signed certificate covers `gateway.invalid` (the proxy), `origin.invalid` and `1.1.1.1` |
| 4 | + * (the origin); the proxy admits only `1.1.1.1:443` and only the bearer tokens it was started with. |
| 5 | + */ |
| 6 | +import { execFile } from 'node:child_process' |
| 7 | +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' |
| 8 | +import { createServer as httpsServer } from 'node:https' |
| 9 | +import { type AddressInfo, connect, type Socket } from 'node:net' |
| 10 | +import { tmpdir } from 'node:os' |
| 11 | +import { join } from 'node:path' |
| 12 | +import type { Duplex } from 'node:stream' |
| 13 | +import { promisify } from 'node:util' |
| 14 | + |
| 15 | +interface GatewayAdmission { |
| 16 | + token: string | undefined |
| 17 | + destination: string | undefined |
| 18 | + sni: string | undefined |
| 19 | +} |
| 20 | + |
| 21 | +export interface GatewayTlsFixture { |
| 22 | + cert: string |
| 23 | + certificatePath: string |
| 24 | + proxyPort: number |
| 25 | + /** Every CONNECT the proxy received, admitted or not. */ |
| 26 | + admissions: GatewayAdmission[] |
| 27 | + /** Each queued entry makes one CONNECT fail: `reset` drops the connection, a number answers with that status. */ |
| 28 | + connectFailures: Array<'reset' | number> |
| 29 | + /** What the origin last received, and how many requests reached it. */ |
| 30 | + origin: { requests: number; headers: Record<string, unknown>; target: string } |
| 31 | + close: () => Promise<void> |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * The origin answers `x-via-proxy: yes` only for a connection the proxy opened, echoes the request |
| 36 | + * target in `x-request-target`, echoes POST and PUT bodies, redirects `/redirect`, and never answers |
| 37 | + * `/wait`. |
| 38 | + */ |
| 39 | +export async function startGatewayTlsFixture( |
| 40 | + acceptedTokens: readonly string[] |
| 41 | +): Promise<GatewayTlsFixture> { |
| 42 | + const certificateDirectory = mkdtempSync(join(tmpdir(), 'gateway-tls-')) |
| 43 | + const certificatePath = join(certificateDirectory, 'cert.pem') |
| 44 | + const keyPath = join(certificateDirectory, 'key.pem') |
| 45 | + await promisify(execFile)('openssl', [ |
| 46 | + 'req', |
| 47 | + '-x509', |
| 48 | + '-newkey', |
| 49 | + 'rsa:2048', |
| 50 | + '-sha256', |
| 51 | + '-nodes', |
| 52 | + '-keyout', |
| 53 | + keyPath, |
| 54 | + '-out', |
| 55 | + certificatePath, |
| 56 | + '-days', |
| 57 | + '2', |
| 58 | + '-subj', |
| 59 | + '/CN=gateway.invalid', |
| 60 | + '-addext', |
| 61 | + 'subjectAltName=DNS:gateway.invalid,DNS:origin.invalid,IP:1.1.1.1', |
| 62 | + '-addext', |
| 63 | + 'extendedKeyUsage=serverAuth', |
| 64 | + ]) |
| 65 | + const cert = readFileSync(certificatePath, 'utf8') |
| 66 | + const key = readFileSync(keyPath, 'utf8') |
| 67 | + const admittedAuthorizations = new Set(acceptedTokens.map((token) => `Bearer ${token}`)) |
| 68 | + const sockets = new Set<Duplex>() |
| 69 | + const proxiedPorts = new Set<number>() |
| 70 | + const admissions: GatewayAdmission[] = [] |
| 71 | + const connectFailures: Array<'reset' | number> = [] |
| 72 | + const origin: GatewayTlsFixture['origin'] = { requests: 0, headers: {}, target: '' } |
| 73 | + |
| 74 | + const secureOrigin = httpsServer({ cert, key }, async (req, res) => { |
| 75 | + res.setHeader('x-via-proxy', proxiedPorts.has(req.socket.remotePort ?? 0) ? 'yes' : 'no') |
| 76 | + origin.requests++ |
| 77 | + origin.headers = req.headers |
| 78 | + origin.target = req.url ?? '' |
| 79 | + res.setHeader('x-request-target', origin.target) |
| 80 | + if (req.url === '/redirect') { |
| 81 | + res.writeHead(302, { location: '/done' }) |
| 82 | + res.end() |
| 83 | + return |
| 84 | + } |
| 85 | + if (req.url === '/wait') return |
| 86 | + const chunks: Buffer[] = [] |
| 87 | + for await (const chunk of req) chunks.push(Buffer.from(chunk)) |
| 88 | + res.end(req.method === 'POST' || req.method === 'PUT' ? Buffer.concat(chunks) : 'tls reached') |
| 89 | + }) |
| 90 | + const proxy = httpsServer({ cert, key }) |
| 91 | + proxy.on('connect', (req, socket, head) => { |
| 92 | + socket.on('error', () => {}) |
| 93 | + const tlsSocket = req.socket as Socket & { servername?: string } |
| 94 | + const authorization = req.headers['proxy-authorization'] |
| 95 | + admissions.push({ token: authorization, destination: req.url, sni: tlsSocket.servername }) |
| 96 | + const failure = connectFailures.shift() |
| 97 | + if (failure === 'reset') { |
| 98 | + socket.destroy() |
| 99 | + return |
| 100 | + } |
| 101 | + if (failure !== undefined) { |
| 102 | + socket.end(`HTTP/1.1 ${failure} Gateway Failure\r\nContent-Length: 0\r\n\r\n`) |
| 103 | + return |
| 104 | + } |
| 105 | + if (!authorization || !admittedAuthorizations.has(authorization)) { |
| 106 | + socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 0\r\n\r\n') |
| 107 | + return |
| 108 | + } |
| 109 | + if (req.url !== '1.1.1.1:443') { |
| 110 | + socket.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n') |
| 111 | + return |
| 112 | + } |
| 113 | + const upstream = connect((secureOrigin.address() as AddressInfo).port, '127.0.0.1', () => { |
| 114 | + if (upstream.localPort) proxiedPorts.add(upstream.localPort) |
| 115 | + socket.write('HTTP/1.1 200 Connection Established\r\n\r\n') |
| 116 | + if (head.length) upstream.write(head) |
| 117 | + socket.pipe(upstream).pipe(socket) |
| 118 | + }) |
| 119 | + upstream.on('error', () => socket.destroy()) |
| 120 | + socket.on('error', () => upstream.destroy()) |
| 121 | + socket.on('close', () => upstream.destroy()) |
| 122 | + sockets.add(upstream) |
| 123 | + upstream.on('close', () => sockets.delete(upstream)) |
| 124 | + }) |
| 125 | + |
| 126 | + for (const server of [secureOrigin, proxy]) { |
| 127 | + server.on('connection', (socket) => { |
| 128 | + sockets.add(socket) |
| 129 | + socket.on('close', () => sockets.delete(socket)) |
| 130 | + }) |
| 131 | + await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve)) |
| 132 | + } |
| 133 | + |
| 134 | + return { |
| 135 | + cert, |
| 136 | + certificatePath, |
| 137 | + proxyPort: (proxy.address() as AddressInfo).port, |
| 138 | + admissions, |
| 139 | + connectFailures, |
| 140 | + origin, |
| 141 | + async close() { |
| 142 | + for (const socket of sockets) socket.destroy() |
| 143 | + await Promise.all( |
| 144 | + [secureOrigin, proxy].map( |
| 145 | + (server) => new Promise<void>((resolve) => server.close(() => resolve())) |
| 146 | + ) |
| 147 | + ) |
| 148 | + rmSync(certificateDirectory, { recursive: true, force: true }) |
| 149 | + }, |
| 150 | + } |
| 151 | +} |
0 commit comments