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 Sandbox.updateNetwork / update_network (#1337)

Mish Ushakovc485bf5476a5
diff --git a/.changeset/sandbox-update-network.md b/.changeset/sandbox-update-network.md
new file mode 100644
index 000000000..8e08d3384
--- /dev/null
+++ b/.changeset/sandbox-update-network.md
@@ -0,0 +1,6 @@
+---
+'e2b': minor
+'@e2b/python-sdk': minor
+---
+
+Add `Sandbox.updateNetwork` / `update_network` to replace a running sandbox's egress configuration (allow / deny lists, per-host rules, internet access toggle).
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index d067e7406..3ae5bdad6 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -295,7 +295,7 @@ export interface paths {
cookie?: never;
};
get?: never;
- /** @description Update the network configuration for a running sandbox. Replaces the current egress rules with the provided configuration. Omitting both fields clears all egress rules. */
+ /** @description Update the network configuration for a running sandbox. Replaces the current egress rules with the provided configuration. Omitting a field clears it. */
put: {
parameters: {
query?: never;
@@ -307,18 +307,7 @@ export interface paths {
};
requestBody: {
content: {
- "application/json": {
- /** @description Allow sandbox to access the internet. When set to false, it behaves the same as specifying denyOut to 0.0.0.0/0 in the network config. */
- allow_internet_access?: boolean;
- /** @description List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries. */
- allowOut?: string[];
- /** @description List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. */
- denyOut?: string[];
- /** @description Per-domain transform rules. Replaces all existing rules when provided. */
- rules?: {
- [key: string]: components["schemas"]["SandboxNetworkRule"][];
- };
- };
+ "application/json": components["schemas"]["SandboxNetworkUpdateConfig"];
};
};
responses: {
@@ -2361,6 +2350,19 @@ export interface components {
[key: string]: string;
};
};
+ /** @description Network configuration update for a running sandbox. Replaces the current egress rules with the provided configuration. Omitting a field clears it. */
+ SandboxNetworkUpdateConfig: {
+ /** @description Allow sandbox to access the internet. When set to false, it behaves the same as specifying denyOut to 0.0.0.0/0 in the network config. */
+ allow_internet_access?: boolean;
+ /** @description List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries. */
+ allowOut?: string[];
+ /** @description List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. */
+ denyOut?: string[];
+ /** @description Per-domain transform rules. Replaces all existing rules when provided. */
+ rules?: {
+ [key: string]: components["schemas"]["SandboxNetworkRule"][];
+ };
+ };
/**
* @description Action taken when the sandbox times out.
* @enum {string}
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 036d112e4..c86a9b545 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -64,6 +64,7 @@ export type {
SandboxNetworkRuleInfo,
SandboxNetworkRules,
SandboxNetworkTransform,
+ SandboxNetworkUpdate,
SandboxLifecycle,
SandboxInfoLifecycle,
SnapshotInfo,
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index d3e699f33..92d4c2457 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -19,6 +19,7 @@ import {
SandboxMetricsOpts,
SandboxApi,
SandboxListOpts,
+ SandboxNetworkUpdate,
SandboxPaginator,
SnapshotListOpts,
SnapshotInfo,
@@ -480,6 +481,26 @@ export class Sandbox extends SandboxApi {
)
}
+ /**
+ * Update the network configuration of the sandbox.
+ *
+ * Replaces the current egress configuration atomically — fields that are
+ * omitted are cleared on the server.
+ *
+ * @param network new network configuration.
+ * @param opts connection options.
+ */
+ async updateNetwork(
+ network: SandboxNetworkUpdate,
+ opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>
+ ) {
+ await SandboxApi.updateNetwork(
+ this.sandboxId,
+ network,
+ this.resolveApiOpts(opts)
+ )
+ }
+
/**
* Kill the sandbox.
*
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index d94d90ca1..04d53722f 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -178,6 +178,25 @@ export type SandboxNetworkInfo = {
maskRequestHost?: string
}
+/**
+ * Subset of {@link SandboxNetworkOpts} accepted by {@link SandboxApi.updateNetwork}.
+ * The update endpoint replaces all egress rules atomically — fields that are
+ * omitted are cleared on the server.
+ */
+export type SandboxNetworkUpdate = {
+ /** See {@link SandboxNetworkOpts.allowOut}. */
+ allowOut?: SandboxNetworkSelector
+ /** See {@link SandboxNetworkOpts.denyOut}. */
+ denyOut?: SandboxNetworkSelector
+ /** See {@link SandboxNetworkOpts.rules}. */
+ rules?: SandboxNetworkRules
+ /**
+ * 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.
+ */
+ allowInternetAccess?: boolean
+}
+
export type SandboxLifecycle = {
/**
* Action to take when sandbox timeout is reached.
@@ -549,13 +568,17 @@ function resolveRulesForBody(
return out
}
-function buildNetworkBody(
- network: SandboxNetworkOpts | undefined
-): components['schemas']['SandboxNetworkConfig'] | undefined {
- if (!network) {
- return undefined
- }
+type NetworkEgressBody = {
+ allowOut?: string[]
+ denyOut?: string[]
+ rules?: Record<string, { transform?: SandboxNetworkTransform }[]>
+}
+function buildNetworkEgress(network: {
+ allowOut?: SandboxNetworkSelector
+ denyOut?: SandboxNetworkSelector
+ rules?: SandboxNetworkRules
+}): NetworkEgressBody {
const rules =
network.rules instanceof Map
? network.rules
@@ -569,6 +592,18 @@ function buildNetworkBody(
...(network.rules !== undefined
? { rules: resolveRulesForBody(rules) }
: {}),
+ }
+}
+
+function buildNetworkBody(
+ network: SandboxNetworkOpts | undefined
+): components['schemas']['SandboxNetworkConfig'] | undefined {
+ if (!network) {
+ return undefined
+ }
+
+ return {
+ ...buildNetworkEgress(network),
...(network.allowPublicTraffic !== undefined
? { allowPublicTraffic: network.allowPublicTraffic }
: {}),
@@ -578,6 +613,16 @@ function buildNetworkBody(
}
}
+function buildNetworkUpdateBody(
+ network: SandboxNetworkUpdate
+): components['schemas']['SandboxNetworkUpdateConfig'] {
+ return {
+ ...buildNetworkEgress(network),
+ ...(network.allowInternetAccess !== undefined
+ ? { allow_internet_access: network.allowInternetAccess }
+ : {}),
+ }
+}
export class SandboxApi {
protected constructor() {}
@@ -727,6 +772,44 @@ export class SandboxApi {
}
}
+ /**
+ * Update the network configuration of a running sandbox.
+ *
+ * Replaces the current egress configuration atomically — fields that are
+ * omitted are cleared on the server.
+ *
+ * @param sandboxId sandbox ID.
+ * @param network new network configuration.
+ * @param opts connection options.
+ */
+ static async updateNetwork(
+ sandboxId: string,
+ network: SandboxNetworkUpdate,
+ opts?: SandboxApiOpts
+ ): Promise<void> {
+ const config = new ConnectionConfig(opts)
+ const client = new ApiClient(config)
+
+ const res = await client.api.PUT('/sandboxes/{sandboxID}/network', {
+ params: {
+ path: {
+ sandboxID: sandboxId,
+ },
+ },
+ body: buildNetworkUpdateBody(network),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ if (res.error?.code === 404) {
+ throw new SandboxNotFoundError(`Sandbox ${sandboxId} not found`)
+ }
+
+ const err = handleApiError(res)
+ if (err) {
+ throw err
+ }
+ }
+
static async getFullInfo(sandboxId: string, opts?: SandboxApiOpts) {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
diff --git a/packages/js-sdk/tests/sandbox/configPropagation.test.ts b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
index f4e031ce1..9e6d8e0f3 100644
--- a/packages/js-sdk/tests/sandbox/configPropagation.test.ts
+++ b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
@@ -68,6 +68,19 @@ describe('Sandbox API config propagation', () => {
assert.equal(opts?.debug, baseConfig.debug)
})
+ test('updateNetwork forwards per-call signal', async () => {
+ const updateNetworkSpy = vi
+ .spyOn(SandboxApi, 'updateNetwork')
+ .mockResolvedValue()
+ const sandbox = createSandbox()
+ const controller = new AbortController()
+
+ await sandbox.updateNetwork({}, { signal: controller.signal })
+
+ const opts = updateNetworkSpy.mock.calls[0][2]
+ assert.equal(opts?.signal, controller.signal)
+ })
+
test('downloadUrl keeps sandbox identity in production direct URLs', async () => {
delete process.env.E2B_SANDBOX_URL
diff --git a/packages/js-sdk/tests/sandbox/network.test.ts b/packages/js-sdk/tests/sandbox/network.test.ts
index 7388d9804..2da46ffd6 100644
--- a/packages/js-sdk/tests/sandbox/network.test.ts
+++ b/packages/js-sdk/tests/sandbox/network.test.ts
@@ -236,6 +236,70 @@ describe('firewall transform injects headers', () => {
)
})
+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.scoped({
+ 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)
+ }
+ )
+})
+
describe('maskRequestHost option', () => {
sandboxTest.scoped({
sandboxOpts: {
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 0b8dc71c9..d574de891 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -87,6 +87,7 @@ from .sandbox.sandbox_api import (
SandboxNetworkSelector,
SandboxNetworkSelectorContext,
SandboxNetworkTransform,
+ SandboxNetworkUpdate,
SandboxQuery,
SandboxState,
SnapshotInfo,
@@ -197,6 +198,7 @@ __all__ = [
"SandboxNetworkRuleInfo",
"SandboxNetworkRules",
"SandboxNetworkTransform",
+ "SandboxNetworkUpdate",
"SandboxLifecycle",
"ALL_TRAFFIC",
# Snapshot
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/put_sandboxes_sandbox_id_network.py b/packages/python-sdk/e2b/api/client/api/sandboxes/put_sandboxes_sandbox_id_network.py
index cf6be790d..965cc9546 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/put_sandboxes_sandbox_id_network.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/put_sandboxes_sandbox_id_network.py
@@ -6,16 +6,14 @@ import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.error import Error
-from ...models.put_sandboxes_sandbox_id_network_body import (
- PutSandboxesSandboxIDNetworkBody,
-)
+from ...models.sandbox_network_update_config import SandboxNetworkUpdateConfig
from ...types import Response
def _get_kwargs(
sandbox_id: str,
*,
- body: PutSandboxesSandboxIDNetworkBody,
+ body: SandboxNetworkUpdateConfig,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
@@ -75,14 +73,16 @@ def sync_detailed(
sandbox_id: str,
*,
client: AuthenticatedClient,
- body: PutSandboxesSandboxIDNetworkBody,
+ body: SandboxNetworkUpdateConfig,
) -> Response[Union[Any, Error]]:
"""Update the network configuration for a running sandbox. Replaces the current egress rules with the
- provided configuration. Omitting both fields clears all egress rules.
+ provided configuration. Omitting a field clears it.
Args:
sandbox_id (str):
- body (PutSandboxesSandboxIDNetworkBody):
+ body (SandboxNetworkUpdateConfig): Network configuration update for a running sandbox.
+ Replaces the current egress rules with the provided configuration. Omitting a field clears
+ it.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
@@ -108,14 +108,16 @@ def sync(
sandbox_id: str,
*,
client: AuthenticatedClient,
- body: PutSandboxesSandboxIDNetworkBody,
+ body: SandboxNetworkUpdateConfig,
) -> Optional[Union[Any, Error]]:
"""Update the network configuration for a running sandbox. Replaces the current egress rules with the
- provided configuration. Omitting both fields clears all egress rules.
+ provided configuration. Omitting a field clears it.
Args:
sandbox_id (str):
- body (PutSandboxesSandboxIDNetworkBody):
+ body (SandboxNetworkUpdateConfig): Network configuration update for a running sandbox.
+ Replaces the current egress rules with the provided configuration. Omitting a field clears
+ it.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
@@ -136,14 +138,16 @@ async def asyncio_detailed(
sandbox_id: str,
*,
client: AuthenticatedClient,
- body: PutSandboxesSandboxIDNetworkBody,
+ body: SandboxNetworkUpdateConfig,
) -> Response[Union[Any, Error]]:
"""Update the network configuration for a running sandbox. Replaces the current egress rules with the
- provided configuration. Omitting both fields clears all egress rules.
+ provided configuration. Omitting a field clears it.
Args:
sandbox_id (str):
- body (PutSandboxesSandboxIDNetworkBody):
+ body (SandboxNetworkUpdateConfig): Network configuration update for a running sandbox.
+ Replaces the current egress rules with the provided configuration. Omitting a field clears
+ it.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
@@ -167,14 +171,16 @@ async def asyncio(
sandbox_id: str,
*,
client: AuthenticatedClient,
- body: PutSandboxesSandboxIDNetworkBody,
+ body: SandboxNetworkUpdateConfig,
) -> Optional[Union[Any, Error]]:
"""Update the network configuration for a running sandbox. Replaces the current egress rules with the
- provided configuration. Omitting both fields clears all egress rules.
+ provided configuration. Omitting a field clears it.
Args:
sandbox_id (str):
- body (PutSandboxesSandboxIDNetworkBody):
+ body (SandboxNetworkUpdateConfig): Network configuration update for a running sandbox.
+ Replaces the current egress rules with the provided configuration. Omitting a field clears
+ it.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.py
index 365bfe9a2..aa5d633ff 100644
--- a/packages/python-sdk/e2b/api/client/models/__init__.py
+++ b/packages/python-sdk/e2b/api/client/models/__init__.py
@@ -42,10 +42,6 @@ from .post_sandboxes_sandbox_id_snapshots_body import (
PostSandboxesSandboxIDSnapshotsBody,
)
from .post_sandboxes_sandbox_id_timeout_body import PostSandboxesSandboxIDTimeoutBody
-from .put_sandboxes_sandbox_id_network_body import PutSandboxesSandboxIDNetworkBody
-from .put_sandboxes_sandbox_id_network_body_rules import (
- PutSandboxesSandboxIDNetworkBodyRules,
-)
from .resumed_sandbox import ResumedSandbox
from .sandbox import Sandbox
from .sandbox_auto_resume_config import SandboxAutoResumeConfig
@@ -62,6 +58,8 @@ from .sandbox_network_config_rules import SandboxNetworkConfigRules
from .sandbox_network_rule import SandboxNetworkRule
from .sandbox_network_transform import SandboxNetworkTransform
from .sandbox_network_transform_headers import SandboxNetworkTransformHeaders
+from .sandbox_network_update_config import SandboxNetworkUpdateConfig
+from .sandbox_network_update_config_rules import SandboxNetworkUpdateConfigRules
from .sandbox_on_timeout import SandboxOnTimeout
from .sandbox_state import SandboxState
from .sandbox_volume_mount import SandboxVolumeMount
@@ -133,8 +131,6 @@ __all__ = (
"PostSandboxesSandboxIDRefreshesBody",
"PostSandboxesSandboxIDSnapshotsBody",
"PostSandboxesSandboxIDTimeoutBody",
- "PutSandboxesSandboxIDNetworkBody",
- "PutSandboxesSandboxIDNetworkBodyRules",
"ResumedSandbox",
"Sandbox",
"SandboxAutoResumeConfig",
@@ -152,6 +148,8 @@ __all__ = (
"SandboxNetworkRule",
"SandboxNetworkTransform",
"SandboxNetworkTransformHeaders",
+ "SandboxNetworkUpdateConfig",
+ "SandboxNetworkUpdateConfigRules",
"SandboxOnTimeout",
"SandboxState",
"SandboxVolumeMount",
diff --git a/packages/python-sdk/e2b/api/client/models/put_sandboxes_sandbox_id_network_body.py b/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.py
similarity index 60%
rename from packages/python-sdk/e2b/api/client/models/put_sandboxes_sandbox_id_network_body.py
rename to packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.py
index c37a89368..a4c5e8fc4 100644
--- a/packages/python-sdk/e2b/api/client/models/put_sandboxes_sandbox_id_network_body.py
+++ b/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config.py
@@ -7,33 +7,35 @@ from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
- from ..models.put_sandboxes_sandbox_id_network_body_rules import (
- PutSandboxesSandboxIDNetworkBodyRules,
+ from ..models.sandbox_network_update_config_rules import (
+ SandboxNetworkUpdateConfigRules,
)
-T = TypeVar("T", bound="PutSandboxesSandboxIDNetworkBody")
+T = TypeVar("T", bound="SandboxNetworkUpdateConfig")
@_attrs_define
-class PutSandboxesSandboxIDNetworkBody:
- """
- Attributes:
- allow_out (Union[Unset, list[str]]): List of allowed destinations for egress traffic. Each entry can be a CIDR
- block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com",
- "*.example.com"). Allowed entries always take precedence over denied entries.
- allow_internet_access (Union[Unset, bool]): Allow sandbox to access the internet. When set to false, it behaves
- the same as specifying denyOut to 0.0.0.0/0 in the network config.
- deny_out (Union[Unset, list[str]]): List of denied CIDR blocks or IP addresses for egress traffic. Domain names
- are not supported for deny rules.
- rules (Union[Unset, PutSandboxesSandboxIDNetworkBodyRules]): Per-domain transform rules. Replaces all existing
- rules when provided.
+class SandboxNetworkUpdateConfig:
+ """Network configuration update for a running sandbox. Replaces the current egress rules with the provided
+ configuration. Omitting a field clears it.
+
+ Attributes:
+ allow_out (Union[Unset, list[str]]): List of allowed destinations for egress traffic. Each entry can be a CIDR
+ block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com",
+ "*.example.com"). Allowed entries always take precedence over denied entries.
+ allow_internet_access (Union[Unset, bool]): Allow sandbox to access the internet. When set to false, it behaves
+ the same as specifying denyOut to 0.0.0.0/0 in the network config.
+ deny_out (Union[Unset, list[str]]): List of denied CIDR blocks or IP addresses for egress traffic. Domain names
+ are not supported for deny rules.
+ rules (Union[Unset, SandboxNetworkUpdateConfigRules]): Per-domain transform rules. Replaces all existing rules
+ when provided.
"""
allow_out: Union[Unset, list[str]] = UNSET
allow_internet_access: Union[Unset, bool] = UNSET
deny_out: Union[Unset, list[str]] = UNSET
- rules: Union[Unset, "PutSandboxesSandboxIDNetworkBodyRules"] = UNSET
+ rules: Union[Unset, "SandboxNetworkUpdateConfigRules"] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
@@ -67,8 +69,8 @@ class PutSandboxesSandboxIDNetworkBody:
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
- from ..models.put_sandboxes_sandbox_id_network_body_rules import (
- PutSandboxesSandboxIDNetworkBodyRules,
+ from ..models.sandbox_network_update_config_rules import (
+ SandboxNetworkUpdateConfigRules,
)
d = dict(src_dict)
@@ -79,21 +81,21 @@ class PutSandboxesSandboxIDNetworkBody:
deny_out = cast(list[str], d.pop("denyOut", UNSET))
_rules = d.pop("rules", UNSET)
- rules: Union[Unset, PutSandboxesSandboxIDNetworkBodyRules]
+ rules: Union[Unset, SandboxNetworkUpdateConfigRules]
if isinstance(_rules, Unset):
rules = UNSET
else:
- rules = PutSandboxesSandboxIDNetworkBodyRules.from_dict(_rules)
+ rules = SandboxNetworkUpdateConfigRules.from_dict(_rules)
- put_sandboxes_sandbox_id_network_body = cls(
+ sandbox_network_update_config = cls(
allow_out=allow_out,
allow_internet_access=allow_internet_access,
deny_out=deny_out,
rules=rules,
)
- put_sandboxes_sandbox_id_network_body.additional_properties = d
- return put_sandboxes_sandbox_id_network_body
+ sandbox_network_update_config.additional_properties = d
+ return sandbox_network_update_config
@property
def additional_keys(self) -> list[str]:
diff --git a/packages/python-sdk/e2b/api/client/models/put_sandboxes_sandbox_id_network_body_rules.py b/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config_rules.py
similarity index 87%
rename from packages/python-sdk/e2b/api/client/models/put_sandboxes_sandbox_id_network_body_rules.py
rename to packages/python-sdk/e2b/api/client/models/sandbox_network_update_config_rules.py
index 1af75b3cb..58d268a27 100644
--- a/packages/python-sdk/e2b/api/client/models/put_sandboxes_sandbox_id_network_body_rules.py
+++ b/packages/python-sdk/e2b/api/client/models/sandbox_network_update_config_rules.py
@@ -8,11 +8,11 @@ if TYPE_CHECKING:
from ..models.sandbox_network_rule import SandboxNetworkRule
-T = TypeVar("T", bound="PutSandboxesSandboxIDNetworkBodyRules")
+T = TypeVar("T", bound="SandboxNetworkUpdateConfigRules")
@_attrs_define
-class PutSandboxesSandboxIDNetworkBodyRules:
+class SandboxNetworkUpdateConfigRules:
"""Per-domain transform rules. Replaces all existing rules when provided."""
additional_properties: dict[str, list["SandboxNetworkRule"]] = _attrs_field(
@@ -34,7 +34,7 @@ class PutSandboxesSandboxIDNetworkBodyRules:
from ..models.sandbox_network_rule import SandboxNetworkRule
d = dict(src_dict)
- put_sandboxes_sandbox_id_network_body_rules = cls()
+ sandbox_network_update_config_rules = cls()
additional_properties = {}
for prop_name, prop_dict in d.items():
@@ -49,10 +49,10 @@ class PutSandboxesSandboxIDNetworkBodyRules:
additional_properties[prop_name] = additional_property
- put_sandboxes_sandbox_id_network_body_rules.additional_properties = (
+ sandbox_network_update_config_rules.additional_properties = (
additional_properties
)
- return put_sandboxes_sandbox_id_network_body_rules
+ return sandbox_network_update_config_rules
@property
def additional_keys(self) -> list[str]:
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index 32f9889ff..6ed58ed51 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -38,6 +38,12 @@ from e2b.api.client.models import (
from e2b.api.client.models import (
SandboxNetworkTransformHeaders as ClientSandboxNetworkTransformHeaders,
)
+from e2b.api.client.models import (
+ SandboxNetworkUpdateConfig,
+)
+from e2b.api.client.models import (
+ SandboxNetworkUpdateConfigRules,
+)
from e2b.api.client.types import Unset
from e2b.connection_config import ApiParams
from e2b.sandbox.mcp import McpServer as BaseMcpServer
@@ -196,6 +202,29 @@ class SandboxNetworkOpts(TypedDict):
"""
+class SandboxNetworkUpdate(TypedDict, total=False):
+ """
+ Subset of :class:`SandboxNetworkOpts` accepted by ``Sandbox.update_network``.
+ The update endpoint replaces all egress rules atomically — fields that are
+ omitted are cleared on the server.
+ """
+
+ allow_out: SandboxNetworkSelector
+ """See :attr:`SandboxNetworkOpts.allow_out`."""
+
+ deny_out: SandboxNetworkSelector
+ """See :attr:`SandboxNetworkOpts.deny_out`."""
+
+ rules: SandboxNetworkRules
+ """See :attr:`SandboxNetworkOpts.rules`."""
+
+ allow_internet_access: bool
+ """
+ Allow sandbox to access the internet. When set to ``False``, it behaves the
+ same as specifying ``deny_out=["0.0.0.0/0"]`` in the network config.
+ """
+
+
class SandboxNetworkInfo(TypedDict, total=False):
"""
Network configuration as returned by the sandbox info endpoint.
@@ -281,13 +310,15 @@ def _build_client_rules(rules: SandboxNetworkRules) -> SandboxNetworkConfigRules
return client_rules
-def build_network_config(
- network: Optional[SandboxNetworkOpts],
-) -> Optional[Dict[str, Any]]:
- """Resolve a :class:`SandboxNetworkOpts` into the dict the API expects."""
- if network is None:
- return None
-
+def _build_network_egress(
+ network: Mapping[str, Any],
+) -> 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.
+ """
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)
@@ -298,7 +329,23 @@ def build_network_config(
if deny_out is not None:
body["deny_out"] = deny_out
if "rules" in network and network["rules"] is not None:
- body["rules"] = _build_client_rules(network["rules"])
+ body["rules"] = _build_client_rules(network["rules"]).additional_properties
+
+ return body
+
+
+def build_network_config(
+ network: Optional[SandboxNetworkOpts],
+) -> Optional[Dict[str, Any]]:
+ """Resolve a :class:`SandboxNetworkOpts` into the dict the API expects."""
+ if network is None:
+ return None
+
+ body = _build_network_egress(network)
+ if "rules" in body:
+ client_rules = SandboxNetworkConfigRules()
+ client_rules.additional_properties = body["rules"]
+ body["rules"] = client_rules
if "allow_public_traffic" in network:
body["allow_public_traffic"] = network["allow_public_traffic"]
if "mask_request_host" in network:
@@ -307,6 +354,27 @@ def build_network_config(
return body
+def build_network_update_body(
+ network: SandboxNetworkUpdate,
+) -> SandboxNetworkUpdateConfig:
+ """Resolve a :class:`SandboxNetworkUpdate` into the API client body."""
+ egress = _build_network_egress(network)
+
+ body = SandboxNetworkUpdateConfig()
+ if "allow_out" in egress:
+ body.allow_out = egress["allow_out"]
+ if "deny_out" in egress:
+ body.deny_out = egress["deny_out"]
+ if "rules" in egress:
+ rules = SandboxNetworkUpdateConfigRules()
+ rules.additional_properties = egress["rules"]
+ body.rules = rules
+ if "allow_internet_access" in network:
+ body.allow_internet_access = network["allow_internet_access"]
+
+ return body
+
+
def from_client_network_config(
network: Union[Unset, ClientSandboxNetworkConfig],
) -> Optional[SandboxNetworkInfo]:
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 11a98923d..74e74dfa5 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -24,6 +24,7 @@ from e2b.sandbox.sandbox_api import (
SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
+ SandboxNetworkUpdate,
SnapshotInfo,
)
from e2b.sandbox.utils import class_method_variant
@@ -435,6 +436,60 @@ class AsyncSandbox(SandboxApi):
**self.connection_config.get_api_params(**opts),
)
+ @overload
+ async def update_network(
+ self,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ Update the network configuration of the sandbox.
+
+ Replaces the current egress configuration atomically — fields that are
+ omitted are cleared on the server.
+
+ :param network: New network configuration.
+ """
+ ...
+
+ @overload
+ @staticmethod
+ async def update_network(
+ sandbox_id: str,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ Update the network configuration of the sandbox specified by sandbox ID.
+
+ Replaces the current egress configuration atomically — fields that are
+ omitted are cleared on the server.
+
+ :param sandbox_id: Sandbox ID.
+ :param network: New network configuration.
+ """
+ ...
+
+ @class_method_variant("_cls_update_network")
+ async def update_network(
+ self,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ Update the network configuration of the sandbox.
+
+ Replaces the current egress configuration atomically — fields that are
+ omitted are cleared on the server.
+
+ :param network: New network configuration.
+ """
+ await SandboxApi._cls_update_network(
+ sandbox_id=self.sandbox_id,
+ network=network,
+ **self.connection_config.get_api_params(**opts),
+ )
+
@overload
async def get_info(
self,
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index 55085293a..a0159cb34 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -14,6 +14,7 @@ from e2b.api.client.api.sandboxes import (
post_sandboxes_sandbox_id_pause,
post_sandboxes_sandbox_id_snapshots,
post_sandboxes_sandbox_id_timeout,
+ put_sandboxes_sandbox_id_network,
)
from e2b.api.client.api.templates import delete_templates_template_id
from e2b.api.client.models import (
@@ -38,11 +39,13 @@ from e2b.exceptions import (
)
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
+ build_network_update_body,
McpServer,
SandboxInfo,
SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
+ SandboxNetworkUpdate,
SandboxQuery,
SnapshotInfo,
build_network_config,
@@ -160,6 +163,28 @@ class SandboxApi(SandboxBase):
if res.status_code >= 300:
raise handle_api_exception(res)
+ @classmethod
+ async def _cls_update_network(
+ cls,
+ sandbox_id: str,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ config = ConnectionConfig(**opts)
+
+ api_client = get_api_client(config)
+ res = await put_sandboxes_sandbox_id_network.asyncio_detailed(
+ sandbox_id,
+ client=api_client,
+ body=build_network_update_body(network),
+ )
+
+ if res.status_code == 404:
+ raise SandboxNotFoundException(f"Sandbox {sandbox_id} not found")
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
@classmethod
async def _create_sandbox(
cls,
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index f00d1b71c..6f2a03625 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -24,6 +24,7 @@ from e2b.sandbox.sandbox_api import (
SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
+ SandboxNetworkUpdate,
SnapshotInfo,
)
from e2b.sandbox.utils import class_method_variant
@@ -436,6 +437,61 @@ class Sandbox(SandboxApi):
**self.connection_config.get_api_params(**opts),
)
+ @overload
+ def update_network(
+ self,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ Update the network configuration of the sandbox.
+
+ Replaces the current egress configuration atomically — fields that are
+ omitted are cleared on the server.
+
+ :param network: New network configuration.
+ """
+ ...
+
+ @overload
+ @staticmethod
+ def update_network(
+ sandbox_id: str,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ Update the network configuration of the sandbox specified by sandbox ID.
+
+ Replaces the current egress configuration atomically — fields that are
+ omitted are cleared on the server.
+
+ :param sandbox_id: Sandbox ID.
+ :param network: New network configuration.
+ """
+ ...
+
+ @class_method_variant("_cls_update_network")
+ def update_network(
+ self,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ Update the network configuration of the sandbox.
+
+ Replaces the current egress configuration atomically — fields that are
+ omitted are cleared on the server.
+
+ :param network: New network configuration.
+ """
+
+ SandboxApi._cls_update_network(
+ sandbox_id=self.sandbox_id,
+ network=network,
+ **self.connection_config.get_api_params(**opts),
+ )
+
@overload
def get_info(
self,
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index b8b923a22..93cbbed6f 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -14,6 +14,7 @@ from e2b.api.client.api.sandboxes import (
post_sandboxes_sandbox_id_pause,
post_sandboxes_sandbox_id_snapshots,
post_sandboxes_sandbox_id_timeout,
+ put_sandboxes_sandbox_id_network,
)
from e2b.api.client.api.templates import delete_templates_template_id
from e2b.api.client.models import (
@@ -37,11 +38,13 @@ from e2b.exceptions import (
)
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
+ build_network_update_body,
McpServer,
SandboxInfo,
SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
+ SandboxNetworkUpdate,
SandboxQuery,
SnapshotInfo,
build_network_config,
@@ -159,6 +162,28 @@ class SandboxApi(SandboxBase):
if res.status_code >= 300:
raise handle_api_exception(res)
+ @classmethod
+ def _cls_update_network(
+ cls,
+ sandbox_id: str,
+ network: SandboxNetworkUpdate,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ config = ConnectionConfig(**opts)
+
+ api_client = get_api_client(config)
+ res = put_sandboxes_sandbox_id_network.sync_detailed(
+ sandbox_id,
+ client=api_client,
+ body=build_network_update_body(network),
+ )
+
+ if res.status_code == 404:
+ raise SandboxNotFoundException(f"Sandbox {sandbox_id} not found")
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
@classmethod
def _create_sandbox(
cls,
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 92227a421..7c77c2dff 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_network.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_network.py
@@ -191,6 +191,63 @@ async def test_firewall_transform_injects_headers(async_sandbox_factory):
)
+async def test_update_network_applies_restrictions(async_sandbox_factory):
+ """update_network can add egress restrictions to a running sandbox."""
+ async_sandbox = await async_sandbox_factory()
+
+ # Baseline: 8.8.8.8 reachable.
+ before = await async_sandbox.commands.run(
+ "curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8"
+ )
+ assert before.exit_code == 0
+
+ await async_sandbox.update_network({"deny_out": ["8.8.8.8"]})
+
+ # 8.8.8.8 is now denied.
+ with pytest.raises(CommandExitException) as exc_info:
+ await async_sandbox.commands.run(
+ "curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8"
+ )
+ assert exc_info.value.exit_code != 0
+
+ # Other destinations stay reachable.
+ result = await async_sandbox.commands.run(
+ "curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
+ )
+ assert result.exit_code == 0
+
+
+async def test_update_network_clears_existing_rules(async_sandbox_factory):
+ """update_network replaces all egress rules; omitted fields are cleared."""
+ async_sandbox = await async_sandbox_factory(
+ network=SandboxNetworkOpts(
+ deny_out=lambda ctx: [ctx.all_traffic],
+ allow_out=["1.1.1.1"],
+ )
+ )
+
+ # Baseline from create-time config: 8.8.8.8 denied.
+ with pytest.raises(CommandExitException):
+ await async_sandbox.commands.run(
+ "curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8"
+ )
+
+ # Empty update clears allow_out / deny_out entirely.
+ await async_sandbox.update_network({})
+
+ r1 = await async_sandbox.commands.run(
+ "curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
+ )
+ assert r1.exit_code == 0
+
+ r2 = await async_sandbox.commands.run(
+ "curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8"
+ )
+ assert r2.exit_code == 0
+
+
@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 7edfae5c5..ab6aa97bd 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
@@ -189,6 +189,59 @@ def test_firewall_transform_injects_headers(sandbox_factory):
)
+def test_update_network_applies_restrictions(sandbox_factory):
+ """update_network can add egress restrictions to a running sandbox."""
+ sandbox = sandbox_factory()
+
+ # Baseline: 8.8.8.8 reachable.
+ before = sandbox.commands.run(
+ "curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8"
+ )
+ assert before.exit_code == 0
+
+ sandbox.update_network({"deny_out": ["8.8.8.8"]})
+
+ # 8.8.8.8 is now denied.
+ with pytest.raises(CommandExitException) as exc_info:
+ sandbox.commands.run(
+ "curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8"
+ )
+ assert exc_info.value.exit_code != 0
+
+ # Other destinations stay reachable.
+ result = sandbox.commands.run(
+ "curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1"
+ )
+ assert result.exit_code == 0
+
+
+def test_update_network_clears_existing_rules(sandbox_factory):
+ """update_network replaces all egress rules; omitted fields are cleared."""
+ sandbox = sandbox_factory(
+ network=SandboxNetworkOpts(
+ deny_out=lambda ctx: [ctx.all_traffic],
+ allow_out=["1.1.1.1"],
+ )
+ )
+
+ # Baseline from create-time config: 8.8.8.8 denied.
+ with pytest.raises(CommandExitException):
+ sandbox.commands.run(
+ "curl --connect-timeout 3 --max-time 5 -Is https://8.8.8.8"
+ )
+
+ # Empty update clears allow_out / deny_out entirely.
+ sandbox.update_network({})
+
+ r1 = sandbox.commands.run("curl -s -o /dev/null -w '%{http_code}' https://1.1.1.1")
+ assert r1.exit_code == 0
+
+ r2 = sandbox.commands.run("curl -s -o /dev/null -w '%{http_code}' https://8.8.8.8")
+ assert r2.exit_code == 0
+
+
@pytest.mark.skip_debug()
def test_mask_request_host(sandbox_factory):
"""Test that mask_request_host modifies the Host header correctly."""
diff --git a/spec/openapi.yml b/spec/openapi.yml
index 464efe67c..87b369ad7 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -290,6 +290,33 @@ components:
items:
$ref: '#/components/schemas/SandboxNetworkRule'
+ SandboxNetworkUpdateConfig:
+ type: object
+ description: Network configuration update for a running sandbox. Replaces the current egress rules with the provided configuration. Omitting a field clears it.
+ properties:
+ allowOut:
+ type: array
+ description: List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries.
+ items:
+ type: string
+ denyOut:
+ type: array
+ description: List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules.
+ items:
+ type: string
+ rules:
+ type: object
+ description: Per-domain transform rules. Replaces all existing rules when provided.
+ additionalProperties:
+ type: array
+ items:
+ $ref: '#/components/schemas/SandboxNetworkRule'
+ allow_internet_access:
+ type: boolean
+ description:
+ Allow sandbox to access the internet. When set to false, it behaves the same as specifying denyOut
+ to 0.0.0.0/0 in the network config.
+
SandboxNetworkRule:
type: object
description: Transform rule applied to egress requests matching a domain pattern.
@@ -2386,7 +2413,7 @@ paths:
/sandboxes/{sandboxID}/network:
put:
- description: Update the network configuration for a running sandbox. Replaces the current egress rules with the provided configuration. Omitting both fields clears all egress rules.
+ description: Update the network configuration for a running sandbox. Replaces the current egress rules with the provided configuration. Omitting a field clears it.
security:
- ApiKeyAuth: []
- Supabase1TokenAuth: []
@@ -2397,30 +2424,7 @@ paths:
content:
application/json:
schema:
- type: object
- properties:
- allowOut:
- type: array
- description: List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries.
- items:
- type: string
- denyOut:
- type: array
- description: List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules.
- items:
- type: string
- rules:
- type: object
- description: Per-domain transform rules. Replaces all existing rules when provided.
- additionalProperties:
- type: array
- items:
- $ref: '#/components/schemas/SandboxNetworkRule'
- allow_internet_access:
- type: boolean
- description:
- Allow sandbox to access the internet. When set to false, it behaves the same as specifying denyOut
- to 0.0.0.0/0 in the network config.
+ $ref: '#/components/schemas/SandboxNetworkUpdateConfig'
parameters:
- $ref: '#/components/parameters/sandboxID'
responses: