Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Allow to block network from SDK (#834)
Jakub Novákf123091e9a35
diff --git a/.changeset/fresh-jobs-rush.md b/.changeset/fresh-jobs-rush.mdnew file mode 100644index 000000000..a8f8d6c3d--- /dev/null+++ b/.changeset/fresh-jobs-rush.md@@ -0,0 +1,6 @@+---+'@e2b/python-sdk': minor+'e2b': minor+---++Add possibility to use without internetdiff --git a/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdxindex 12939b6a2..323201f12 100644--- a/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdx@@ -2,6 +2,32 @@Every sandbox has access to the internet and can be reached by a public URL.+## Controlling internet access++You can control whether a sandbox has access to the internet by using the `allowInternetAccess` parameter when creating a sandbox. By default, internet access is enabled (`true`), but you can disable it for security-sensitive workloads.++<CodeGroup>+```js+import { Sandbox } from '@e2b/code-interpreter'++// Create sandbox with internet access enabled (default)+const sandbox = await Sandbox.create({ allowInternetAccess: true })++// Create sandbox without internet access+const isolatedSandbox = await Sandbox.create({ allowInternetAccess: false })+```+```python+from e2b_code_interpreter import Sandbox++# Create sandbox with internet access enabled (default)+sandbox = Sandbox(allow_internet_access=True)++# Create sandbox without internet access+isolated_sandbox = Sandbox(allow_internet_access=False)+```+</CodeGroup>++When internet access is disabled, the sandbox cannot make outbound network connections, which provides an additional layer of security for sensitive code execution.## Sandbox public URLEvery sandbox has a public URL that can be used to access running services inside the sandbox.diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.tsindex f02f8ffb7..bf874c5cb 100644--- a/packages/js-sdk/src/api/schema.gen.ts+++ b/packages/js-sdk/src/api/schema.gen.ts@@ -1035,6 +1035,8 @@ export interface components {name: string;};NewSandbox: {+ /** @description Allow sandbox to access the internet */+ allow_internet_access?: boolean;/*** @description Automatically pauses the sandbox after the timeout* @default falsediff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.tsindex ac07d6bf3..fa7a0a5be 100644--- a/packages/js-sdk/src/index.ts+++ b/packages/js-sdk/src/index.ts@@ -32,7 +32,7 @@ export type {PtyOutput,CommandHandle,} from './sandbox/commands/commandHandle'-export type { SandboxApiOpts } from './sandbox/sandboxApi'+export type { SandboxApiOpts, SandboxCreateOpts } from './sandbox/sandboxApi'export type {ProcessInfo,diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex 321dab312..3801f02f1 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -50,6 +50,13 @@ export interface SandboxOpts extends ConnectionOpts {* @default false*/secure?: boolean++ /**+ * Allow sandbox to access the internet+ *+ * @default true+ */+ allowInternetAccess?: boolean}/**@@ -170,8 +177,8 @@ export class Sandbox extends SandboxApi {// E2B endpoints should be safe to use with redirect: "follow" https://github.com/e2b-dev/E2B/issues/531#issuecomment-2779492867const headers = new Headers(this.connectionConfig.headers)- new Headers(options?.headers).forEach(- (value, key) => headers.append(key, value)+ new Headers(options?.headers).forEach((value, key) =>+ headers.append(key, value))if (this.envdAccessToken) {diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsindex 1c3579545..7dac6d823 100644--- a/packages/js-sdk/src/sandbox/sandboxApi.ts+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -14,6 +14,31 @@ export interface SandboxApiOpts>> {}+/**+ * Options for create sandbox request.+ */+export interface SandboxCreateOpts extends SandboxApiOpts {+ /**+ * Custom metadata for the sandbox+ */+ metadata?: Record<string, string>++ /**+ * Custom environment variables for the sandbox+ */+ envs?: Record<string, string>++ /**+ * Envd is secured with access token and cannot be used without it+ */+ secure?: boolean++ /**+ * Allow sandbox to access the internet, defaults to `true`.+ */+ allowInternetAccess?: boolean+}+export interface SandboxListOpts extends SandboxApiOpts {/*** Filter the list of sandboxes, e.g. by metadata `metadata:{"key": "value"}`, if there are multiple filters they are combined with AND.@@ -397,11 +422,7 @@ export class SandboxApi {protected static async createSandbox(template: string,timeoutMs: number,- opts?: SandboxApiOpts & {- metadata?: Record<string, string>- envs?: Record<string, string>- secure?: boolean- }+ opts?: SandboxCreateOpts): Promise<{sandboxId: stringsandboxDomain?: string@@ -419,6 +440,7 @@ export class SandboxApi {envVars: opts?.envs,timeout: this.timeoutToSeconds(timeoutMs),secure: opts?.secure,+ allow_internet_access: opts?.allowInternetAccess ?? true,},signal: config.getSignal(opts?.requestTimeoutMs),})diff --git a/packages/js-sdk/tests/sandbox/internetAccess.test.ts b/packages/js-sdk/tests/sandbox/internetAccess.test.tsnew file mode 100644index 000000000..cf704cfc0--- /dev/null+++ b/packages/js-sdk/tests/sandbox/internetAccess.test.ts@@ -0,0 +1,56 @@+import { assert, test } from 'vitest'++import { CommandExitError, Sandbox } from '../../src'+import { template, isDebug } from '../setup.js'++test.skipIf(isDebug)('internet access enabled', async () => {+ const sbx = await Sandbox.create(template, {+ allowInternetAccess: true,+ })+ try {+ // Test internet connectivity by making a curl request to a reliable external site+ const result = await sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert.equal(result.exitCode, 0)+ assert.equal(result.stdout.trim(), '200')+ } finally {+ await sbx.kill()+ }+})++test.skipIf(isDebug)('internet access disabled', async () => {+ const sbx = await Sandbox.create(template, {+ allowInternetAccess: false,+ })+ try {+ // Test that internet connectivity is blocked by making a curl request+ try {+ await sbx.commands.run(+ 'curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev'+ )+ // If we reach here, the command succeeded, which means internet access is not properly disabled+ assert.fail('Expected command to fail when internet access is disabled')+ } catch (error) {+ // The command should fail or timeout when internet access is disabled+ assert.isTrue(error instanceof CommandExitError)+ assert.notEqual(error.exitCode, 0)+ }+ } finally {+ await sbx.kill()+ }+})++test.skipIf(isDebug)('internet access default', async () => {+ const sbx = await Sandbox.create(template)+ try {+ // Test internet connectivity by making a curl request to a reliable external site+ const result = await sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert.equal(result.exitCode, 0)+ assert.equal(result.stdout.trim(), '200')+ } finally {+ await sbx.kill()+ }+})diff --git a/packages/python-sdk/e2b/api/client/models/new_sandbox.py b/packages/python-sdk/e2b/api/client/models/new_sandbox.pyindex 7c59167bd..70c2f9117 100644--- a/packages/python-sdk/e2b/api/client/models/new_sandbox.py+++ b/packages/python-sdk/e2b/api/client/models/new_sandbox.py@@ -14,6 +14,7 @@ class NewSandbox:"""Attributes:template_id (str): Identifier of the required template+ allow_internet_access (Union[Unset, bool]): Allow sandbox to access the internetauto_pause (Union[Unset, bool]): Automatically pauses the sandbox after the timeout Default: False.env_vars (Union[Unset, Any]):metadata (Union[Unset, Any]):@@ -22,6 +23,7 @@ class NewSandbox:"""template_id: str+ allow_internet_access: Union[Unset, bool] = UNSETauto_pause: Union[Unset, bool] = Falseenv_vars: Union[Unset, Any] = UNSETmetadata: Union[Unset, Any] = UNSET@@ -32,6 +34,8 @@ class NewSandbox:def to_dict(self) -> dict[str, Any]:template_id = self.template_id+ allow_internet_access = self.allow_internet_access+auto_pause = self.auto_pauseenv_vars = self.env_vars@@ -49,6 +53,8 @@ class NewSandbox:"templateID": template_id,})+ if allow_internet_access is not UNSET:+ field_dict["allow_internet_access"] = allow_internet_accessif auto_pause is not UNSET:field_dict["autoPause"] = auto_pauseif env_vars is not UNSET:@@ -67,6 +73,8 @@ class NewSandbox:d = dict(src_dict)template_id = d.pop("templateID")+ allow_internet_access = d.pop("allow_internet_access", UNSET)+auto_pause = d.pop("autoPause", UNSET)env_vars = d.pop("envVars", UNSET)@@ -79,6 +87,7 @@ class NewSandbox:new_sandbox = cls(template_id=template_id,+ allow_internet_access=allow_internet_access,auto_pause=auto_pause,env_vars=env_vars,metadata=metadata,diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.pyindex 69a591658..e2a4d8f71 100644--- a/packages/python-sdk/e2b/sandbox_async/main.py+++ b/packages/python-sdk/e2b/sandbox_async/main.py@@ -209,6 +209,7 @@ class AsyncSandbox(SandboxSetup, SandboxApi):request_timeout: Optional[float] = None,proxy: Optional[ProxyTypes] = None,secure: Optional[bool] = None,+ allow_internet_access: Optional[bool] = True,):"""Create a new sandbox.@@ -223,6 +224,7 @@ class AsyncSandbox(SandboxSetup, SandboxApi)::param request_timeout: Timeout for the request in **seconds**:param proxy: Proxy to use for the request and for the **requests made to the returned sandbox**:param secure: Envd is secured with access token and cannot be used without it+ :param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.:return: sandbox instance for the new sandbox@@ -248,6 +250,7 @@ class AsyncSandbox(SandboxSetup, SandboxApi):env_vars=envs,secure=secure,proxy=proxy,+ allow_internet_access=allow_internet_access,)sandbox_id = response.sandbox_iddiff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex 200fab131..bddc6886c 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -261,6 +261,7 @@ class SandboxApi(SandboxApiBase):request_timeout: Optional[float] = None,headers: Optional[Dict[str, str]] = None,proxy: Optional[ProxyTypes] = None,+ allow_internet_access: Optional[bool] = True,) -> SandboxCreateResponse:config = ConnectionConfig(api_key=api_key,@@ -282,6 +283,7 @@ class SandboxApi(SandboxApiBase):timeout=timeout,env_vars=env_vars or {},secure=secure or False,+ allow_internet_access=allow_internet_access,),client=api_client,)diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.pyindex bbe99b01b..412eb2569 100644--- a/packages/python-sdk/e2b/sandbox_sync/main.py+++ b/packages/python-sdk/e2b/sandbox_sync/main.py@@ -122,6 +122,7 @@ class Sandbox(SandboxSetup, SandboxApi):sandbox_id: Optional[str] = None,request_timeout: Optional[float] = None,proxy: Optional[ProxyTypes] = None,+ allow_internet_access: Optional[bool] = True,):"""Create a new sandbox.@@ -135,6 +136,7 @@ class Sandbox(SandboxSetup, SandboxApi)::param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable:param request_timeout: Timeout for the request in **seconds**:param proxy: Proxy to use for the request and for the **requests made to the returned sandbox**+ :param allow_internet_access: Allow sandbox to access the internet, defaults to `True`:return: sandbox instance for the new sandbox"""@@ -186,6 +188,7 @@ class Sandbox(SandboxSetup, SandboxApi):request_timeout=request_timeout,secure=secure or False,proxy=proxy,+ allow_internet_access=allow_internet_access,)self._sandbox_id = response.sandbox_iddiff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex 109d3235c..42dbe33ae 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -256,6 +256,7 @@ class SandboxApi(SandboxApiBase):request_timeout: Optional[float] = None,headers: Optional[Dict[str, str]] = None,proxy: Optional[ProxyTypes] = None,+ allow_internet_access: Optional[bool] = True,) -> SandboxCreateResponse:config = ConnectionConfig(api_key=api_key,@@ -274,6 +275,7 @@ class SandboxApi(SandboxApiBase):timeout=timeout,env_vars=env_vars or {},secure=secure or False,+ allow_internet_access=allow_internet_access,),client=api_client,)diff --git a/packages/python-sdk/tests/async/sandbox_async/test_internet_access.py b/packages/python-sdk/tests/async/sandbox_async/test_internet_access.pynew file mode 100644index 000000000..8065472f6--- /dev/null+++ b/packages/python-sdk/tests/async/sandbox_async/test_internet_access.py@@ -0,0 +1,51 @@+import pytest++from e2b import AsyncSandbox+from e2b.sandbox.commands.command_handle import CommandExitException++[email protected]_debug()+async def test_internet_access_enabled(template):+ """Test that sandbox with internet access enabled can reach external websites."""+ sbx = await AsyncSandbox.create(template, allow_internet_access=True)+ try:+ # Test internet connectivity by making a curl request to a reliable external site+ result = await sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"+ finally:+ await sbx.kill()++[email protected]_debug()+async def test_internet_access_disabled(template):+ """Test that sandbox with internet access disabled cannot reach external websites."""+ sbx = await AsyncSandbox.create(template, allow_internet_access=False)+ try:+ # Test that internet connectivity is blocked by making a curl request+ with pytest.raises(CommandExitException) as exc_info:+ await sbx.commands.run(+ "curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev"+ )+ # The command should fail or timeout when internet access is disabled+ assert exc_info.value.exit_code != 0++ finally:+ await sbx.kill()++[email protected]_debug()+async def test_internet_access_default(template):+ """Test that sandbox with default settings (no explicit allow_internet_access) has internet access."""+ sbx = await AsyncSandbox.create(template)+ try:+ # Test internet connectivity by making a curl request to a reliable external site+ result = await sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"+ finally:+ await sbx.kill()diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.py b/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.pynew file mode 100644index 000000000..bbfce8d0d--- /dev/null+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.py@@ -0,0 +1,51 @@+import pytest++from e2b import Sandbox+from e2b.sandbox.commands.command_handle import CommandExitException++[email protected]_debug()+def test_internet_access_enabled(template):+ """Test that sandbox with internet access enabled can reach external websites."""+ sbx = Sandbox(template, allow_internet_access=True)+ try:+ # Test internet connectivity by making a curl request to a reliable external site+ result = sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"+ finally:+ sbx.kill()++[email protected]_debug()+def test_internet_access_disabled(template):+ """Test that sandbox with internet access disabled cannot reach external websites."""+ sbx = Sandbox(template, allow_internet_access=False)+ try:+ # Test that internet connectivity is blocked by making a curl request+ with pytest.raises(CommandExitException) as exc_info:+ sbx.commands.run(+ "curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev"+ )+ # The command should fail or timeout when internet access is disabled+ assert exc_info.value.exit_code != 0++ finally:+ sbx.kill()++[email protected]_debug()+def test_internet_access_default(template):+ """Test that sandbox with default settings (no explicit allow_internet_access) has internet access."""+ sbx = Sandbox(template)+ try:+ # Test internet connectivity by making a curl request to a reliable external site+ result = sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"+ finally:+ sbx.kill()diff --git a/spec/openapi.yml b/spec/openapi.ymlindex c24d683be..8bc6cee96 100644--- a/spec/openapi.yml+++ b/spec/openapi.yml@@ -386,6 +386,9 @@ components:secure:type: booleandescription: Secure all system communication with sandbox+ allow_internet_access:+ type: boolean+ description: Allow sandbox to access the internetmetadata:$ref: "#/components/schemas/SandboxMetadata"envVars:@@ -1379,6 +1382,68 @@ paths:"500":$ref: "#/components/responses/500"+ /v2/templates:+ post:+ description: Create a new template+ tags: [templates]+ security:+ - AccessTokenAuth: []+ - ApiKeyAuth: []+ - Supabase1TokenAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/TemplateBuildRequestV2"++ responses:+ "202":+ description: The build was requested successfully+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Template"+ "400":+ $ref: "#/components/responses/400"+ "401":+ $ref: "#/components/responses/401"+ "500":+ $ref: "#/components/responses/500"++ /templates/{templateID}/files/{hash}:+ get:+ description: Get an upload link for a tar file containing build layer files+ tags: [templates]+ security:+ - AccessTokenAuth: []+ - ApiKeyAuth: []+ - Supabase1TokenAuth: []+ parameters:+ - $ref: "#/components/parameters/templateID"+ - in: path+ name: hash+ required: true+ schema:+ type: string+ description: Hash of the files++ responses:+ "201":+ description: The upload link where to upload the tar file+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/TemplateBuildFileUpload"+ "400":+ $ref: "#/components/responses/400"+ "401":+ $ref: "#/components/responses/401"+ "404":+ $ref: "#/components/responses/404"+ "500":+ $ref: "#/components/responses/500"+/templates:get:description: List all templates@@ -1543,6 +1608,31 @@ paths:"500":$ref: "#/components/responses/500"+ /v2/templates/{templateID}/builds/{buildID}:+ post:+ description: Start the build+ tags: [templates]+ security:+ - AccessTokenAuth: []+ - ApiKeyAuth: []+ - Supabase1TokenAuth: []+ parameters:+ - $ref: "#/components/parameters/templateID"+ - $ref: "#/components/parameters/buildID"+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/TemplateBuildStartV2"+ responses:+ "202":+ description: The build has started+ "401":+ $ref: "#/components/responses/401"+ "500":+ $ref: "#/components/responses/500"+/templates/{templateID}/builds/{buildID}/status:get:description: Get template build info