Skip to content

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

fix(sdk): address redirect review findings (Request options, first-hop deadline)

LiuZhangHao10956dc44b96
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.md
index 2b2963bb8..e73d868cf 100644
--- a/docs/sdks/javascript.md
+++ b/docs/sdks/javascript.md
@@ -528,6 +528,11 @@ combination of scheme, host, and port, so changing any of those values is
cross-origin. Other custom headers are not stripped automatically. Requests that do
not carry any protected header keep the runtime's default redirect behavior.
+When a guarded request is redirected, the request timeout applies as a single budget
+for the whole chain rather than per hop: the deadline starts with the first dispatch,
+and the caller's abort signal (plus any fetch options set on the `Request`) is carried
+across every hop.
+
File uploads never follow redirects, because a streamed or in-memory multipart body
cannot always be replayed. A redirect response from an upload is surfaced as a
`SandboxApiException` with the original status code on Node.js; in browsers the
diff --git a/sdks/sandbox/javascript/src/config/redirectFetch.ts b/sdks/sandbox/javascript/src/config/redirectFetch.ts
index 765ed83f2..4abd2adcf 100644
--- a/sdks/sandbox/javascript/src/config/redirectFetch.ts
+++ b/sdks/sandbox/javascript/src/config/redirectFetch.ts
@@ -169,6 +169,25 @@ function combineSignals(
return controller.signal;
}
+/**
+ * The fetch options a `Request` input carries that `init` does not. Rebuilding a
+ * hop as `(url, init)` would otherwise reset them to their platform defaults —
+ * notably `credentials`, so a credentialed request would silently become
+ * same-origin only. `redirect` is intentionally absent: the manual loop owns it
+ * per hop.
+ */
+function requestLevelInit(request: Request): RequestInit {
+ return {
+ credentials: request.credentials,
+ mode: request.mode,
+ cache: request.cache,
+ referrer: request.referrer,
+ referrerPolicy: request.referrerPolicy,
+ integrity: request.integrity,
+ keepalive: request.keepalive,
+ };
+}
+
/**
* Wrap `baseFetch` so protected OpenSandbox headers are stripped before
* following a redirect whose target origin differs from `baseUrl`'s origin.
@@ -214,7 +233,15 @@ export function createRedirectSafeFetch(
// Other init fields (e.g. the undici `dispatcher`) are carried onto every
// hop; per-hop fields are overridden below.
- const baseInit: RequestInit = { ...(init ?? {}) };
+ //
+ // A `Request` input keeps most of its fetch options off `init`. Every hop is
+ // dispatched as `(url, init)`, so those options are copied in explicitly or
+ // the rebuilt request silently falls back to the platform defaults. The
+ // caller's `init` still wins wherever it sets the same field.
+ const baseInit: RequestInit = {
+ ...(request ? requestLevelInit(request) : {}),
+ ...(init ?? {}),
+ };
let currentUrl: string;
let method: string;
@@ -279,7 +306,7 @@ export function createRedirectSafeFetch(
signal: hopSignal,
redirect: "manual",
}
- : { ...baseInit, redirect: "manual" };
+ : { ...baseInit, signal: hopSignal, redirect: "manual" };
if (nextBody == null) {
// `duplex` is body-coupled; some runtimes reject it on a body-less hop.
delete (hopInit as Record<string, unknown>).duplex;
diff --git a/sdks/sandbox/javascript/tests/diagnostics.test.mjs b/sdks/sandbox/javascript/tests/diagnostics.test.mjs
index 274446c28..8c08fd9d4 100644
--- a/sdks/sandbox/javascript/tests/diagnostics.test.mjs
+++ b/sdks/sandbox/javascript/tests/diagnostics.test.mjs
@@ -19,6 +19,15 @@ import { createDiagnosticClient, createLifecycleClient } from "../dist/internal.
const context = { sandboxId: "sbx-1", backendType: "kubernetes", backendIdentifiers: { namespace: "tenant-ns" } };
+/**
+ * Normalize a transport call into a Request. The redirect-guarded lifecycle
+ * transport dispatches hops as `(url, init)` — valid per the fetch contract —
+ * while unguarded paths pass a Request, so these mocks must not assume either.
+ */
+function toRequest(input, init) {
+ return input instanceof Request ? input : new Request(input, init);
+}
+
function mockConfig(handler, options = {}) {
const config = new ConnectionConfig({
domain: "localhost:8080", protocol: "http", apiKey: "key", headers: { "x-custom": "custom" },
@@ -32,8 +41,8 @@ function mockConfig(handler, options = {}) {
test("manager diagnostics uses lifecycle transport and preserves descriptor metadata", async () => {
const calls = [];
const manager = SandboxManager.create({ connectionConfig: mockConfig(
- async (input) => {
- const req = input instanceof Request ? input : new Request(input);
+ async (input, init) => {
+ const req = toRequest(input, init);
calls.push(req);
assert.equal(req.headers.get("OPEN-SANDBOX-API-KEY"), "key");
assert.equal(req.headers.get("x-custom"), "custom");
@@ -67,9 +76,7 @@ for (const source of ["config", "environment"]) {
process.env.OPEN_SANDBOX_API_KEY = "environment-key";
const calls = [];
const manager = SandboxManager.create({ connectionConfig: mockConfig(async (input, init) => {
- // The redirect-safe transport dispatches guarded hops as (url, init), so
- // normalize the input instead of assuming a Request (same as above).
- const req = input instanceof Request ? input : new Request(input, init);
+ const req = toRequest(input, init);
calls.push(req);
assert.equal(req.headers.get("OPEN-SANDBOX-API-KEY"), "explicit-header-key");
if (new URL(req.url).pathname.endsWith("/context")) return Response.json(context);
@@ -121,7 +128,8 @@ test("diagnostic and lifecycle clients share environment and URL defaults", asyn
const previousKey = process.env.OPEN_SANDBOX_API_KEY;
process.env.OPEN_SANDBOX_API_KEY = "environment-key";
const calls = [];
- const fetch = async (req) => {
+ const fetch = async (input, init) => {
+ const req = toRequest(input, init);
calls.push(req);
assert.equal(req.headers.get("OPEN-SANDBOX-API-KEY"), "environment-key");
return Response.json(context);
@@ -145,7 +153,8 @@ test("diagnostic and lifecycle clients share environment and URL defaults", asyn
test("inline diagnostics preserves content without requiring an expiry", async () => {
for (const expiry of [{}, { expiresAt: null }]) {
- const manager = SandboxManager.create({ connectionConfig: mockConfig(async (req) => {
+ const manager = SandboxManager.create({ connectionConfig: mockConfig(async (input, init) => {
+ const req = toRequest(input, init);
const kind = new URL(req.url).pathname.endsWith("/logs") ? "logs" : "events";
return Response.json({
sandboxId: "sbx-1", kind, scope: "all", delivery: "inline", contentType: "text/plain",
diff --git a/sdks/sandbox/javascript/tests/redirect-headers.test.mjs b/sdks/sandbox/javascript/tests/redirect-headers.test.mjs
index 21ba5857f..a23b26d35 100644
--- a/sdks/sandbox/javascript/tests/redirect-headers.test.mjs
+++ b/sdks/sandbox/javascript/tests/redirect-headers.test.mjs
@@ -217,6 +217,65 @@ test("the request signal is carried across redirected hops", async () => {
assert.equal(signals[1].aborted, true);
});
+test("Request-level fetch options survive the rebuild of every guarded hop", async () => {
+ const inits = [];
+ const baseFetch = async (input, init) => {
+ inits.push(init);
+ if (inits.length === 1) {
+ return new Response(null, { status: 307, headers: { location: "http://other.test/final" } });
+ }
+ return new Response("ok", { status: 200 });
+ };
+ const safeFetch = createRedirectSafeFetch("http://a.test", baseFetch);
+
+ const request = new Request("http://a.test/start", {
+ method: "POST",
+ body: "payload",
+ headers: { "OPEN-SANDBOX-API-KEY": "tenant-secret" },
+ credentials: "include",
+ cache: "no-store",
+ referrerPolicy: "no-referrer",
+ });
+
+ const res = await safeFetch(request);
+ assert.equal(res.status, 200);
+ assert.equal(inits.length, 2);
+ for (const init of inits) {
+ // Options that only live on the Request input must be copied onto the
+ // rebuilt (url, init) hop instead of falling back to platform defaults.
+ assert.equal(init.credentials, "include");
+ assert.equal(init.cache, "no-store");
+ assert.equal(init.referrerPolicy, "no-referrer");
+ // ...while the loop keeps ownership of the redirect mode.
+ assert.equal(init.redirect, "manual");
+ }
+});
+
+test("the overall redirect deadline bounds the first URL-input hop", async () => {
+ const signals = [];
+ const baseFetch = async (input, init) => {
+ signals.push(init?.signal);
+ await new Promise((resolve) => {
+ init?.signal?.addEventListener("abort", resolve, { once: true });
+ setTimeout(resolve, 1000);
+ });
+ if (init?.signal?.aborted) throw init.signal.reason;
+ return new Response("late", { status: 200 });
+ };
+ const safeFetch = createRedirectSafeFetch("http://a.test", baseFetch, {
+ overallTimeoutMs: 20,
+ });
+
+ await assert.rejects(
+ safeFetch("http://a.test/start", { headers: { "OPEN-SANDBOX-API-KEY": "tenant-secret" } }),
+ /Redirect chain timed out/,
+ );
+ // A string/URL input used to take the header-less first hop without any
+ // signal, so the overall deadline only started at the first redirect.
+ assert.equal(signals.length, 1);
+ assert.equal(signals[0].aborted, true);
+});
+
test("303 and POST 301/302 convert to GET and drop entity headers", async () => {
const calls = [];
const baseFetch = async (input, init) => {