@namzu/sandbox 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +474 -0
  2. package/LICENSE.md +110 -0
  3. package/README.md +148 -0
  4. package/dist/backends/aci-standby-pool/index.d.ts +104 -0
  5. package/dist/backends/aci-standby-pool/index.d.ts.map +1 -0
  6. package/dist/backends/aci-standby-pool/index.js +425 -0
  7. package/dist/backends/aci-standby-pool/index.js.map +1 -0
  8. package/dist/backends/docker/__tests__/leaf-permissions.smoke.test.d.ts +40 -0
  9. package/dist/backends/docker/__tests__/leaf-permissions.smoke.test.d.ts.map +1 -0
  10. package/dist/backends/docker/__tests__/leaf-permissions.smoke.test.js +157 -0
  11. package/dist/backends/docker/__tests__/leaf-permissions.smoke.test.js.map +1 -0
  12. package/dist/backends/docker/index.d.ts +118 -0
  13. package/dist/backends/docker/index.d.ts.map +1 -0
  14. package/dist/backends/docker/index.js +645 -0
  15. package/dist/backends/docker/index.js.map +1 -0
  16. package/dist/backends/firecracker/__tests__/backend.test.d.ts +13 -0
  17. package/dist/backends/firecracker/__tests__/backend.test.d.ts.map +1 -0
  18. package/dist/backends/firecracker/__tests__/backend.test.js +353 -0
  19. package/dist/backends/firecracker/__tests__/backend.test.js.map +1 -0
  20. package/dist/backends/firecracker/__tests__/control-plane-mtls.test.d.ts +19 -0
  21. package/dist/backends/firecracker/__tests__/control-plane-mtls.test.d.ts.map +1 -0
  22. package/dist/backends/firecracker/__tests__/control-plane-mtls.test.js +201 -0
  23. package/dist/backends/firecracker/__tests__/control-plane-mtls.test.js.map +1 -0
  24. package/dist/backends/firecracker/__tests__/fixtures/mtls-pki.d.ts +39 -0
  25. package/dist/backends/firecracker/__tests__/fixtures/mtls-pki.d.ts.map +1 -0
  26. package/dist/backends/firecracker/__tests__/fixtures/mtls-pki.js +149 -0
  27. package/dist/backends/firecracker/__tests__/fixtures/mtls-pki.js.map +1 -0
  28. package/dist/backends/firecracker/__tests__/protocol.test.d.ts +6 -0
  29. package/dist/backends/firecracker/__tests__/protocol.test.d.ts.map +1 -0
  30. package/dist/backends/firecracker/__tests__/protocol.test.js +77 -0
  31. package/dist/backends/firecracker/__tests__/protocol.test.js.map +1 -0
  32. package/dist/backends/firecracker/__tests__/transport.test.d.ts +20 -0
  33. package/dist/backends/firecracker/__tests__/transport.test.d.ts.map +1 -0
  34. package/dist/backends/firecracker/__tests__/transport.test.js +449 -0
  35. package/dist/backends/firecracker/__tests__/transport.test.js.map +1 -0
  36. package/dist/backends/firecracker/index.d.ts +124 -0
  37. package/dist/backends/firecracker/index.d.ts.map +1 -0
  38. package/dist/backends/firecracker/index.js +334 -0
  39. package/dist/backends/firecracker/index.js.map +1 -0
  40. package/dist/backends/firecracker/protocol.d.ts +132 -0
  41. package/dist/backends/firecracker/protocol.d.ts.map +1 -0
  42. package/dist/backends/firecracker/protocol.js +112 -0
  43. package/dist/backends/firecracker/protocol.js.map +1 -0
  44. package/dist/backends/firecracker/transport.d.ts +251 -0
  45. package/dist/backends/firecracker/transport.d.ts.map +1 -0
  46. package/dist/backends/firecracker/transport.js +524 -0
  47. package/dist/backends/firecracker/transport.js.map +1 -0
  48. package/dist/index.d.ts +611 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +376 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/index.test.d.ts +28 -0
  53. package/dist/index.test.d.ts.map +1 -0
  54. package/dist/index.test.js +670 -0
  55. package/dist/index.test.js.map +1 -0
  56. package/package.json +54 -0
  57. package/src/backends/aci-standby-pool/index.ts +602 -0
  58. package/src/backends/docker/__tests__/leaf-permissions.smoke.test.ts +169 -0
  59. package/src/backends/docker/index.ts +826 -0
  60. package/src/backends/firecracker/__tests__/backend.test.ts +418 -0
  61. package/src/backends/firecracker/__tests__/control-plane-mtls.test.ts +253 -0
  62. package/src/backends/firecracker/__tests__/fixtures/mtls-pki.ts +166 -0
  63. package/src/backends/firecracker/__tests__/protocol.test.ts +90 -0
  64. package/src/backends/firecracker/__tests__/transport.test.ts +526 -0
  65. package/src/backends/firecracker/index.ts +528 -0
  66. package/src/backends/firecracker/protocol.ts +191 -0
  67. package/src/backends/firecracker/transport.ts +667 -0
  68. package/src/index.test.ts +731 -0
  69. package/src/index.ts +930 -0
@@ -0,0 +1,526 @@
1
+ /**
2
+ * Loopback transport round-trip tests for the Firecracker vsock path.
3
+ *
4
+ * These prove the NEW transport (host dialer ↔ in-VM agent) over a
5
+ * **unix-socket stand-in** — the faithful local peer for AF_VSOCK,
6
+ * because the production vsock path also terminates on a host
7
+ * unix socket (see `transport.ts` docblock). The peer is the REAL
8
+ * `agent/agent.cjs` connection handler (its spawn/jail + NDJSON shapes
9
+ * verbatim), driven in-process over a temp unix socket; the client is
10
+ * the REAL {@link VsockAgentTransport}. So one test exercises:
11
+ * - exec → streamed stdout/stderr/result NDJSON, accumulated;
12
+ * - writeFile / readFile → base64 round-trip through the jail;
13
+ * - a simulated resume (server torn down + re-listened) survived by
14
+ * the dialer's connect-retry budget — the FC #4713 invariant.
15
+ *
16
+ * No docker, no Azure, no AF_VSOCK kernel support required: pure
17
+ * loopback, safe in CI.
18
+ */
19
+
20
+ import { mkdtempSync, rmSync } from 'node:fs'
21
+ import { type Server, type Socket, createServer, connect as netConnect } from 'node:net'
22
+ import { tmpdir } from 'node:os'
23
+ import { join } from 'node:path'
24
+ import { type TLSSocket, type Server as TlsServer, createServer as createTlsServer } from 'node:tls'
25
+
26
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
27
+
28
+ import { VsockAgentTransport } from '../transport.js'
29
+
30
+ // The agent is a CommonJS module that reads NAMZU_SANDBOX_WORKSPACE at
31
+ // require-time. Set the env, then require it through createRequire so
32
+ // each test file gets a fresh module bound to its own workspace dir.
33
+ import { createRequire } from 'node:module'
34
+
35
+ const require_ = createRequire(import.meta.url)
36
+
37
+ interface AgentModule {
38
+ handleConnection(socket: Socket): void
39
+ }
40
+
41
+ let workDir: string
42
+ let sockPath: string
43
+ let server: Server | undefined
44
+ let agent: AgentModule
45
+
46
+ function startAgentServer(connHandler: (s: Socket) => void): Promise<Server> {
47
+ return new Promise((resolve, reject) => {
48
+ const s = createServer(connHandler)
49
+ s.on('error', reject)
50
+ s.listen(sockPath, () => resolve(s))
51
+ })
52
+ }
53
+
54
+ beforeEach(() => {
55
+ workDir = mkdtempSync(join(tmpdir(), 'fc-agent-test-'))
56
+ sockPath = join(workDir, 'agent.sock')
57
+ // Bind the agent's workspace jail to the temp dir BEFORE requiring it.
58
+ process.env.NAMZU_SANDBOX_WORKSPACE = workDir
59
+ // The agent's root-normalization filters env on PRESENCE; `= undefined`
60
+ // sets the literal string "undefined" and would widen READ/WRITE_ROOTS, so
61
+ // these must be true deletes.
62
+ // biome-ignore lint/performance/noDelete: must remove the var, not set "undefined".
63
+ delete process.env.NAMZU_SANDBOX_READ_ROOTS
64
+ // biome-ignore lint/performance/noDelete: must remove the var, not set "undefined".
65
+ delete process.env.NAMZU_SANDBOX_WRITE_ROOTS
66
+ // Fresh module each test so WORKSPACE_ROOT is rebound.
67
+ delete require_.cache[require_.resolve('../../../../agent/agent.cjs')]
68
+ agent = require_('../../../../agent/agent.cjs') as AgentModule
69
+ })
70
+
71
+ afterEach(async () => {
72
+ if (server) {
73
+ await new Promise<void>((r) => server?.close(() => r()))
74
+ server = undefined
75
+ }
76
+ rmSync(workDir, { recursive: true, force: true })
77
+ })
78
+
79
+ describe('VsockAgentTransport over a unix-socket loopback agent', () => {
80
+ it('streams stdout/stderr/result NDJSON from an exec', async () => {
81
+ server = await startAgentServer(agent.handleConnection)
82
+ const transport = new VsockAgentTransport({ kind: 'unix', path: sockPath })
83
+
84
+ const r = await transport.execute({
85
+ command: '/bin/sh',
86
+ args: ['-c', 'echo out-line; echo err-line 1>&2; exit 3'],
87
+ })
88
+ expect(r.stdout).toContain('out-line')
89
+ expect(r.stderr).toContain('err-line')
90
+ expect(r.exitCode).toBe(3)
91
+ expect(r.timedOut).toBe(false)
92
+ expect(r.durationMs).toBeGreaterThanOrEqual(0)
93
+ })
94
+
95
+ it('streams a large multi-chunk stdout intact (delta accumulation)', async () => {
96
+ server = await startAgentServer(agent.handleConnection)
97
+ const transport = new VsockAgentTransport({ kind: 'unix', path: sockPath })
98
+
99
+ // 200 lines so the agent emits multiple stdout_delta frames the
100
+ // FrameReader must reassemble across socket chunks.
101
+ const r = await transport.execute({
102
+ command: '/bin/sh',
103
+ args: ['-c', 'for i in $(seq 1 200); do echo "line-$i"; done'],
104
+ })
105
+ expect(r.exitCode).toBe(0)
106
+ const lines = r.stdout.trim().split('\n')
107
+ expect(lines.length).toBe(200)
108
+ expect(lines[0]).toBe('line-1')
109
+ expect(lines[199]).toBe('line-200')
110
+ })
111
+
112
+ it('round-trips writeFile/readFile as base64 through the workspace jail', async () => {
113
+ server = await startAgentServer(agent.handleConnection)
114
+ const transport = new VsockAgentTransport({ kind: 'unix', path: sockPath })
115
+
116
+ // Binary content (non-UTF8 bytes) proves base64 fidelity, not
117
+ // just text.
118
+ const payload = Buffer.from([0x00, 0xff, 0x10, 0x42, 0x00, 0x99, 0xfe])
119
+ await transport.writeFile('sub/dir/blob.bin', payload)
120
+ const read = await transport.readFile('sub/dir/blob.bin')
121
+ expect(read.equals(payload)).toBe(true)
122
+ })
123
+
124
+ it('rejects a path that escapes the workspace jail', async () => {
125
+ server = await startAgentServer(agent.handleConnection)
126
+ const transport = new VsockAgentTransport({ kind: 'unix', path: sockPath })
127
+ await expect(transport.readFile('../../../../etc/passwd')).rejects.toThrow(/escapes/)
128
+ })
129
+
130
+ it('healthz returns true against a live agent', async () => {
131
+ server = await startAgentServer(agent.handleConnection)
132
+ const transport = new VsockAgentTransport({ kind: 'unix', path: sockPath })
133
+ expect(await transport.healthz()).toBe(true)
134
+ })
135
+
136
+ it('surfaces an exec error event as a thrown error', async () => {
137
+ server = await startAgentServer(agent.handleConnection)
138
+ const transport = new VsockAgentTransport({ kind: 'unix', path: sockPath })
139
+ // Empty command name → agent emits { type: 'error' }.
140
+ await expect(transport.execute({ command: '' })).rejects.toThrow()
141
+ })
142
+
143
+ it('survives a simulated resume: server torn down then re-listened, dialer reconnects', async () => {
144
+ // 1. Agent is up; one exec succeeds.
145
+ server = await startAgentServer(agent.handleConnection)
146
+ const transport = new VsockAgentTransport(
147
+ { kind: 'unix', path: sockPath },
148
+ // Tight retry budget so the test is fast but still proves retry.
149
+ { connectRetryBudgetMs: 5_000, connectRetryIntervalMs: 50, connectTimeoutMs: 1_000 },
150
+ )
151
+ const first = await transport.execute({ command: '/bin/sh', args: ['-c', 'echo before'] })
152
+ expect(first.stdout).toContain('before')
153
+
154
+ // 2. Simulate a resume: the FC vsock driver closes all connections
155
+ // and the listener is gone until the agent re-LISTENs. Tear the
156
+ // server down entirely.
157
+ await new Promise<void>((r) => server?.close(() => r()))
158
+ server = undefined
159
+
160
+ // 3. Kick off an exec WHILE the agent is still down. The dialer's
161
+ // connect-retry budget must hold (ECONNREFUSED) until the agent
162
+ // re-listens — this is the FC #4713 / TRANSPORT_RESET-not-
163
+ // delivered mitigation: the host re-dials rather than hanging.
164
+ const pending = transport.execute({ command: '/bin/sh', args: ['-c', 'echo after'] })
165
+
166
+ // 4. After a beat, the agent re-establishes its listen on the SAME
167
+ // address (the resume re-listen invariant).
168
+ await new Promise((r) => setTimeout(r, 300))
169
+ server = await startAgentServer(agent.handleConnection)
170
+
171
+ const after = await pending
172
+ expect(after.stdout).toContain('after')
173
+ expect(after.exitCode).toBe(0)
174
+ })
175
+
176
+ it('connect-retry budget gives up with a clear error when the agent never returns', async () => {
177
+ // No server started at all. The dialer should exhaust its budget
178
+ // and throw a descriptive error rather than hang forever.
179
+ const transport = new VsockAgentTransport(
180
+ { kind: 'unix', path: sockPath },
181
+ { connectRetryBudgetMs: 400, connectRetryIntervalMs: 50, connectTimeoutMs: 200 },
182
+ )
183
+ await expect(transport.healthz()).resolves.toBe(false)
184
+ await expect(transport.readFile('x')).rejects.toThrow(/could not connect to agent/)
185
+ })
186
+ })
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Ring-0 mTLS arm — pure-local TLS loopback "relay" (no Azure, no FC host)
190
+ // ---------------------------------------------------------------------------
191
+ //
192
+ // Proves the ADDITIVE `kind:'mtls'` transport arm without a real fleet:
193
+ // - a `tls.createServer` plays the per-FC-host RELAY (requestCert +
194
+ // rejectUnauthorized), reads the `SANDBOX <id>` routing preamble,
195
+ // then bridges verbatim to the SAME `agent.handleConnection` peer
196
+ // the vsock/unix arms use — so the IDENTICAL framing round-trips.
197
+ // - the dialer presents the fleet CLIENT cert and verifies the relay
198
+ // server cert; a WRONG-CA client is rejected at the TLS layer.
199
+ // - the `SANDBOX <id>` preamble is the FIRST bytes after the
200
+ // handshake (the relay's routing key), and the caller never writes
201
+ // a guest `CONNECT 1024` line (the relay issues that host-side).
202
+ //
203
+ // The cert material is a throwaway P-256 test PKI (CA + server leaf +
204
+ // client leaf + an unrelated rogue client) baked in as PEM constants —
205
+ // no openssl/forge at test time, keeping the package dependency-light.
206
+
207
+ // Test PKI. Minted offline with: openssl ec/x509 self-signed CA + leaves
208
+ // (server SAN = DNS:sandbox.fc.internal, IP:127.0.0.1). Far-future expiry.
209
+ // `ROGUE_*` chains to a DIFFERENT CA to prove rejectUnauthorized blocks it.
210
+ const CA_CRT = `-----BEGIN CERTIFICATE-----
211
+ MIIBjjCCATWgAwIBAgIUGXUtG14KQr4spNGW7rpfjZGoBIIwCgYIKoZIzj0EAwIw
212
+ HDEaMBgGA1UEAwwRdmFuZGFsLWZjLXRlc3QtY2EwIBcNMjYwNjE2MDgzMjUyWhgP
213
+ MjEyNjA1MjMwODMyNTJaMBwxGjAYBgNVBAMMEXZhbmRhbC1mYy10ZXN0LWNhMFkw
214
+ EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5l+vjhjm/PX02D55n56EwelgvM1jrqQM
215
+ Z+ezzvMmrZEBGWInvBND3z3kc6nv7snu6fHT2HHOyhwUNoLqmrIg/qNTMFEwHQYD
216
+ VR0OBBYEFP0M8/KZY1ovxyGDci5iuoYXcmZgMB8GA1UdIwQYMBaAFP0M8/KZY1ov
217
+ xyGDci5iuoYXcmZgMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDRwAwRAIg
218
+ C0xtFDASnwsOYT0GiZwzYWTOBfgmjDWK7ANXQQFNTh4CICVLQwq5eLy3424drEHk
219
+ 5Ol/FNKVZcGRjE96rB0mRUOp
220
+ -----END CERTIFICATE-----
221
+ `
222
+
223
+ const SERVER_CRT = `-----BEGIN CERTIFICATE-----
224
+ MIIBsDCCAVWgAwIBAgIUYkXroqlz9blXW8llis6e2OxOc1MwCgYIKoZIzj0EAwIw
225
+ HDEaMBgGA1UEAwwRdmFuZGFsLWZjLXRlc3QtY2EwIBcNMjYwNjE2MDgzMjUyWhgP
226
+ MjEyNjA1MjMwODMyNTJaMBIxEDAOBgNVBAMMB2ZjLWhvc3QwWTATBgcqhkjOPQIB
227
+ BggqhkjOPQMBBwNCAAQodCSHY8Sz5Lh/4K6+SzekkrRCeKMBfmonVb7dUhM0ZWpo
228
+ ePCcRrMcJp5aNxLxEgkl2EMMMMwE3LlLSOX5LZz6o30wezAkBgNVHREEHTAbghNz
229
+ YW5kYm94LmZjLmludGVybmFshwR/AAABMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0G
230
+ A1UdDgQWBBRXHU1vlX7WvqzcbaNxRxV4f3gfDDAfBgNVHSMEGDAWgBT9DPPymWNa
231
+ L8chg3IuYrqGF3JmYDAKBggqhkjOPQQDAgNJADBGAiEAlqzKqgBf5hxJqd26QwcY
232
+ n3cvEKi4f2BSLe1Rfzr5oSoCIQD0izUOJXLNvmac9cMgV0HvkftBerDKFOcGeGTN
233
+ g3Eunw==
234
+ -----END CERTIFICATE-----
235
+ `
236
+
237
+ const SERVER_KEY = `-----BEGIN PRIVATE KEY-----
238
+ MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg/ROnYXIkMKnipbLt
239
+ JnFEwXAifgeOv9TGLcK2RojE7jmhRANCAAQodCSHY8Sz5Lh/4K6+SzekkrRCeKMB
240
+ fmonVb7dUhM0ZWpoePCcRrMcJp5aNxLxEgkl2EMMMMwE3LlLSOX5LZz6
241
+ -----END PRIVATE KEY-----
242
+ `
243
+
244
+ const CLIENT_CRT = `-----BEGIN CERTIFICATE-----
245
+ MIIBjjCCATWgAwIBAgIUYkXroqlz9blXW8llis6e2OxOc1QwCgYIKoZIzj0EAwIw
246
+ HDEaMBgGA1UEAwwRdmFuZGFsLWZjLXRlc3QtY2EwIBcNMjYwNjE2MDgzMjUyWhgP
247
+ MjEyNjA1MjMwODMyNTJaMBgxFjAUBgNVBAMMDWNhLXZhbmRhbC1hcHAwWTATBgcq
248
+ hkjOPQIBBggqhkjOPQMBBwNCAASlCMCwjtrQUicWcWsO29R5S7fzjMbbxXvDh8/K
249
+ w57x/PN/uQwLHWCz1Tsyk0FnbrwGP+nPtwrUPIxrLN//euXko1cwVTATBgNVHSUE
250
+ DDAKBggrBgEFBQcDAjAdBgNVHQ4EFgQU2cxDCNrlVkk4ODs6ZPrkC6GzHjkwHwYD
251
+ VR0jBBgwFoAU/Qzz8pljWi/HIYNyLmK6hhdyZmAwCgYIKoZIzj0EAwIDRwAwRAIg
252
+ RghqArNm3bXnWnRi+jkEEJa8mRb2z0Wj4G7SIhtMurUCIBQSllVtICgZB9hvcM0D
253
+ d24fcW4nlfvaZJMJ6dRC1Wle
254
+ -----END CERTIFICATE-----
255
+ `
256
+
257
+ const CLIENT_KEY = `-----BEGIN PRIVATE KEY-----
258
+ MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgaamj/ycrEuPqpiC2
259
+ IhAYx/M5iN4t4P+B17V4GO54Nb2hRANCAASlCMCwjtrQUicWcWsO29R5S7fzjMbb
260
+ xXvDh8/Kw57x/PN/uQwLHWCz1Tsyk0FnbrwGP+nPtwrUPIxrLN//euXk
261
+ -----END PRIVATE KEY-----
262
+ `
263
+
264
+ const ROGUE_CLIENT_CRT = `-----BEGIN CERTIFICATE-----
265
+ MIIBhjCCASugAwIBAgIUbAYOlW4PQGyXjjRsjCPy62EHUmIwCgYIKoZIzj0EAwIw
266
+ EzERMA8GA1UEAwwIcm9ndWUtY2EwIBcNMjYwNjE2MDgzMjUyWhgPMjEyNjA1MjMw
267
+ ODMyNTJaMBcxFTATBgNVBAMMDHJvZ3VlLWNsaWVudDBZMBMGByqGSM49AgEGCCqG
268
+ SM49AwEHA0IABOPSzdzQTQz3M5CDHLVPguvHd10ncaDV9t4zKUy/PCE+U7GTJwN2
269
+ TtypGnmYEahbcl45j94hwu495P5VbR5ohb6jVzBVMBMGA1UdJQQMMAoGCCsGAQUF
270
+ BwMCMB0GA1UdDgQWBBTf0woauniche3/ps77+Kd0dsbbSDAfBgNVHSMEGDAWgBSX
271
+ Yu0IJlPxi79Gyi5hR1IfS/sqyzAKBggqhkjOPQQDAgNJADBGAiEAxD4N4XWtaHPJ
272
+ yaCOzQP0e5RRyNst3QrhH0NSMyPw89wCIQC+bezLX97TuV1sId53Bo1l9j1TSOMa
273
+ EZotN/Wsq6L+qw==
274
+ -----END CERTIFICATE-----
275
+ `
276
+
277
+ const ROGUE_CLIENT_KEY = `-----BEGIN PRIVATE KEY-----
278
+ MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgR6fGq27O9eT/hi0Q
279
+ c+L5+lSm5fbDEghVJCo6k7HrG62hRANCAATj0s3c0E0M9zOQgxy1T4Lrx3ddJ3Gg
280
+ 1fbeMylMvzwhPlOxkycDdk7cqRp5mBGoW3JeOY/eIcLuPeT+VW0eaIW+
281
+ -----END PRIVATE KEY-----
282
+ `
283
+
284
+ interface RelayHandle {
285
+ readonly server: TlsServer
286
+ readonly port: number
287
+ /** sandboxId from the first connection's `SANDBOX <id>` preamble. */
288
+ preamble(): Promise<string>
289
+ }
290
+
291
+ /**
292
+ * A loopback stand-in for the per-FC-host mTLS relay.
293
+ *
294
+ * Terminates mTLS (requestCert + rejectUnauthorized + CA pin), reads the
295
+ * `SANDBOX <id>\n` routing preamble line, then bridges the rest of the
296
+ * TLS stream verbatim to a FRESH `net.connect` to `agentSockPath` (the
297
+ * unix-socket-backed real agent) — exactly the dumb byte-pump the
298
+ * production relay is. It does NOT speak framing itself and does NOT
299
+ * send an ack line (matching the transport's no-ack INTEGRATE contract).
300
+ */
301
+ function startMtlsRelay(agentSockPath: string, listenPort = 0): Promise<RelayHandle> {
302
+ let resolvePreamble: (id: string) => void
303
+ const preamble = new Promise<string>((r) => {
304
+ resolvePreamble = r
305
+ })
306
+
307
+ return new Promise<RelayHandle>((resolve, reject) => {
308
+ const server = createTlsServer(
309
+ {
310
+ requestCert: true,
311
+ rejectUnauthorized: true,
312
+ ca: CA_CRT,
313
+ cert: SERVER_CRT,
314
+ key: SERVER_KEY,
315
+ minVersion: 'TLSv1.3',
316
+ },
317
+ (tlsSock: TLSSocket) => {
318
+ // Read exactly the `SANDBOX <id>\n` preamble line, then bridge.
319
+ let pre = Buffer.alloc(0)
320
+ const onPreambleData = (chunk: Buffer) => {
321
+ pre = Buffer.concat([pre, chunk])
322
+ const nl = pre.indexOf(0x0a)
323
+ if (nl < 0) return
324
+ tlsSock.removeListener('data', onPreambleData)
325
+ // Pause + unshift any post-preamble bytes so flowing-mode
326
+ // data is not dropped between removing this listener and
327
+ // attaching the pipe (the framed request can arrive in the
328
+ // same OR a later chunk). `pipe` resumes the stream.
329
+ tlsSock.pause()
330
+ const line = pre.subarray(0, nl).toString('utf8')
331
+ const rest = pre.subarray(nl + 1)
332
+ if (rest.length > 0) tlsSock.unshift(rest)
333
+ const m = /^SANDBOX (.+)$/.exec(line)
334
+ const id = m?.[1]
335
+ if (id === undefined) {
336
+ tlsSock.destroy()
337
+ return
338
+ }
339
+ resolvePreamble(id)
340
+ // 1 inbound mTLS conn -> 1 FRESH local agent connect (the
341
+ // resume-survival invariant the relay must preserve).
342
+ const upstream = netConnect({ path: agentSockPath })
343
+ upstream.on('error', () => tlsSock.destroy())
344
+ tlsSock.on('error', () => upstream.destroy())
345
+ upstream.once('connect', () => {
346
+ tlsSock.pipe(upstream)
347
+ upstream.pipe(tlsSock)
348
+ })
349
+ }
350
+ tlsSock.on('data', onPreambleData)
351
+ },
352
+ )
353
+ server.on('error', reject)
354
+ server.listen(listenPort, '127.0.0.1', () => {
355
+ const addr = server.address()
356
+ if (addr === null || typeof addr === 'string') {
357
+ reject(new Error('relay: no TCP port'))
358
+ return
359
+ }
360
+ resolve({ server, port: addr.port, preamble: () => preamble })
361
+ })
362
+ })
363
+ }
364
+
365
+ /** Re-listen the relay on a FIXED port (the host-bridge-restart case). */
366
+ function startMtlsRelayOnPort(agentSockPath: string, port: number): Promise<RelayHandle> {
367
+ return startMtlsRelay(agentSockPath, port)
368
+ }
369
+
370
+ describe('VsockAgentTransport mtls arm over a TLS loopback relay', () => {
371
+ let agentServer: Server | undefined
372
+ let relay: RelayHandle | undefined
373
+
374
+ afterEach(async () => {
375
+ if (relay) {
376
+ await new Promise<void>((r) => relay?.server.close(() => r()))
377
+ relay = undefined
378
+ }
379
+ if (agentServer) {
380
+ await new Promise<void>((r) => agentServer?.close(() => r()))
381
+ agentServer = undefined
382
+ }
383
+ })
384
+
385
+ function mtlsTransport(opts?: ConstructorParameters<typeof VsockAgentTransport>[1]) {
386
+ if (!relay) throw new Error('relay not started')
387
+ return new VsockAgentTransport(
388
+ {
389
+ kind: 'mtls',
390
+ host: '127.0.0.1',
391
+ port: relay.port,
392
+ sandboxId: 'sbx-ring0-abc123',
393
+ tls: {
394
+ ca: CA_CRT,
395
+ cert: CLIENT_CRT,
396
+ key: CLIENT_KEY,
397
+ servername: 'sandbox.fc.internal',
398
+ },
399
+ },
400
+ opts,
401
+ )
402
+ }
403
+
404
+ it('round-trips exec + write/read + healthz through the mTLS relay', async () => {
405
+ agentServer = await startAgentServer(agent.handleConnection)
406
+ relay = await startMtlsRelay(sockPath)
407
+ const transport = mtlsTransport()
408
+
409
+ const r = await transport.execute({
410
+ command: '/bin/sh',
411
+ args: ['-c', 'echo mtls-out; echo mtls-err 1>&2; exit 7'],
412
+ })
413
+ expect(r.stdout).toContain('mtls-out')
414
+ expect(r.stderr).toContain('mtls-err')
415
+ expect(r.exitCode).toBe(7)
416
+
417
+ const payload = Buffer.from([0x00, 0xff, 0x10, 0x42, 0x00, 0x99, 0xfe])
418
+ await transport.writeFile('m/blob.bin', payload)
419
+ const read = await transport.readFile('m/blob.bin')
420
+ expect(read.equals(payload)).toBe(true)
421
+
422
+ expect(await transport.healthz()).toBe(true)
423
+ })
424
+
425
+ it('sends `SANDBOX <id>` as the first bytes after the handshake (no CONNECT line)', async () => {
426
+ agentServer = await startAgentServer(agent.handleConnection)
427
+ relay = await startMtlsRelay(sockPath)
428
+ const transport = mtlsTransport()
429
+
430
+ // Any op drives a dial; the relay records the preamble line.
431
+ expect(await transport.healthz()).toBe(true)
432
+ // The caller's first line is the routing preamble, NOT `CONNECT 1024`
433
+ // — the relay issues the guest CONNECT host-side.
434
+ await expect(relay.preamble()).resolves.toBe('sbx-ring0-abc123')
435
+ })
436
+
437
+ it('rejects a client presenting a wrong-CA cert (rejectUnauthorized blocks it)', async () => {
438
+ agentServer = await startAgentServer(agent.handleConnection)
439
+ relay = await startMtlsRelay(sockPath)
440
+ // Rogue client cert chains to a DIFFERENT CA than the relay trusts.
441
+ const rogue = new VsockAgentTransport(
442
+ {
443
+ kind: 'mtls',
444
+ host: '127.0.0.1',
445
+ port: relay.port,
446
+ sandboxId: 'sbx-ring0-abc123',
447
+ tls: {
448
+ ca: CA_CRT,
449
+ cert: ROGUE_CLIENT_CRT,
450
+ key: ROGUE_CLIENT_KEY,
451
+ servername: 'sandbox.fc.internal',
452
+ },
453
+ },
454
+ { connectRetryBudgetMs: 600, connectRetryIntervalMs: 50, connectTimeoutMs: 300 },
455
+ )
456
+ // The relay's `rejectUnauthorized` drops the connection AFTER the
457
+ // client handshake completes (the client trusts the server CA), so
458
+ // the failure surfaces as a torn-down round-trip, not a TLS verify
459
+ // error on the client side. Either way no agent traffic completes:
460
+ // healthz swallows it into `false`; readFile rejects.
461
+ expect(await rogue.healthz()).toBe(false)
462
+ await expect(rogue.readFile('x')).rejects.toThrow()
463
+ })
464
+
465
+ it('rejects a server whose cert does not chain to the pinned CA (caller-side verify)', async () => {
466
+ agentServer = await startAgentServer(agent.handleConnection)
467
+ relay = await startMtlsRelay(sockPath)
468
+ // The CALLER pins the ROGUE CA, so the relay's good-CA server cert
469
+ // fails verification — proves the dialer's rejectUnauthorized works.
470
+ const wrongCaCaller = new VsockAgentTransport(
471
+ {
472
+ kind: 'mtls',
473
+ host: '127.0.0.1',
474
+ port: relay.port,
475
+ sandboxId: 'sbx-ring0-abc123',
476
+ tls: {
477
+ ca: ROGUE_CLIENT_CRT, // not the issuing CA → server cert unverifiable
478
+ cert: CLIENT_CRT,
479
+ key: CLIENT_KEY,
480
+ servername: 'sandbox.fc.internal',
481
+ },
482
+ },
483
+ { connectRetryBudgetMs: 600, connectRetryIntervalMs: 50, connectTimeoutMs: 300 },
484
+ )
485
+ await expect(wrongCaCaller.readFile('x')).rejects.toThrow(/could not connect to agent/)
486
+ })
487
+
488
+ it('survives a simulated resume through the relay (relay torn down then re-listened on the same port)', async () => {
489
+ agentServer = await startAgentServer(agent.handleConnection)
490
+ relay = await startMtlsRelay(sockPath)
491
+ const fixedPort = relay.port
492
+ const transport = new VsockAgentTransport(
493
+ {
494
+ kind: 'mtls',
495
+ host: '127.0.0.1',
496
+ port: fixedPort,
497
+ sandboxId: 'sbx-ring0-abc123',
498
+ tls: {
499
+ ca: CA_CRT,
500
+ cert: CLIENT_CRT,
501
+ key: CLIENT_KEY,
502
+ servername: 'sandbox.fc.internal',
503
+ },
504
+ },
505
+ { connectRetryBudgetMs: 5_000, connectRetryIntervalMs: 50, connectTimeoutMs: 1_000 },
506
+ )
507
+ const first = await transport.execute({ command: '/bin/sh', args: ['-c', 'echo before'] })
508
+ expect(first.stdout).toContain('before')
509
+
510
+ // Simulate the FC host bridge going away then coming back (the
511
+ // network analogue of a vsock re-LISTEN): tear the relay down so the
512
+ // caller's TLS connect gets ECONNREFUSED, and the per-request fresh
513
+ // dial must ride the connect-retry budget until the relay is back.
514
+ await new Promise<void>((r) => relay?.server.close(() => r()))
515
+ relay = undefined
516
+
517
+ const pending = transport.execute({ command: '/bin/sh', args: ['-c', 'echo after'] })
518
+ await new Promise((r) => setTimeout(r, 300))
519
+ // Re-listen the relay on the SAME port (the host bridge restarts).
520
+ relay = await startMtlsRelayOnPort(sockPath, fixedPort)
521
+
522
+ const after = await pending
523
+ expect(after.stdout).toContain('after')
524
+ expect(after.exitCode).toBe(0)
525
+ })
526
+ })