Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(sdk): allow disabling client-side API key validation (#1360)

Mish Ushakov78c200afc898
diff --git a/.changeset/disable-api-key-validation.md b/.changeset/disable-api-key-validation.md
new file mode 100644
index 000000000..5f09cb09b
--- /dev/null
+++ b/.changeset/disable-api-key-validation.md
@@ -0,0 +1,6 @@
+---
+'e2b': patch
+'@e2b/python-sdk': patch
+---
+
+Allow disabling client-side API key format validation. Set the `E2B_VALIDATE_API_KEY` environment variable to `false`, or pass the `validateApiKey: false` (JS) / `validate_api_key=False` (Python) connection option, when your deployment issues API keys that don't match the default `e2b_` format.
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index ced62f84b..8c5040a7a 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -83,7 +83,7 @@ class ApiClient {
)
}
- if (config.apiKey) {
+ if (config.apiKey && config.validateApiKey) {
validateApiKey(config.apiKey)
}
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index 35ee59e77..29b9378c0 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -21,6 +21,14 @@ export interface ConnectionOpts {
* @default E2B_API_KEY // environment variable
*/
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`
+ */
+ validateApiKey?: boolean
/**
* E2B access token to use for authentication.
*
@@ -198,6 +206,7 @@ export class ConnectionConfig {
readonly requestTimeoutMs: number
readonly apiKey?: string
+ readonly validateApiKey: boolean
readonly accessToken?: string
readonly headers?: Record<string, string>
@@ -206,6 +215,8 @@ export class ConnectionConfig {
constructor(opts?: ConnectionOpts) {
this.apiKey = opts?.apiKey || ConnectionConfig.apiKey
+ this.validateApiKey =
+ opts?.validateApiKey ?? ConnectionConfig.validateApiKey
this.debug = opts?.debug ?? ConnectionConfig.debug
this.domain = opts?.domain || ConnectionConfig.domain
this.accessToken = opts?.accessToken || ConnectionConfig.accessToken
@@ -243,6 +254,12 @@ export class ConnectionConfig {
return getEnvVar('E2B_API_KEY')
}
+ private static get validateApiKey() {
+ return (
+ (getEnvVar('E2B_VALIDATE_API_KEY') || 'true').toLowerCase() !== 'false'
+ )
+ }
+
private static get accessToken() {
return getEnvVar('E2B_ACCESS_TOKEN')
}
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 007a936cf..d4e1fc763 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -232,6 +232,7 @@ export interface SandboxApiOpts
Pick<
ConnectionOpts,
| 'apiKey'
+ | 'validateApiKey'
| 'headers'
| 'apiHeaders'
| 'debug'
diff --git a/packages/js-sdk/tests/api/validateApiKey.test.ts b/packages/js-sdk/tests/api/validateApiKey.test.ts
index c490d1c9d..eaade6840 100644
--- a/packages/js-sdk/tests/api/validateApiKey.test.ts
+++ b/packages/js-sdk/tests/api/validateApiKey.test.ts
@@ -1,5 +1,6 @@
import { assert, test, describe } from 'vitest'
-import { validateApiKey } from '../../src/api'
+import { ApiClient, validateApiKey } from '../../src/api'
+import { ConnectionConfig } from '../../src/connectionConfig'
import { AuthenticationError } from '../../src/errors'
describe('validateApiKey', () => {
@@ -51,3 +52,18 @@ describe('validateApiKey', () => {
}
})
})
+
+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))
+ })
+})
diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.ts
index dbb0aabff..c3d01f077 100644
--- a/packages/js-sdk/tests/connectionConfig.test.ts
+++ b/packages/js-sdk/tests/connectionConfig.test.ts
@@ -13,6 +13,7 @@ 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,
}
})
@@ -146,6 +147,27 @@ 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 7fdb0df55..93b815b3c 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -149,7 +149,7 @@ class ApiClient(AuthenticatedClient):
)
token = config.api_key
- if config.api_key is not None:
+ if config.api_key is not None and config.validate_api_key:
validate_api_key(config.api_key)
if require_access_token:
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index d1b80ca0f..01eda5ce7 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -33,6 +33,12 @@ class ApiParams(TypedDict, total=False):
api_key: Optional[str]
"""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`."""
+
domain: Optional[str]
"""E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable."""
@@ -68,6 +74,10 @@ 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")
@@ -85,6 +95,7 @@ class ConnectionConfig:
domain: Optional[str] = None,
debug: Optional[bool] = None,
api_key: Optional[str] = None,
+ validate_api_key: Optional[bool] = None,
api_url: Optional[str] = None,
sandbox_url: Optional[str] = None,
access_token: Optional[str] = None,
@@ -97,6 +108,11 @@ 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.access_token = access_token or ConnectionConfig._access_token()
self.headers = {**(headers or {}), **(api_headers or {})}
self.headers["User-Agent"] = f"e2b-python-sdk/{package_version}"
@@ -191,6 +207,7 @@ class ConnectionConfig:
api_headers = opts.get("api_headers")
request_timeout = opts.get("request_timeout")
api_key = opts.get("api_key")
+ validate_api_key = opts.get("validate_api_key")
api_url = opts.get("api_url")
domain = opts.get("domain")
debug = opts.get("debug")
@@ -206,6 +223,9 @@ class ConnectionConfig:
return dict(
ApiParams(
api_key=api_key if api_key is not None else self.api_key,
+ validate_api_key=validate_api_key
+ if validate_api_key is not None
+ else self.validate_api_key,
api_url=api_url if api_url is not None else self.api_url,
domain=domain if domain is not None else self.domain,
debug=debug if debug is not None else self.debug,
diff --git a/packages/python-sdk/tests/test_connection_config.py b/packages/python-sdk/tests/test_connection_config.py
index 67daad871..5853e97dd 100644
--- a/packages/python-sdk/tests/test_connection_config.py
+++ b/packages/python-sdk/tests/test_connection_config.py
@@ -28,6 +28,27 @@ 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
index 28e5fa5f5..508037088 100644
--- a/packages/python-sdk/tests/test_validate_api_key.py
+++ b/packages/python-sdk/tests/test_validate_api_key.py
@@ -1,6 +1,7 @@
import pytest
-from e2b.api import validate_api_key
+from e2b import ConnectionConfig
+from e2b.api import ApiClient, validate_api_key
from e2b.exceptions import AuthenticationException
@@ -36,3 +37,15 @@ 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)