@namzu/sandbox 2.0.2 → 2.0.3

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