Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(sdk): add httpsPorts network config for HTTPS sandbox backends (#1546)

Mish Ushakov08efa36132f0
diff --git a/.changeset/https-backend-ports.md b/.changeset/https-backend-ports.md
new file mode 100644
index 000000000..f7c9a45ae
--- /dev/null
+++ b/.changeset/https-backend-ports.md
@@ -0,0 +1,6 @@
+---
+"e2b": minor
+"@e2b/python-sdk": minor
+---
+
+Add `httpsPorts` (JS) / `https_ports` (Python) to the sandbox network config. Ports listed there have their public URLs proxied to the sandbox over HTTPS — use it when the service listening on the port serves TLS itself. This is not TLS passthrough: traffic is still terminated at the E2B proxy and re-encrypted on the hop to the sandbox, and the backend certificate is not verified, so self-signed certificates work. The configured ports are also returned in the sandbox info network config.
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index e2f822793..2dd9c392d 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -315,6 +315,21 @@ export type SandboxNetworkOpts = {
* @default ${PORT}-sandboxid.e2b.app
*/
maskRequestHost?: string
+
+ /**
+ * Ports whose public URLs should connect to the sandbox using HTTPS.
+ *
+ * Use this when the service listening on the port serves HTTPS (TLS)
+ * itself. This is not TLS passthrough — traffic is still terminated at the
+ * E2B proxy and re-encrypted on the hop to the sandbox. The backend
+ * certificate is not verified, so self-signed certificates work.
+ *
+ * @example
+ * ```ts
+ * await Sandbox.create({ network: { httpsPorts: [3000] } })
+ * ```
+ */
+ httpsPorts?: number[]
}
/**
@@ -334,6 +349,7 @@ export type SandboxNetworkInfo = {
egressProxy?: SandboxEgressProxyInfo
allowPublicTraffic?: boolean
maskRequestHost?: string
+ httpsPorts?: number[]
}
/**
@@ -1145,6 +1161,9 @@ function buildNetworkBody(
...(network.maskRequestHost !== undefined
? { maskRequestHost: network.maskRequestHost }
: {}),
+ ...(network.httpsPorts !== undefined
+ ? { httpsPorts: network.httpsPorts }
+ : {}),
}
}
@@ -1307,6 +1326,7 @@ export class SandboxApi extends ClientFactory {
egressProxy: fromApiEgressProxy(res.data.network.egressProxy),
allowPublicTraffic: res.data.network.allowPublicTraffic,
maskRequestHost: res.data.network.maskRequestHost,
+ httpsPorts: res.data.network.httpsPorts,
}
: undefined,
lifecycle: res.data.lifecycle
diff --git a/packages/js-sdk/tests/sandbox/host.test.ts b/packages/js-sdk/tests/sandbox/host.test.ts
index 37e45f68c..c21c06e79 100644
--- a/packages/js-sdk/tests/sandbox/host.test.ts
+++ b/packages/js-sdk/tests/sandbox/host.test.ts
@@ -1,6 +1,6 @@
import { assert } from 'vitest'
-import { isDebug, sandboxTest, wait } from '../setup.js'
+import { isDebug, sandboxTest, waitForHttpStatus } from '../setup.js'
import { catchCmdExitErrorInBackground } from '../cmdHelper.js'
sandboxTest(
'ping server in running sandbox',
@@ -12,21 +12,8 @@ sandboxTest(
const disable = catchCmdExitErrorInBackground(cmd)
try {
- await wait(1000)
-
const host = sandbox.getHost(8000)
-
- let res = await fetch(`${isDebug ? 'http' : 'https'}://${host}`)
-
- for (let i = 0; i < 20; i++) {
- if (res.status === 200) {
- break
- }
-
- res = await fetch(`${isDebug ? 'http' : 'https'}://${host}`)
- await wait(500)
- }
- assert.equal(res.status, 200)
+ await waitForHttpStatus(`${isDebug ? 'http' : 'https'}://${host}`, 200)
disable()
} finally {
try {
diff --git a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
index 3ad684502..bb371e1e7 100644
--- a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
+++ b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
@@ -1,7 +1,7 @@
import { assert, expect, test, vi } from 'vitest'
import { InvalidArgumentError, Sandbox } from '../../src'
-import { isDebug, sandboxTest, template } from '../setup.js'
+import { isDebug, sandboxTest, template, waitForHttpStatus } from '../setup.js'
async function waitForState(
sandbox: Sandbox,
@@ -18,20 +18,6 @@ async function waitForState(
)
}
-async function waitForStatus(url: string, status: number): Promise<void> {
- await vi.waitFor(
- async () => {
- const response = await fetch(url, {
- signal: AbortSignal.timeout(5_000),
- })
- const actualStatus = response.status
- await response.body?.cancel()
- assert.equal(actualStatus, status)
- },
- { timeout: 30_000, interval: 500 }
- )
-}
-
async function triggerAutoResume(url: string): Promise<void> {
try {
const response = await fetch(url, {
@@ -179,7 +165,7 @@ sandboxTest.skipIf(isDebug)(
const url = withRequestSource(`https://${sandbox.getHost(8000)}`)
await triggerAutoResume(url)
await waitForState(sandbox, 'running')
- await waitForStatus(url, 200)
+ await waitForHttpStatus(url, 200)
assert.isTrue(await sandbox.isRunning())
} catch (error) {
let state = 'unknown'
diff --git a/packages/js-sdk/tests/sandbox/network.test.ts b/packages/js-sdk/tests/sandbox/network.test.ts
index ef6359f42..c61ba7e58 100644
--- a/packages/js-sdk/tests/sandbox/network.test.ts
+++ b/packages/js-sdk/tests/sandbox/network.test.ts
@@ -1,28 +1,9 @@
-import { assert, expect, describe, vi } from 'vitest'
+import { assert, expect, describe } from 'vitest'
import { CommandExitError, Sandbox } from '../../src'
-import { sandboxTest, isDebug, template } from '../setup.js'
+import { sandboxTest, isDebug, template, waitForHttpStatus } from '../setup.js'
import { httpbinTemplate } from '../template.js'
-async function waitForStatus(
- url: string,
- status: number,
- init?: RequestInit
-): Promise<void> {
- await vi.waitFor(
- async () => {
- const response = await fetch(url, {
- ...init,
- signal: AbortSignal.timeout(5_000),
- })
- const actualStatus = response.status
- await response.body?.cancel()
- assert.equal(actualStatus, status)
- },
- { timeout: 20_000, interval: 500 }
- )
-}
-
describe('allow only 1.1.1.1', () => {
sandboxTest.override({
sandboxOpts: {
@@ -165,10 +146,10 @@ describe('allowPublicTraffic=false', () => {
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Test 1: Request without traffic access token should fail with 403
- await waitForStatus(sandboxUrl, 403)
+ await waitForHttpStatus(sandboxUrl, 403)
// Test 2: Request with valid traffic access token should succeed
- await waitForStatus(sandboxUrl, 200, {
+ await waitForHttpStatus(sandboxUrl, 200, {
headers: {
'e2b-traffic-access-token': sandbox.trafficAccessToken,
},
@@ -200,7 +181,7 @@ describe('allowPublicTraffic=true', () => {
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Request without traffic access token should succeed (public access enabled)
- await waitForStatus(sandboxUrl, 200)
+ await waitForHttpStatus(sandboxUrl, 200)
},
60_000
)
@@ -332,6 +313,57 @@ describe('updateNetwork clears existing rules when fields are omitted', () => {
)
})
+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)
+ 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: {
@@ -369,7 +401,7 @@ http.server.HTTPServer(('', ${port}), H).handle_request()
// Make a request from OUTSIDE the sandbox through the proxy
// The Host header should be modified according to maskRequestHost
- await waitForStatus(sandboxUrl, 200)
+ await waitForHttpStatus(sandboxUrl, 200)
// Read the captured headers from inside the sandbox
const headers = await sandbox.files.read(outputFile)
diff --git a/packages/js-sdk/tests/sandbox/snapshot.test.ts b/packages/js-sdk/tests/sandbox/snapshot.test.ts
index 1ae5d6b9d..3aada50ac 100644
--- a/packages/js-sdk/tests/sandbox/snapshot.test.ts
+++ b/packages/js-sdk/tests/sandbox/snapshot.test.ts
@@ -1,39 +1,6 @@
import { assert, describe } from 'vitest'
-import { sandboxTest, isDebug } from '../setup.js'
-
-async function waitForHttpStatus(
- url: string,
- expectedStatus: number,
- timeoutMs = 30_000
-) {
- const deadline = Date.now() + timeoutMs
- let lastStatus: number | undefined
-
- while (Date.now() < deadline) {
- const requestTimeoutMs = Math.min(5_000, deadline - Date.now())
- const controller = new AbortController()
- const requestTimeout = setTimeout(
- () => controller.abort(),
- requestTimeoutMs
- )
- try {
- const response = await fetch(url, { signal: controller.signal })
- lastStatus = response.status
- await response.body?.cancel()
- if (lastStatus === expectedStatus) return
- } catch {
- // The sandbox proxy may not have a route until the guest server is ready.
- } finally {
- clearTimeout(requestTimeout)
- }
- await new Promise((resolve) => setTimeout(resolve, 500))
- }
-
- assert.fail(
- `Timed out waiting for ${url} to return ${expectedStatus}; last status: ${lastStatus ?? 'request failed'}`
- )
-}
+import { sandboxTest, isDebug, waitForHttpStatus } from '../setup.js'
sandboxTest.skipIf(isDebug)(
'pause and resume a sandbox',
diff --git a/packages/js-sdk/tests/setup.ts b/packages/js-sdk/tests/setup.ts
index 91d427c3c..e088f3712 100644
--- a/packages/js-sdk/tests/setup.ts
+++ b/packages/js-sdk/tests/setup.ts
@@ -158,6 +158,50 @@ export async function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
+/**
+ * Poll `url` until it returns `expectedStatus`, tolerating connection errors —
+ * the sandbox proxy may not have a route until the guest server is ready.
+ * Returns the body text of the matching response.
+ */
+export async function waitForHttpStatus(
+ url: string,
+ expectedStatus: number,
+ init?: RequestInit,
+ timeoutMs = 30_000
+): Promise<string> {
+ const deadline = Date.now() + timeoutMs
+ let lastStatus: number | undefined
+
+ while (Date.now() < deadline) {
+ const requestTimeoutMs = Math.min(5_000, deadline - Date.now())
+ const controller = new AbortController()
+ const requestTimeout = setTimeout(
+ () => controller.abort(),
+ requestTimeoutMs
+ )
+ try {
+ const response = await fetch(url, {
+ ...init,
+ signal: controller.signal,
+ })
+ lastStatus = response.status
+ if (lastStatus === expectedStatus) {
+ return await response.text()
+ }
+ await response.body?.cancel()
+ } catch {
+ // The sandbox proxy may not have a route until the guest server is ready.
+ } finally {
+ clearTimeout(requestTimeout)
+ }
+ await wait(500)
+ }
+
+ throw new Error(
+ `Timed out waiting for ${url} to return ${expectedStatus}; last status: ${lastStatus ?? 'request failed'}`
+ )
+}
+
/**
* Returns the API URL for the given path, using E2B_DOMAIN env var.
* Supports msw path parameters like :templateID
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index d8e14ca39..cce1d4851 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -384,6 +384,18 @@ class SandboxNetworkOpts(TypedDict):
- Custom subdomain: `"${PORT}-myapp.example.com"`
"""
+ https_ports: NotRequired[List[int]]
+ """
+ Ports whose public URLs should connect to the sandbox using HTTPS.
+
+ Use this when the service listening on the port serves HTTPS (TLS) itself.
+ This is not TLS passthrough — traffic is still terminated at the E2B proxy
+ and re-encrypted on the hop to the sandbox. The backend certificate is not
+ verified, so self-signed certificates work.
+
+ Example: ``Sandbox.create(network={"https_ports": [3000]})``
+ """
+
class SandboxNetworkUpdate(TypedDict, total=False):
"""
@@ -478,6 +490,7 @@ class SandboxNetworkInfo(TypedDict, total=False):
"""
allow_public_traffic: bool
mask_request_host: str
+ https_ports: List[int]
class SandboxOnTimeoutPause(TypedDict):
@@ -777,6 +790,8 @@ def build_network_config(
body["allow_public_traffic"] = network["allow_public_traffic"]
if "mask_request_host" in network:
body["mask_request_host"] = network["mask_request_host"]
+ if network.get("https_ports") is not None:
+ body["https_ports"] = list(network["https_ports"])
return body
@@ -984,6 +999,8 @@ def from_client_network_config(
result["allow_public_traffic"] = network.allow_public_traffic
if not isinstance(network.mask_request_host, Unset):
result["mask_request_host"] = network.mask_request_host
+ if not isinstance(network.https_ports, Unset):
+ result["https_ports"] = list(network.https_ports)
return result
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_network.py b/packages/python-sdk/tests/async/sandbox_async/test_network.py
index d99e3c2a3..671b8b3c7 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_network.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_network.py
@@ -296,6 +296,54 @@ async def test_update_network_clears_existing_rules(async_sandbox_factory):
assert r2.exit_code == 0
+async def test_https_ports(async_sandbox_factory):
+ """Test that a port listed in https_ports proxies to an HTTPS backend."""
+ port = 8443
+ async_sandbox = await async_sandbox_factory(
+ network=SandboxNetworkOpts(https_ports=[port])
+ )
+
+ # Generate a self-signed certificate inside the sandbox
+ keygen = await async_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 keygen.exit_code == 0
+
+ # Start an HTTPS server on the configured port
+ await async_sandbox.commands.run(
+ f"""python3 -c "
+import http.server, ssl
+class H(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ 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,
+ )
+
+ sandbox_url = f"https://{async_sandbox.get_host(port)}"
+
+ async with httpx.AsyncClient() as client:
+ response = await wait_for_status(client, sandbox_url, 200)
+ assert response.status_code == 200
+ assert response.text == "https backend"
+
+ # The port is reported back in the sandbox info
+ info = await async_sandbox.get_info()
+ assert info.network is not None
+ assert info.network.get("https_ports") == [port]
+
+
@pytest.mark.skip_debug()
async def test_mask_request_host(async_sandbox_factory):
"""Test that mask_request_host modifies the Host header correctly."""
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_network.py b/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
index 60b0cf5c0..141ed420a 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
@@ -289,6 +289,52 @@ def test_update_network_clears_existing_rules(sandbox_factory):
assert r2.exit_code == 0
+def test_https_ports(sandbox_factory):
+ """Test that a port listed in https_ports proxies to an HTTPS backend."""
+ port = 8443
+ sandbox = sandbox_factory(network=SandboxNetworkOpts(https_ports=[port]))
+
+ # Generate a self-signed certificate inside the sandbox
+ keygen = 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 keygen.exit_code == 0
+
+ # Start an HTTPS server on the configured port
+ sandbox.commands.run(
+ f"""python3 -c "
+import http.server, ssl
+class H(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ 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,
+ )
+
+ sandbox_url = f"https://{sandbox.get_host(port)}"
+
+ with httpx.Client() as client:
+ response = wait_for_status(client, sandbox_url, 200)
+ assert response.status_code == 200
+ assert response.text == "https backend"
+
+ # The port is reported back in the sandbox info
+ info = sandbox.get_info()
+ assert info.network is not None
+ assert info.network.get("https_ports") == [port]
+
+
@pytest.mark.skip_debug()
def test_mask_request_host(sandbox_factory):
"""Test that mask_request_host modifies the Host header correctly."""