Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
fix: reject unrecognized onTimeout and onResume values (#1822)
Babis Chalios58c81f1019e3
diff --git a/.changeset/validate-lifecycle-enums.md b/.changeset/validate-lifecycle-enums.mdnew file mode 100644index 000000000..6946097fa--- /dev/null+++ b/.changeset/validate-lifecycle-enums.md@@ -0,0 +1,6 @@+---+'e2b': patch+'@e2b/python-sdk': patch+---++`onTimeout` / `on_timeout` and `onResume` / `on_resume` now raise `InvalidArgumentError` / `InvalidArgumentException` for a value outside their two literals, instead of silently resolving it to the other one. Both are resolved into a boolean before the request is built, so the value never reaches the API and a typo cannot be rejected server-side: `on_timeout="Pause"` previously resolved to `kill` and deleted the sandbox and its snapshot at timeout, and `on_resume="Reboot"` previously restored the memory the caller asked to skip. A nullish value still means "not configured" and leaves the choice to the API.diff --git a/packages/desktop-python/uv.lock b/packages/desktop-python/uv.lockindex 9acf4fbb5..9950a670b 100644--- a/packages/desktop-python/uv.lock+++ b/packages/desktop-python/uv.lock@@ -352,7 +352,7 @@ wheels = [[[package]]name = "e2b"-version = "2.46.4"+version = "2.47.0"source = { editable = "../python-sdk" }dependencies = [{ name = "attrs" },@@ -487,7 +487,7 @@ name = "exceptiongroup"version = "1.3.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "typing-extensions", marker = "python_full_version < '3.13'" },+ { name = "typing-extensions" },]sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }wheels = [diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsindex be60ab1fb..e2f822793 100644--- a/packages/js-sdk/src/sandbox/sandboxApi.ts+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -456,6 +456,8 @@ export type SandboxLifecycle = {* `'kill'`, or `{ action, keepMemory }` to also control the pause snapshot kind.* Omitted from the create request when unset, leaving the API's default* (currently `kill`) in effect.+ *+ * @throws {@link InvalidArgumentError} if the action is outside the two literals.*/onTimeout: SandboxOnTimeout@@ -693,6 +695,7 @@ export type SandboxConnectOpts = ConnectionOpts & {* already running.** @default 'restore'+ * @throws {@link InvalidArgumentError} if the value is outside the two literals.*/onResume?: SandboxOnResume}@@ -1645,6 +1648,19 @@ export class SandboxApi extends ClientFactory {const onTimeoutConfigured = requestedOnTimeout != nullconst onTimeout = requestedOnTimeout ?? 'kill'const action = typeof onTimeout === 'string' ? onTimeout : onTimeout.action+ const allowedActions = ['pause', 'kill']+ if (onTimeoutConfigured && !allowedActions.includes(action)) {+ // Name the field the caller wrote: the object form's bad value is on+ // `.action`, not on `onTimeout` itself.+ const field =+ typeof onTimeout === 'string' ? 'onTimeout' : 'onTimeout.action'+ throw new InvalidArgumentError(+ `${field} must be one of: ${allowedActions.join(', ')} (got ${JSON.stringify(action)}).`+ )+ }+ // The action never reaches the API — it is resolved here into the boolean+ // autoPause — so an unrecognized value cannot be rejected server-side, and+ // resolving it to kill would delete the sandbox a caller asked to preserve.const hasKeepMemory =typeof onTimeout !== 'string' && 'keepMemory' in onTimeoutconst keepMemory =@@ -1809,6 +1825,18 @@ export class SandboxApi extends ClientFactory {const config = new ConnectionConfig(apiOpts)const client = new ApiClient(config)+ // A nullish value is not a choice of restore, matching every other nullish+ // option. Any other value outside the union never reaches the API — it is+ // resolved here into the boolean memory field — so it cannot be rejected+ // server-side, and resolving it to restore would silently skip the reboot.+ const onResume = apiOpts?.onResume ?? undefined+ const allowedOnResume = ['restore', 'reboot']+ if (onResume !== undefined && !allowedOnResume.includes(onResume)) {+ throw new InvalidArgumentError(+ `onResume must be one of: ${allowedOnResume.join(', ')} (got ${JSON.stringify(onResume)}).`+ )+ }+const res = await client.api.POST('/sandboxes/{sandboxID}/connect', {params: {path: {@@ -1817,7 +1845,7 @@ export class SandboxApi extends ClientFactory {},body: {timeout: timeoutToSeconds(timeoutMs),- memory: apiOpts?.onResume === 'reboot' ? false : undefined,+ memory: onResume === 'reboot' ? false : undefined,},signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),})diff --git a/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts b/packages/js-sdk/tests/sandbox/lifecycleRequest.test.tsindex e3c5bb6ce..12fe5d5f0 100644--- a/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts+++ b/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts@@ -154,3 +154,50 @@ test('an explicit null autoResume from an untyped caller is omitted', async () =expect(lastCreateBody).not.toHaveProperty('autoResume')})++// onTimeout is resolved into the boolean autoPause before the request is built,+// so the API never sees the action and cannot reject a typo. Resolving it to+// kill would delete a sandbox the caller asked to preserve.+const unrecognizedOnTimeout = [+ 'Pause',+ 'PAUSE',+ 'pause\n',+ 'paused',+ true,+ { action: 'Pause' },+ {},+]++test.for(unrecognizedOnTimeout)(+ 'an unrecognized onTimeout %o is rejected',+ async (onTimeout) => {+ await expect(+ Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ // @ts-expect-error deliberately outside the union+ lifecycle: { onTimeout },+ })+ ).rejects.toThrowError(InvalidArgumentError)++ expect(lastCreateBody).toBeUndefined()+ }+)++test.for([+ ['Pause', 'onTimeout'],+ [{ action: 'Pause' }, 'onTimeout.action'],+ [{}, 'onTimeout.action'],+] as const)(+ 'the error for %o names the field the caller wrote',+ async ([onTimeout, expectedField]) => {+ await expect(+ Sandbox.create('base', {+ apiKey: TEST_API_KEY,+ // @ts-expect-error deliberately outside the union+ lifecycle: { onTimeout },+ })+ ).rejects.toThrowError(+ new RegExp(`^${expectedField.replace('.', '\\.')} must be one of`)+ )+ }+)diff --git a/packages/js-sdk/tests/sandbox/onResumeRequest.test.ts b/packages/js-sdk/tests/sandbox/onResumeRequest.test.tsindex f62a4dd35..4f3edcd10 100644--- a/packages/js-sdk/tests/sandbox/onResumeRequest.test.ts+++ b/packages/js-sdk/tests/sandbox/onResumeRequest.test.ts@@ -2,7 +2,7 @@ import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'import { http, HttpResponse } from 'msw'import { setupServer } from 'msw/node'-import { Sandbox } from '../../src'+import { InvalidArgumentError, Sandbox } from '../../src'import { TEST_API_KEY, apiUrl } from '../setup'let lastConnectBody: Record<string, unknown> | undefined@@ -67,14 +67,40 @@ test('sandbox.connect carries onResume on the instance form too', async () => {expect(lastConnectBody).not.toHaveProperty('memory')})-test('an untyped onResume value never sends memory: false', async () => {- // Untyped callers can pass anything; only the 'reboot' literal opts into a- // cold boot, so an unrecognized value must fall back to a memory restore.+test('a nullish onResume is treated as absent', async () => {await Sandbox.connect('test-sandbox-id', {apiKey: TEST_API_KEY,- // @ts-expect-error 'Reboot' is not a valid onResume value- onResume: 'Reboot',+ // @ts-expect-error null is not a valid onResume value+ onResume: null,})expect(lastConnectBody).not.toHaveProperty('memory')})++// The option is resolved into a boolean before the request is built, so the API+// never sees it and cannot reject a typo. Falling back to a restore would+// silently skip the reboot the caller asked for.+const unrecognized = [+ 'Reboot',+ 'REBOOT',+ 'reboot\n',+ ' reboot',+ 'rebooted',+ false,+ 0,+]++test.for(unrecognized)(+ 'an unrecognized onResume %o is rejected',+ async (value) => {+ await expect(+ Sandbox.connect('test-sandbox-id', {+ apiKey: TEST_API_KEY,+ // @ts-expect-error deliberately outside the union+ onResume: value,+ })+ ).rejects.toThrowError(InvalidArgumentError)++ expect(lastConnectBody).toBeUndefined()+ }+)diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.pyindex f8302eadc..d8e14ca39 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py@@ -539,7 +539,8 @@ class SandboxLifecycle(TypedDict):What should happen to the sandbox when timeout is reached. `"kill"` terminatesthe sandbox; `"pause"` pauses it for later resume. Accepts either the bareaction or an object `{"action": "pause", "keep_memory": ...}` /- `{"action": "kill"}` to also control the pause snapshot kind. Omitted from the+ `{"action": "kill"}` to also control the pause snapshot kind. A value outside+ the two actions raises `InvalidArgumentException`. Omitted from thecreate request when unset, leaving the API's default (currently `"kill"`) ineffect."""@@ -570,6 +571,28 @@ class SandboxInfoLifecycle(TypedDict):"""+def resolve_connect_memory(+ on_resume: Optional["SandboxOnResume"],+) -> Union[Unset, bool]:+ """Resolve ``on_resume`` into ``ConnectSandbox.memory``.++ ``"restore"`` is the API's own default, so it travels as an omitted field.+ """+ # A nullish value is not a choice of restore, matching how every other+ # nullish option is treated. Any other value outside the union never reaches+ # the API — it is resolved here into the boolean memory field — so it cannot+ # be rejected server-side, and resolving it to restore would silently skip+ # the reboot the caller asked for.+ if on_resume is None:+ return UNSET+ allowed = ("restore", "reboot")+ if on_resume not in allowed:+ raise InvalidArgumentException(+ f"on_resume must be one of: {', '.join(allowed)} (got {on_resume!r})."+ )+ return False if on_resume == "reboot" else UNSET++SandboxOnResume = Literal["restore", "reboot"]"""How a paused sandbox comes back.@@ -824,16 +847,14 @@ def build_lifecycle_config(unset unless the caller chose ``keep_memory``."""# on_timeout accepts a bare action or {"action", "keep_memory"}; normalize.- # Only the object form carries keep_memory; anything else (a bare action- # string, or an unexpected value from an untyped caller) passes through as- # the action, so a non-"pause" value resolves to kill instead of crashing.+ # Only the object form carries keep_memory.on_timeout_raw = lifecycle.get("on_timeout") if lifecycle else None# A missing on_timeout — or an explicit None from an untyped caller — is not# a choice of kill. It only resolves to kill semantics locally, for the# validation below and for keep_memory.on_timeout_configured = on_timeout_raw is not Noneif isinstance(on_timeout_raw, dict):- on_timeout = on_timeout_raw.get("action", "kill")+ on_timeout = on_timeout_raw.get("action")keep_memory_provided = "keep_memory" in on_timeout_rawkeep_memory = on_timeout_raw.get("keep_memory")else:@@ -843,6 +864,20 @@ def build_lifecycle_config(keep_memory = Nonekeep_memory_provided = False+ allowed_actions = ("pause", "kill")+ if on_timeout_configured and on_timeout not in allowed_actions:+ # Name the field the caller wrote: the object form's bad value is on+ # "action", not on on_timeout itself.+ field = (+ 'on_timeout["action"]' if isinstance(on_timeout_raw, dict) else "on_timeout"+ )+ raise InvalidArgumentException(+ f"{field} must be one of: {', '.join(allowed_actions)} (got {on_timeout!r})."+ )+ # The action never reaches the API — it is resolved here into the boolean+ # auto_pause — so an unrecognized value cannot be rejected server-side, and+ # resolving it to kill would delete the sandbox a caller asked to preserve.+# keep_memory only governs a pause action. The discriminated union type# forbids it on action="kill"; re-check at runtime for callers that# bypass the type.diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.pyindex 7b1d7253d..e3912b270 100644--- a/packages/python-sdk/e2b/sandbox_async/main.py+++ b/packages/python-sdk/e2b/sandbox_async/main.py@@ -282,7 +282,8 @@ class AsyncSandbox(SandboxApi)::param on_resume: `"restore"` (the default) restores the memory snapshot; `"reboot"`cold-boots from disk state, so writes not flushed before the pause may be lost.Rejected where filesystem-only resume is not enabled; a no-op for a snapshot- without memory or a sandbox that is already running.+ without memory or a sandbox that is already running. A value outside the two+ literals raises `InvalidArgumentException`.:return: A running sandbox instance@example@@ -319,7 +320,8 @@ class AsyncSandbox(SandboxApi)::param on_resume: `"restore"` (the default) restores the memory snapshot; `"reboot"`cold-boots from disk state, so writes not flushed before the pause may be lost.Rejected where filesystem-only resume is not enabled; a no-op for a snapshot- without memory or a sandbox that is already running.+ without memory or a sandbox that is already running. A value outside the two+ literals raises `InvalidArgumentException`.:return: A running sandbox instance@example@@ -352,7 +354,8 @@ class AsyncSandbox(SandboxApi)::param on_resume: `"restore"` (the default) restores the memory snapshot; `"reboot"`cold-boots from disk state, so writes not flushed before the pause may be lost.Rejected where filesystem-only resume is not enabled; a no-op for a snapshot- without memory or a sandbox that is already running.+ without memory or a sandbox that is already running. A value outside the two+ literals raises `InvalidArgumentException`.:return: A running sandbox instance@examplediff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex b4171327f..8fd0dcb3f 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -57,6 +57,7 @@ from e2b.sandbox.sandbox_api import (SandboxNetworkOpts,SandboxNetworkUpdate,SandboxOnResume,+ resolve_connect_memory,SandboxQuery,SnapshotInfo,build_iam_config,@@ -542,7 +543,7 @@ class SandboxApi(SandboxBase):client=api_client,body=ConnectSandbox(timeout=timeout,- memory=False if on_resume == "reboot" else UNSET,+ memory=resolve_connect_memory(on_resume),),)diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.pyindex 80b4ff1e9..976d7c357 100644--- a/packages/python-sdk/e2b/sandbox_sync/main.py+++ b/packages/python-sdk/e2b/sandbox_sync/main.py@@ -276,7 +276,8 @@ class Sandbox(SandboxApi)::param on_resume: `"restore"` (the default) restores the memory snapshot; `"reboot"`cold-boots from disk state, so writes not flushed before the pause may be lost.Rejected where filesystem-only resume is not enabled; a no-op for a snapshot- without memory or a sandbox that is already running.+ without memory or a sandbox that is already running. A value outside the two+ literals raises `InvalidArgumentException`.:return: A running sandbox instance@example@@ -314,7 +315,8 @@ class Sandbox(SandboxApi)::param on_resume: `"restore"` (the default) restores the memory snapshot; `"reboot"`cold-boots from disk state, so writes not flushed before the pause may be lost.Rejected where filesystem-only resume is not enabled; a no-op for a snapshot- without memory or a sandbox that is already running.+ without memory or a sandbox that is already running. A value outside the two+ literals raises `InvalidArgumentException`.:return: A running sandbox instance@example@@ -347,7 +349,8 @@ class Sandbox(SandboxApi)::param on_resume: `"restore"` (the default) restores the memory snapshot; `"reboot"`cold-boots from disk state, so writes not flushed before the pause may be lost.Rejected where filesystem-only resume is not enabled; a no-op for a snapshot- without memory or a sandbox that is already running.+ without memory or a sandbox that is already running. A value outside the two+ literals raises `InvalidArgumentException`.:return: A running sandbox instance@examplediff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex d0d9d1656..61c668ce0 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -56,6 +56,7 @@ from e2b.sandbox.sandbox_api import (SandboxNetworkOpts,SandboxNetworkUpdate,SandboxOnResume,+ resolve_connect_memory,SandboxQuery,SnapshotInfo,build_iam_config,@@ -356,7 +357,7 @@ class SandboxApi(SandboxBase):client=api_client,body=ConnectSandbox(timeout=timeout,- memory=False if on_resume == "reboot" else UNSET,+ memory=resolve_connect_memory(on_resume),),)diff --git a/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py b/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.pyindex e52bab1eb..6a736823d 100644--- a/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py+++ b/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py@@ -193,3 +193,69 @@ async def test_async_create_sends_auto_resume_only_when_configured(assert "autoResume" not in bodyelse:assert body["autoResume"] == auto_resume+++# on_timeout is resolved into the boolean autoPause before the request is built,+# so the API never sees the action and cannot reject a typo. Resolving it to+# kill would delete a sandbox the caller asked to preserve.+UNRECOGNIZED_ON_TIMEOUT = [+ "Pause",+ "PAUSE",+ "pause\n",+ "paused",+ True,+ {"action": "Pause"},+ {},+]++[email protected]("on_timeout", UNRECOGNIZED_ON_TIMEOUT)+def test_create_rejects_an_unrecognized_on_timeout(+ monkeypatch, test_api_key, on_timeout+):+ request = Mock(return_value=_created_sandbox())+ monkeypatch.setattr(post_sandboxes, "sync_detailed", request)++ with pytest.raises(InvalidArgumentException):+ Sandbox.create(+ api_key=test_api_key, lifecycle=cast(Any, {"on_timeout": on_timeout})+ )++ request.assert_not_called()++[email protected]("on_timeout", UNRECOGNIZED_ON_TIMEOUT)+async def test_async_create_rejects_an_unrecognized_on_timeout(+ monkeypatch, test_api_key, on_timeout+):+ request = AsyncMock(return_value=_created_sandbox())+ monkeypatch.setattr(post_sandboxes, "asyncio_detailed", request)++ with pytest.raises(InvalidArgumentException):+ await AsyncSandbox.create(+ api_key=test_api_key, lifecycle=cast(Any, {"on_timeout": on_timeout})+ )++ request.assert_not_called()+++ "on_timeout,expected_field",+ [+ ("Pause", "on_timeout"),+ ({"action": "Pause"}, 'on_timeout["action"]'),+ ({}, 'on_timeout["action"]'),+ ],+)+def test_the_error_names_the_field_the_caller_wrote(+ monkeypatch, test_api_key, on_timeout, expected_field+):+ request = Mock(return_value=_created_sandbox())+ monkeypatch.setattr(post_sandboxes, "sync_detailed", request)++ with pytest.raises(InvalidArgumentException) as excinfo:+ Sandbox.create(+ api_key=test_api_key, lifecycle=cast(Any, {"on_timeout": on_timeout})+ )++ assert str(excinfo.value).startswith(f"{expected_field} must be one of")diff --git a/packages/python-sdk/tests/shared/sandbox/test_on_resume_request.py b/packages/python-sdk/tests/shared/sandbox/test_on_resume_request.pyindex 7338ab3d2..7249a78a3 100644--- a/packages/python-sdk/tests/shared/sandbox/test_on_resume_request.py+++ b/packages/python-sdk/tests/shared/sandbox/test_on_resume_request.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, Mockimport pytestfrom e2b import AsyncSandbox, Sandbox+from e2b.exceptions import InvalidArgumentExceptionfrom e2b.api.client.api.sandboxes import post_sandboxes_sandbox_id_connectfrom e2b.api.client.models import Sandbox as SandboxModelfrom e2b.sandbox_async.sandbox_api import SandboxApi as AsyncSandboxApi@@ -50,11 +51,15 @@ MEMORY_CASES = [pytest.param({}, None, id="default"),pytest.param({"on_resume": "restore"}, None, id="explicit-restore"),pytest.param({"on_resume": "reboot"}, False, id="reboot"),- # Untyped callers can pass anything; only the "reboot" literal opts into a- # cold boot, so an unrecognized value must fall back to a memory restore.- pytest.param(cast(Any, {"on_resume": "Reboot"}), None, id="unrecognized-value"),+ # A nullish value is not a choice, so it travels as an omitted field.+ pytest.param(cast(Any, {"on_resume": None}), None, id="none-is-absent"),]+# The option is resolved into a boolean before the request is built, so the API+# never sees it and cannot reject a typo. Falling back to a restore would+# silently skip the reboot the caller asked for.+UNRECOGNIZED = ["Reboot", "REBOOT", "reboot\n", " reboot", "rebooted", False, 0]+@pytest.mark.parametrize("kwargs, memory", MEMORY_CASES)def test_connect_sends_memory_only_for_reboot(@@ -144,3 +149,29 @@ def test_on_resume_is_keyword_only_on_the_instance_form(sandbox):assert signature.parameters["on_resume"].kind is inspect.Parameter.KEYWORD_ONLYassert signature.parameters["timeout"].kind is not inspect.Parameter.KEYWORD_ONLY++[email protected]("value", UNRECOGNIZED)+def test_connect_rejects_an_unrecognized_on_resume(monkeypatch, test_api_key, value):+ request = Mock(return_value=_connected_sandbox())+ monkeypatch.setattr(post_sandboxes_sandbox_id_connect, "sync_detailed", request)++ with pytest.raises(InvalidArgumentException):+ Sandbox.connect(SANDBOX_ID, api_key=test_api_key, on_resume=cast(Any, value))++ request.assert_not_called()++[email protected]("value", UNRECOGNIZED)+async def test_async_connect_rejects_an_unrecognized_on_resume(+ monkeypatch, test_api_key, value+):+ request = AsyncMock(return_value=_connected_sandbox())+ monkeypatch.setattr(post_sandboxes_sandbox_id_connect, "asyncio_detailed", request)++ with pytest.raises(InvalidArgumentException):+ await AsyncSandbox.connect(+ SANDBOX_ID, api_key=test_api_key, on_resume=cast(Any, value)+ )++ request.assert_not_called()