Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { e2bSandbox } from '../src/index'
3import type { SandboxHandle } from '@tanstack/ai-sandbox'
4
5// Auto-gate: only run when an E2B API key is present (these tests create real
6// cloud sandboxes).
7const apiKey = process.env.E2B_API_KEY
8
9describe.skipIf(!apiKey)('e2b provider (gated on E2B_API_KEY)', () => {
10 it('creates a sandbox, runs exec, fs round-trip + destroy', async () => {
11 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
12 let sbx: SandboxHandle | undefined
13 try {
14 sbx = await provider.create({ id: 'live-test' })
15
16 const echo = await sbx.process.exec('echo hello-e2b; pwd')
17 expect(echo.stdout).toContain('hello-e2b')
18 expect(echo.stdout).toContain('/home/user/workspace')
19 expect(echo.exitCode).toBe(0)
20
21 // Non-zero exit is a result with stderr intact, not an exception.
22 const failed = await sbx.process.exec('echo nope >&2; exit 7')
23 expect(failed.exitCode).toBe(7)
24 expect(failed.stderr).toContain('nope')
25
26 // Per-command env arrives natively, and env.set overlays it.
27 await sbx.env.set({ BASE_VAR: 'base' })
28 const env = await sbx.process.exec('echo "$BASE_VAR:$EXTRA_VAR"', {
29 env: { EXTRA_VAR: 'extra' },
30 })
31 expect(env.stdout.trim()).toBe('base:extra')
32
33 await sbx.fs.write('/workspace/nested/note.txt', 'inside e2b')
34 expect(await sbx.fs.exists('/workspace/nested/note.txt')).toBe(true)
35 expect(await sbx.fs.read('/workspace/nested/note.txt')).toBe('inside e2b')
36 expect(await sbx.fs.lstat!('/workspace/nested/note.txt')).toMatchObject({
37 type: 'file',
38 size: 10,
39 })
40 expect(await sbx.fs.lstat!('/workspace/absent')).toBeUndefined()
41
42 const bytes = new Uint8Array([0, 1, 2, 250])
43 await sbx.fs.write('/workspace/bin', bytes)
44 expect(Array.from(await sbx.fs.readBytes('/workspace/bin'))).toEqual([
45 0, 1, 2, 250,
46 ])
47
48 expect(await sbx.fs.list('/workspace')).toEqual(
49 expect.arrayContaining([
50 { name: 'nested', path: '/workspace/nested', type: 'dir' },
51 { name: 'bin', path: '/workspace/bin', type: 'file' },
52 ]),
53 )
54 await sbx.fs.rename('/workspace/bin', '/workspace/bin2')
55 expect(await sbx.fs.exists('/workspace/bin')).toBe(false)
56 await sbx.fs.remove('/workspace/nested')
57 expect(await sbx.fs.exists('/workspace/nested')).toBe(false)
58
59 // Background process: separate streams, real pid, exit code.
60 const split = await sbx.process.spawn('echo to-out; echo to-err >&2')
61 expect(split.pid).toBeGreaterThan(0)
62 let sOut = ''
63 let sErr = ''
64 await Promise.all([
65 (async () => {
66 for await (const c of split.stdout) sOut += c
67 })(),
68 (async () => {
69 for await (const c of split.stderr) sErr += c
70 })(),
71 ])
72 expect(await split.wait()).toBe(0)
73 expect(sOut).toContain('to-out')
74 expect(sOut).not.toContain('to-err')
75 expect(sErr).toContain('to-err')
76
77 // Preview channel is an https URL on the sandbox host.
78 const channel = await sbx.ports.connect(3000)
79 expect(channel.url).toMatch(/^https:\/\/3000-/)
80 } finally {
81 await sbx?.destroy()
82 }
83 }, 300_000)
84
85 // MEASURES writableStdin: `cat` only exits if stdin really closes.
86 it('feeds a spawned process over stdin and closes it', async () => {
87 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
88 let sbx: SandboxHandle | undefined
89 try {
90 sbx = await provider.create({})
91 const proc = await sbx.process.spawn('cat')
92 await proc.stdin.write('fed-over-stdin\n')
93 await proc.stdin.end()
94 let out = ''
95 for await (const chunk of proc.stdout) out += chunk
96 expect(out).toContain('fed-over-stdin')
97 expect(await proc.wait()).toBe(0)
98 } finally {
99 await sbx?.destroy()
100 }
101 }, 300_000)
102
103 // MEASURES killableProcesses: the marker file proves the process died
104 // server-side rather than the client merely detaching from it.
105 it('kill() actually terminates the process inside the sandbox', async () => {
106 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
107 let sbx: SandboxHandle | undefined
108 try {
109 sbx = await provider.create({})
110 const proc = await sbx.process.spawn(
111 'sleep 5 && touch /home/user/workspace/survived',
112 )
113 expect(proc.pid).toBeGreaterThan(0)
114 await proc.kill()
115 // A signalled process reports a non-zero (signal) exit, never 0.
116 expect(await proc.wait()).not.toBe(0)
117 // Outlive the original sleep, then confirm it never completed.
118 await new Promise((r) => setTimeout(r, 8000))
119 expect(await sbx.fs.exists('/workspace/survived')).toBe(false)
120 } finally {
121 await sbx?.destroy()
122 }
123 }, 300_000)
124
125 // MEASURES the abort path: the SDK's own signal only detaches the client, so
126 // the provider must kill the process itself.
127 it('aborting exec kills the sandbox-side process', async () => {
128 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
129 let sbx: SandboxHandle | undefined
130 try {
131 sbx = await provider.create({})
132 const controller = new AbortController()
133 const pending = sbx.process.exec(
134 'sleep 5 && touch /home/user/workspace/survived-abort',
135 { signal: controller.signal },
136 )
137 await new Promise((r) => setTimeout(r, 500))
138 controller.abort()
139 expect((await pending).exitCode).not.toBe(0)
140 await new Promise((r) => setTimeout(r, 6000))
141 expect(await sbx.fs.exists('/workspace/survived-abort')).toBe(false)
142 } finally {
143 await sbx?.destroy()
144 }
145 }, 300_000)
146
147 it('snapshots a sandbox and restores it into a new one', async () => {
148 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
149 let source: SandboxHandle | undefined
150 let restored: SandboxHandle | undefined
151 try {
152 source = await provider.create({})
153 await source.fs.write('/workspace/keep.txt', 'survives snapshot')
154
155 const ref = await source.snapshot?.('after-setup')
156 expect(ref?.id).toBeTruthy()
157
158 restored = await provider.restoreSnapshot!({ snapshotId: ref!.id })
159 expect(restored.id).not.toBe(source.id)
160 expect(await restored.fs.read('/workspace/keep.txt')).toBe(
161 'survives snapshot',
162 )
163 } finally {
164 await Promise.allSettled([source?.destroy(), restored?.destroy()])
165 }
166 }, 600_000)
167
168 // MEASURES fork: the copy carries state and then diverges.
169 it('fork branches a sandbox from current state', async () => {
170 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
171 let src: SandboxHandle | undefined
172 let forked: SandboxHandle | undefined
173 try {
174 src = await provider.create({})
175 await src.fs.write('/workspace/before-fork.txt', 'carried over')
176 forked = await src.fork!()
177 expect(forked.id).not.toBe(src.id)
178 expect(await forked.fs.read('/workspace/before-fork.txt')).toBe(
179 'carried over',
180 )
181 await forked.fs.write('/workspace/only-in-fork.txt', 'x')
182 expect(await src.fs.exists('/workspace/only-in-fork.txt')).toBe(false)
183 } finally {
184 await Promise.allSettled([src?.destroy(), forked?.destroy()])
185 }
186 }, 600_000)
187
188 it('resume reconnects to a live sandbox and returns null once it is destroyed', async () => {
189 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
190 const sbx = await provider.create({})
191 try {
192 await sbx.fs.write('/workspace/state.txt', 'still here')
193 const resumed = await provider.resume({ id: sbx.id })
194 expect(resumed?.id).toBe(sbx.id)
195 expect(await resumed!.fs.read('/workspace/state.txt')).toBe('still here')
196 } finally {
197 await sbx.destroy()
198 }
199 expect(await provider.resume({ id: sbx.id })).toBeNull()
200 // Destroying an already-destroyed sandbox is not an error.
201 await expect(provider.destroy({ id: sbx.id })).resolves.toBeUndefined()
202 }, 300_000)
203
204 // MEASURES networkPolicy: a deny policy must actually block egress.
205 it('a deny network policy blocks outbound traffic', async () => {
206 const provider = e2bSandbox({ apiKey, timeoutMs: 5 * 60_000 })
207 const PROBE =
208 'curl -s -m 10 -o /dev/null -w "%{http_code}" https://example.com'
209 let denied: SandboxHandle | undefined
210 let control: SandboxHandle | undefined
211 try {
212 const [deniedRes, controlRes] = await Promise.allSettled([
213 provider.create({ policy: { capabilities: { network: 'deny' } } }),
214 provider.create({}),
215 ])
216 if (deniedRes.status === 'fulfilled') denied = deniedRes.value
217 if (controlRes.status === 'fulfilled') control = controlRes.value
218 if (deniedRes.status === 'rejected') throw deniedRes.reason
219 if (controlRes.status === 'rejected') throw controlRes.reason
220
221 // POSITIVE CONTROL: without it the test passes whenever the probe fails
222 // for an unrelated reason even though egress is wide open.
223 const reachable = await control!.process.exec(PROBE)
224 expect(reachable.stdout).toContain('200')
225
226 expect((await denied!.process.exec('command -v curl')).exitCode).toBe(0)
227 const blocked = await denied!.process.exec(PROBE)
228 expect(blocked.exitCode).not.toBe(0)
229 expect(blocked.stdout).not.toContain('200')
230 } finally {
231 await Promise.allSettled([denied?.destroy(), control?.destroy()])
232 }
233 }, 600_000)
234
235 // MEASURES the traffic token: a port of a sandbox with public traffic
236 // disabled answers only when the returned header is attached.
237 it('gates preview URLs behind the traffic token when public traffic is off', async () => {
238 const provider = e2bSandbox({
239 apiKey,
240 timeoutMs: 5 * 60_000,
241 allowPublicTraffic: false,
242 })
243 let sbx: SandboxHandle | undefined
244 try {
245 sbx = await provider.create({})
246 const server = await sbx.process.spawn('python3 -m http.server 8000')
247 await new Promise((r) => setTimeout(r, 2000))
248 const channel = await sbx.ports.connect(8000)
249 expect(channel.token).toBeTruthy()
250 expect(channel.headers).toBeDefined()
251
252 const anonymous = await fetch(channel.url)
253 expect(anonymous.status).toBe(403)
254 const authed = await fetch(channel.url, { headers: channel.headers })
255 expect(authed.status).toBe(200)
256 await server.kill()
257 } finally {
258 await sbx?.destroy()
259 }
260 }, 300_000)
261})