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 API-only header options (#1395)

Tomas Valenta073661a8b572
diff --git a/.changeset/js-sdk-envd-rpc-headers.md b/.changeset/js-sdk-envd-rpc-headers.md
new file mode 100644
index 000000000..514a597e3
--- /dev/null
+++ b/.changeset/js-sdk-envd-rpc-headers.md
@@ -0,0 +1,6 @@
+---
+"e2b": minor
+"@e2b/python-sdk": minor
+---
+
+Add API-only custom header options for the JavaScript and Python SDKs.
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index a1004b5c1..ef034fb3b 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -64,9 +64,16 @@ export interface ConnectionOpts {
/**
* Additional headers to send with the request.
+ *
+ * @deprecated Use `apiHeaders` instead.
*/
headers?: Record<string, string>
+ /**
+ * Additional headers to send with E2B API requests.
+ */
+ apiHeaders?: Record<string, string>
+
/**
* An optional `AbortSignal` that can be used to cancel the in-flight request.
* When the signal is aborted, the underlying `fetch` is aborted and the
@@ -193,7 +200,7 @@ export class ConnectionConfig {
this.accessToken = opts?.accessToken || ConnectionConfig.accessToken
this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
this.logger = opts?.logger
- this.headers = opts?.headers || {}
+ this.headers = { ...(opts?.headers ?? {}), ...(opts?.apiHeaders ?? {}) }
this.headers['User-Agent'] = `e2b-js-sdk/${version}`
this.apiUrl =
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 92d4c2457..918234176 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -172,7 +172,9 @@ export class Sandbox extends SandboxApi {
// connect-web package uses redirect: "error" which is not supported in edge runtimes
// E2B endpoints should be safe to use with redirect: "follow" https://github.com/e2b-dev/E2B/issues/531#issuecomment-2779492867
- const headers = new Headers(this.connectionConfig.headers)
+ const headers = new Headers({
+ 'User-Agent': this.connectionConfig.headers?.['User-Agent'] ?? '',
+ })
new Headers(options?.headers).forEach((value, key) =>
headers.append(key, value)
)
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 5141e56c8..d2003e36f 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -231,7 +231,13 @@ export interface SandboxApiOpts
extends Partial<
Pick<
ConnectionOpts,
- 'apiKey' | 'headers' | 'debug' | 'domain' | 'requestTimeoutMs' | 'signal'
+ | 'apiKey'
+ | 'headers'
+ | 'apiHeaders'
+ | 'debug'
+ | 'domain'
+ | 'requestTimeoutMs'
+ | 'signal'
>
> {}
diff --git a/packages/js-sdk/tests/sandbox/configPropagation.test.ts b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
index 5e3d719fe..eef1314bb 100644
--- a/packages/js-sdk/tests/sandbox/configPropagation.test.ts
+++ b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
@@ -11,7 +11,7 @@ const baseConfig = {
domain: 'base.e2b.dev',
requestTimeoutMs: 1111,
debug: false,
- headers: { 'X-Test': 'base' },
+ apiHeaders: { 'X-Test': 'base' },
}
function createSandbox() {
@@ -50,7 +50,15 @@ describe('Sandbox API config propagation', () => {
assert.equal(opts?.domain, baseConfig.domain)
assert.equal(opts?.requestTimeoutMs, baseConfig.requestTimeoutMs)
assert.equal(opts?.debug, baseConfig.debug)
- assert.equal(opts?.headers?.['X-Test'], baseConfig.headers['X-Test'])
+ assert.equal(opts?.headers?.['X-Test'], baseConfig.apiHeaders['X-Test'])
+ })
+
+ test('accepts apiHeaders in static Sandbox API options', () => {
+ const opts = { apiHeaders: baseConfig.apiHeaders } satisfies Parameters<
+ typeof Sandbox.kill
+ >[1]
+
+ assert.equal(opts.apiHeaders['X-Test'], baseConfig.apiHeaders['X-Test'])
})
test('lets public method call overrides win over connectionConfig', async () => {
diff --git a/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts b/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts
new file mode 100644
index 000000000..3c7e205d7
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts
@@ -0,0 +1,47 @@
+import { assert, test, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ rpcFetch: vi.fn(async () => new Response(null, { status: 204 })),
+ transportFetch: undefined as typeof fetch | undefined,
+}))
+
+vi.mock('@connectrpc/connect-web', () => ({
+ createConnectTransport: vi.fn((opts: { fetch: typeof fetch }) => {
+ mocks.transportFetch = opts.fetch
+ return {}
+ }),
+}))
+
+vi.mock('../../src/envd/http2', () => ({
+ createEnvdFetch: vi.fn(() => vi.fn()),
+ createEnvdRpcFetch: vi.fn(() => mocks.rpcFetch),
+}))
+
+test('does not pass custom connection headers to envd RPC requests', async () => {
+ const { Sandbox } = await import('../../src')
+ const sandbox = new Sandbox({
+ sandboxId: 'sbx-test',
+ sandboxDomain: 'sandbox.e2b.dev',
+ envdVersion: '0.2.4',
+ envdAccessToken: 'tok',
+ headers: {
+ Authorization: 'Bearer user-token',
+ 'X-Custom': 'secret',
+ },
+ })
+
+ assert.equal(sandbox.sandboxId, 'sbx-test')
+ assert.ok(mocks.transportFetch)
+ await mocks.transportFetch('https://sandbox.e2b.dev/rpc', {
+ headers: { 'Connect-Protocol-Version': '1' },
+ })
+
+ const headers = new Headers(mocks.rpcFetch.mock.calls[0][1]?.headers)
+
+ assert.equal(headers.get('Authorization'), null)
+ assert.equal(headers.get('X-Custom'), null)
+ assert.equal(headers.get('User-Agent')?.startsWith('e2b-js-sdk/'), true)
+ assert.equal(headers.get('E2b-Sandbox-Id'), 'sbx-test')
+ assert.equal(headers.get('X-Access-Token'), 'tok')
+ assert.equal(headers.get('Connect-Protocol-Version'), '1')
+})
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index 1b914093b..e24cedad2 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -25,7 +25,10 @@ class ApiParams(TypedDict, total=False):
"""Timeout for the request in **seconds**, defaults to 60 seconds."""
headers: Optional[Dict[str, str]]
- """Additional headers to send with the request."""
+ """Additional headers to send with the request. Deprecated, use api_headers instead."""
+
+ api_headers: Optional[Dict[str, str]]
+ """Additional headers to send with E2B API requests."""
api_key: Optional[str]
"""E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable."""
@@ -87,6 +90,7 @@ class ConnectionConfig:
access_token: Optional[str] = None,
request_timeout: Optional[float] = None,
headers: Optional[Dict[str, str]] = None,
+ api_headers: Optional[Dict[str, str]] = None,
extra_sandbox_headers: Optional[Dict[str, str]] = None,
proxy: Optional[ProxyTypes] = None,
):
@@ -94,7 +98,7 @@ class ConnectionConfig:
self.debug = debug or ConnectionConfig._debug()
self.api_key = api_key or ConnectionConfig._api_key()
self.access_token = access_token or ConnectionConfig._access_token()
- self.headers = headers or {}
+ self.headers = {**(headers or {}), **(api_headers or {})}
self.headers["User-Agent"] = f"e2b-python-sdk/{package_version}"
self.__extra_sandbox_headers = extra_sandbox_headers or {}
@@ -184,6 +188,7 @@ class ConnectionConfig:
:return: Dictionary of parameters for the API call
"""
headers = opts.get("headers")
+ api_headers = opts.get("api_headers")
request_timeout = opts.get("request_timeout")
api_key = opts.get("api_key")
api_url = opts.get("api_url")
@@ -194,6 +199,8 @@ class ConnectionConfig:
req_headers = self.headers.copy()
if headers is not None:
req_headers.update(headers)
+ if api_headers is not None:
+ req_headers.update(api_headers)
return dict(
ApiParams(
@@ -213,7 +220,7 @@ class ConnectionConfig:
We need this separate as we use the same header for E2B access token to API and envd access token to sandbox.
"""
return {
- **self.headers,
+ "User-Agent": self.headers["User-Agent"],
**self.__extra_sandbox_headers,
}
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
index 2f2f60ed3..c69f9f611 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
@@ -44,7 +44,7 @@ def create_sandbox(monkeypatch, api_key: str) -> AsyncSandbox:
domain=BASE_DOMAIN,
request_timeout=BASE_REQUEST_TIMEOUT,
debug=BASE_DEBUG,
- headers=BASE_HEADERS,
+ api_headers=BASE_HEADERS,
),
)
@@ -77,7 +77,7 @@ async def test_pause_applies_overrides(monkeypatch, test_api_key):
await sandbox.pause(
domain="override.e2b.dev",
request_timeout=20,
- headers={"X-Extra": "1"},
+ api_headers={"X-Extra": "1"},
)
mock_pause.assert_awaited_once()
@@ -103,9 +103,12 @@ async def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_ke
)
monkeypatch.setattr(sandbox_async_main.SandboxApi, "_cls_connect", mock_connect)
- sandbox = await AsyncSandbox.connect("sbx-test", api_key=test_api_key)
+ sandbox = await AsyncSandbox.connect(
+ "sbx-test", api_key=test_api_key, headers=BASE_HEADERS
+ )
assert sandbox.envd_api_url == "https://sandbox.e2b.app"
+ assert "X-Test" not in sandbox.connection_config.sandbox_headers
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Id"] == "sbx-test"
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Port"] == str(
ConnectionConfig.envd_port
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
index f458024f5..b78c282d8 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
@@ -42,7 +42,7 @@ def create_sandbox(monkeypatch, api_key: str) -> Sandbox:
domain=BASE_DOMAIN,
request_timeout=BASE_REQUEST_TIMEOUT,
debug=BASE_DEBUG,
- headers=BASE_HEADERS,
+ api_headers=BASE_HEADERS,
),
)
@@ -73,7 +73,7 @@ def test_pause_applies_overrides(monkeypatch, test_api_key):
sandbox.pause(
domain="override.e2b.dev",
request_timeout=20,
- headers={"X-Extra": "1"},
+ api_headers={"X-Extra": "1"},
)
mock_pause.assert_called_once()
@@ -99,9 +99,10 @@ def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_key):
)
monkeypatch.setattr(sandbox_sync_main.SandboxApi, "_cls_connect", mock_connect)
- sandbox = Sandbox.connect("sbx-test", api_key=test_api_key)
+ sandbox = Sandbox.connect("sbx-test", api_key=test_api_key, headers=BASE_HEADERS)
assert sandbox.envd_api_url == "https://sandbox.e2b.app"
+ assert "X-Test" not in sandbox.connection_config.sandbox_headers
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Id"] == "sbx-test"
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Port"] == str(
ConnectionConfig.envd_port