Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(sdk): remove client-side API key format validation (#1751)

devin-ai-integration[bot]9d1c90d13294
diff --git a/.changeset/plenty-donuts-argue.md b/.changeset/plenty-donuts-argue.md
new file mode 100644
index 000000000..917e3720b
--- /dev/null
+++ b/.changeset/plenty-donuts-argue.md
@@ -0,0 +1,6 @@
+---
+'e2b': minor
+'@e2b/python-sdk': minor
+---
+
+Remove client-side API key format validation. The SDK no longer checks that the API key matches the `e2b_` hex format — only that a key is present. The `validateApiKey`/`validate_api_key` option is deprecated and has no effect, and the `E2B_VALIDATE_API_KEY` environment variable is no longer read. The server remains the source of truth for key validity.
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 66726513b..756f5efb6 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -7,22 +7,6 @@ import { ConnectionConfig } from '../connectionConfig'
import { AuthenticationError, RateLimitError, SandboxError } from '../errors'
import { createApiLogger } from '../logs'
-const API_KEY_PATTERN = /^e2b_[0-9a-f]+$/
-const API_KEY_EXAMPLE = `e2b_${'0'.repeat(40)}`
-
-/**
- * Validates that an E2B API key has the expected `e2b_` prefix followed by
- * hex characters. Throws `AuthenticationError` otherwise.
- */
-export function validateApiKey(apiKey: string): void {
- if (!API_KEY_PATTERN.test(apiKey)) {
- throw new AuthenticationError(
- `Invalid API key format: expected "e2b_" followed by hex characters (e.g. "${API_KEY_EXAMPLE}"). ` +
- 'Visit the API Keys tab at https://e2b.dev/dashboard?tab=keys to get your API key.'
- )
- }
-}
-
/**
* Map an API error code and message to the matching error class — the same
* mapping {@link handleApiError} applies to HTTP responses, usable for error
@@ -104,10 +88,6 @@ class ApiClient {
)
}
- if (config.apiKey && config.validateApiKey) {
- validateApiKey(config.apiKey)
- }
-
this.api = createClient<paths>({
baseUrl: config.apiUrl,
fetch: createApiFetch(config.proxy),
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index 680723f1b..e1fd10d47 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -23,10 +23,9 @@ export interface ConnectionOpts {
apiKey?: string
/**
* Whether to validate the format of the E2B API key on the client side.
- * Disable this when your deployment issues API keys that don't match the
- * default `e2b_` format.
*
- * @default E2B_VALIDATE_API_KEY // environment variable or `true`
+ * @deprecated The API key format is no longer validated on the client side;
+ * this option has no effect.
*/
validateApiKey?: boolean
/**
@@ -397,7 +396,11 @@ export class ConnectionConfig {
readonly requestTimeoutMs: number
readonly apiKey?: string
- readonly validateApiKey: boolean
+ /**
+ * @deprecated The API key format is no longer validated on the client side;
+ * this option has no effect.
+ */
+ readonly validateApiKey?: boolean
readonly headers?: Record<string, string>
@@ -405,8 +408,7 @@ export class ConnectionConfig {
constructor(opts?: ConnectionOpts) {
this.apiKey = opts?.apiKey || ConnectionConfig.apiKey
- this.validateApiKey =
- opts?.validateApiKey ?? ConnectionConfig.validateApiKey
+ this.validateApiKey = opts?.validateApiKey
this.debug = opts?.debug ?? ConnectionConfig.debug
this.domain = opts?.domain || ConnectionConfig.domain
this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
@@ -480,12 +482,6 @@ export class ConnectionConfig {
return getEnvVar('E2B_API_KEY')
}
- private static get validateApiKey() {
- return (
- (getEnvVar('E2B_VALIDATE_API_KEY') || 'true').toLowerCase() !== 'false'
- )
- }
-
getSignal(requestTimeoutMs?: number, signal?: AbortSignal) {
return buildRequestSignal(requestTimeoutMs ?? this.requestTimeoutMs, signal)
}
diff --git a/packages/js-sdk/tests/api/apiKey.test.ts b/packages/js-sdk/tests/api/apiKey.test.ts
new file mode 100644
index 000000000..6adfcc782
--- /dev/null
+++ b/packages/js-sdk/tests/api/apiKey.test.ts
@@ -0,0 +1,26 @@
+import { assert, test, describe, vi, afterEach } from 'vitest'
+import { ApiClient } from '../../src/api'
+import { ConnectionConfig } from '../../src/connectionConfig'
+import { AuthenticationError } from '../../src/errors'
+
+describe('ApiClient API key requirement', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ test('throws when no API key is supplied', () => {
+ vi.stubEnv('E2B_API_KEY', '')
+ const config = new ConnectionConfig({})
+ assert.throws(
+ () => new ApiClient(config),
+ AuthenticationError,
+ /API key is required/
+ )
+ })
+
+ test('does not require an API key when requireApiKey is false', () => {
+ vi.stubEnv('E2B_API_KEY', '')
+ const config = new ConnectionConfig({})
+ assert.doesNotThrow(() => new ApiClient(config, { requireApiKey: false }))
+ })
+})
diff --git a/packages/js-sdk/tests/api/validateApiKey.test.ts b/packages/js-sdk/tests/api/validateApiKey.test.ts
deleted file mode 100644
index af710b0a6..000000000
--- a/packages/js-sdk/tests/api/validateApiKey.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { assert, test, describe, vi, afterEach } from 'vitest'
-import { ApiClient, validateApiKey } from '../../src/api'
-import { ConnectionConfig } from '../../src/connectionConfig'
-import { AuthenticationError } from '../../src/errors'
-
-describe('validateApiKey', () => {
- const validKey = 'e2b_' + '0123456789abcdef'.repeat(2) + '01234567'
-
- test('accepts a well-formed key', () => {
- assert.doesNotThrow(() => validateApiKey(validKey))
- })
-
- test('rejects a key without the e2b_ prefix', () => {
- assert.throws(
- () => validateApiKey('sk_' + '0'.repeat(40)),
- AuthenticationError,
- /Invalid API key format/
- )
- })
-
- test('accepts a key with a non-default body length', () => {
- assert.doesNotThrow(() => validateApiKey('e2b_' + '0'.repeat(20)))
- })
-
- test('rejects an empty body after the prefix', () => {
- assert.throws(
- () => validateApiKey('e2b_'),
- AuthenticationError,
- /Invalid API key format/
- )
- })
-
- test('rejects a key with non-hex characters in the body', () => {
- assert.throws(
- () => validateApiKey('e2b_' + 'z'.repeat(40)),
- AuthenticationError,
- /Invalid API key format/
- )
- })
-
- test('error message includes an example token', () => {
- try {
- validateApiKey('nope')
- assert.fail('expected validateApiKey to throw')
- } catch (err) {
- assert.instanceOf(err, AuthenticationError)
- assert.match(
- (err as Error).message,
- /e2b_0{40}/,
- 'expected example token in error message'
- )
- }
- })
-})
-
-describe('ApiClient API key validation', () => {
- test('throws on a malformed key by default', () => {
- const config = new ConnectionConfig({ apiKey: 'not-a-valid-key' })
- assert.throws(() => new ApiClient(config), AuthenticationError)
- })
-
- test('skips validation when validateApiKey is false', () => {
- const config = new ConnectionConfig({
- apiKey: 'not-a-valid-key',
- validateApiKey: false,
- })
- assert.doesNotThrow(() => new ApiClient(config))
- })
-})
-
-describe('ApiClient API key requirement', () => {
- afterEach(() => {
- vi.unstubAllEnvs()
- })
-
- test('throws when no API key is supplied', () => {
- vi.stubEnv('E2B_API_KEY', '')
- const config = new ConnectionConfig({})
- assert.throws(
- () => new ApiClient(config),
- AuthenticationError,
- /API key is required/
- )
- })
-
- test('does not require an API key when requireApiKey is false', () => {
- vi.stubEnv('E2B_API_KEY', '')
- const config = new ConnectionConfig({})
- assert.doesNotThrow(() => new ApiClient(config, { requireApiKey: false }))
- })
-})
diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.ts
index 1af6edc8c..df826d969 100644
--- a/packages/js-sdk/tests/connectionConfig.test.ts
+++ b/packages/js-sdk/tests/connectionConfig.test.ts
@@ -14,7 +14,6 @@ beforeEach(() => {
E2B_DOMAIN: process.env.E2B_DOMAIN,
E2B_SANDBOX_URL: process.env.E2B_SANDBOX_URL,
E2B_DEBUG: process.env.E2B_DEBUG,
- E2B_VALIDATE_API_KEY: process.env.E2B_VALIDATE_API_KEY,
}
})
@@ -151,27 +150,6 @@ test('sandbox_url stays localhost in debug mode', () => {
)
})
-test('validateApiKey defaults to true', () => {
- delete process.env.E2B_VALIDATE_API_KEY
-
- const config = new ConnectionConfig()
- assert.equal(config.validateApiKey, true)
-})
-
-test('validateApiKey disabled via env var', () => {
- process.env.E2B_VALIDATE_API_KEY = 'false'
-
- const config = new ConnectionConfig()
- assert.equal(config.validateApiKey, false)
-})
-
-test('validateApiKey in args has priority over env var', () => {
- process.env.E2B_VALIDATE_API_KEY = 'true'
-
- const config = new ConnectionConfig({ validateApiKey: false })
- assert.equal(config.validateApiKey, false)
-})
-
test('debug false in args overrides E2B_DEBUG env var', () => {
process.env.E2B_DEBUG = 'true'
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 2db0fa80c..b33fdba62 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,7 +1,6 @@
import json
import logging
import os
-import re
from dataclasses import dataclass
from types import TracebackType
from typing import NamedTuple, Optional, Protocol, Tuple, Union
@@ -195,22 +194,6 @@ class SupportsApiErrorResponse(Protocol):
def content(self) -> Union[str, bytes]: ...
-_API_KEY_PATTERN = re.compile(r"\Ae2b_[0-9a-f]+\Z")
-_API_KEY_EXAMPLE = "e2b_" + "0" * 40
-
-
-def validate_api_key(api_key: str) -> None:
- """Validate that an E2B API key has the expected ``e2b_`` prefix
- followed by hex characters. Raises ``AuthenticationException`` otherwise.
- """
- if not _API_KEY_PATTERN.match(api_key):
- raise AuthenticationException(
- 'Invalid API key format: expected "e2b_" followed by hex '
- f'characters (e.g. "{_API_KEY_EXAMPLE}"). '
- "Visit the API Keys tab at https://e2b.dev/dashboard?tab=keys to get your API key."
- )
-
-
class ApiClient(AuthenticatedClient):
"""
The client for interacting with the E2B API.
@@ -237,9 +220,6 @@ class ApiClient(AuthenticatedClient):
'or you can pass it directly to the method like api_key="e2b_..."',
)
- if config.api_key is not None and config.validate_api_key:
- validate_api_key(config.api_key)
-
token = config.api_key
auth_header_name = "X-API-KEY"
prefix = ""
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index 8729419a6..71bef0991 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -57,10 +57,8 @@ class ApiParams(TypedDict, total=False):
"""E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable."""
validate_api_key: Optional[bool]
- """Whether to validate the format of the E2B API key on the client side.
- Disable this when your deployment issues API keys that don't match the
- default `e2b_` format. Defaults to `E2B_VALIDATE_API_KEY` environment
- variable or `True`."""
+ """Deprecated: the API key format is no longer validated on the client side;
+ this option has no effect."""
domain: Optional[str]
"""E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable."""
@@ -177,10 +175,6 @@ class ConnectionConfig:
def _api_key():
return os.getenv("E2B_API_KEY")
- @staticmethod
- def _validate_api_key():
- return os.getenv("E2B_VALIDATE_API_KEY", "true").lower() != "false"
-
@staticmethod
def _api_url():
return os.getenv("E2B_API_URL")
@@ -237,11 +231,7 @@ class ConnectionConfig:
self.domain = domain or ConnectionConfig._domain()
self.debug = debug if debug is not None else ConnectionConfig._debug()
self.api_key = api_key or ConnectionConfig._api_key()
- self.validate_api_key = (
- validate_api_key
- if validate_api_key is not None
- else ConnectionConfig._validate_api_key()
- )
+ self.validate_api_key = validate_api_key
self.headers = {**(headers or {}), **(api_headers or {})}
self._user_agent_is_sdk_built = self._apply_user_agent(
self.headers,
diff --git a/packages/python-sdk/tests/test_api_key.py b/packages/python-sdk/tests/test_api_key.py
new file mode 100644
index 000000000..d5169bef5
--- /dev/null
+++ b/packages/python-sdk/tests/test_api_key.py
@@ -0,0 +1,12 @@
+import pytest
+
+from e2b import ConnectionConfig
+from e2b.api import ApiClient
+from e2b.exceptions import AuthenticationException
+
+
+def test_api_client_requires_api_key(monkeypatch):
+ monkeypatch.delenv("E2B_API_KEY", raising=False)
+ config = ConnectionConfig()
+ with pytest.raises(AuthenticationException, match=r"API key is required"):
+ ApiClient(config)
diff --git a/packages/python-sdk/tests/test_connection_config.py b/packages/python-sdk/tests/test_connection_config.py
index 9c7c6802e..a9df7733b 100644
--- a/packages/python-sdk/tests/test_connection_config.py
+++ b/packages/python-sdk/tests/test_connection_config.py
@@ -28,27 +28,6 @@ def test_api_url_has_correct_priority(monkeypatch):
assert config.api_url == "http://localhost:8080"
-def test_validate_api_key_defaults_to_true(monkeypatch):
- monkeypatch.delenv("E2B_VALIDATE_API_KEY", raising=False)
-
- config = ConnectionConfig()
- assert config.validate_api_key is True
-
-
-def test_validate_api_key_disabled_via_env_var(monkeypatch):
- monkeypatch.setenv("E2B_VALIDATE_API_KEY", "false")
-
- config = ConnectionConfig()
- assert config.validate_api_key is False
-
-
-def test_validate_api_key_arg_has_priority_over_env_var(monkeypatch):
- monkeypatch.setenv("E2B_VALIDATE_API_KEY", "true")
-
- config = ConnectionConfig(validate_api_key=False)
- assert config.validate_api_key is False
-
-
def test_sandbox_url_uses_stable_host_for_supported_domain():
config = ConnectionConfig(domain="e2b.app")
diff --git a/packages/python-sdk/tests/test_validate_api_key.py b/packages/python-sdk/tests/test_validate_api_key.py
deleted file mode 100644
index 4e23b370c..000000000
--- a/packages/python-sdk/tests/test_validate_api_key.py
+++ /dev/null
@@ -1,58 +0,0 @@
-import pytest
-
-from e2b import ConnectionConfig
-from e2b.api import ApiClient, validate_api_key
-from e2b.exceptions import AuthenticationException
-
-
-def test_accepts_well_formed_key(test_api_key):
- validate_api_key(test_api_key)
-
-
-def test_rejects_missing_prefix():
- with pytest.raises(AuthenticationException, match=r"Invalid API key format"):
- validate_api_key("sk_" + "0" * 40)
-
-
-def test_accepts_non_default_body_length():
- validate_api_key("e2b_" + "0" * 20)
-
-
-def test_rejects_empty_body():
- with pytest.raises(AuthenticationException, match=r"Invalid API key format"):
- validate_api_key("e2b_")
-
-
-def test_rejects_non_hex_body():
- with pytest.raises(AuthenticationException, match=r"Invalid API key format"):
- validate_api_key("e2b_" + "z" * 40)
-
-
-def test_rejects_trailing_newline(test_api_key):
- with pytest.raises(AuthenticationException, match=r"Invalid API key format"):
- validate_api_key(test_api_key + "\n")
-
-
-def test_error_message_includes_example_token(test_api_key):
- with pytest.raises(AuthenticationException) as exc_info:
- validate_api_key("nope")
- assert test_api_key in str(exc_info.value)
-
-
-def test_api_client_validates_key_by_default():
- config = ConnectionConfig(api_key="not-a-valid-key")
- with pytest.raises(AuthenticationException, match=r"Invalid API key format"):
- ApiClient(config)
-
-
-def test_api_client_skips_validation_when_disabled():
- config = ConnectionConfig(api_key="not-a-valid-key", validate_api_key=False)
- # Should not raise: validation is disabled.
- ApiClient(config)
-
-
-def test_api_client_requires_api_key(monkeypatch):
- monkeypatch.delenv("E2B_API_KEY", raising=False)
- config = ConnectionConfig()
- with pytest.raises(AuthenticationException, match=r"API key is required"):
- ApiClient(config)