Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(sdk): keep the tenant API key out of direct code-interpreter requests

JasonBuildAI3b25df2451c4
diff --git a/docs/sdks/csharp.md b/docs/sdks/csharp.md
index 8a1c80dc7..536e5782d 100644
--- a/docs/sdks/csharp.md
+++ b/docs/sdks/csharp.md
@@ -535,6 +535,12 @@ var config2 = new ConnectionConfig(new ConnectionConfigOptions
`Sandbox.CreateAsync` reports create latency to `POST /v1/metrics/events` by default. Set `ConnectionConfigOptions.DisableMetrics = true` or export `OPENSANDBOX_DISABLE_METRICS=1` to opt out. See [SDK Telemetry](/sdks/observability#creation-metrics).
:::
+The C# Code Interpreter SDK inherits the sandbox's connection configuration.
+With `UseServerProxy = true`, context requests and streamed code execution
+include the configured API key in `OPEN-SANDBOX-API-KEY` for server
+authentication. In direct mode, the SDK does not attach this key to code
+execution requests.
+
### 2. SDK Logging
The SDK uses `Microsoft.Extensions.Logging` abstractions. `SdkDiagnosticsOptions`
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.md
index 2e38c6c9e..805ddc341 100644
--- a/docs/sdks/javascript.md
+++ b/docs/sdks/javascript.md
@@ -515,6 +515,12 @@ const config2 = new ConnectionConfig({
});
```
+The JavaScript Code Interpreter SDK inherits the sandbox's connection
+configuration. With `useServerProxy: true`, context requests and streamed code
+execution include the configured API key in `OPEN-SANDBOX-API-KEY` for server
+authentication. In direct mode, the SDK does not attach this key to code
+execution requests.
+
### 2. Sandbox Creation Configuration
`Sandbox.create()` allows configuring the sandbox environment.
diff --git a/sdks/code-interpreter/csharp/src/OpenSandbox.CodeInterpreter/CodeInterpreter.cs b/sdks/code-interpreter/csharp/src/OpenSandbox.CodeInterpreter/CodeInterpreter.cs
index 0d2c75bb8..5e09eb1ba 100644
--- a/sdks/code-interpreter/csharp/src/OpenSandbox.CodeInterpreter/CodeInterpreter.cs
+++ b/sdks/code-interpreter/csharp/src/OpenSandbox.CodeInterpreter/CodeInterpreter.cs
@@ -17,6 +17,7 @@ using OpenSandbox.CodeInterpreter.Factory;
using OpenSandbox.CodeInterpreter.Services;
using OpenSandbox.Config;
using OpenSandbox.Core;
+using OpenSandbox.Factory;
using OpenSandbox.Internal;
using OpenSandbox.Services;
using Microsoft.Extensions.Logging;
@@ -180,7 +181,7 @@ public sealed class CodeInterpreter
logger.LogInformation("Creating code interpreter for sandbox: {SandboxId}", sandbox.Id);
var protocol = sandbox.ConnectionConfig.Protocol == ConnectionProtocol.Https ? "https" : "http";
var execdBaseUrl = $"{protocol}://{endpoint.EndpointAddress}";
- var execdHeaders = MergeHeaders(sandbox.ConnectionConfig.Headers, endpoint.Headers);
+ var execdHeaders = DefaultAdapterFactory.BuildDataPlaneHeaders(sandbox.ConnectionConfig, endpoint.Headers);
var adapterFactory = options?.AdapterFactory ?? DefaultCodeInterpreterAdapterFactory.Create();
var codes = adapterFactory.CreateCodes(new CreateCodesStackOptions
@@ -355,20 +356,4 @@ public sealed class CodeInterpreter
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
}
-
- private static IReadOnlyDictionary<string, string> MergeHeaders(
- IReadOnlyDictionary<string, string> baseHeaders,
- IReadOnlyDictionary<string, string>? overrideHeaders)
- {
- var merged = baseHeaders.ToDictionary(header => header.Key, header => header.Value);
- if (overrideHeaders != null)
- {
- foreach (var header in overrideHeaders)
- {
- merged[header.Key] = header.Value;
- }
- }
-
- return merged;
- }
}
diff --git a/sdks/code-interpreter/csharp/tests/OpenSandbox.CodeInterpreter.Tests/DataPlaneAuthTests.cs b/sdks/code-interpreter/csharp/tests/OpenSandbox.CodeInterpreter.Tests/DataPlaneAuthTests.cs
new file mode 100644
index 000000000..80963d2e6
--- /dev/null
+++ b/sdks/code-interpreter/csharp/tests/OpenSandbox.CodeInterpreter.Tests/DataPlaneAuthTests.cs
@@ -0,0 +1,140 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using Moq;
+using OpenSandbox.CodeInterpreter.Factory;
+using OpenSandbox.CodeInterpreter.Services;
+using OpenSandbox.Config;
+using OpenSandbox.Factory;
+using OpenSandbox.Models;
+using OpenSandbox.Services;
+using Xunit;
+
+namespace OpenSandbox.CodeInterpreter.Tests;
+
+public class DataPlaneAuthTests
+{
+ private const string ApiKeyHeader = "OPEN-SANDBOX-API-KEY";
+
+ [Fact]
+ public async Task CreateAsync_DirectMode_OmitsTenantApiKeyFromExecdHeaders()
+ {
+ var options = await CaptureCodesOptionsAsync(useServerProxy: false);
+
+ Assert.False(options.ExecdHeaders.ContainsKey(ApiKeyHeader));
+ }
+
+ [Fact]
+ public async Task CreateAsync_ServerProxyMode_RetainsTenantApiKeyInExecdHeaders()
+ {
+ var options = await CaptureCodesOptionsAsync(useServerProxy: true);
+
+ Assert.Equal("tenant-secret", options.ExecdHeaders[ApiKeyHeader]);
+ }
+
+ [Fact]
+ public async Task CreateAsync_ServerProxyMode_EndpointApiKeyWinsOverTenantKey()
+ {
+ var options = await CaptureCodesOptionsAsync(
+ useServerProxy: true,
+ endpointHeaders: new Dictionary<string, string> { [ApiKeyHeader] = "endpoint-secret" });
+
+ Assert.Equal("endpoint-secret", options.ExecdHeaders[ApiKeyHeader]);
+ }
+
+ private static async Task<CreateCodesStackOptions> CaptureCodesOptionsAsync(
+ bool useServerProxy,
+ IReadOnlyDictionary<string, string>? endpointHeaders = null)
+ {
+ var captured = new CapturingAdapterFactory();
+ var sandbox = await CreateSandboxAsync(useServerProxy, endpointHeaders);
+ await CodeInterpreter.CreateAsync(sandbox, new CodeInterpreterCreateOptions
+ {
+ AdapterFactory = captured,
+ SkipHealthCheck = true
+ });
+ await sandbox.DisposeAsync();
+
+ Assert.NotNull(captured.Options);
+ return captured.Options!;
+ }
+
+ private static async Task<Sandbox> CreateSandboxAsync(
+ bool useServerProxy,
+ IReadOnlyDictionary<string, string>? endpointHeaders)
+ {
+ var sandboxesMock = new Mock<ISandboxes>();
+ sandboxesMock
+ .Setup(x => x.GetSandboxEndpointAsync(
+ It.IsAny<string>(),
+ It.IsAny<int>(),
+ It.IsAny<bool>(),
+ It.IsAny<CancellationToken>()))
+ .ReturnsAsync(new Endpoint
+ {
+ EndpointAddress = "127.0.0.1:44772",
+ Headers = endpointHeaders ?? new Dictionary<string, string>()
+ });
+
+ var adapterFactoryMock = new Mock<IAdapterFactory>();
+ adapterFactoryMock
+ .Setup(x => x.CreateLifecycleStack(It.IsAny<CreateLifecycleStackOptions>()))
+ .Returns(new LifecycleStack
+ {
+ Sandboxes = sandboxesMock.Object
+ });
+
+ adapterFactoryMock
+ .Setup(x => x.CreateExecdStack(It.IsAny<CreateExecdStackOptions>()))
+ .Returns(new ExecdStack
+ {
+ Commands = Mock.Of<IExecdCommands>(),
+ Files = Mock.Of<ISandboxFiles>(),
+ Health = Mock.Of<IExecdHealth>(),
+ Metrics = Mock.Of<IExecdMetrics>(),
+ Isolation = Mock.Of<IIsolatedSessions>()
+ });
+
+ adapterFactoryMock
+ .Setup(x => x.CreateEgressStack(It.IsAny<CreateEgressStackOptions>()))
+ .Returns(new EgressStack
+ {
+ Egress = Mock.Of<IEgress>()
+ });
+
+ return await Sandbox.ConnectAsync(new SandboxConnectOptions
+ {
+ SandboxId = "sbx-code-interpreter-data-plane-auth",
+ ConnectionConfig = new ConnectionConfig(new ConnectionConfigOptions
+ {
+ Domain = "localhost:8080",
+ ApiKey = "tenant-secret",
+ UseServerProxy = useServerProxy
+ }),
+ AdapterFactory = adapterFactoryMock.Object,
+ SkipHealthCheck = true
+ });
+ }
+
+ private sealed class CapturingAdapterFactory : ICodeInterpreterAdapterFactory
+ {
+ public CreateCodesStackOptions? Options { get; private set; }
+
+ public ICodes CreateCodes(CreateCodesStackOptions options)
+ {
+ Options = options;
+ return Mock.Of<ICodes>();
+ }
+ }
+}
diff --git a/sdks/code-interpreter/javascript/src/factory/defaultAdapterFactory.ts b/sdks/code-interpreter/javascript/src/factory/defaultAdapterFactory.ts
index 9f798aeb2..64f82f102 100644
--- a/sdks/code-interpreter/javascript/src/factory/defaultAdapterFactory.ts
+++ b/sdks/code-interpreter/javascript/src/factory/defaultAdapterFactory.ts
@@ -12,17 +12,24 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-import { createExecdClient } from "@alibaba-group/opensandbox/internal";
+import {
+ createDataPlaneHeaders,
+ createExecdClient,
+} from "@alibaba-group/opensandbox/internal";
import type { AdapterFactory, CreateCodesStackOptions } from "./adapterFactory.js";
import { CodesAdapter } from "../adapters/codesAdapter.js";
import type { Codes } from "../services/codes.js";
export class DefaultAdapterFactory implements AdapterFactory {
createCodes(opts: CreateCodesStackOptions): Codes {
- const headers: Record<string, string> = {
- ...(opts.sandbox.connectionConfig.headers ?? {}),
- ...(opts.endpointHeaders ?? {}),
- };
+ // The tenant API key only travels with server-proxied requests; execd on the
+ // sandbox endpoint performs no authentication.
+ const headers = createDataPlaneHeaders(
+ opts.sandbox.connectionConfig.headers ?? {},
+ opts.endpointHeaders,
+ opts.sandbox.connectionConfig.useServerProxy,
+ opts.sandbox.connectionConfig.apiKey,
+ );
const client = createExecdClient({
baseUrl: opts.execdBaseUrl,
headers,
diff --git a/sdks/code-interpreter/javascript/tests/data-plane-auth.test.mjs b/sdks/code-interpreter/javascript/tests/data-plane-auth.test.mjs
new file mode 100644
index 000000000..12ee69579
--- /dev/null
+++ b/sdks/code-interpreter/javascript/tests/data-plane-auth.test.mjs
@@ -0,0 +1,108 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ConnectionConfig } from "@alibaba-group/opensandbox";
+import { DefaultAdapterFactory } from "../dist/index.js";
+
+const API_KEY_HEADER = "open-sandbox-api-key";
+
+function createConfig(useServerProxy, requests, includeExplicitApiKey = false) {
+ const fetchImpl = async (input, init) => {
+ const request = input instanceof Request ? input : new Request(input, init);
+ requests.push(request);
+
+ if (new URL(request.url).pathname === "/code/context") {
+ return Response.json({ id: "ctx-1", language: "python" });
+ }
+ return new Response(
+ [
+ JSON.stringify({ type: "stdout", text: "hello", timestamp: 1 }),
+ JSON.stringify({ type: "execution_complete", execution_time: 2, timestamp: 2 }),
+ ].join("\n"),
+ {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ },
+ );
+ };
+
+ const headers = { "x-custom-header": "custom-value" };
+ if (includeExplicitApiKey) {
+ headers[API_KEY_HEADER] = "explicit-secret";
+ }
+
+ const config = new ConnectionConfig({
+ domain: "api.opensandbox.test",
+ apiKey: "tenant-secret",
+ headers,
+ useServerProxy,
+ });
+ config._fetch = fetchImpl;
+ config._sseFetch = fetchImpl;
+ return config;
+}
+
+async function sendCodeRequests(useServerProxy, useEndpointApiKey = false) {
+ const requests = [];
+ const connectionConfig = createConfig(
+ useServerProxy,
+ requests,
+ !useServerProxy,
+ );
+ const factory = new DefaultAdapterFactory();
+ const codes = factory.createCodes({
+ sandbox: { connectionConfig },
+ execdBaseUrl: "http://execd.opensandbox.test",
+ endpointHeaders: {
+ "x-endpoint-token": "execd-token",
+ ...(useEndpointApiKey ? { [API_KEY_HEADER]: "endpoint-secret" } : {}),
+ },
+ });
+
+ await codes.createContext("python");
+ await codes.run("print('hello')");
+ return requests;
+}
+
+test("direct code requests omit the tenant API key", async () => {
+ const requests = await sendCodeRequests(false);
+
+ assert.equal(requests.length, 2);
+ for (const request of requests) {
+ assert.equal(request.headers.has(API_KEY_HEADER), false);
+ assert.equal(request.headers.get("x-custom-header"), "custom-value");
+ assert.ok(request.headers.get("x-endpoint-token"));
+ }
+});
+
+test("server-proxied code requests retain the tenant API key", async () => {
+ const requests = await sendCodeRequests(true);
+
+ assert.equal(requests.length, 2);
+ for (const request of requests) {
+ assert.equal(request.headers.get(API_KEY_HEADER), "tenant-secret");
+ }
+});
+
+test("server-proxied code requests preserve endpoint-specific API keys", async () => {
+ const requests = await sendCodeRequests(true, true);
+
+ assert.equal(requests.length, 2);
+ for (const request of requests) {
+ assert.equal(request.headers.get(API_KEY_HEADER), "endpoint-secret");
+ }
+});
diff --git a/sdks/sandbox/javascript/src/factory/defaultAdapterFactory.ts b/sdks/sandbox/javascript/src/factory/defaultAdapterFactory.ts
index 0459b3f89..988096fe7 100644
--- a/sdks/sandbox/javascript/src/factory/defaultAdapterFactory.ts
+++ b/sdks/sandbox/javascript/src/factory/defaultAdapterFactory.ts
@@ -40,7 +40,19 @@ import type {
const API_KEY_HEADER = "OPEN-SANDBOX-API-KEY";
-function createDataPlaneHeaders(
+/**
+ * Builds headers for a data-plane request (execd or egress).
+ *
+ * The tenant API key is attached only in server-proxy mode: direct requests go
+ * straight to the sandbox, which performs no authentication, so the key must
+ * never travel into it. A credential minted for a specific endpoint wins over
+ * the connection-level key.
+ *
+ * Exported through the internal entrypoint so companion SDKs that build their
+ * own data-plane clients (for example the code interpreter) share this policy
+ * instead of re-implementing it.
+ */
+export function createDataPlaneHeaders(
connectionHeaders: Record<string, string>,
endpointHeaders: Record<string, string> | undefined,
useServerProxy: boolean,
diff --git a/sdks/sandbox/javascript/src/internal.ts b/sdks/sandbox/javascript/src/internal.ts
index 4a936db72..447976a3c 100644
--- a/sdks/sandbox/javascript/src/internal.ts
+++ b/sdks/sandbox/javascript/src/internal.ts
@@ -31,6 +31,9 @@ export type { ExecdClient } from "./openapi/execdClient.js";
export { createEgressClient } from "./openapi/egressClient.js";
export type { EgressClient } from "./openapi/egressClient.js";
+// Data-plane header policy, shared with companion SDKs such as the code interpreter.
+export { createDataPlaneHeaders } from "./factory/defaultAdapterFactory.js";
+
// OpenAPI schema types (NOT stable public API; internal-only).
export type { paths as LifecyclePaths } from "./api/lifecycle.js";
export type { paths as ExecdPaths } from "./api/execd.js";