Skip to content

Commit 63cfea1

Browse files
authored
fix(network): run the Bun-runtime gateway check in the integration tier (#10378)
* fix(network): run the Bun-runtime gateway check in the integration tier * fix(network): restore the Socket type import and shrink the test-types baseline * fix(audits): skip test-helper fixtures in the egress scan and bar production code from loading them
1 parent fb545bd commit 63cfea1

6 files changed

Lines changed: 299 additions & 212 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Proves organization gateway routing under the real Bun runtime, which the Node-hosted unit suite
3+
* cannot: undici and the pinned fetch ride Bun's own `node:net`/`node:tls` shims there. The probe is
4+
* a separate Bun process, so most of its cost is starting Bun and loading the gateway's module graph.
5+
* That cost runs from about 0.1s idle to several seconds on a saturated unit shard, which is why the
6+
* probe lives in this one-file-at-a-time tier rather than inside a unit test's 10s budget.
7+
*/
8+
import { execFile } from 'node:child_process'
9+
import { fileURLToPath } from 'node:url'
10+
import { promisify } from 'node:util'
11+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
12+
import {
13+
type GatewayTlsFixture,
14+
startGatewayTlsFixture,
15+
} from '@/lib/core/network/gateway-tls.test-helpers'
16+
17+
const GATEWAY_TOKEN = 'a'.repeat(48)
18+
let fixture: GatewayTlsFixture
19+
beforeAll(async () => {
20+
fixture = await startGatewayTlsFixture([GATEWAY_TOKEN])
21+
})
22+
afterAll(() => fixture.close())
23+
24+
describe('organization gateways under the Bun runtime', () => {
25+
it('routes and verifies TLS under the actual Bun runtime', async () => {
26+
await promisify(execFile)(
27+
'bun',
28+
[
29+
'--no-env-file',
30+
'run',
31+
fileURLToPath(new URL('./fixtures/gateway-runtime.fixture.ts', import.meta.url)),
32+
String(fixture.proxyPort),
33+
fixture.certificatePath,
34+
],
35+
{
36+
timeout: 25_000,
37+
env: {
38+
...process.env,
39+
NODE_EXTRA_CA_CERTS: fixture.certificatePath,
40+
OUTBOUND_ROUTING_SOURCE: 'env',
41+
OUTBOUND_ROUTING_CONFIG: JSON.stringify({
42+
schemaVersion: 1,
43+
revision: 'test',
44+
organizations: { org_test: { kind: 'gateway', gatewayId: 'synthetic' } },
45+
}),
46+
OUTBOUND_GATEWAYS: JSON.stringify({
47+
synthetic: {
48+
organizationId: 'org_test',
49+
url: `https://127.0.0.1:${fixture.proxyPort}`,
50+
servername: 'gateway.invalid',
51+
credentialId: 'synthetic',
52+
},
53+
}),
54+
OUTBOUND_GATEWAY_CREDENTIALS: JSON.stringify({
55+
synthetic: { token: GATEWAY_TOKEN, ca: fixture.cert },
56+
}),
57+
},
58+
}
59+
)
60+
expect(fixture.admissions.map((admission) => admission.token)).toEqual(
61+
Array(4).fill(`Bearer ${GATEWAY_TOKEN}`)
62+
)
63+
})
64+
})
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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

Comments
 (0)