Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
refactor(sdks): tidy SDK auth and deprecate ConnectionConfig access token (#1452)
Mish Ushakovf3e7f3397378
diff --git a/.changeset/quick-spoons-remove.md b/.changeset/quick-spoons-remove.mdnew file mode 100644index 000000000..62954bfa9--- /dev/null+++ b/.changeset/quick-spoons-remove.md@@ -0,0 +1,13 @@+---+"@e2b/python-sdk": patch+"e2b": patch+"@e2b/cli": patch+---++Tidy up SDK authentication and deprecate the access token in `ConnectionConfig`.++- Deprecated the `accessToken` (JS) / `access_token` (Python) option on `ConnectionConfig`. It still works exactly as before — when set (or via `E2B_ACCESS_TOKEN`), the `Authorization: Bearer` header is still sent — but you should pass custom auth through `apiHeaders` instead, e.g. `new ConnectionConfig({ apiHeaders: { Authorization: 'Bearer <token>' } })`.+- The SDK now raises a clear error when no API key is supplied, pointing to the API Keys tab (`https://e2b.dev/dashboard?tab=keys`). In JS this is controlled by a `requireApiKey` option (default `true`) so callers that authenticate differently — like the CLI hitting `/teams` with an access token — can opt out; in Python the API key is always required.+- Removed the unused access-token toggle from the API clients: `requireAccessToken` (JS) and `require_access_token` (Python). No caller ever set it to a non-default value, so behavior is unchanged.+- The CLI now passes the access token to the `/teams` endpoint through `apiHeaders` instead of the deprecated option.+- Decoupled the sandbox-scoped envd access token from `ConnectionConfig`: `EnvdApiClient` now owns its own `accessToken` field and sets the `X-Access-Token` header itself.diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.tsindex bcbfe2393..207545a79 100644--- a/packages/cli/src/api.ts+++ b/packages/cli/src/api.ts@@ -95,8 +95,17 @@ export function resolveTeamId(const userConfig = getUserConfig()+const resolvedAccessToken =+ process.env.E2B_ACCESS_TOKEN || userConfig?.accessToken+export const connectionConfig = new e2b.ConnectionConfig({- accessToken: process.env.E2B_ACCESS_TOKEN || userConfig?.accessToken,apiKey: process.env.E2B_API_KEY || userConfig?.teamApiKey,+ apiHeaders: resolvedAccessToken+ ? { Authorization: `Bearer ${resolvedAccessToken}` }+ : undefined,+})+// The CLI authenticates team-scoped endpoints (e.g. `/teams`) with the access+// token instead of an API key, so don't require an API key here.+export const client = new e2b.ApiClient(connectionConfig, {+ requireApiKey: false,})-export const client = new e2b.ApiClient(connectionConfig)diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.tsindex 10c8138cd..9b0b9faae 100644--- a/packages/cli/src/commands/auth/login.ts+++ b/packages/cli/src/commands/auth/login.ts@@ -46,9 +46,9 @@ export const loginCommand = new commander.Command('login')const signal = connectionConfig.getSignal()const config = new e2b.ConnectionConfig({- accessToken,+ apiHeaders: { Authorization: `Bearer ${accessToken}` },})- const client = new e2b.ApiClient(config)+ const client = new e2b.ApiClient(config, { requireApiKey: false })const res = await client.api.GET('/teams', { signal })handleE2BRequestError(res, 'Error getting teams')diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.tsindex 8c5040a7a..a52fe09ec 100644--- a/packages/js-sdk/src/api/index.ts+++ b/packages/js-sdk/src/api/index.ts@@ -71,13 +71,12 @@ class ApiClient {constructor(config: ConnectionConfig,opts: {- requireAccessToken?: booleanrequireApiKey?: boolean- } = { requireAccessToken: false, requireApiKey: false }+ } = {}) {- if (opts?.requireApiKey && !config.apiKey) {+ if ((opts.requireApiKey ?? true) && !config.apiKey) {throw new AuthenticationError(- 'API key is required, please visit the Team tab at https://e2b.dev/dashboard to get your API key. ' ++ 'API key is required, please visit the API Keys tab at https://e2b.dev/dashboard?tab=keys to get your API key. ' +'You can either set the environment variable `E2B_API_KEY` ' +"or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })")@@ -87,13 +86,6 @@ class ApiClient {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. ' +- 'You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `accessToken` in options.'- )- }-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.tsindex c73b627af..85e707e73 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -32,6 +32,9 @@ export interface ConnectionOpts {/*** E2B access token to use for authentication.*+ * @deprecated Pass the token through `apiHeaders` instead, e.g.+ * `apiHeaders: { Authorization: \`Bearer ${token}\` }`.+ ** @default E2B_ACCESS_TOKEN // environment variable*/accessToken?: string@@ -224,6 +227,9 @@ export class ConnectionConfig {readonly apiKey?: stringreadonly validateApiKey: boolean+ /**+ * @deprecated Pass the token through `apiHeaders` instead.+ */readonly accessToken?: stringreadonly integration?: stringdiff --git a/packages/js-sdk/src/envd/api.ts b/packages/js-sdk/src/envd/api.tsindex 02a185568..673648c88 100644--- a/packages/js-sdk/src/envd/api.ts+++ b/packages/js-sdk/src/envd/api.ts@@ -195,7 +195,11 @@ class EnvdApiClient {readonly version: stringconstructor(- config: Pick<ConnectionConfig, 'apiUrl' | 'logger' | 'accessToken'> & {+ config: Pick<ConnectionConfig, 'apiUrl' | 'logger'> & {+ /**+ * Sandbox-scoped envd access token, sent as the `X-Access-Token` header.+ */+ envdAccessToken?: stringfetch?: (request: Request) => ReturnType<typeof fetch>headers?: Record<string, string>},@@ -206,7 +210,12 @@ class EnvdApiClient {this.api = createClient({baseUrl: config.apiUrl,fetch: config?.fetch,- headers: config?.headers,+ headers: {+ ...config?.headers,+ ...(config.envdAccessToken && {+ 'X-Access-Token': config.envdAccessToken,+ }),+ },// In HTTP 1.1, all connections are considered persistent unless declared otherwise// keepalive: true,})diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex 660536e44..e330ccaac 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -200,13 +200,10 @@ export class Sandbox extends SandboxApi {{apiUrl: this.envdApiUrl,logger: opts?.logger,- accessToken: this.envdAccessToken,+ envdAccessToken: this.envdAccessToken,headers: {'User-Agent': this.connectionConfig.headers?.['User-Agent'] ?? '',...sandboxHeaders,- ...(this.envdAccessToken- ? { 'X-Access-Token': this.envdAccessToken }- : {}),},fetch: (request) => envdFetch(request),},diff --git a/packages/js-sdk/tests/api/validateApiKey.test.ts b/packages/js-sdk/tests/api/validateApiKey.test.tsindex eaade6840..af710b0a6 100644--- a/packages/js-sdk/tests/api/validateApiKey.test.ts+++ b/packages/js-sdk/tests/api/validateApiKey.test.ts@@ -1,4 +1,4 @@-import { assert, test, describe } from 'vitest'+import { assert, test, describe, vi, afterEach } from 'vitest'import { ApiClient, validateApiKey } from '../../src/api'import { ConnectionConfig } from '../../src/connectionConfig'import { AuthenticationError } from '../../src/errors'@@ -67,3 +67,25 @@ describe('ApiClient API key validation', () => {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/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.pyindex 93b815b3c..2b854ff12 100644--- a/packages/python-sdk/e2b/api/__init__.py+++ b/packages/python-sdk/e2b/api/__init__.py@@ -105,8 +105,6 @@ class ApiClient(AuthenticatedClient):def __init__(self,config: ConnectionConfig,- require_api_key: bool = True,- require_access_token: bool = False,transport: Optional[Union[BaseTransport, AsyncBaseTransport]] = None,transport_factory: Optional[Callable[[], BaseTransport]] = None,async_transport_factory: Optional[Callable[[], AsyncBaseTransport]] = None,@@ -129,45 +127,30 @@ class ApiClient(AuthenticatedClient):] = weakref.WeakKeyDictionary()self._proxy = config.proxy- if require_api_key and require_access_token:+ if config.api_key is None:raise AuthenticationException(- "Only one of api_key or access_token can be required, not both",+ "API key is required, please visit the API Keys tab at https://e2b.dev/dashboard?tab=keys to get your API key. "+ "You can either set the environment variable `E2B_API_KEY` "+ 'or you can pass it directly to the method like api_key="e2b_..."',)- if not require_api_key and not require_access_token:- raise AuthenticationException(- "Either api_key or access_token is required",- )-- token = None- if require_api_key:- if config.api_key is None:- raise AuthenticationException(- "API key is required, please visit the Team tab at https://e2b.dev/dashboard to get your API key. "- "You can either set the environment variable `E2B_API_KEY` "- 'or you can pass it directly to the method like api_key="e2b_..."',- )- token = config.api_key-if config.api_key is not None and config.validate_api_key:validate_api_key(config.api_key)- if require_access_token:- if config.access_token is None:- raise AuthenticationException(- "Access token is required, please visit the Personal tab at https://e2b.dev/dashboard to get your access token. "- "You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `access_token` in options.",- )- token = config.access_token-- auth_header_name = "X-API-KEY" if require_api_key else "Authorization"- prefix = "" if require_api_key else "Bearer"+ token = config.api_key+ auth_header_name = "X-API-KEY"+ prefix = ""headers = {**default_headers,**(config.headers or {}),}+ # Deprecated: send the access token alongside the API key when one is+ # available, mirroring the JS SDK. Prefer `api_headers` instead.+ if config.access_token is not None:+ headers["Authorization"] = f"Bearer {config.access_token}"+# Prevent passing these parameters twicemore_headers: Optional[dict] = kwargs.pop("headers", None)if more_headers:diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.pyindex 335751faa..d67a9151e 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -128,6 +128,8 @@ class ConnectionConfig:if validate_api_key is not Noneelse ConnectionConfig._validate_api_key())+ # Deprecated: pass the token through `api_headers` instead, e.g.+ # api_headers={"Authorization": f"Bearer {token}"}.self.access_token = access_token or ConnectionConfig._access_token()self.integration = integrationself.headers = {**(headers or {}), **(api_headers or {})}diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.pyindex b894ffb1f..8324c5ca0 100644--- a/packages/python-sdk/e2b/template_async/main.py+++ b/packages/python-sdk/e2b/template_async/main.py@@ -237,8 +237,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)data = await AsyncTemplate._build(@@ -328,8 +326,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return await AsyncTemplate._build(@@ -367,8 +363,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return await get_build_status(api_client,@@ -425,8 +419,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return await check_alias_exists(api_client, alias)@@ -458,8 +450,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)normalized_tags = [tags] if isinstance(tags, str) else tags@@ -491,8 +481,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)normalized_tags = [tags] if isinstance(tags, str) else tags@@ -521,8 +509,6 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return await get_template_tags(api_client, template_id)diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.pyindex 075882178..d1d4f35f5 100644--- a/packages/python-sdk/e2b/template_sync/main.py+++ b/packages/python-sdk/e2b/template_sync/main.py@@ -237,8 +237,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)data = Template._build(@@ -328,8 +326,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return Template._build(@@ -367,8 +363,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return get_build_status(@@ -426,8 +420,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return check_alias_exists(api_client, alias)@@ -459,8 +451,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)normalized_tags = [tags] if isinstance(tags, str) else tags@@ -492,8 +482,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)normalized_tags = [tags] if isinstance(tags, str) else tags@@ -522,8 +510,6 @@ class Template(TemplateBase):config = ConnectionConfig(**opts)api_client = get_api_client(config,- require_api_key=True,- require_access_token=False,)return get_template_tags(api_client, template_id)diff --git a/packages/python-sdk/tests/test_validate_api_key.py b/packages/python-sdk/tests/test_validate_api_key.pyindex 508037088..4e23b370c 100644--- a/packages/python-sdk/tests/test_validate_api_key.py+++ b/packages/python-sdk/tests/test_validate_api_key.py@@ -49,3 +49,10 @@ 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)