Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(sdk): route sandbox egress through your own SOCKS5 proxy (BYOP) (#1688)
cursor[bot]6824cdf31343
diff --git a/.changeset/sandbox-egress-proxy.md b/.changeset/sandbox-egress-proxy.mdnew file mode 100644index 000000000..8d506b874--- /dev/null+++ b/.changeset/sandbox-egress-proxy.md@@ -0,0 +1,98 @@+---+'e2b': minor+'@e2b/python-sdk': minor+---++Add `network.egressProxy` / `network["egress_proxy"]` for routing a sandbox's outbound TCP through a SOCKS5 proxy you operate ("bring your own proxy"). Tunneling happens on the host after the `allowOut` / `denyOut` lists are evaluated, so nothing runs inside the sandbox and code running there can neither see the proxy nor route around it. UDP-based traffic — DNS and QUIC/HTTP3 — is not tunneled.++```ts+import { Sandbox } from 'e2b'++const sandbox = await Sandbox.create({+ network: {+ egressProxy: {+ address: 'proxy.example.com:1080',+ username: 'proxy-user',+ password: 'proxy-password',+ },+ },+})+```++```python+from e2b import Sandbox++sandbox = Sandbox.create(+ network={+ "egress_proxy": {+ "address": "proxy.example.com:1080",+ "username": "proxy-user",+ "password": "proxy-password",+ },+ },+)+```++It combines with the rest of the network configuration — here everything except `api.example.com` is denied, and the traffic that is allowed goes through your proxy:++```ts+await Sandbox.create({+ network: {+ allowOut: ['api.example.com'],+ denyOut: ({ allTraffic }) => [allTraffic],+ egressProxy: { address: 'proxy.example.com:1080' },+ },+})+```++```python+Sandbox.create(+ network={+ "allow_out": ["api.example.com"],+ "deny_out": lambda ctx: [ctx.all_traffic],+ "egress_proxy": {"address": "proxy.example.com:1080"},+ },+)+```++`updateNetwork` / `update_network` sets or replaces the proxy on a sandbox that is already running, with no restart. The update replaces the whole configuration instead of merging into it, so an update that leaves the proxy out stops tunneling — repeat it in every update that should keep it.++```ts+// Start tunneling on the running sandbox+await sandbox.updateNetwork({+ allowOut: ['api.example.com'],+ denyOut: ({ allTraffic }) => [allTraffic],+ egressProxy: { address: 'proxy.example.com:1080' },+})++// Stop tunneling: an update without egressProxy clears it+await sandbox.updateNetwork({})+```++```python+# Start tunneling on the running sandbox+sandbox.update_network({+ "allow_out": ["api.example.com"],+ "deny_out": lambda ctx: [ctx.all_traffic],+ "egress_proxy": {"address": "proxy.example.com:1080"},+})++# Stop tunneling: an update without egress_proxy clears it+sandbox.update_network({})+```++`getInfo` / `get_info` reports the proxy the sandbox's egress is currently tunneled through. The password is never returned, so the returned `SandboxEgressProxyInfo` does not have the field at all:++```ts+const info = await sandbox.getInfo()+console.log(info.network?.egressProxy)+// { address: 'proxy.example.com:1080', username: 'proxy-user' }+```++```python+info = sandbox.get_info()+print(info.network["egress_proxy"])+# {'address': 'proxy.example.com:1080', 'username': 'proxy-user'}+```++Egress fails closed: when the proxy is unreachable or does not speak SOCKS5, outbound connections fail rather than falling back to a direct connection. The address is validated server-side when the sandbox is created — a rejected create leaves nothing behind. Available on E2B Cloud and in BYOC deployments; a sandbox that names a proxy on a deployment built from the open source `e2b-dev/infra` repository is rejected as unsupported.diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.tsindex af0145485..4ebca8c6c 100644--- a/packages/js-sdk/src/api/schema.gen.ts+++ b/packages/js-sdk/src/api/schema.gen.ts@@ -1935,6 +1935,13 @@ export interface components {/** @description Number of sandboxes successfully killed */killedCount: number;};+ /** @description Cached live sandbox index count keyed by team ID. Counts may briefly+ * include sandboxes transitioning out of running; teams without indexed+ * sandboxes are omitted.+ * */+ AdminTeamRunningSandboxCounts: {+ [key: string]: number;+ };AssignedTemplateTags: {/*** Format: uuid@@ -2276,8 +2283,6 @@ export interface components {version: string;};NodeDetail: {- /** @description List of cached builds id on the node */- cachedBuilds: string[];/** @description Identifier of the cluster */clusterID: string;/** @description Commit of the orchestrator */@@ -2463,6 +2468,15 @@ export interface components {templateID: string;volumeMounts?: components["schemas"]["SandboxVolumeMount"][];};+ /** @description SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use remote DNS (ATYP=domain). */+ SandboxEgressProxyConfig: {+ /** @description SOCKS5 proxy address in host:port format (e.g. "proxy.example.com:1080"). */+ address: string;+ /** @description Optional SOCKS5 password (RFC 1929), max 255 bytes. */+ password?: string;+ /** @description Optional SOCKS5 username (RFC 1929), max 255 bytes. */+ username?: string;+ } | null;SandboxesWithMetrics: {sandboxes: {[key: string]: components["schemas"]["SandboxMetric"];@@ -2605,6 +2619,7 @@ export interface components {allowPublicTraffic?: boolean;/** @description List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. */denyOut?: string[];+ egressProxy?: components["schemas"]["SandboxEgressProxyConfig"];/** @description Specify host mask which will be used for all sandbox requests */maskRequestHost?: string;/** @description Per-domain transform rules applied to matching egress HTTP/HTTPS requests. Keys are domains (e.g. "api.example.com", "example.com"). A domain listed here is not automatically allowed - use allowOut to permit the traffic.@@ -2633,6 +2648,7 @@ export interface components {allowOut?: string[];/** @description List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. */denyOut?: string[];+ egressProxy?: components["schemas"]["SandboxEgressProxyConfig"];/** @description Per-domain transform rules. Replaces all existing rules when provided. */rules?: {[key: string]: components["schemas"]["SandboxNetworkRule"][];diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.tsindex 606c0c281..b67c07c08 100644--- a/packages/js-sdk/src/index.ts+++ b/packages/js-sdk/src/index.ts@@ -65,6 +65,8 @@ export type {SandboxIamOpts,SandboxIamToken,SandboxIamTokenType,+ SandboxEgressProxyOpts,+ SandboxEgressProxyInfo,SandboxNetworkOpts,SandboxNetworkInfo,SandboxNetworkSelector,diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsindex 7d4f1ad51..270faddea 100644--- a/packages/js-sdk/src/sandbox/sandboxApi.ts+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -146,6 +146,72 @@ export type SandboxNetworkSelector =| string[]| ((ctx: SandboxNetworkSelectorContext) => string[])+/**+ * SOCKS5 proxy the sandbox's outbound TCP is tunneled through — "bring your+ * own proxy".+ *+ * Tunneling happens on the host, after+ * {@link SandboxNetworkOpts.allowOut}/{@link SandboxNetworkOpts.denyOut}+ * filtering, so nothing runs inside the sandbox and code running there can+ * neither see the proxy nor route around it. UDP-based traffic — DNS and+ * QUIC/HTTP3 — is not tunneled and leaves the sandbox the usual way.+ *+ * Egress fails closed: when the proxy is unreachable or does not speak SOCKS5,+ * outbound connections fail rather than falling back to a direct connection.+ *+ * @example+ * ```ts+ * const sandbox = await Sandbox.create({+ * network: {+ * egressProxy: {+ * address: 'proxy.example.com:1080',+ * username: 'proxy-user',+ * password: 'proxy-password',+ * },+ * },+ * })+ * ```+ */+export type SandboxEgressProxyOpts = {+ /**+ * SOCKS5 proxy address in `host:port` form, e.g.+ * `'proxy.example.com:1080'`. The host can be a hostname or an IP literal;+ * a hostname is re-resolved at dial time and the resolved address is pinned+ * for that connection, so a DNS change cannot redirect a connection that is+ * already being established.+ *+ * The proxy has to be reachable from E2B's infrastructure: an address that+ * does not resolve, or that resolves into a private or otherwise internal+ * range, is rejected before the sandbox exists.+ */+ address: string++ /**+ * SOCKS5 username+ * ([RFC 1929](https://datatracker.ietf.org/doc/html/rfc1929)), up to 255+ * bytes. Omit it for a proxy that takes no credentials.+ */+ username?: string++ /**+ * SOCKS5 password, up to 255 bytes. Only valid together with+ * {@link SandboxEgressProxyOpts.username}.+ */+ password?: string+}++/**+ * Egress proxy as returned by the sandbox info endpoint. Mirrors+ * {@link SandboxEgressProxyOpts} without `password` — the API never returns+ * it.+ */+export type SandboxEgressProxyInfo = {+ /** See {@link SandboxEgressProxyOpts.address}. */+ address: string+ /** See {@link SandboxEgressProxyOpts.username}. */+ username?: string+}+export type SandboxNetworkOpts = {/*** Allow outbound traffic from the sandbox to the specified addresses.@@ -211,6 +277,31 @@ export type SandboxNetworkOpts = {*/rules?: SandboxNetworkRules+ /**+ * Tunnel the sandbox's outbound TCP through a SOCKS5 proxy you operate.+ *+ * Filtering runs first, so a connection {@link denyOut} blocks never reaches+ * the proxy, and per-host {@link rules} transforms still apply before the+ * connection is dialed. Omit it to send the sandbox's traffic out directly.+ *+ * Available on E2B Cloud and in BYOC deployments; a sandbox that names a+ * proxy on a deployment built from the open source `e2b-dev/infra`+ * repository is rejected as unsupported.+ *+ * @example+ * ```ts+ * // Deny everything except api.example.com, and tunnel what is left+ * await Sandbox.create({+ * network: {+ * allowOut: ['api.example.com'],+ * denyOut: ({ allTraffic }) => [allTraffic],+ * egressProxy: { address: 'proxy.example.com:1080' },+ * },+ * })+ * ```+ */+ egressProxy?: SandboxEgressProxyOpts+/*** Specify if the sandbox URLs should be accessible only with authentication.* @default true@@ -234,6 +325,12 @@ export type SandboxNetworkInfo = {allowOut?: string[]denyOut?: string[]rules?: Record<string, SandboxNetworkRuleInfo[]>+ /**+ * Proxy the sandbox's egress is currently tunneled through, absent when it+ * goes out directly. See {@link SandboxEgressProxyInfo} for why the password+ * is missing.+ */+ egressProxy?: SandboxEgressProxyInfoallowPublicTraffic?: booleanmaskRequestHost?: string}@@ -255,6 +352,17 @@ export type SandboxNetworkUpdate = {* its placeholder and a typo only surfaces at the destination.*/rules?: SandboxNetworkRules+ /**+ * See {@link SandboxNetworkOpts.egressProxy}. Sets or replaces the proxy on a+ * sandbox that is already running, with no restart.+ *+ * The update replaces the whole configuration instead of merging into it, so+ * an update that leaves this out stops tunneling and sends the sandbox's+ * traffic out directly — even when the update was only meant to change the+ * allow and deny lists. Repeat it in every update that should keep+ * tunneling.+ */+ egressProxy?: SandboxEgressProxyOpts/*** Allow sandbox to access the internet. When set to `false`, it behaves the* same as specifying `denyOut: ['0.0.0.0/0']` in the network config.@@ -882,9 +990,30 @@ function resolveRulesForBody(return out}+/**+ * Rebuild the proxy config from the known fields so stray properties on the+ * caller's object never reach the wire and a later mutation of it cannot alter+ * the in-flight request. Validation is the server's — it is the only side that+ * can tell whether the address resolves, and to where.+ */+function buildEgressProxyBody(+ egressProxy: SandboxEgressProxyOpts+): components['schemas']['SandboxEgressProxyConfig'] {+ return {+ address: egressProxy.address,+ ...(egressProxy.username !== undefined+ ? { username: egressProxy.username }+ : {}),+ ...(egressProxy.password !== undefined+ ? { password: egressProxy.password }+ : {}),+ }+}+type NetworkEgressBody = {allowOut?: string[]denyOut?: string[]+ egressProxy?: components['schemas']['SandboxEgressProxyConfig']rules?: Record<string, { transform?: SandboxNetworkTransform }[]>}@@ -892,6 +1021,7 @@ function buildNetworkEgress(network: {allowOut?: SandboxNetworkSelectordenyOut?: SandboxNetworkSelector+ egressProxy?: SandboxEgressProxyOptsrules?: SandboxNetworkRules},transformContext: SandboxNetworkTransformContext@@ -906,12 +1036,38 @@ function buildNetworkEgress(return {...(allowOut !== undefined ? { allowOut } : {}),...(denyOut !== undefined ? { denyOut } : {}),+ // `!= null` also covers an explicit `egressProxy: null`, which untyped+ // callers spell "no proxy" as; Python checks `is not None` the same way+ // (not truthiness — an empty object must still reach the builder).+ ...(network.egressProxy != null+ ? { egressProxy: buildEgressProxyBody(network.egressProxy) }+ : {}),...(network.rules !== undefined? { rules: resolveRulesForBody(rules, transformContext) }: {}),}}+/**+ * Map the wire proxy config into the SDK-owned shape: `password` is dropped+ * because the API never returns it, and the wire's `null` for "no proxy" is+ * normalized so the union never reaches a consumer.+ */+function fromApiEgressProxy(+ egressProxy: components['schemas']['SandboxEgressProxyConfig'] | undefined+): SandboxEgressProxyInfo | undefined {+ if (!egressProxy) {+ return undefined+ }++ return {+ address: egressProxy.address,+ ...(egressProxy.username !== undefined+ ? { username: egressProxy.username }+ : {}),+ }+}+function buildNetworkBody(network: SandboxNetworkOpts | undefined,iam: components['schemas']['SandboxIam'] | undefined@@ -1086,6 +1242,7 @@ export class SandboxApi {allowOut: res.data.network.allowOut,denyOut: res.data.network.denyOut,rules: res.data.network.rules ?? undefined,+ egressProxy: fromApiEgressProxy(res.data.network.egressProxy),allowPublicTraffic: res.data.network.allowPublicTraffic,maskRequestHost: res.data.network.maskRequestHost,}diff --git a/packages/js-sdk/tests/sandbox/egressProxy.test.ts b/packages/js-sdk/tests/sandbox/egressProxy.test.tsnew file mode 100644index 000000000..b861fd2df--- /dev/null+++ b/packages/js-sdk/tests/sandbox/egressProxy.test.ts@@ -0,0 +1,217 @@+import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'+import { http, HttpResponse } from 'msw'+import { setupServer } from 'msw/node'++import { Sandbox } from '../../src'+import { TEST_API_KEY, apiUrl } from '../setup'++const sandboxId = 'test-sandbox-id'++let lastCreateBody: Record<string, any> | undefined+let lastUpdateBody: Record<string, any> | undefined+let sandboxNetwork: Record<string, any> | undefined++const server = setupServer(+ http.post(apiUrl('/sandboxes'), async ({ request }) => {+ lastCreateBody = (await request.json()) as Record<string, any>+ return HttpResponse.json({+ sandboxID: sandboxId,+ templateID: 'base',+ envdVersion: '0.2.4',+ })+ }),+ http.put(apiUrl(`/sandboxes/${sandboxId}/network`), async ({ request }) => {+ lastUpdateBody = (await request.json()) as Record<string, any>+ return new HttpResponse(null, { status: 204 })+ }),+ http.get(apiUrl(`/sandboxes/${sandboxId}`), () =>+ HttpResponse.json({+ sandboxID: sandboxId,+ templateID: 'base',+ clientID: 'test-client',+ envdVersion: '0.2.4',+ startedAt: '2026-01-01T00:00:00Z',+ endAt: '2026-01-01T01:00:00Z',+ state: 'running',+ cpuCount: 2,+ memoryMB: 512,+ diskSizeMB: 1024,+ network: sandboxNetwork,+ })+ )+)++beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))++afterAll(() => server.close())++afterEach(() => {+ lastCreateBody = undefined+ lastUpdateBody = undefined+ sandboxNetwork = undefined+ server.resetHandlers()+})++test('Sandbox.create sends the egress proxy in the request body', async () => {+ await Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ network: {+ egressProxy: {+ address: 'proxy.example.com:1080',+ username: 'proxy-user',+ password: 'proxy-password',+ },+ },+ })++ expect(lastCreateBody?.network).toEqual({+ egressProxy: {+ address: 'proxy.example.com:1080',+ username: 'proxy-user',+ password: 'proxy-password',+ },+ })+})++test('Sandbox.create sends an address-only egress proxy without credentials', async () => {+ await Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ network: { egressProxy: { address: 'proxy.example.com:1080' } },+ })++ expect(lastCreateBody?.network.egressProxy).toEqual({+ address: 'proxy.example.com:1080',+ })+})++test('Sandbox.create combines the egress proxy with allow and deny lists', async () => {+ await Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ network: {+ allowOut: ['api.example.com'],+ denyOut: ({ allTraffic }) => [allTraffic],+ egressProxy: { address: 'proxy.example.com:1080' },+ },+ })++ expect(lastCreateBody?.network).toEqual({+ allowOut: ['api.example.com'],+ denyOut: ['0.0.0.0/0'],+ egressProxy: { address: 'proxy.example.com:1080' },+ })+})++test('Sandbox.create omits the egress proxy when not provided', async () => {+ await Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ network: { allowOut: ['api.example.com'] },+ })++ expect(lastCreateBody?.network).toBeDefined()+ expect(lastCreateBody?.network).not.toHaveProperty('egressProxy')+})++test('Sandbox.create strips unknown egress proxy properties', async () => {+ await Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ network: {+ egressProxy: {+ address: 'proxy.example.com:1080',+ // An untyped caller can copy an extra key out of a config file; the+ // API rejects unknown properties.+ protocol: 'socks5',+ } as never,+ },+ })++ expect(lastCreateBody?.network.egressProxy).toEqual({+ address: 'proxy.example.com:1080',+ })+})++test('a later mutation of the caller object does not reach the wire', async () => {+ const egressProxy = { address: 'proxy.example.com:1080', username: 'before' }++ const create = Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ network: { egressProxy },+ })+ egressProxy.username = 'after'+ await create++ expect(lastCreateBody?.network.egressProxy.username).toEqual('before')+})++test('updateNetwork sets the egress proxy on a running sandbox', async () => {+ await Sandbox.updateNetwork(+ sandboxId,+ {+ allowOut: ['api.example.com'],+ denyOut: ({ allTraffic }) => [allTraffic],+ egressProxy: { address: 'proxy.example.com:1080' },+ },+ { apiKey: TEST_API_KEY }+ )++ expect(lastUpdateBody).toEqual({+ allowOut: ['api.example.com'],+ denyOut: ['0.0.0.0/0'],+ egressProxy: { address: 'proxy.example.com:1080' },+ })+})++test('an update without the egress proxy clears it', async () => {+ // The update replaces the whole configuration instead of merging into it, so+ // omitting the proxy stops tunneling rather than leaving it in place.+ await Sandbox.updateNetwork(sandboxId, {}, { apiKey: TEST_API_KEY })++ expect(lastUpdateBody).toEqual({})+})++test('getInfo reports the active egress proxy without the password', async () => {+ sandboxNetwork = {+ allowOut: ['api.example.com'],+ egressProxy: { address: 'proxy.example.com:1080', username: 'proxy-user' },+ }++ const info = await Sandbox.getInfo(sandboxId, { apiKey: TEST_API_KEY })++ expect(info.network?.egressProxy).toEqual({+ address: 'proxy.example.com:1080',+ username: 'proxy-user',+ })+})++test('getInfo drops a password the API unexpectedly returns', async () => {+ // SandboxEgressProxyInfo says the password is not there, so it must not be+ // there even if a future API version starts echoing it back.+ sandboxNetwork = {+ egressProxy: {+ address: 'proxy.example.com:1080',+ password: 'proxy-password',+ },+ }++ const info = await Sandbox.getInfo(sandboxId, { apiKey: TEST_API_KEY })++ expect(info.network?.egressProxy).toEqual({+ address: 'proxy.example.com:1080',+ })+})++test.for([+ ['omitted', {}],+ ['null', { egressProxy: null }],+])(+ 'getInfo reports no egress proxy when the API returns %s',+ async ([, network]: [string, Record<string, any>]) => {+ // The wire field is nullable; absence has to be `undefined` either way so+ // the null never reaches a consumer.+ sandboxNetwork = network++ const info = await Sandbox.getInfo(sandboxId, { apiKey: TEST_API_KEY })++ expect(info.network).toBeDefined()+ expect(info.network?.egressProxy).toBeUndefined()+ }+)diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex 11ae55d80..3a152f15f 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -75,6 +75,8 @@ from .sandbox.sandbox_api import (GitHubMcpServer,GitHubMcpServerConfig,McpServer,+ SandboxEgressProxyInfo,+ SandboxEgressProxyOpts,SandboxIamOpts,SandboxIamToken,SandboxIamTokenType,@@ -198,6 +200,8 @@ __all__ = ["WriteInfo","FileType",# Network+ "SandboxEgressProxyOpts",+ "SandboxEgressProxyInfo","SandboxNetworkOpts","SandboxNetworkInfo","SandboxNetworkSelector",diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.pyindex 997ffb895..5483749de 100644--- a/packages/python-sdk/e2b/api/client/models/__init__.py+++ b/packages/python-sdk/e2b/api/client/models/__init__.py@@ -2,6 +2,7 @@from .admin_build_cancel_result import AdminBuildCancelResultfrom .admin_sandbox_kill_result import AdminSandboxKillResult+from .admin_team_running_sandbox_counts import AdminTeamRunningSandboxCountsfrom .assign_template_tags_request import AssignTemplateTagsRequestfrom .assigned_template_tags import AssignedTemplateTagsfrom .aws_registry import AWSRegistry@@ -39,6 +40,7 @@ from .resumed_sandbox import ResumedSandboxfrom .sandbox import Sandboxfrom .sandbox_auto_resume_config import SandboxAutoResumeConfigfrom .sandbox_detail import SandboxDetail+from .sandbox_egress_proxy_config_type_0 import SandboxEgressProxyConfigType0from .sandbox_fork_request import SandboxForkRequestfrom .sandbox_fork_result import SandboxForkResultfrom .sandbox_iam import SandboxIam@@ -97,6 +99,7 @@ from .volume_token import VolumeToken__all__ = ("AdminBuildCancelResult","AdminSandboxKillResult",+ "AdminTeamRunningSandboxCounts","AssignedTemplateTags","AssignTemplateTagsRequest","AWSRegistry",@@ -134,6 +137,7 @@ __all__ = ("Sandbox","SandboxAutoResumeConfig","SandboxDetail",+ "SandboxEgressProxyConfigType0","SandboxesWithMetrics","SandboxForkRequest","SandboxForkResult",diff --git a/packages/python-sdk/e2b/api/client/models/admin_team_running_sandbox_counts.py b/packages/python-sdk/e2b/api/client/models/admin_team_running_sandbox_counts.pynew file mode 100644index 000000000..d40e33af2--- /dev/null+++ b/packages/python-sdk/e2b/api/client/models/admin_team_running_sandbox_counts.py@@ -0,0 +1,48 @@+from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="AdminTeamRunningSandboxCounts")+++@_attrs_define+class AdminTeamRunningSandboxCounts:+ """Cached live sandbox index count keyed by team ID. Counts may briefly+ include sandboxes transitioning out of running; teams without indexed+ sandboxes are omitted.++ """++ additional_properties: dict[str, int] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ admin_team_running_sandbox_counts = cls()++ admin_team_running_sandbox_counts.additional_properties = d+ return admin_team_running_sandbox_counts++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> int:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: int) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/packages/python-sdk/e2b/api/client/models/node_detail.py b/packages/python-sdk/e2b/api/client/models/node_detail.pyindex 9aabc2525..b5b5c0145 100644--- a/packages/python-sdk/e2b/api/client/models/node_detail.py+++ b/packages/python-sdk/e2b/api/client/models/node_detail.py@@ -1,6 +1,6 @@import datetimefrom collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar, cast+from typing import TYPE_CHECKING, Any, TypeVarfrom attrs import define as _attrs_definefrom attrs import field as _attrs_field@@ -33,7 +33,6 @@ class NodeDetail:status_changed_at (datetime.datetime): Time when the node status was last changedsandbox_count (int): Number of sandboxes running on the nodemetrics (NodeMetrics): Node metrics- cached_builds (list[str]): List of cached builds id on the nodecreate_successes (int): Number of sandbox create successescreate_fails (int): Number of sandbox create fails"""@@ -48,7 +47,6 @@ class NodeDetail:status_changed_at: datetime.datetimesandbox_count: intmetrics: "NodeMetrics"- cached_builds: list[str]create_successes: intcreate_fails: intadditional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)@@ -74,8 +72,6 @@ class NodeDetail:metrics = self.metrics.to_dict()- cached_builds = self.cached_builds-create_successes = self.create_successescreate_fails = self.create_fails@@ -94,7 +90,6 @@ class NodeDetail:"statusChangedAt": status_changed_at,"sandboxCount": sandbox_count,"metrics": metrics,- "cachedBuilds": cached_builds,"createSuccesses": create_successes,"createFails": create_fails,}@@ -128,8 +123,6 @@ class NodeDetail:metrics = NodeMetrics.from_dict(d.pop("metrics"))- cached_builds = cast(list[str], d.pop("cachedBuilds"))-create_successes = d.pop("createSuccesses")create_fails = d.pop("createFails")@@ -145,7 +138,6 @@ class NodeDetail:status_changed_at=status_changed_at,sandbox_count=sandbox_count,metrics=metrics,- cached_builds=cached_builds,create_successes=create_successes,create_fails=create_fails,)diff --git a/packages/python-sdk/e2b/api/client/models/sandbox_egress_proxy_config_type_0.py b/packages/python-sdk/e2b/api/client/models/sandbox_egress_proxy_config_type_0.pynew file mode 100644index 000000000..8f5c32e33--- /dev/null+++ b/packages/python-sdk/e2b/api/client/models/sandbox_egress_proxy_config_type_0.py@@ -0,0 +1,81 @@+from collections.abc import Mapping+from typing import Any, TypeVar, Union++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="SandboxEgressProxyConfigType0")+++@_attrs_define+class SandboxEgressProxyConfigType0:+ """SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the proxy after allow/deny filtering; the sandbox+ is unaware. Domain-matched flows use remote DNS (ATYP=domain).++ Attributes:+ address (str): SOCKS5 proxy address in host:port format (e.g. "proxy.example.com:1080").+ username (Union[Unset, str]): Optional SOCKS5 username (RFC 1929), max 255 bytes.+ password (Union[Unset, str]): Optional SOCKS5 password (RFC 1929), max 255 bytes.+ """++ address: str+ username: Union[Unset, str] = UNSET+ password: Union[Unset, str] = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ address = self.address++ username = self.username++ password = self.password++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "address": address,+ }+ )+ if username is not UNSET:+ field_dict["username"] = username+ if password is not UNSET:+ field_dict["password"] = password++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ address = d.pop("address")++ username = d.pop("username", UNSET)++ password = d.pop("password", UNSET)++ sandbox_egress_proxy_config_type_0 = cls(+ address=address,+ username=username,+ password=password,+ )++ sandbox_egress_proxy_config_type_0.additional_properties = d+ return sandbox_egress_proxy_config_type_0++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/packages/python-sdk/e2b/api/client/models/sandbox_network_config.py b/packages/python-sdk/e2b/api/client/models/sandbox_network_config.pyindex e5626276a..970666efe 100644--- a/packages/python-sdk/e2b/api/client/models/sandbox_network_config.py+++ b/packages/python-sdk/e2b/api/client/models/sandbox_network_config.py@@ -7,6 +7,9 @@ from attrs import field as _attrs_fieldfrom ..types import UNSET, Unsetif TYPE_CHECKING:+ from ..models.sandbox_egress_proxy_config_type_0 import (+ SandboxEgressProxyConfigType0,+ )from ..models.sandbox_network_config_rules import SandboxNetworkConfigRules@@ -24,6 +27,9 @@ class SandboxNetworkConfig:"*.example.com"). Allowed entries always take precedence over denied entries.deny_out (Union[Unset, list[str]]): List of denied CIDR blocks or IP addresses for egress traffic. Domain namesare not supported for deny rules.+ egress_proxy (Union['SandboxEgressProxyConfigType0', None, Unset]): SOCKS5 proxy for sandbox egress. Outbound+ TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use+ remote DNS (ATYP=domain).mask_request_host (Union[Unset, str]): Specify host mask which will be used for all sandbox requestsrules (Union[Unset, SandboxNetworkConfigRules]): Per-domain transform rules applied to matching egressHTTP/HTTPS requests. Keys are domains (e.g. "api.example.com", "example.com"). A domain listed here is not@@ -33,11 +39,16 @@ class SandboxNetworkConfig:allow_public_traffic: Union[Unset, bool] = Trueallow_out: Union[Unset, list[str]] = UNSETdeny_out: Union[Unset, list[str]] = UNSET+ egress_proxy: Union["SandboxEgressProxyConfigType0", None, Unset] = UNSETmask_request_host: Union[Unset, str] = UNSETrules: Union[Unset, "SandboxNetworkConfigRules"] = UNSETadditional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)def to_dict(self) -> dict[str, Any]:+ from ..models.sandbox_egress_proxy_config_type_0 import (+ SandboxEgressProxyConfigType0,+ )+allow_public_traffic = self.allow_public_trafficallow_out: Union[Unset, list[str]] = UNSET@@ -48,6 +59,14 @@ class SandboxNetworkConfig:if not isinstance(self.deny_out, Unset):deny_out = self.deny_out+ egress_proxy: Union[None, Unset, dict[str, Any]]+ if isinstance(self.egress_proxy, Unset):+ egress_proxy = UNSET+ elif isinstance(self.egress_proxy, SandboxEgressProxyConfigType0):+ egress_proxy = self.egress_proxy.to_dict()+ else:+ egress_proxy = self.egress_proxy+mask_request_host = self.mask_request_hostrules: Union[Unset, dict[str, Any]] = UNSET@@ -63,6 +82,8 @@ class SandboxNetworkConfig:field_dict["allowOut"] = allow_outif deny_out is not UNSET:field_dict["denyOut"] = deny_out+ if egress_proxy is not UNSET:+ field_dict["egressProxy"] = egress_proxyif mask_request_host is not UNSET:field_dict["maskRequestHost"] = mask_request_hostif rules is not UNSET:@@ -72,6 +93,9 @@ class SandboxNetworkConfig:@classmethoddef from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.sandbox_egress_proxy_config_type_0 import (+ SandboxEgressProxyConfigType0,+ )from ..models.sandbox_network_config_rules import SandboxNetworkConfigRulesd = dict(src_dict)@@ -81,6 +105,27 @@ class SandboxNetworkConfig:deny_out = cast(list[str], d.pop("denyOut", UNSET))+ def _parse_egress_proxy(+ data: object,+ ) -> Union["SandboxEgressProxyConfigType0", None, Unset]:+ if data is None:+ return data+ if isinstance(data, Unset):+ return data+ try:+ if not isinstance(data, dict):+ raise TypeError()+ componentsschemas_sandbox_egress_proxy_config_type_0 = (+ SandboxEgressProxyConfigType0.from_dict(data)+ )++ return componentsschemas_sandbox_egress_proxy_config_type_0+ except: # noqa: E722+ pass+ return cast(Union["SandboxEgressProxyConfigType0", None, Unset], data)++ egress_proxy = _parse_egress_proxy(d.pop("egressProxy", UNSET))+mask_request_host = d.pop("maskRequestHost", UNSET)_rules = d.pop("rules", UNSET)@@ -94,6 +139,7 @@ class SandboxNetworkConfig:allow_public_traffic=allow_public_traffic,allow_out=allow_out,deny_out=deny_out,+ egress_proxy=egress_proxy,mask_request_host=mask_request_host,rules=rules,)diff --git a/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.py b/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.pyindex 8df263214..1a47ddc7f 100644--- a/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.py+++ b/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.py@@ -7,6 +7,9 @@ from attrs import field as _attrs_fieldfrom ..types import UNSET, Unsetif TYPE_CHECKING:+ from ..models.sandbox_egress_proxy_config_type_0 import (+ SandboxEgressProxyConfigType0,+ )from ..models.sandbox_network_update_config_rules import (SandboxNetworkUpdateConfigRules,)@@ -26,6 +29,9 @@ class SandboxNetworkUpdateConfig:"*.example.com"). Allowed entries always take precedence over denied entries.deny_out (Union[Unset, list[str]]): List of denied CIDR blocks or IP addresses for egress traffic. Domain namesare not supported for deny rules.+ egress_proxy (Union['SandboxEgressProxyConfigType0', None, Unset]): SOCKS5 proxy for sandbox egress. Outbound+ TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use+ remote DNS (ATYP=domain).rules (Union[Unset, SandboxNetworkUpdateConfigRules]): Per-domain transform rules. Replaces all existing ruleswhen provided.allow_internet_access (Union[Unset, bool]): Allow sandbox to access the internet. When set to false, it behaves@@ -34,11 +40,16 @@ class SandboxNetworkUpdateConfig:allow_out: Union[Unset, list[str]] = UNSETdeny_out: Union[Unset, list[str]] = UNSET+ egress_proxy: Union["SandboxEgressProxyConfigType0", None, Unset] = UNSETrules: Union[Unset, "SandboxNetworkUpdateConfigRules"] = UNSETallow_internet_access: Union[Unset, bool] = UNSETadditional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)def to_dict(self) -> dict[str, Any]:+ from ..models.sandbox_egress_proxy_config_type_0 import (+ SandboxEgressProxyConfigType0,+ )+allow_out: Union[Unset, list[str]] = UNSETif not isinstance(self.allow_out, Unset):allow_out = self.allow_out@@ -47,6 +58,14 @@ class SandboxNetworkUpdateConfig:if not isinstance(self.deny_out, Unset):deny_out = self.deny_out+ egress_proxy: Union[None, Unset, dict[str, Any]]+ if isinstance(self.egress_proxy, Unset):+ egress_proxy = UNSET+ elif isinstance(self.egress_proxy, SandboxEgressProxyConfigType0):+ egress_proxy = self.egress_proxy.to_dict()+ else:+ egress_proxy = self.egress_proxy+rules: Union[Unset, dict[str, Any]] = UNSETif not isinstance(self.rules, Unset):rules = self.rules.to_dict()@@ -60,6 +79,8 @@ class SandboxNetworkUpdateConfig:field_dict["allowOut"] = allow_outif deny_out is not UNSET:field_dict["denyOut"] = deny_out+ if egress_proxy is not UNSET:+ field_dict["egressProxy"] = egress_proxyif rules is not UNSET:field_dict["rules"] = rulesif allow_internet_access is not UNSET:@@ -69,6 +90,9 @@ class SandboxNetworkUpdateConfig:@classmethoddef from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.sandbox_egress_proxy_config_type_0 import (+ SandboxEgressProxyConfigType0,+ )from ..models.sandbox_network_update_config_rules import (SandboxNetworkUpdateConfigRules,)@@ -78,6 +102,27 @@ class SandboxNetworkUpdateConfig:deny_out = cast(list[str], d.pop("denyOut", UNSET))+ def _parse_egress_proxy(+ data: object,+ ) -> Union["SandboxEgressProxyConfigType0", None, Unset]:+ if data is None:+ return data+ if isinstance(data, Unset):+ return data+ try:+ if not isinstance(data, dict):+ raise TypeError()+ componentsschemas_sandbox_egress_proxy_config_type_0 = (+ SandboxEgressProxyConfigType0.from_dict(data)+ )++ return componentsschemas_sandbox_egress_proxy_config_type_0+ except: # noqa: E722+ pass+ return cast(Union["SandboxEgressProxyConfigType0", None, Unset], data)++ egress_proxy = _parse_egress_proxy(d.pop("egressProxy", UNSET))+_rules = d.pop("rules", UNSET)rules: Union[Unset, SandboxNetworkUpdateConfigRules]if isinstance(_rules, Unset):@@ -90,6 +135,7 @@ class SandboxNetworkUpdateConfig:sandbox_network_update_config = cls(allow_out=allow_out,deny_out=deny_out,+ egress_proxy=egress_proxy,rules=rules,allow_internet_access=allow_internet_access,)diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.pyindex 8855966fa..b6ebf2ea2 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py@@ -25,6 +25,9 @@ from e2b.api.client.models import (from e2b.api.client.models import (SandboxLifecycle as ClientSandboxLifecycle,)+from e2b.api.client.models import (+ SandboxEgressProxyConfigType0 as ClientSandboxEgressProxyConfig,+)from e2b.api.client.models import (SandboxNetworkConfig as ClientSandboxNetworkConfig,)@@ -212,6 +215,74 @@ and returns the same."""+class SandboxEgressProxyOpts(TypedDict):+ """+ SOCKS5 proxy the sandbox's outbound TCP is tunneled through — "bring your+ own proxy".++ Tunneling happens on the host, after :attr:`SandboxNetworkOpts.allow_out` /+ :attr:`SandboxNetworkOpts.deny_out` filtering, so nothing runs inside the+ sandbox and code running there can neither see the proxy nor route around+ it. UDP-based traffic — DNS and QUIC/HTTP3 — is not tunneled and leaves the+ sandbox the usual way.++ Egress fails closed: when the proxy is unreachable or does not speak+ SOCKS5, outbound connections fail rather than falling back to a direct+ connection.++ Pass credentials when the proxy requires them::++ sandbox = Sandbox.create(+ network={+ "egress_proxy": {+ "address": "proxy.example.com:1080",+ "username": "proxy-user",+ "password": "proxy-password",+ },+ },+ )+ """++ address: str+ """+ SOCKS5 proxy address in ``host:port`` form, e.g.+ ``"proxy.example.com:1080"``. The host can be a hostname or an IP literal;+ a hostname is re-resolved at dial time and the resolved address is pinned+ for that connection, so a DNS change cannot redirect a connection that is+ already being established.++ The proxy has to be reachable from E2B's infrastructure: an address that+ does not resolve, or that resolves into a private or otherwise internal+ range, is rejected before the sandbox exists.+ """++ username: NotRequired[str]+ """+ SOCKS5 username (`RFC 1929 <https://datatracker.ietf.org/doc/html/rfc1929>`_),+ up to 255 bytes. Omit it for a proxy that takes no credentials.+ """++ password: NotRequired[str]+ """+ SOCKS5 password, up to 255 bytes. Only valid together with+ :attr:`username`.+ """+++class SandboxEgressProxyInfo(TypedDict):+ """+ Egress proxy as returned by the sandbox info endpoint. Mirrors+ :class:`SandboxEgressProxyOpts` without ``password`` — the API never+ returns it.+ """++ address: str+ """See :attr:`SandboxEgressProxyOpts.address`."""++ username: NotRequired[str]+ """See :attr:`SandboxEgressProxyOpts.username`."""++class SandboxNetworkOpts(TypedDict):"""Sandbox network configuration options.@@ -272,6 +343,29 @@ class SandboxNetworkOpts(TypedDict):}"""+ egress_proxy: NotRequired[SandboxEgressProxyOpts]+ """+ Tunnel the sandbox's outbound TCP through a SOCKS5 proxy you operate.++ Filtering runs first, so a connection ``deny_out`` blocks never reaches the+ proxy, and per-host :attr:`rules` transforms still apply before the+ connection is dialed. Omit it to send the sandbox's traffic out directly.++ Available on E2B Cloud and in BYOC deployments; a sandbox that names a+ proxy on a deployment built from the open source ``e2b-dev/infra``+ repository is rejected as unsupported.++ Deny everything except a host, and tunnel what is left::++ Sandbox.create(+ network={+ "allow_out": ["api.example.com"],+ "deny_out": lambda ctx: [ctx.all_traffic],+ "egress_proxy": {"address": "proxy.example.com:1080"},+ },+ )+ """+allow_public_traffic: NotRequired[bool]"""Controls whether sandbox URLs should be publicly accessible or require authentication.@@ -309,6 +403,17 @@ class SandboxNetworkUpdate(TypedDict, total=False):its placeholder and a typo only surfaces at the destination."""+ egress_proxy: SandboxEgressProxyOpts+ """+ See :attr:`SandboxNetworkOpts.egress_proxy`. Sets or replaces the proxy on a+ sandbox that is already running, with no restart.++ The update replaces the whole configuration instead of merging into it, so+ an update that leaves this out stops tunneling and sends the sandbox's+ traffic out directly — even when the update was only meant to change the+ allow and deny lists. Repeat it in every update that should keep tunneling.+ """+allow_internet_access: bool"""Allow sandbox to access the internet. When set to ``False``, it behaves the@@ -362,6 +467,12 @@ class SandboxNetworkInfo(TypedDict, total=False):allow_out: List[str]deny_out: List[str]rules: Dict[str, List[SandboxNetworkRuleInfo]]+ egress_proxy: SandboxEgressProxyInfo+ """+ Proxy the sandbox's egress is currently tunneled through, absent when it+ goes out directly. See :class:`SandboxEgressProxyInfo` for why the password+ is missing.+ """allow_public_traffic: boolmask_request_host: str@@ -530,25 +641,63 @@ def _build_client_rules(return client_rules+def _build_egress_proxy(+ egress_proxy: SandboxEgressProxyOpts,+) -> ClientSandboxEgressProxyConfig:+ """+ Rebuild the proxy config from the known fields so stray keys in the+ caller's dict never reach the wire. Address reachability is the server's —+ it is the only side that can tell whether the address resolves, and to where.+ The required ``address`` key is checked here so an untyped caller that+ omits it gets :class:`InvalidArgumentException` rather than a bare+ ``KeyError`` from deep inside create.+ """+ # Re-check at runtime for callers that bypass the TypedDict — a bare+ # KeyError from deep inside create would not name the option.+ if not isinstance(egress_proxy, Mapping) or not isinstance(+ egress_proxy.get("address"), str+ ):+ raise InvalidArgumentException(+ "network egress_proxy must be a dict with a string 'address' "+ "(e.g. 'proxy.example.com:1080')."+ )++ body = ClientSandboxEgressProxyConfig(address=egress_proxy["address"])+ if "username" in egress_proxy:+ body.username = egress_proxy["username"]+ if "password" in egress_proxy:+ body.password = egress_proxy["password"]++ return body++def _build_network_egress(network: Mapping[str, Any],ctx: SandboxNetworkTransformContext,) -> Dict[str, Any]:"""- Resolve the shared egress fields (``allow_out`` / ``deny_out`` / per-host- ``rules``) used by both the create and update endpoints. ``rules`` in the- returned dict is the inner ``Dict[host, List[ClientSandboxNetworkRule]]``- — callers wrap it in their endpoint-specific rules attrs class.+ Resolve the shared egress fields (``allow_out`` / ``deny_out`` /+ ``egress_proxy`` / per-host ``rules``) used by both the create and update+ endpoints. ``rules`` in the returned dict is the inner+ ``Dict[host, List[ClientSandboxNetworkRule]]`` — callers wrap it in their+ endpoint-specific rules attrs class."""rules = network.get("rules") or {}allow_out = _resolve_network_selector(network.get("allow_out"), rules)deny_out = _resolve_network_selector(network.get("deny_out"), rules)+ # `is not None` also covers an explicit `"egress_proxy": None`, which+ # untyped callers spell "no proxy" as; the JS SDK's `!= null` does the+ # same. Do not use truthiness — an empty dict must reach the builder so+ # it fails loudly instead of silently disabling tunneling.+ egress_proxy = network.get("egress_proxy")body: Dict[str, Any] = {}if allow_out is not None:body["allow_out"] = allow_outif deny_out is not None:body["deny_out"] = deny_out+ if egress_proxy is not None:+ body["egress_proxy"] = _build_egress_proxy(egress_proxy)if "rules" in network and network["rules"] is not None:body["rules"] = _build_client_rules(network["rules"], ctx).additional_properties@@ -646,6 +795,8 @@ def build_network_update_body(body.allow_out = egress["allow_out"]if "deny_out" in egress:body.deny_out = egress["deny_out"]+ if "egress_proxy" in egress:+ body.egress_proxy = egress["egress_proxy"]if "rules" in egress:rules = SandboxNetworkUpdateConfigRules()rules.additional_properties = egress["rules"]@@ -656,6 +807,24 @@ def build_network_update_body(return body+def _from_client_egress_proxy(+ egress_proxy: Union[ClientSandboxEgressProxyConfig, None, Unset],+) -> Optional[SandboxEgressProxyInfo]:+ """+ Map the wire proxy config into the SDK-owned shape: ``password`` is dropped+ because the API never returns it, and the wire's ``None`` for "no proxy"+ becomes an absent key.+ """+ if not isinstance(egress_proxy, ClientSandboxEgressProxyConfig):+ return None++ result: SandboxEgressProxyInfo = {"address": egress_proxy.address}+ if not isinstance(egress_proxy.username, Unset):+ result["username"] = egress_proxy.username++ return result++def from_client_network_config(network: Union[Unset, ClientSandboxNetworkConfig],) -> Optional[SandboxNetworkInfo]:@@ -672,6 +841,9 @@ def from_client_network_config(result["rules"] = cast(Dict[str, List[SandboxNetworkRuleInfo]], network.rules.to_dict())+ egress_proxy = _from_client_egress_proxy(network.egress_proxy)+ if egress_proxy is not None:+ result["egress_proxy"] = egress_proxyif not isinstance(network.allow_public_traffic, Unset):result["allow_public_traffic"] = network.allow_public_trafficif not isinstance(network.mask_request_host, Unset):diff --git a/packages/python-sdk/tests/shared/sandbox/test_egress_proxy.py b/packages/python-sdk/tests/shared/sandbox/test_egress_proxy.pynew file mode 100644index 000000000..e097ee171--- /dev/null+++ b/packages/python-sdk/tests/shared/sandbox/test_egress_proxy.py@@ -0,0 +1,162 @@+from typing import Any, cast++import pytest++from e2b import SandboxNetworkOpts, SandboxNetworkUpdate+from e2b.api.client.models import SandboxNetworkConfig+from e2b.api.client.models import (+ SandboxEgressProxyConfigType0 as ClientSandboxEgressProxyConfig,+)+from e2b.api.client.types import UNSET+from e2b.exceptions import InvalidArgumentException+from e2b.sandbox.sandbox_api import (+ build_network_config,+ build_network_update_body,+ from_client_network_config,+)+++def test_create_sends_the_egress_proxy():+ network: SandboxNetworkOpts = {+ "egress_proxy": {+ "address": "proxy.example.com:1080",+ "username": "proxy-user",+ "password": "proxy-password",+ },+ }++ body = build_network_config(network)+ assert body is not None+ assert body["egress_proxy"].to_dict() == {+ "address": "proxy.example.com:1080",+ "username": "proxy-user",+ "password": "proxy-password",+ }+++def test_create_sends_an_address_only_egress_proxy():+ body = build_network_config({"egress_proxy": {"address": "proxy.example.com:1080"}})+ assert body is not None+ assert body["egress_proxy"].to_dict() == {"address": "proxy.example.com:1080"}+++def test_create_combines_the_egress_proxy_with_allow_and_deny_lists():+ network: SandboxNetworkOpts = {+ "allow_out": ["api.example.com"],+ "deny_out": lambda ctx: [ctx.all_traffic],+ "egress_proxy": {"address": "proxy.example.com:1080"},+ }++ body = build_network_config(network)+ assert body is not None+ assert body["allow_out"] == ["api.example.com"]+ assert body["deny_out"] == ["0.0.0.0/0"]+ assert body["egress_proxy"].to_dict() == {"address": "proxy.example.com:1080"}+++ "network",+ [+ pytest.param({"allow_out": ["api.example.com"]}, id="omitted"),+ # Untyped callers spell "no proxy" as None; the JS SDK treats an+ # explicit null the same way.+ pytest.param({"egress_proxy": None}, id="none"),+ ],+)+def test_create_omits_the_egress_proxy(network):+ body = build_network_config(cast(Any, network))+ assert body is not None+ assert "egress_proxy" not in body+++ "egress_proxy",+ [+ # An empty dict is falsy but present — it must not silently disable+ # tunneling the way `or None` used to. Match JS: fail loudly.+ pytest.param({}, id="empty"),+ pytest.param({"username": "proxy-user"}, id="missing-address"),+ pytest.param({"address": 1080}, id="non-string-address"),+ pytest.param("proxy.example.com:1080", id="string"),+ ],+)+def test_create_rejects_a_malformed_egress_proxy(egress_proxy):+ with pytest.raises(InvalidArgumentException, match="egress_proxy"):+ build_network_config(cast(Any, {"egress_proxy": egress_proxy}))+++def test_create_strips_unknown_egress_proxy_keys():+ # An untyped caller can copy an extra key out of a config file; the API+ # rejects unknown properties.+ network = cast(+ Any,+ {+ "egress_proxy": {+ "address": "proxy.example.com:1080",+ "protocol": "socks5",+ },+ },+ )++ body = build_network_config(network)+ assert body is not None+ assert body["egress_proxy"].to_dict() == {"address": "proxy.example.com:1080"}+++def test_update_sets_the_egress_proxy():+ network: SandboxNetworkUpdate = {+ "allow_out": ["api.example.com"],+ "deny_out": lambda ctx: [ctx.all_traffic],+ "egress_proxy": {"address": "proxy.example.com:1080"},+ }++ assert build_network_update_body(network).to_dict() == {+ "allowOut": ["api.example.com"],+ "denyOut": ["0.0.0.0/0"],+ "egressProxy": {"address": "proxy.example.com:1080"},+ }+++def test_update_without_the_egress_proxy_clears_it():+ # The update replaces the whole configuration instead of merging into it, so+ # omitting the proxy stops tunneling rather than leaving it in place.+ assert build_network_update_body({}).to_dict() == {}+++def test_get_info_reports_the_active_egress_proxy_without_the_password():+ info = from_client_network_config(+ SandboxNetworkConfig(+ allow_out=["api.example.com"],+ egress_proxy=ClientSandboxEgressProxyConfig(+ address="proxy.example.com:1080",+ username="proxy-user",+ # SandboxEgressProxyInfo says the password is not there, so it+ # must not be there even if a future API version starts echoing+ # it back.+ password="proxy-password",+ ),+ )+ )++ assert info is not None+ assert info["egress_proxy"] == {+ "address": "proxy.example.com:1080",+ "username": "proxy-user",+ }+++ "egress_proxy",+ [+ pytest.param(UNSET, id="unset"),+ # The wire field is nullable; absence has to read the same either way.+ pytest.param(None, id="none"),+ ],+)+def test_get_info_reports_no_egress_proxy(egress_proxy):+ info = from_client_network_config(+ SandboxNetworkConfig(allow_out=["api.example.com"], egress_proxy=egress_proxy)+ )++ assert info is not None+ assert "egress_proxy" not in infodiff --git a/spec/infra-ref b/spec/infra-refindex 07c850597..a62a397a1 100644--- a/spec/infra-ref+++ b/spec/infra-ref@@ -1 +1 @@-24a054bca26ec50a6d59031d9360c1582612b3f8+0716edb9e840f110c5f87c186876c01e61553098diff --git a/spec/openapi.yml b/spec/openapi.ymlindex 39a344ccd..bb2747b77 100644--- a/spec/openapi.yml+++ b/spec/openapi.yml@@ -311,13 +311,7 @@ components:items:type: stringegressProxy:- allOf:- - $ref: "#/components/schemas/SandboxEgressProxyConfig"- description: >-- SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the- proxy after allow/deny filtering; the sandbox is unaware. Domain-matched- flows use remote DNS (ATYP=domain).- x-not-implemented: true+ $ref: "#/components/schemas/SandboxEgressProxyConfig"maskRequestHost:type: stringdescription: Specify host mask which will be used for all sandbox requests@@ -347,13 +341,7 @@ components:items:type: stringegressProxy:- allOf:- - $ref: "#/components/schemas/SandboxEgressProxyConfig"- description: >-- SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the- proxy after allow/deny filtering; the sandbox is unaware. Domain-matched- flows use remote DNS (ATYP=domain).- x-not-implemented: true+ $ref: "#/components/schemas/SandboxEgressProxyConfig"rules:type: objectdescription: Per-domain transform rules. Replaces all existing rules when provided.@@ -390,7 +378,6 @@ components:SandboxEgressProxyConfig:type: objectnullable: true- x-not-implemented: truedescription: >-SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through theproxy after allow/deny filtering; the sandbox is unaware. Domain-matched@@ -970,6 +957,17 @@ components:type: integerdescription: Number of sandboxes that failed to kill+ AdminTeamRunningSandboxCounts:+ type: object+ description: |+ Cached live sandbox index count keyed by team ID. Counts may briefly+ include sandboxes transitioning out of running; teams without indexed+ sandboxes are omitted.+ additionalProperties:+ type: integer+ format: int64+ minimum: 1+AdminBuildCancelResult:required:- cancelledCount@@ -1775,7 +1773,6 @@ components:- status- statusChangedAt- sandboxCount- - cachedBuilds- createSuccesses- createFails- version@@ -1812,11 +1809,6 @@ components:description: Number of sandboxes running on the nodemetrics:$ref: "#/components/schemas/NodeMetrics"- cachedBuilds:- type: array- description: List of cached builds id on the node- items:- type: stringcreateSuccesses:type: integerformat: uint64@@ -3627,6 +3619,27 @@ paths:"500":$ref: "#/components/responses/500"+ /admin/sandboxes/running-counts:+ get:+ summary: Count running sandboxes by team+ description: |+ Returns a shared snapshot normally refreshed after five seconds. A+ sandbox transitioning out of running can remain counted until removal.+ tags: [admin]+ security:+ - AdminApiKeyAuth: []+ responses:+ "200":+ description: Running sandbox counts keyed by team ID+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/AdminTeamRunningSandboxCounts"+ "401":+ $ref: "#/components/responses/401"+ "500":+ $ref: "#/components/responses/500"+/admin/teams/{teamID}/builds/cancel:post:summary: Cancel all builds for a team