Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(sdk): validate E2B API key format client-side (#1356)

Mish Ushakov4a4bb36839ca
diff --git a/.changeset/validate-api-key-format.md b/.changeset/validate-api-key-format.md
new file mode 100644
index 000000000..9713b194b
--- /dev/null
+++ b/.changeset/validate-api-key-format.md
@@ -0,0 +1,6 @@
+---
+'e2b': patch
+'@e2b/python-sdk': patch
+---
+
+Validate the E2B API key format client-side. SDKs now throw an `AuthenticationError` / `AuthenticationException` with an example token (e.g. `e2b_0000000000000000000000000000000000000000`) when the key does not start with `e2b_` followed by hex characters.
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 7b6db519e..afb6fe81d 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -7,6 +7,22 @@ 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.'
+ )
+ }
+}
+
export function handleApiError(
response: FetchResponse<any, any, any>,
errorClass: new (
@@ -66,6 +82,10 @@ class ApiClient {
)
}
+ if (config.apiKey) {
+ validateApiKey(config.apiKey)
+ }
+
if (opts?.requireAccessToken && !config.accessToken) {
throw new AuthenticationError(
'Access token is required, please visit the Personal tab at https://e2b.dev/dashboard to get your access token. ' +
diff --git a/packages/js-sdk/tests/api/validateApiKey.test.ts b/packages/js-sdk/tests/api/validateApiKey.test.ts
new file mode 100644
index 000000000..c490d1c9d
--- /dev/null
+++ b/packages/js-sdk/tests/api/validateApiKey.test.ts
@@ -0,0 +1,53 @@
+import { assert, test, describe } from 'vitest'
+import { validateApiKey } from '../../src/api'
+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'
+ )
+ }
+ })
+})
diff --git a/packages/js-sdk/tests/sandbox/abortSignal.test.ts b/packages/js-sdk/tests/sandbox/abortSignal.test.ts
index fda6e2636..2aa767ce2 100644
--- a/packages/js-sdk/tests/sandbox/abortSignal.test.ts
+++ b/packages/js-sdk/tests/sandbox/abortSignal.test.ts
@@ -3,7 +3,7 @@ import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { Sandbox } from '../../src'
-import { apiUrl } from '../setup'
+import { TEST_API_KEY, apiUrl } from '../setup'
// Hold the request open until the caller aborts. If the signal is already
// aborted by the time the handler runs, `addEventListener('abort', …)` would
@@ -63,7 +63,7 @@ test('Sandbox.create rejects when AbortSignal is aborted', async () => {
const requestStarted = nextRequestStart()
const promise = Sandbox.create('base', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -79,7 +79,7 @@ test('Sandbox.create rejects immediately when signal is already aborted', async
await expect(
Sandbox.create('base', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
).rejects.toThrow()
@@ -90,7 +90,7 @@ test('Sandbox.kill rejects when AbortSignal is aborted', async () => {
const requestStarted = nextRequestStart()
const promise = Sandbox.kill('some-sandbox', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -104,7 +104,9 @@ test('SandboxPaginator.nextItems rejects when per-call AbortSignal is aborted',
const controller = new AbortController()
const requestStarted = nextRequestStart()
- const paginator = Sandbox.list({ apiKey: 'test-key' })
+ const paginator = Sandbox.list({
+ apiKey: TEST_API_KEY,
+ })
const promise = paginator.nextItems({ signal: controller.signal })
await requestStarted
diff --git a/packages/js-sdk/tests/sandbox/configPropagation.test.ts b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
index 9e6d8e0f3..5e3d719fe 100644
--- a/packages/js-sdk/tests/sandbox/configPropagation.test.ts
+++ b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
@@ -2,11 +2,12 @@ import { afterEach, assert, beforeEach, describe, test, vi } from 'vitest'
import { Sandbox } from '../../src'
import { SandboxApi } from '../../src/sandbox/sandboxApi'
+import { TEST_API_KEY } from '../setup'
let originalSandboxUrl: string | undefined
const baseConfig = {
- apiKey: 'base-api-key',
+ apiKey: TEST_API_KEY,
domain: 'base.e2b.dev',
requestTimeoutMs: 1111,
debug: false,
diff --git a/packages/js-sdk/tests/setup.ts b/packages/js-sdk/tests/setup.ts
index be1f74b83..898924217 100644
--- a/packages/js-sdk/tests/setup.ts
+++ b/packages/js-sdk/tests/setup.ts
@@ -140,6 +140,9 @@ export const volumeTest = base.extend<VolumeFixture>({
export const isDebug = process.env.E2B_DEBUG !== undefined
export const isIntegrationTest = process.env.E2B_INTEGRATION_TEST !== undefined
+/** Placeholder API key with a valid format for tests that don't hit the API. */
+export const TEST_API_KEY = `e2b_${'0'.repeat(40)}`
+
function generateRandomString(length: number = 8): string {
return Math.random()
.toString(36)
diff --git a/packages/js-sdk/tests/template/abortSignal.test.ts b/packages/js-sdk/tests/template/abortSignal.test.ts
index 4df5a5bb6..9d54e32dc 100644
--- a/packages/js-sdk/tests/template/abortSignal.test.ts
+++ b/packages/js-sdk/tests/template/abortSignal.test.ts
@@ -3,7 +3,7 @@ import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { Template } from '../../src'
-import { apiUrl } from '../setup'
+import { TEST_API_KEY, apiUrl } from '../setup'
// Hold the request open until the caller aborts. If the signal is already
// aborted by the time the handler runs, `addEventListener('abort', …)` would
@@ -79,7 +79,7 @@ test('Template.build rejects when AbortSignal is aborted', async () => {
const template = Template().fromBaseImage()
const promise = Template.build(template, 'test-template', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -96,7 +96,7 @@ test('Template.build rejects immediately when signal is already aborted', async
const template = Template().fromBaseImage()
await expect(
Template.build(template, 'test-template', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
).rejects.toThrow()
@@ -108,7 +108,7 @@ test('Template.buildInBackground rejects when AbortSignal is aborted', async ()
const template = Template().fromBaseImage()
const promise = Template.buildInBackground(template, 'test-template', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -123,7 +123,7 @@ test('Template.exists rejects when AbortSignal is aborted', async () => {
const requestStarted = nextRequestStart()
const promise = Template.exists('some-template', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -140,7 +140,7 @@ test('Template.getBuildStatus rejects when AbortSignal is aborted', async () =>
const promise = Template.getBuildStatus(
{ templateId: 'tpl-1', buildId: 'build-1' },
{
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
}
)
@@ -156,7 +156,7 @@ test('Template.assignTags rejects when AbortSignal is aborted', async () => {
const requestStarted = nextRequestStart()
const promise = Template.assignTags('some-template:v1', 'stable', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -171,7 +171,7 @@ test('Template.removeTags rejects when AbortSignal is aborted', async () => {
const requestStarted = nextRequestStart()
const promise = Template.removeTags('some-template', 'stable', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
@@ -186,7 +186,7 @@ test('Template.getTags rejects when AbortSignal is aborted', async () => {
const requestStarted = nextRequestStart()
const promise = Template.getTags('some-template', {
- apiKey: 'test-key',
+ apiKey: TEST_API_KEY,
signal: controller.signal,
})
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index c30b037e9..07830bc12 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,6 +1,7 @@
import json
import logging
import os
+import re
from dataclasses import dataclass
from types import TracebackType
from typing import Optional, Protocol, Union
@@ -74,6 +75,22 @@ 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.
@@ -108,6 +125,9 @@ class ApiClient(AuthenticatedClient):
)
token = config.api_key
+ if config.api_key is not None:
+ validate_api_key(config.api_key)
+
if require_access_token:
if config.access_token is None:
raise AuthenticationException(
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
index 0e547ad0c..d44f93db6 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
@@ -9,14 +9,13 @@ from e2b.connection_config import ConnectionConfig
import e2b.sandbox_async.main as sandbox_async_main
-BASE_API_KEY = "base-api-key"
BASE_DOMAIN = "base.e2b.dev"
BASE_REQUEST_TIMEOUT = 11
BASE_DEBUG = False
BASE_HEADERS = {"X-Test": "base"}
-def create_sandbox(monkeypatch) -> AsyncSandbox:
+def create_sandbox(monkeypatch, api_key: str) -> AsyncSandbox:
dummy_transport = SimpleNamespace(pool=object())
monkeypatch.setattr(
@@ -41,7 +40,7 @@ def create_sandbox(monkeypatch) -> AsyncSandbox:
envd_access_token="tok",
traffic_access_token="tok",
connection_config=ConnectionConfig(
- api_key=BASE_API_KEY,
+ api_key=api_key,
domain=BASE_DOMAIN,
request_timeout=BASE_REQUEST_TIMEOUT,
debug=BASE_DEBUG,
@@ -51,16 +50,18 @@ def create_sandbox(monkeypatch) -> AsyncSandbox:
@pytest.mark.skip_debug()
-async def test_pause_passes_connection_config_without_overrides(monkeypatch):
+async def test_pause_passes_connection_config_without_overrides(
+ monkeypatch, test_api_key
+):
mock_pause = AsyncMock(return_value="sbx-test")
monkeypatch.setattr(sandbox_async_main.SandboxApi, "_cls_pause", mock_pause)
- sandbox = create_sandbox(monkeypatch)
+ sandbox = create_sandbox(monkeypatch, test_api_key)
await sandbox.pause()
mock_pause.assert_awaited_once()
assert mock_pause.call_args.kwargs["sandbox_id"] == "sbx-test"
- assert mock_pause.call_args.kwargs["api_key"] == BASE_API_KEY
+ assert mock_pause.call_args.kwargs["api_key"] == test_api_key
assert mock_pause.call_args.kwargs["domain"] == BASE_DOMAIN
assert mock_pause.call_args.kwargs["request_timeout"] == BASE_REQUEST_TIMEOUT
assert mock_pause.call_args.kwargs["debug"] == BASE_DEBUG
@@ -68,11 +69,11 @@ async def test_pause_passes_connection_config_without_overrides(monkeypatch):
@pytest.mark.skip_debug()
-async def test_pause_applies_overrides(monkeypatch):
+async def test_pause_applies_overrides(monkeypatch, test_api_key):
mock_pause = AsyncMock(return_value="sbx-test")
monkeypatch.setattr(sandbox_async_main.SandboxApi, "_cls_pause", mock_pause)
- sandbox = create_sandbox(monkeypatch)
+ sandbox = create_sandbox(monkeypatch, test_api_key)
await sandbox.pause(
domain="override.e2b.dev",
request_timeout=20,
@@ -81,7 +82,7 @@ async def test_pause_applies_overrides(monkeypatch):
mock_pause.assert_awaited_once()
assert mock_pause.call_args.kwargs["sandbox_id"] == "sbx-test"
- assert mock_pause.call_args.kwargs["api_key"] == BASE_API_KEY
+ assert mock_pause.call_args.kwargs["api_key"] == test_api_key
assert mock_pause.call_args.kwargs["domain"] == "override.e2b.dev"
assert mock_pause.call_args.kwargs["request_timeout"] == 20
assert mock_pause.call_args.kwargs["debug"] == BASE_DEBUG
diff --git a/packages/python-sdk/tests/async/volume_async/test_volume.py b/packages/python-sdk/tests/async/volume_async/test_volume.py
index 24e22aba1..4f80f8e10 100644
--- a/packages/python-sdk/tests/async/volume_async/test_volume.py
+++ b/packages/python-sdk/tests/async/volume_async/test_volume.py
@@ -17,8 +17,8 @@ _volumes: dict[str, VolumeAndToken] = {}
@pytest.fixture(autouse=True)
-def mock_volume_api(monkeypatch):
- monkeypatch.setenv("E2B_API_KEY", "test-api-key")
+def mock_volume_api(monkeypatch, test_api_key):
+ monkeypatch.setenv("E2B_API_KEY", test_api_key)
_volumes.clear()
async def mock_post_volumes(*, client, body):
diff --git a/packages/python-sdk/tests/conftest.py b/packages/python-sdk/tests/conftest.py
index 2c5f02263..3d7d8bdf7 100644
--- a/packages/python-sdk/tests/conftest.py
+++ b/packages/python-sdk/tests/conftest.py
@@ -22,6 +22,12 @@ from e2b import (
)
+def test_api_key() -> str:
+ """Placeholder API key with a valid format for tests that don't hit the API."""
+ return "e2b_" + "0" * 40
+
+
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
index 8874ad53c..508c2f01c 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
@@ -9,14 +9,13 @@ from e2b.connection_config import ConnectionConfig
import e2b.sandbox_sync.main as sandbox_sync_main
-BASE_API_KEY = "base-api-key"
BASE_DOMAIN = "base.e2b.dev"
BASE_REQUEST_TIMEOUT = 11
BASE_DEBUG = False
BASE_HEADERS = {"X-Test": "base"}
-def create_sandbox(monkeypatch) -> Sandbox:
+def create_sandbox(monkeypatch, api_key: str) -> Sandbox:
dummy_transport = SimpleNamespace(pool=object())
monkeypatch.setattr(
@@ -39,7 +38,7 @@ def create_sandbox(monkeypatch) -> Sandbox:
envd_access_token="tok",
traffic_access_token="tok",
connection_config=ConnectionConfig(
- api_key=BASE_API_KEY,
+ api_key=api_key,
domain=BASE_DOMAIN,
request_timeout=BASE_REQUEST_TIMEOUT,
debug=BASE_DEBUG,
@@ -49,16 +48,16 @@ def create_sandbox(monkeypatch) -> Sandbox:
@pytest.mark.skip_debug()
-def test_pause_passes_connection_config_without_overrides(monkeypatch):
+def test_pause_passes_connection_config_without_overrides(monkeypatch, test_api_key):
mock_pause = Mock(return_value="sbx-test")
monkeypatch.setattr(sandbox_sync_main.SandboxApi, "_cls_pause", mock_pause)
- sandbox = create_sandbox(monkeypatch)
+ sandbox = create_sandbox(monkeypatch, test_api_key)
sandbox.pause()
mock_pause.assert_called_once()
assert mock_pause.call_args.kwargs["sandbox_id"] == "sbx-test"
- assert mock_pause.call_args.kwargs["api_key"] == BASE_API_KEY
+ assert mock_pause.call_args.kwargs["api_key"] == test_api_key
assert mock_pause.call_args.kwargs["domain"] == BASE_DOMAIN
assert mock_pause.call_args.kwargs["request_timeout"] == BASE_REQUEST_TIMEOUT
assert mock_pause.call_args.kwargs["debug"] == BASE_DEBUG
@@ -66,11 +65,11 @@ def test_pause_passes_connection_config_without_overrides(monkeypatch):
@pytest.mark.skip_debug()
-def test_pause_applies_overrides(monkeypatch):
+def test_pause_applies_overrides(monkeypatch, test_api_key):
mock_pause = Mock(return_value="sbx-test")
monkeypatch.setattr(sandbox_sync_main.SandboxApi, "_cls_pause", mock_pause)
- sandbox = create_sandbox(monkeypatch)
+ sandbox = create_sandbox(monkeypatch, test_api_key)
sandbox.pause(
domain="override.e2b.dev",
request_timeout=20,
@@ -79,7 +78,7 @@ def test_pause_applies_overrides(monkeypatch):
mock_pause.assert_called_once()
assert mock_pause.call_args.kwargs["sandbox_id"] == "sbx-test"
- assert mock_pause.call_args.kwargs["api_key"] == BASE_API_KEY
+ assert mock_pause.call_args.kwargs["api_key"] == test_api_key
assert mock_pause.call_args.kwargs["domain"] == "override.e2b.dev"
assert mock_pause.call_args.kwargs["request_timeout"] == 20
assert mock_pause.call_args.kwargs["debug"] == BASE_DEBUG
diff --git a/packages/python-sdk/tests/sync/volume_sync/test_volume.py b/packages/python-sdk/tests/sync/volume_sync/test_volume.py
index f634f113e..331e767fa 100644
--- a/packages/python-sdk/tests/sync/volume_sync/test_volume.py
+++ b/packages/python-sdk/tests/sync/volume_sync/test_volume.py
@@ -17,8 +17,8 @@ _volumes: dict[str, VolumeAndToken] = {}
@pytest.fixture(autouse=True)
-def mock_volume_api(monkeypatch):
- monkeypatch.setenv("E2B_API_KEY", "test-api-key")
+def mock_volume_api(monkeypatch, test_api_key):
+ monkeypatch.setenv("E2B_API_KEY", test_api_key)
_volumes.clear()
def mock_post_volumes(*, client, body):
diff --git a/packages/python-sdk/tests/test_api_client_transport.py b/packages/python-sdk/tests/test_api_client_transport.py
index 5c6a71431..3bbe1d4e3 100644
--- a/packages/python-sdk/tests/test_api_client_transport.py
+++ b/packages/python-sdk/tests/test_api_client_transport.py
@@ -11,10 +11,10 @@ from e2b.api.client_sync import get_transport as get_sync_transport
from e2b.connection_config import ConnectionConfig
-def test_sync_api_client_proxy_uses_explicit_transport():
+def test_sync_api_client_proxy_uses_explicit_transport(test_api_key):
TransportWithLogger._instances.clear()
config = ConnectionConfig(
- api_key="test",
+ api_key=test_api_key,
proxy="http://127.0.0.1:9999",
)
@@ -30,9 +30,9 @@ def test_sync_api_client_proxy_uses_explicit_transport():
TransportWithLogger._instances.clear()
-def test_sync_get_transport_http2_opt_out_returns_distinct_instance():
+def test_sync_get_transport_http2_opt_out_returns_distinct_instance(test_api_key):
TransportWithLogger._instances.clear()
- config = ConnectionConfig(api_key="test")
+ config = ConnectionConfig(api_key=test_api_key)
try:
http2_transport = get_sync_transport(config)
@@ -50,10 +50,10 @@ def test_sync_get_transport_http2_opt_out_returns_distinct_instance():
@pytest.mark.asyncio
-async def test_async_api_client_proxy_uses_explicit_transport():
+async def test_async_api_client_proxy_uses_explicit_transport(test_api_key):
AsyncTransportWithLogger._instances.clear()
config = ConnectionConfig(
- api_key="test",
+ api_key=test_api_key,
proxy="http://127.0.0.1:9999",
)
@@ -73,9 +73,11 @@ async def test_async_api_client_proxy_uses_explicit_transport():
@pytest.mark.asyncio
-async def test_async_get_transport_http2_opt_out_returns_distinct_instance():
+async def test_async_get_transport_http2_opt_out_returns_distinct_instance(
+ test_api_key,
+):
AsyncTransportWithLogger._instances.clear()
- config = ConnectionConfig(api_key="test")
+ config = ConnectionConfig(api_key=test_api_key)
try:
http2_transport = get_async_transport(config)
diff --git a/packages/python-sdk/tests/test_validate_api_key.py b/packages/python-sdk/tests/test_validate_api_key.py
new file mode 100644
index 000000000..28e5fa5f5
--- /dev/null
+++ b/packages/python-sdk/tests/test_validate_api_key.py
@@ -0,0 +1,38 @@
+import pytest
+
+from e2b.api import 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)