Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
import { assert, expect, describe } from 'vitest'
import { CommandExitError, Sandbox } from '../../src'
import {
sandboxTest,
isDebug,
template,
corsHttpServerCmd,
waitForHttpStatus,
} from '../setup.js'
import { httpbinTemplate } from '../template.js'
describe('allow only 1.1.1.1', () => {
sandboxTest.override({
sandboxOpts: {
network: {
denyOut: ({ allTraffic }) => [allTraffic],
allowOut: ['1.1.1.1'],
},
},
})
sandboxTest.skipIf(isDebug)(
'allow specific IP with deny all traffic',
async ({ sandbox }) => {
// Test that allowed IP works
const result = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
)
assert.equal(result.exitCode, 0)
assert.equal(result.stdout.trim(), '301')
// Test that other IPs are denied
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8'
)
).rejects.toBeInstanceOf(CommandExitError)
}
)
})
describe('deny specific IP address', () => {
sandboxTest.override({
sandboxOpts: {
network: {
denyOut: ['8.8.8.8'],
},
},
})
sandboxTest.skipIf(isDebug)(
'deny specific IP address',
async ({ sandbox }) => {
// Test that denied IP fails
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8'
)
).rejects.toBeInstanceOf(CommandExitError)
// Test that other IPs work
const result = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
)
assert.equal(result.exitCode, 0)
assert.equal(result.stdout.trim(), '301')
}
)
})
describe('deny all traffic using allTraffic selector', () => {
sandboxTest.override({
sandboxOpts: {
network: {
denyOut: ({ allTraffic }) => [allTraffic],
},
},
})
sandboxTest.skipIf(isDebug)(
'deny all traffic using allTraffic selector',
async ({ sandbox }) => {
// Test that all traffic is denied
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://1.1.1.1'
)
).rejects.toBeInstanceOf(CommandExitError)
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8'
)
).rejects.toBeInstanceOf(CommandExitError)
}
)
})
describe('allow takes precedence over deny', () => {
sandboxTest.override({
sandboxOpts: {
network: {
denyOut: ({ allTraffic }) => [allTraffic],
allowOut: ['1.1.1.1', '8.8.8.8'],
},
},
})
sandboxTest.skipIf(isDebug)(
'allow takes precedence over deny',
async ({ sandbox }) => {
// Test that 1.1.1.1 works (explicitly allowed)
const result1 = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
)
assert.equal(result1.exitCode, 0)
assert.equal(result1.stdout.trim(), '301')
// Test that 8.8.8.8 also works (explicitly allowed, takes precedence over denyOut)
const result2 = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8"
)
assert.equal(result2.exitCode, 0)
assert.equal(result2.stdout.trim(), '302')
}
)
})
describe('allowPublicTraffic=false', () => {
sandboxTest.override({
sandboxOpts: {
network: {
allowPublicTraffic: false,
},
},
})
sandboxTest.skipIf(isDebug)(
'sandbox requires traffic access token',
async ({ sandbox }) => {
// Verify the sandbox was created successfully and has a traffic access token
assert(sandbox.trafficAccessToken)
// Start a simple HTTP server in the sandbox
const port = 8080
sandbox.commands.run(corsHttpServerCmd(port), {
background: true,
})
// Get the public URL for the sandbox
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Test 1: Request without traffic access token should fail with 403
await waitForHttpStatus(sandboxUrl, 403)
// Test 2: Request with valid traffic access token should succeed
await waitForHttpStatus(sandboxUrl, 200, {
init: {
headers: {
'e2b-traffic-access-token': sandbox.trafficAccessToken,
},
},
})
},
60_000
)
})
describe('allowPublicTraffic=true', () => {
sandboxTest.override({
sandboxOpts: {
network: {
allowPublicTraffic: true,
},
},
})
sandboxTest.skipIf(isDebug)(
'sandbox works without token',
async ({ sandbox }) => {
// Start a simple HTTP server in the sandbox
const port = 8080
sandbox.commands.run(corsHttpServerCmd(port), {
background: true,
})
// Get the public URL for the sandbox
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Request without traffic access token should succeed (public access enabled)
await waitForHttpStatus(sandboxUrl, 200)
},
60_000
)
})
describe('firewall transform injects headers', () => {
const injectedHeader = 'X-Test-Token'
const injectedValue = 'e2b-transform-value-123'
// Port the httpbin template's start command listens on.
const httpbinPort = 8080
sandboxTest.skipIf(isDebug)(
'injected header is reflected by the httpbin sidecar',
async ({ sandboxTestId }) => {
// The transform is applied by the egress proxy on the way out of the
// sandbox, so the target has to be reachable from the public internet —
// a CI service container would not be. A sidecar sandbox running the
// httpbin template is that target, which keeps the test off any
// externally hosted service. Its ready command has already passed by the
// time create resolves, so the server is serving.
const httpbin = await Sandbox.create(httpbinTemplate, {
metadata: { sandboxTestId },
network: { allowPublicTraffic: true },
})
let sandbox: Sandbox | undefined
try {
const httpbinHost = httpbin.getHost(httpbinPort)
sandbox = await Sandbox.create(template, {
metadata: { sandboxTestId },
network: {
rules: {
[httpbinHost]: [
{
transform: {
headers: {
[injectedHeader]: injectedValue,
},
},
},
],
},
},
})
const result = await sandbox.commands.run(
`curl -sS --retry 5 --retry-connrefused --max-time 10 https://${httpbinHost}/headers`
)
assert.equal(result.exitCode, 0)
const parsed = JSON.parse(result.stdout) as {
headers: Record<string, string[]>
}
const reflected = parsed.headers[injectedHeader]
assert.deepEqual(
reflected,
[injectedValue],
`expected httpbin to reflect ${injectedHeader}=${injectedValue}, got headers: ${JSON.stringify(parsed.headers)}`
)
} finally {
await Promise.allSettled([sandbox?.kill(), httpbin.kill()])
}
}
)
})
describe('updateNetwork applies new egress rules', () => {
sandboxTest.skipIf(isDebug)(
'denies a previously reachable IP after update',
async ({ sandbox }) => {
// Baseline: 8.8.8.8 is reachable.
const before = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8"
)
assert.equal(before.exitCode, 0)
await sandbox.updateNetwork({ denyOut: ['8.8.8.8'] })
// 8.8.8.8 should now be denied.
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8'
)
).rejects.toBeInstanceOf(CommandExitError)
// Other destinations stay reachable.
const after = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
)
assert.equal(after.exitCode, 0)
}
)
})
describe('updateNetwork clears existing rules when fields are omitted', () => {
sandboxTest.override({
sandboxOpts: {
network: {
denyOut: ({ allTraffic }) => [allTraffic],
allowOut: ['1.1.1.1'],
},
},
})
sandboxTest.skipIf(isDebug)(
'omitting fields replaces all egress rules',
async ({ sandbox }) => {
// Baseline from create-time config: 8.8.8.8 denied.
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8'
)
).rejects.toBeInstanceOf(CommandExitError)
// Empty update clears allow_out / deny_out entirely.
await sandbox.updateNetwork({})
const r1 = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
)
assert.equal(r1.exitCode, 0)
const r2 = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8"
)
assert.equal(r2.exitCode, 0)
}
)
})
// Sends one DNS query for example.com to `server` over UDP. Fails if no reply comes back.
const dnsProbeCmd = (server: string) => `python3 -c "
import socket
q = bytes.fromhex('abcd01000001000000000000076578616d706c6503636f6d0000010001')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(3)
s.sendto(q, ('${server}', 53))
s.recv(512)
"`
// These tests need an API that supports dnsServers. Call this on a sandbox
// created with dnsServers set: if getInfo doesn't report them back, skip.
async function skipUnlessDnsServersSupported(
sandbox: Sandbox,
skip: () => void
) {
const info = await sandbox.getInfo()
if (info.network?.dnsServers === undefined) skip()
}
describe('dnsServers: [] allows no DNS server for a domain allowlist', () => {
sandboxTest.override({
sandboxOpts: {
network: {
allowOut: ['example.com'],
denyOut: ({ allTraffic }) => [allTraffic],
dnsServers: [],
},
},
})
sandboxTest.skipIf(isDebug)(
'blocks 8.8.8.8 and keeps the allowed domain reachable',
async ({ sandbox, skip }) => {
await skipUnlessDnsServersSupported(sandbox, skip)
await expect(
sandbox.commands.run(dnsProbeCmd('8.8.8.8'))
).rejects.toBeInstanceOf(CommandExitError)
await expect(
sandbox.commands.run(
'curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8'
)
).rejects.toBeInstanceOf(CommandExitError)
// Allowed domains are matched by name, not by IP, so any public IP in
// /etc/hosts works.
await sandbox.commands.run("echo '1.1.1.1 example.com' >> /etc/hosts", {
user: 'root',
})
const result = await sandbox.commands.run(
"curl -s -o /dev/null -w '%{http_code}' https://example.com"
)
assert.equal(result.stdout.trim(), '200')
const info = await sandbox.getInfo()
assert.deepEqual(info.network?.dnsServers, [])
},
60_000
)
})
describe('dnsServers allows the listed servers instead of 8.8.8.8', () => {
sandboxTest.override({
sandboxOpts: {
network: {
allowOut: ['example.com'],
denyOut: ({ allTraffic }) => [allTraffic],
dnsServers: ['1.1.1.1'],
},
},
})
sandboxTest.skipIf(isDebug)(
'reaches 1.1.1.1 and blocks 8.8.8.8',
async ({ sandbox, skip }) => {
await skipUnlessDnsServersSupported(sandbox, skip)
const result = await sandbox.commands.run(dnsProbeCmd('1.1.1.1'))
assert.equal(result.exitCode, 0)
await expect(
sandbox.commands.run(dnsProbeCmd('8.8.8.8'))
).rejects.toBeInstanceOf(CommandExitError)
const info = await sandbox.getInfo()
assert.deepEqual(info.network?.dnsServers, ['1.1.1.1'])
},
60_000
)
})
describe('updateNetwork resets dnsServers when omitted', () => {
sandboxTest.override({
sandboxOpts: {
network: {
allowOut: ['example.com'],
denyOut: ({ allTraffic }) => [allTraffic],
dnsServers: [],
},
},
})
sandboxTest.skipIf(isDebug)(
'goes back to 8.8.8.8 when the field is left out',
async ({ sandbox, skip }) => {
await skipUnlessDnsServersSupported(sandbox, skip)
const network = {
allowOut: ['example.com'],
denyOut: ['0.0.0.0/0'],
}
// Left out, so it goes back to the default (8.8.8.8).
await sandbox.updateNetwork(network)
const reset = await sandbox.commands.run(dnsProbeCmd('8.8.8.8'))
assert.equal(reset.exitCode, 0)
const info = await sandbox.getInfo()
assert.isUndefined(info.network?.dnsServers)
await sandbox.updateNetwork({ ...network, dnsServers: [] })
await expect(
sandbox.commands.run(dnsProbeCmd('8.8.8.8'))
).rejects.toBeInstanceOf(CommandExitError)
await sandbox.updateNetwork({ ...network, dnsServers: ['8.8.8.8'] })
const reopened = await sandbox.commands.run(dnsProbeCmd('8.8.8.8'))
assert.equal(reopened.exitCode, 0)
},
60_000
)
})
describe('a domain allowlist allows 8.8.8.8 by default', () => {
sandboxTest.override({
sandboxOpts: {
network: {
allowOut: ['example.com'],
denyOut: ({ allTraffic }) => [allTraffic],
},
},
})
sandboxTest.skipIf(isDebug)(
'resolves names through 8.8.8.8',
async ({ sandbox }) => {
const result = await sandbox.commands.run(dnsProbeCmd('8.8.8.8'))
assert.equal(result.exitCode, 0)
const info = await sandbox.getInfo()
assert.isUndefined(info.network?.dnsServers)
}
)
})
describe('httpsPorts option', () => {
const port = 8443
sandboxTest.scoped({
sandboxOpts: {
network: {
httpsPorts: [port],
},
},
})
sandboxTest.skipIf(isDebug)(
'public URL proxies to an HTTPS backend in the sandbox',
async ({ sandbox }) => {
// Generate a self-signed certificate inside the sandbox
const keygen = await sandbox.commands.run(
'openssl req -x509 -newkey rsa:2048 -keyout /tmp/https-backend-key.pem -out /tmp/https-backend-cert.pem -days 1 -nodes -subj "/CN=localhost"'
)
assert.equal(keygen.exitCode, 0)
// Start an HTTPS server on the configured port
sandbox.commands.run(
`python3 -c "
import http.server, ssl
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
# Opt into cross-origin reads so the browser leg can read the body
# (see corsHttpServerCmd in tests/setup.ts).
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(b'https backend')
def log_message(self, *a): pass
server = http.server.ThreadingHTTPServer(('0.0.0.0', ${port}), H)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/tmp/https-backend-cert.pem', '/tmp/https-backend-key.pem')
server.socket = context.wrap_socket(server.socket, server_side=True)
server.serve_forever()
"`,
{ background: true }
)
// Poll the public URL until the server responds
const sandboxUrl = `https://${sandbox.getHost(port)}`
const body = await waitForHttpStatus(sandboxUrl, 200)
assert.equal(body, 'https backend')
// The port is reported back in the sandbox info
const info = await sandbox.getInfo()
assert.deepEqual(info.network?.httpsPorts, [port])
}
)
})
describe('maskRequestHost option', () => {
sandboxTest.override({
sandboxOpts: {
network: {
maskRequestHost: 'custom-host.example.com:${PORT}',
},
},
})
sandboxTest.skipIf(isDebug)(
'verify maskRequestHost modifies Host header correctly',
async ({ sandbox }) => {
const port = 8080
const outputFile = '/tmp/headers.txt'
// Start a Python HTTP server that captures request headers and writes them to a file
await sandbox.commands.run(
`python3 -c "
import http.server
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
with open('${outputFile}', 'w') as f:
for k, v in self.headers.items():
f.write(k + ': ' + v + chr(10))
self.send_response(200)
# Opt into cross-origin reads so the browser leg can see the status
# (see corsHttpServerCmd in tests/setup.ts).
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
def log_message(self, *a): pass
http.server.HTTPServer(('', ${port}), H).handle_request()
"`,
{ background: true }
)
// Get the public URL for the sandbox
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Make a request from OUTSIDE the sandbox through the proxy
// The Host header should be modified according to maskRequestHost
await waitForHttpStatus(sandboxUrl, 200)
// Read the captured headers from inside the sandbox
const headers = await sandbox.files.read(outputFile)
// Verify the Host header was modified according to maskRequestHost
assert.include(headers, 'Host:')
assert.include(headers, 'custom-host.example.com')
assert.include(headers, `${port}`)
},
60_000
)
})