Skip to content

An open-source, faster Devin alternative

TypeScript

VM-DO exec data plane: host-dialed VmSession DO + per-sandbox HMAC connect token

Brian Reardonbc24b5731ef1
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index ccd0ccf0..8641fdca 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -327,6 +327,71 @@ describe("/internal/model-billing/enable — scoped-secret auth boundary", () =>
});
});
+describe("api-edge VM-DO exec routing", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ sandboxIndexInserts.length = 0;
+ });
+
+ // A VmSession DO namespace stub whose /exec returns `doResponse`. The exec
+ // fast path is gated on SESSION_JWT_SECRET, which the base test env already sets.
+ const vmEnv = (doResponse: Response) =>
+ ({
+ ...env,
+ VM_SESSIONS: {
+ idFromName: (s: string) => s,
+ get: () => ({ fetch: async () => doResponse.clone() }),
+ },
+ }) as unknown as Env;
+
+ const runAsync = (e: Env) =>
+ worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes/sb-123/exec/run-async", {
+ method: "POST",
+ headers: { "X-API-Key": "osb_test", "content-type": "application/json" },
+ body: JSON.stringify({ cmd: "sh", args: ["-c", "node -v"], timeout: 60 }),
+ }),
+ e,
+ ctx,
+ );
+
+ it("serves exec inline from the DO and does not hit the tunnel", async () => {
+ const tunnel = vi.fn(async () => new Response("TUNNEL", { status: 200 }));
+ vi.stubGlobal("fetch", tunnel);
+ const resp = await runAsync(vmEnv(new Response(JSON.stringify({ exitCode: 0, stdout: "v20.0.0\n", stderr: "" }), { status: 200 })));
+ expect(resp.status).toBe(200);
+ expect(await resp.json()).toEqual({ exitCode: 0, stdout: "v20.0.0\n", stderr: "" });
+ expect(tunnel).not.toHaveBeenCalled(); // one hop: edge→DO, no tunnel
+ });
+
+ it("falls back to the tunnel when the DO channel is not connected", async () => {
+ const tunnel = vi.fn(async () => new Response(JSON.stringify({ execId: "e1", running: true }), { status: 200 }));
+ vi.stubGlobal("fetch", tunnel);
+ const resp = await runAsync(vmEnv(new Response(JSON.stringify({ connected: false }), { status: 409 })));
+ expect(resp.status).toBe(200);
+ expect(tunnel).toHaveBeenCalledTimes(1); // degraded → tunnel
+ });
+
+ it("only routes run-async to the DO — other exec sub-paths take the tunnel", async () => {
+ // The result-poll (GET /exec/:id/result), files, pty, etc. must not touch the
+ // DO; the fast path is scoped to POST /exec/run-async.
+ const tunnel = vi.fn(async () => new Response("proxied", { status: 200 }));
+ vi.stubGlobal("fetch", tunnel);
+ const doGet = vi.fn();
+ const e = { ...env, VM_SESSIONS: { idFromName: (s: string) => s, get: doGet } } as unknown as Env;
+ const resp = await worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-1/result", {
+ headers: { "X-API-Key": "osb_test" },
+ }),
+ e,
+ ctx,
+ );
+ expect(resp.status).toBe(200);
+ expect(doGet).not.toHaveBeenCalled(); // result poll → tunnel, never the DO
+ expect(tunnel).toHaveBeenCalledTimes(1);
+ });
+});
+
describe("safeReturnTo — deferred-action deep-link validation", () => {
it("accepts same-origin paths (incl. query strings)", () => {
expect(safeReturnTo("/do?action=abc")).toBe("/do?action=abc");
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index cdbf1d28..13e2c1f3 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -20,6 +20,7 @@
// GET /health
export { CreditAccount } from "../../shared/credit_account";
+export { VmSession } from "./vm_session";
import { handleDashboard, type DashboardEnv } from "./dashboard";
import {
AGENT_SECURITY_NOTIFICATION_PATH,
@@ -90,6 +91,12 @@ export interface Env extends DashboardEnv {
// DEDICATED HMAC secret for handing a freshly-minted OR key to sessions-api
// (NOT the generic internal-auth — this route carries a live model key). §6.7.5.
OC_MANAGED_CRED_HMAC_SECRET: string;
+ // VM-DO exec data plane (vm_do_datapane_validation). One DO per sandbox holds a
+ // persistent host-dialed WebSocket to the QEMU worker; exec routes edge→DO→VM
+ // instead of tunnel→CP→worker, with automatic tunnel fallback when unconnected.
+ // The host's /connect is authed by a per-sandbox HMAC over SESSION_JWT_SECRET
+ // (see the /internal/vms/:id/connect route) — no dedicated secret.
+ VM_SESSIONS: DurableObjectNamespace;
}
const DEFAULT_MAX_CONCURRENT_SANDBOXES = 50;
@@ -171,6 +178,33 @@ function isWebSocketUpgrade(req: Request): boolean {
return req.headers.get("upgrade")?.toLowerCase() === "websocket";
}
+// Length-hiding constant-time secret compare: hash both sides to a fixed 32
+// bytes before XOR so the loop time can't leak the expected length. Used for the
+// VM-DO host-dial connect secret (vm_session.ts), which arrives as a WS
+// subprotocol value rather than an HMAC signature.
+async function tokenMatches(provided: string | null, expected: string): Promise<boolean> {
+ if (!provided || !expected) return false;
+ const encoder = new TextEncoder();
+ const [left, right] = await Promise.all([
+ crypto.subtle.digest("SHA-256", encoder.encode(provided)),
+ crypto.subtle.digest("SHA-256", encoder.encode(expected)),
+ ]);
+ const a = new Uint8Array(left);
+ const b = new Uint8Array(right);
+ let mismatch = 0;
+ for (let i = 0; i < a.length; i++) mismatch |= a[i] ^ b[i];
+ return mismatch === 0;
+}
+
+// The host presents the connect secret as the 2nd WS subprotocol, after the
+// wire-format marker "oc-protobuf-v1". Browsers/proxies can't set arbitrary WS
+// headers but CAN set Sec-WebSocket-Protocol, so this carries the credential on
+// the upgrade without a query-string leak. Returns null if the marker is absent.
+function socketSecret(req: Request): string | null {
+ const protocols = req.headers.get("sec-websocket-protocol")?.split(",").map((v) => v.trim()) ?? [];
+ return protocols[0] === "oc-protobuf-v1" ? (protocols[1] ?? null) : null;
+}
+
function apiKeyFromRequest(req: Request): string | null {
const headerKey = req.headers.get("X-API-Key");
if (headerKey) return headerKey;
@@ -233,6 +267,24 @@ const concurrencyCountCache = new Map<string, { count: number; cachedAtMs: numbe
// the waitUntil-deferred insertSandboxIndex write does. Never caches misses.
const sandboxRouteCache = new Map<string, { cellID: string; orgID: string }>();
+// resolveSandboxRoute returns a sandbox's { cellID, orgID } from the route cache,
+// falling back to a single D1 read (which it then caches). null = no such
+// sandbox. Shared by proxyToCellSDK and the VM-DO exec fast path so both enforce
+// the same org-ownership authz off the same cached mapping.
+async function resolveSandboxRoute(env: Env, id: string): Promise<{ cellID: string; orgID: string } | null> {
+ let route = sandboxRouteCache.get(id);
+ if (!route) {
+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id FROM sandboxes_index WHERE id = ?1")
+ .bind(id)
+ .first<{ cell_id: string; org_id: string }>();
+ if (!row) return null;
+ route = { cellID: row.cell_id, orgID: row.org_id };
+ if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
+ sandboxRouteCache.set(id, route);
+ }
+ return route;
+}
+
function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number): void {
if (nowMs - entry.lastBumpMs < LAST_USED_BUMP_MS) return;
entry.lastBumpMs = nowMs;
@@ -1007,6 +1059,40 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
return json({ ...sandboxRowToJSON(row), cellEndpoint: cell ? cell.base_url : null });
}
+// tryVmDoExec routes POST /:id/exec/run-async through the sandbox's VmSession
+// Durable Object (the VM-DO exec data plane, vm_do_datapane_validation) instead
+// of the tunnel→CP→worker chain. Returns a Response when the DO handled it (a
+// served result, or an authz 404), or null to tell the caller to fall back to
+// the tunnel (proxyToCellSDK) — the automatic, flag-free degradation whenever
+// the host→DO channel isn't live. The DO's 200 body is already the SDK's inline
+// run-async shape ({exitCode,stdout,stderr}, no execId), so exec.run()
+// short-circuits without polling — one edge→DO→host→agent hop. Authz mirrors
+// proxyToCellSDK exactly (same route lookup + org-ownership check) so the DO
+// path can't be used to exec on another org's sandbox. See vm_session.ts.
+async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string): Promise<Response | null> {
+ const route = await resolveSandboxRoute(env, id);
+ if (!route) return json({ error: "sandbox not found" }, 404);
+ if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
+ try {
+ // clone() so the original request body stays readable for the tunnel
+ // fallback when the DO reports the channel isn't connected.
+ const body = await req.clone().text();
+ const stub = env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(id));
+ const doResp = await stub.fetch("https://do/exec", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body,
+ });
+ // 200 = DO ran it. 409 (connected:false / channel error) = fall back.
+ if (doResp.status === 200) {
+ return new Response(doResp.body, { status: 200, headers: { "content-type": "application/json" } });
+ }
+ } catch {
+ // DO unreachable — fall through to the tunnel.
+ }
+ return null;
+}
+
// Proxy the request to the owning cell's CP. Used for SDK runtime calls
// (`/api/sandboxes/:id/exec`, `/files`, `/pty`, etc.). The caller has been
// authenticated at the edge against D1; we mint a short-lived IdentityToken
@@ -1017,16 +1103,8 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string): Promise<Response> {
// Route cache first — the sandbox→cell mapping is immutable, and the D1 read
// it replaces is a blocking per-sub-op cost (2-3× per SDK runCommand).
- let route = sandboxRouteCache.get(id);
- if (!route) {
- const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id FROM sandboxes_index WHERE id = ?1")
- .bind(id)
- .first<{ cell_id: string; org_id: string }>();
- if (!row) return json({ error: "sandbox not found" }, 404);
- route = { cellID: row.cell_id, orgID: row.org_id };
- if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
- sandboxRouteCache.set(id, route);
- }
+ const route = await resolveSandboxRoute(env, id);
+ if (!route) return json({ error: "sandbox not found" }, 404);
// Authorization: the sandbox must belong to the caller's org. Without this,
// any authenticated org could exec/files/pty/delete/hibernate/wake another
// org's sandbox by id (the cell trusts the edge for authz). 404 not 403 so
@@ -2661,6 +2739,28 @@ export default {
return json({ ok: true, env: env.WORKER_ENV });
}
+ // VM-DO host dial: the QEMU worker host opens a persistent WebSocket to the
+ // per-sandbox VmSession DO here (vm_session.ts). Auth is a per-sandbox connect
+ // token = HMAC(SESSION_JWT_SECRET, "vmdo:"+id), minted by the CP and delivered
+ // to the worker over the create/claim/wake gRPC; the worker holds no signing
+ // secret. We re-derive it here from the id in the path and the shared secret
+ // (same construction as auth.MintVMDOConnectToken) and compare to the token
+ // the host presents as the 2nd WS subprotocol. No location hint on get() → CF
+ // places the DO near the host's colo (eastus→IAD, westus2→SEA).
+ {
+ const vmConnect = path.match(/^\/internal\/vms\/([^/]+)\/connect$/);
+ if (vmConnect && isWebSocketUpgrade(req)) {
+ const expected = env.SESSION_JWT_SECRET
+ ? await hmacHex(env.SESSION_JWT_SECRET, "vmdo:" + vmConnect[1])
+ : "";
+ if (!expected || !(await tokenMatches(socketSecret(req), expected))) {
+ return new Response("unauthorized", { status: 401 });
+ }
+ const stub = env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(vmConnect[1]));
+ return stub.fetch(new Request("https://do/connect", req));
+ }
+ }
+
if (path === "/internal/halt-list") {
if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
return haltList(req, env);
@@ -3097,6 +3197,15 @@ export default {
// SDK's api-key existing in cell PG.
const caller = await authenticate(req, env);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
+ // VM-DO exec fast path: route POST /:id/exec/run-async through the
+ // sandbox's VmSession DO. Automatic tunnel fallback (no flag) whenever the
+ // channel isn't live (DO 409) — so this is safe even before/while workers
+ // roll out the host dialer. Gated only on SESSION_JWT_SECRET (present
+ // wherever the DO auth can be verified at all).
+ if (env.SESSION_JWT_SECRET && req.method === "POST" && rest === "/exec/run-async") {
+ const doResp = await tryVmDoExec(req, env, caller, id);
+ if (doResp) return doResp;
+ }
return proxyToCellSDK(req, env, ctx, caller, id);
}
diff --git a/cloudflare-workers/api-edge/src/protocol.ts b/cloudflare-workers/api-edge/src/protocol.ts
new file mode 100644
index 00000000..eeb991ea
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/protocol.ts
@@ -0,0 +1,121 @@
+export interface ExecRequest {
+ requestId: number;
+ command: string;
+ cwd: string;
+ timeoutMs: number;
+ env: Record<string, string>;
+}
+
+export interface ExecResult {
+ requestId: number;
+ exitCode: number;
+ durationMs: number;
+ stdout: string;
+ stderr: string;
+ error?: string;
+}
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+function varint(value: number): number[] {
+ const bytes: number[] = [];
+ let remaining = value >>> 0;
+ while (remaining > 0x7f) {
+ bytes.push((remaining & 0x7f) | 0x80);
+ remaining >>>= 7;
+ }
+ bytes.push(remaining);
+ return bytes;
+}
+
+function fieldVarint(field: number, value: number): number[] {
+ return [...varint(field << 3), ...varint(value)];
+}
+
+function fieldBytes(field: number, value: Uint8Array): number[] {
+ return [...varint((field << 3) | 2), ...varint(value.byteLength), ...value];
+}
+
+function stringField(field: number, value: string): number[] {
+ return value ? fieldBytes(field, encoder.encode(value)) : [];
+}
+
+function envEntry(key: string, value: string): Uint8Array {
+ return Uint8Array.from([...stringField(1, key), ...stringField(2, value)]);
+}
+
+export function encodeExec(request: ExecRequest): ArrayBuffer {
+ const bytes = [
+ ...fieldVarint(1, request.requestId),
+ ...stringField(2, request.command),
+ ...stringField(3, request.cwd),
+ ...fieldVarint(4, request.timeoutMs),
+ ];
+ for (const [key, value] of Object.entries(request.env)) bytes.push(...fieldBytes(5, envEntry(key, value)));
+ return Uint8Array.from(bytes).buffer;
+}
+
+class Reader {
+ private offset = 0;
+
+ constructor(private readonly bytes: Uint8Array) {}
+
+ get done(): boolean {
+ return this.offset >= this.bytes.byteLength;
+ }
+
+ uint32(): number {
+ let value = 0;
+ for (let shift = 0; shift < 35; shift += 7) {
+ if (this.offset >= this.bytes.byteLength) throw new Error("truncated protobuf varint");
+ const byte = this.bytes[this.offset++];
+ value |= (byte & 0x7f) << shift;
+ if ((byte & 0x80) === 0) return value >>> 0;
+ }
+ throw new Error("protobuf varint exceeds uint32");
+ }
+
+ bytesValue(): Uint8Array {
+ const length = this.uint32();
+ const end = this.offset + length;
+ if (end > this.bytes.byteLength) throw new Error("truncated protobuf bytes");
+ const value = this.bytes.subarray(this.offset, end);
+ this.offset = end;
+ return value;
+ }
+
+ skip(wireType: number): void {
+ if (wireType === 0) {
+ this.uint32();
+ return;
+ }
+ if (wireType === 2) {
+ this.bytesValue();
+ return;
+ }
+ throw new Error(`unsupported protobuf wire type ${wireType}`);
+ }
+}
+
+function zigZagDecode(value: number): number {
+ return (value >>> 1) ^ -(value & 1);
+}
+
+export function decodeResult(input: ArrayBuffer): ExecResult {
+ const reader = new Reader(new Uint8Array(input));
+ const result: ExecResult = { requestId: 0, exitCode: 0, durationMs: 0, stdout: "", stderr: "" };
+ while (!reader.done) {
+ const tag = reader.uint32();
+ const field = tag >>> 3;
+ const wireType = tag & 7;
+ if (field === 1 && wireType === 0) result.requestId = reader.uint32();
+ else if (field === 2 && wireType === 0) result.exitCode = zigZagDecode(reader.uint32());
+ else if (field === 3 && wireType === 0) result.durationMs = reader.uint32();
+ else if (field === 4 && wireType === 2) result.stdout = decoder.decode(reader.bytesValue());
+ else if (field === 5 && wireType === 2) result.stderr = decoder.decode(reader.bytesValue());
+ else if (field === 6 && wireType === 2) result.error = decoder.decode(reader.bytesValue());
+ else reader.skip(wireType);
+ }
+ return result;
+}
diff --git a/cloudflare-workers/api-edge/src/vm_session.ts b/cloudflare-workers/api-edge/src/vm_session.ts
new file mode 100644
index 00000000..42872592
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/vm_session.ts
@@ -0,0 +1,162 @@
+import { decodeResult, encodeExec, type ExecResult } from "./protocol";
+
+// VmSession — one Durable Object per sandbox, holding a persistent, hibernatable
+// WebSocket that the QEMU worker HOST dials into (host-dialed, not guest-dialed).
+// Exec requests arrive over HTTP (from the edge's exec route) and are relayed to
+// the host as a protobuf frame; the reply is correlated by requestId. This
+// re-homes the internal/wsgateway broker concept back into an edge DO.
+//
+// Auth is enforced at the edge /internal/vms/:id/connect route (a per-sandbox
+// HMAC over SESSION_JWT_SECRET) before the upgrade reaches this DO, so the DO
+// itself is unauthenticated glue.
+// Written in the plain-class DO style (like shared/credit_account.ts) so it needs
+// no `cloudflare:workers` import and loads under the plain-node vitest setup.
+
+interface PendingCommand {
+ resolve: (result: ExecResult) => void;
+ reject: (error: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+interface RunBody {
+ cmd?: string;
+ args?: string[];
+ cwd?: string;
+ envs?: Record<string, string>;
+ timeout?: number;
+}
+
+function json(value: unknown, init: ResponseInit = {}): Response {
+ const headers = new Headers(init.headers);
+ headers.set("content-type", "application/json");
+ return new Response(JSON.stringify(value), { ...init, headers });
+}
+
+// commandFrom flattens the SDK's {cmd,args} into a single shell string for the
+// agent's one-shot Exec. The common `sh -c "<script>"` shape is passed through
+// verbatim; anything else is shell-quoted.
+function commandFrom(body: RunBody): string {
+ if (body.cmd === "sh" && body.args?.[0] === "-c" && typeof body.args[1] === "string") return body.args[1];
+ if (!body.cmd) throw new Error("cmd is required");
+ return [body.cmd, ...(body.args ?? [])].map((part) => `'${part.replaceAll("'", `'\\''`)}'`).join(" ");
+}
+
+export class VmSession {
+ state: DurableObjectState;
+
+ private readonly pending = new Map<number, PendingCommand>();
+ private nextRequestId = Math.floor(Math.random() * 0x7fffffff) + 1;
+
+ constructor(state: DurableObjectState, _env: unknown) {
+ this.state = state;
+ // Rebind hibernation-restored sockets' message/close handlers to this
+ // instance (the runtime re-creates the DO on wake with the sockets intact).
+ // acceptWebSocket already tagged them "vm"; nothing else to restore.
+ }
+
+ // The live host WebSocket (hibernatable, tagged "vm"), if connected.
+ private connectedSocket(): WebSocket | undefined {
+ return this.state.getWebSockets("vm").find((socket) => socket.readyState === WebSocket.OPEN);
+ }
+
+ async fetch(request: Request): Promise<Response> {
+ const url = new URL(request.url);
+ if (url.pathname === "/connect") return this.acceptHostConnection();
+ if (url.pathname === "/status") return json({ connected: this.connectedSocket() !== undefined });
+ if (url.pathname === "/location") {
+ const trace = await fetch("https://www.cloudflare.com/cdn-cgi/trace").then((r) => r.text());
+ const fields = Object.fromEntries(trace.trim().split("\n").map((l) => l.split("=", 2)));
+ return json({ colo: fields.colo ?? null, loc: fields.loc ?? null });
+ }
+ if (url.pathname === "/exec" && request.method === "POST") {
+ let body: RunBody;
+ try {
+ body = (await request.json()) as RunBody;
+ } catch {
+ return json({ error: "invalid body" }, { status: 400 });
+ }
+ // connected:false lets the edge fall back to the tunnel path (no flag).
+ if (!this.connectedSocket()) return json({ connected: false, error: "vm not connected" }, { status: 409 });
+ try {
+ const result = await this.run(
+ commandFrom(body),
+ body.cwd ?? "",
+ body.envs ?? {},
+ Math.max(1, body.timeout ?? 60) * 1000,
+ );
+ return json({ exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr });
+ } catch (e) {
+ // Channel dropped mid-exec, or command errored on the agent side — 409
+ // so the edge can retry via the tunnel instead of surfacing a 500.
+ return json({ connected: false, error: String((e as Error)?.message ?? e) }, { status: 409 });
+ }
+ }
+ return new Response("not found", { status: 404 });
+ }
+
+ private acceptHostConnection(): Response {
+ // Only one host socket per box; a redial replaces the old one.
+ for (const socket of this.state.getWebSockets("vm")) socket.close(1012, "replaced");
+ const pair = new WebSocketPair();
+ const [client, server] = Object.values(pair);
+ this.state.acceptWebSocket(server, ["vm"]); // hibernatable — survives DO eviction
+ server.serializeAttachment({ role: "vm", connectedAt: Date.now() });
+ return new Response(null, {
+ status: 101,
+ headers: { "sec-websocket-protocol": "oc-protobuf-v1" },
+ webSocket: client,
+ });
+ }
+
+ private async run(command: string, cwd: string, env: Record<string, string>, timeoutMs: number): Promise<ExecResult> {
+ // Reconnect grace: a dropped socket takes the host one backoff cycle to
+ // redial. Wait briefly so a redial-in-flight becomes a slightly slower exec
+ // rather than a hard failure.
+ let socket = this.connectedSocket();
+ for (let waited = 0; !socket && waited < 3_000; waited += 100) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ socket = this.connectedSocket();
+ }
+ if (!socket) throw new Error("vm not connected");
+ const requestId = this.nextRequestId++ >>> 0 || 1;
+ const result = new Promise<ExecResult>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(requestId);
+ reject(new Error(`command timed out after ${timeoutMs}ms`));
+ }, timeoutMs + 1_000);
+ this.pending.set(requestId, { resolve, reject, timer });
+ });
+ socket.send(encodeExec({ requestId, command, cwd, timeoutMs, env }));
+ return result;
+ }
+
+ webSocketMessage(_socket: WebSocket, message: string | ArrayBuffer): void {
+ if (!(message instanceof ArrayBuffer)) return;
+ let result: ExecResult;
+ try {
+ result = decodeResult(message);
+ } catch (error) {
+ console.error("invalid VM frame", error);
+ return;
+ }
+ const pending = this.pending.get(result.requestId);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ this.pending.delete(result.requestId);
+ if (result.error) pending.reject(new Error(result.error));
+ else pending.resolve(result);
+ }
+
+ webSocketClose(_socket: WebSocket, code: number, reason: string): void {
+ const error = new Error(`vm disconnected (${code}: ${reason})`);
+ for (const [requestId, pending] of this.pending) {
+ clearTimeout(pending.timer);
+ pending.reject(error);
+ this.pending.delete(requestId);
+ }
+ }
+
+ webSocketError(_socket: WebSocket, error: unknown): void {
+ console.error("vm websocket error", error);
+ }
+}
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 31e4dab4..dfdf202d 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -86,14 +86,22 @@ name = "CREDIT_ACCOUNT"
class_name = "CreditAccount"
script_name = "opensandbox-edge-dev"
+# VM-DO exec data plane (vm_do_datapane_validation): one DO per sandbox holds the
+# host-dialed WebSocket to the QEMU worker. No script_name → same-script binding.
+[[durable_objects.bindings]]
+name = "VM_SESSIONS"
+class_name = "VmSession"
+
[[migrations]]
tag = "v1"
new_sqlite_classes = ["CreditAccount"]
-# v2 / v3 reconciliation entries were dropped after a clean `wrangler delete`
-# reset the migration ledger to v1. If you ever apply a DO change out-of-band
-# again, re-add the placeholder pattern (see git log for the old comments) or
-# just `wrangler delete --force` to reset.
+# The prior v2/v3 reconciliation entries were dropped after a clean `wrangler
+# delete` reset the migration ledger to v1; v2 below is the first real migration
+# since, adding the VmSession DO class.
+[[migrations]]
+tag = "v2"
+new_sqlite_classes = ["VmSession"]
# Secrets (set via `wrangler secret put`):
# SESSION_JWT_SECRET — HMAC for session JWT (shared with all CPs in cell fleet)
@@ -112,6 +120,9 @@ new_sqlite_classes = ["CreditAccount"]
# exposure alerts from sessions-api.
# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with the
# managed-agents backend.
+# The VM-DO exec data plane (VM_SESSIONS DO) needs NO dedicated secret: the worker
+# host authenticates its /internal/vms/:id/connect dial with a per-sandbox HMAC
+# over the already-shared SESSION_JWT_SECRET (minted by the CP, re-derived here).
# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),
# OPENROUTER_MARKUP_BPS (env-default markup; per-org orgs.model_markup_bps wins).
diff --git a/cloudflare-workers/vm-do-poc/src/index.ts b/cloudflare-workers/vm-do-poc/src/index.ts
index ee5de8ee..504730d3 100644
--- a/cloudflare-workers/vm-do-poc/src/index.ts
+++ b/cloudflare-workers/vm-do-poc/src/index.ts
@@ -157,13 +157,19 @@ export class VmSession extends DurableObject<WorkerEnv> {
}
}
+// locOpts turns DO_LOCATION_HINT into get() options. Non-empty → that
+// continental hint (wnam/enam/…). EMPTY/unset → no hint, which lets CF place
+// the DO in proximity to the colo of the request that first creates it. For a
+// VmSession that's the agent's /connect from its VM's region (westus2 → SEA,
+// eastus2 → IAD), giving tighter DO↔VM co-location than the coarse hint's pick
+// (wnam landed at LAX, ~25ms from westus2). Placement is sticky at creation, so
+// this only affects freshly-created DOs.
+function locOpts(env: { DO_LOCATION_HINT?: string }): { locationHint: DurableObjectLocationHint } | undefined {
+ return env.DO_LOCATION_HINT ? { locationHint: env.DO_LOCATION_HINT as DurableObjectLocationHint } : undefined;
+}
+
function stubFor(env: WorkerEnv, sandboxId: string): DurableObjectStub {
- // Placement hint is config, not code: the DO must sit in the same region as
- // the VM it fronts (the persistent WS is the long-lived hop; the Worker→DO
- // leg rides Cloudflare's backbone from any ingress colo). enam matches the
- // original IAD/eastus2 proof; our dev VMs are westus2 → wnam.
- const hint = (env.DO_LOCATION_HINT || "enam") as DurableObjectLocationHint;
- return env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(sandboxId), { locationHint: hint });
+ return env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(sandboxId), locOpts(env));
}
async function requireApiAuth(request: Request, env: WorkerEnv): Promise<Response | null> {
@@ -211,8 +217,7 @@ export class VmRoster extends DurableObject<WorkerEnv> {
// isLiveDiag returns liveness + a short diagnostic string (DEBUG).
private async isLiveDiag(id: string): Promise<[boolean, string]> {
try {
- const hint = (this.env.DO_LOCATION_HINT || "enam") as DurableObjectLocationHint;
- const stub = this.env.VM_SESSIONS.get(this.env.VM_SESSIONS.idFromName(id), { locationHint: hint });
+ const stub = this.env.VM_SESSIONS.get(this.env.VM_SESSIONS.idFromName(id), locOpts(this.env));
const r = await stub.fetch("https://do/lease"); // VmSession /lease → {connected}
const body = await r.text();
if (!r.ok) return [false, `${id}:status=${r.status}`];
@@ -265,13 +270,39 @@ export class VmRoster extends DurableObject<WorkerEnv> {
this.persist();
return json({ id: leasedId });
}
+ // Batch lease: hand out up to n live, unleased ids in one call. The edge
+ // Worker holds the returned batch in isolate memory and serves individual
+ // creates from it, so the per-create hot path is a local pop — 0 DO hops —
+ // and the roster (+ its liveness probe) is touched once per ~batch instead
+ // of once per create. The probe is amortised the same way. This is the POC
+ // analogue of the production PoolStock reserve.
+ if (url.pathname === "/lease-batch" && request.method === "POST") {
+ const body = (await request.json().catch(() => ({}))) as { n?: number };
+ const want = Math.max(1, Math.min(64, body.n ?? 16));
+ const out: string[] = [];
+ const dead: string[] = [];
+ for (const id of this.ids) {
+ if (out.length >= want) break;
+ if (this.leases.has(id)) continue;
+ if (await this.isLive(id)) {
+ this.leases.set(id, now);
+ out.push(id);
+ } else {
+ dead.push(id);
+ }
+ }
+ if (dead.length) this.ids = this.ids.filter((x) => !dead.includes(x));
+ this.persist();
+ return json({ ids: out });
+ }
if (url.pathname === "/release" && request.method === "POST") {
- const body = (await request.json()) as { id?: string };
- if (body.id) {
- this.leases.delete(body.id);
+ const body = (await request.json()) as { id?: string; ids?: string[] };
+ const ids = body.ids ?? (body.id ? [body.id] : []);
+ if (ids.length) {
+ for (const id of ids) this.leases.delete(id);
this.persist();
}
- return json({ ok: true });
+ return json({ ok: true, released: ids.length });
}
if (url.pathname === "/known" && request.method === "POST") {
const body = (await request.json()) as { id?: string };
@@ -285,10 +316,16 @@ export class VmRoster extends DurableObject<WorkerEnv> {
}
function rosterStub(env: WorkerEnv): DurableObjectStub {
- const hint = (env.DO_LOCATION_HINT || "enam") as DurableObjectLocationHint;
- return env.VM_ROSTER.get(env.VM_ROSTER.idFromName("roster"), { locationHint: hint });
+ return env.VM_ROSTER.get(env.VM_ROSTER.idFromName("roster"), locOpts(env));
}
+// Isolate-local pre-leased batch. create() pops from here (0 DO hops); it's
+// refilled from the roster's /lease-batch when empty. Per-isolate, so isolates
+// hold disjoint batches (the roster hands out non-overlapping ids) — no
+// cross-isolate double-allocation. Survives for the isolate's lifetime.
+const LEASE_BATCH = 16;
+let leaseBatch: string[] = [];
+
// No per-id addressability gate: the bench token is the auth, and the roster's
// job is ALLOCATION (create leases, DELETE releases), not access control. An
// exec against an id with no connected agent fails in the DO ("warm VM is not
@@ -346,18 +383,27 @@ export default {
}
if (url.pathname === "/api/sandboxes" && request.method === "POST") {
- // Real allocation: lease a VM from the roster (one DO round trip — the
- // cost the single-VM floor test omitted). Falls back to the static
- // single-VM flow when no roster is seeded.
+ // Allocation on the hot path is an isolate-local pop from a pre-leased
+ // batch (leaseBatch), so create pays 0 DO round-trips in the common case.
+ // The batch is refilled from the roster (one DO call per ~16 creates),
+ // which is where the real lease + liveness check happen — amortised, off
+ // the per-create critical path. Falls back to the static single-VM id
+ // when the roster is empty/unseeded (the original floor-test flow).
const startedAt = performance.now();
- let vmId = env.POC_VM_ID;
- const lease = await rosterStub(env).fetch("https://do/lease", { method: "POST" });
- if (lease.ok) {
- vmId = ((await lease.json()) as { id: string }).id;
- } else if (lease.status === 409) {
+ let vmId = leaseBatch.pop();
+ if (!vmId) {
+ const r = await rosterStub(env).fetch("https://do/lease-batch", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ n: LEASE_BATCH }),
+ });
+ if (r.ok) leaseBatch = ((await r.json()) as { ids: string[] }).ids ?? [];
+ vmId = leaseBatch.pop();
+ }
+ if (!vmId) {
const status = await (await rosterStub(env).fetch("https://do/status")).json<{ total: number }>();
if (status.total > 0) return json({ error: "no VMs available" }, { status: 503 });
- // total 0 → roster never seeded → static single-VM fallback
+ vmId = env.POC_VM_ID; // total 0 → roster never seeded → static fallback
}
return json({
sandboxID: vmId,
diff --git a/cloudflare-workers/vm-do-poc/wrangler.dev.jsonc b/cloudflare-workers/vm-do-poc/wrangler.dev.jsonc
index 11747feb..2e3c4195 100644
--- a/cloudflare-workers/vm-do-poc/wrangler.dev.jsonc
+++ b/cloudflare-workers/vm-do-poc/wrangler.dev.jsonc
@@ -33,7 +33,7 @@
],
"vars": {
"POC_VM_ID": "sb-ac0af601-w2",
- "DO_LOCATION_HINT": "wnam"
+ "DO_LOCATION_HINT": ""
},
"observability": {
"enabled": true,
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 5838a0cf..c8ef396c 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -673,6 +673,12 @@ func main() {
grpcServer.SetAxiomConfig(cfg.AxiomIngestToken, cfg.AxiomDataset)
// Tag wake-source metrics with the worker's region.
grpcServer.SetRegion(cfg.Region)
+ // Wire the VM-DO exec data plane. Empty URL leaves it inert (exec stays on the
+ // tunnel path); per-box it also needs a CP-minted connect token. See dodialer.go.
+ grpcServer.SetVMDialer(cfg.VMDOEdgeURL)
+ if cfg.VMDOEdgeURL != "" {
+ log.Printf("opensandbox-worker: VM-DO exec data plane enabled (edge=%s)", cfg.VMDOEdgeURL)
+ }
if cfg.AxiomIngestToken != "" {
log.Printf("opensandbox-worker: sandbox session log shipping enabled (dataset=%s)", cfg.AxiomDataset)
}
diff --git a/internal/api/router.go b/internal/api/router.go
index 6ccdd2a8..79cdd8b6 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -47,6 +47,7 @@ type Server struct {
store *db.Store // nil in combined/dev mode without PG
jwtIssuer *auth.JWTIssuer // nil if JWT not configured
capTokenIssuer *auth.JWTIssuer // verifies edge→CP capability tokens; nil if SESSION_JWT_SECRET unset
+ sessionJWTSecret string // raw shared edge↔CP HMAC secret; mints per-sandbox VM-DO connect tokens (see auth.MintVMDOConnectToken)
requireCapToken bool // derived from PRO_BILLING_AUTHORITY=edge: reject direct API-key creates that bypass edge billing (split mode only)
cfAdminSecret string // HMAC shared with CreditAccount DO for /admin/halt-org and /admin/resume-org; empty disables auth (dev only)
cfEventSecret string // HMAC shared with the api-edge Worker for /internal/secret-refresh and other edge-→cell push paths
@@ -190,6 +191,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.jwtIssuer = opts.JWTIssuer
if opts.SessionJWTSecret != "" {
s.capTokenIssuer = auth.NewJWTIssuer(opts.SessionJWTSecret)
+ s.sessionJWTSecret = opts.SessionJWTSecret // raw key for VM-DO connect-token minting
}
s.requireCapToken = opts.RequireCapToken
s.cfAdminSecret = opts.CFAdminSecret
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 3cf4b72f..47dbdd7d 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -691,12 +691,13 @@ func (s *Server) tryClaimPooled(c echo.Context, ctx context.Context, cfg types.S
grpcCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
claimResp, err := client.ClaimSandbox(grpcCtx, &pb.ClaimSandboxRequest{
- SandboxId: box.SandboxID,
- Timeout: int32(cfg.Timeout),
- Envs: cfg.Envs,
- SecretEnvs: cfg.SecretEnvs,
- MemoryMb: int32(cfg.MemoryMB),
- CpuCount: int32(cfg.CpuCount),
+ SandboxId: box.SandboxID,
+ Timeout: int32(cfg.Timeout),
+ Envs: cfg.Envs,
+ SecretEnvs: cfg.SecretEnvs,
+ MemoryMb: int32(cfg.MemoryMB),
+ CpuCount: int32(cfg.CpuCount),
+ VmdoConnectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, box.SandboxID),
})
if err != nil {
log.Printf("sandbox: ClaimSandbox %s failed (%v) — failing it + cold create", box.SandboxID, err)
@@ -935,6 +936,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
SecretAllowedHosts: flattenSecretAllowedHosts(cfg.SecretAllowedHosts),
SecretEnvs: cfg.SecretEnvs,
DiskMb: int32(cfg.DiskMB),
+ VmdoConnectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, sandboxID),
})
if err != nil {
// Mark session as failed so it doesn't count as active.
@@ -2440,9 +2442,10 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W
defer cancel()
grpcResp, err := grpcClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{
- SandboxId: sandboxID,
- CheckpointKey: hibernation.HibernationKey,
- Timeout: int32(req.Timeout),
+ SandboxId: sandboxID,
+ CheckpointKey: hibernation.HibernationKey,
+ Timeout: int32(req.Timeout),
+ VmdoConnectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, sandboxID),
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
@@ -3364,6 +3367,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
EgressAllowlist: originalCfg.EgressAllowlist,
SecretAllowedHosts: flattenSecretAllowedHosts(originalCfg.SecretAllowedHosts),
SecretEnvs: originalCfg.SecretEnvs,
+ VmdoConnectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, sandboxID),
})
createErr = err
if resp != nil {
diff --git a/internal/auth/vmdo_token.go b/internal/auth/vmdo_token.go
new file mode 100644
index 00000000..e2fdea01
--- /dev/null
+++ b/internal/auth/vmdo_token.go
@@ -0,0 +1,29 @@
+package auth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+)
+
+// VM-DO connect token (vm_do_datapane_validation): the credential the QEMU worker
+// host presents when it dials a sandbox's VmSession Durable Object on the edge.
+//
+// It is a per-sandbox HMAC over the sandbox id, keyed by SESSION_JWT_SECRET — the
+// secret the edge and CP already share (the CP mints it, the edge re-verifies).
+// The worker never holds the signing key, only this derived token, so a
+// compromised worker can hijack at most the one channel it was handed, never
+// forge a token for another sandbox. The "vmdo:" domain prefix keeps it from
+// colliding with any other HMAC use of the same secret.
+//
+// The edge's verifier (cloudflare-workers/api-edge/src/index.ts) recomputes this
+// exact construction — keep the two in lockstep: lower-hex(HMAC_SHA256(secret,
+// "vmdo:"+id)).
+func MintVMDOConnectToken(sessionJWTSecret, sandboxID string) string {
+ if sessionJWTSecret == "" || sandboxID == "" {
+ return ""
+ }
+ mac := hmac.New(sha256.New, []byte(sessionJWTSecret))
+ mac.Write([]byte("vmdo:" + sandboxID))
+ return hex.EncodeToString(mac.Sum(nil))
+}
diff --git a/internal/auth/vmdo_token_test.go b/internal/auth/vmdo_token_test.go
new file mode 100644
index 00000000..2c1f2c96
--- /dev/null
+++ b/internal/auth/vmdo_token_test.go
@@ -0,0 +1,34 @@
+package auth
+
+import "testing"
+
+func TestMintVMDOConnectToken(t *testing.T) {
+ // Golden vector: lower-hex(HMAC_SHA256("test-secret", "vmdo:sb-123")).
+ // Independently reproduced with:
+ // printf 'vmdo:sb-123' | openssl dgst -sha256 -hmac 'test-secret' -r
+ // The edge verifier (api-edge hmacHex(SESSION_JWT_SECRET, "vmdo:"+id)) MUST
+ // produce this same string — if you change the construction, change both.
+ const want = "0620f45637a37ca53c93dcf2e33f63e3f6c56124f0c929a6ae25e7b9ef25e477"
+ if got := MintVMDOConnectToken("test-secret", "sb-123"); got != want {
+ t.Errorf("token = %q, want %q", got, want)
+ }
+}
+
+func TestMintVMDOConnectTokenEmpty(t *testing.T) {
+ if MintVMDOConnectToken("", "sb-123") != "" {
+ t.Error("no secret should yield empty token")
+ }
+ if MintVMDOConnectToken("secret", "") != "" {
+ t.Error("no sandbox id should yield empty token")
+ }
+}
+
+func TestMintVMDOConnectTokenPerSandbox(t *testing.T) {
+ // Different sandbox ids must yield different tokens (per-box scoping is the
+ // whole point — a leaked token can't be replayed against another box).
+ a := MintVMDOConnectToken("secret", "sb-a")
+ b := MintVMDOConnectToken("secret", "sb-b")
+ if a == b || a == "" {
+ t.Errorf("tokens should differ per sandbox: %q vs %q", a, b)
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index ac424650..fbf5bc09 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -200,6 +200,15 @@ type Config struct {
AxiomQueryToken string
AxiomDataset string
+ // VM-DO exec data plane (vm_do_datapane_validation). When set, the worker host
+ // dials a per-sandbox VmSession Durable Object on the edge and serves exec over
+ // that persistent WebSocket (edge→DO→host→agent), bypassing the tunnel→CP→worker
+ // hop — but only for boxes the CP hands a connect token (per-sandbox, on
+ // create/claim/wake; the worker holds no signing secret). Empty = the dialer is
+ // inert and every exec takes the tunnel path (the edge's automatic fallback).
+ // VMDOEdgeURL is the wss:// (or https://) base of the api-edge Worker.
+ VMDOEdgeURL string
+
// AWS Secrets Manager — if set, secrets are fetched at startup using IAM credentials.
// The secret should be a JSON object with keys matching env var names (e.g. OPENSANDBOX_JWT_SECRET).
// Env vars take precedence over secret values (for local overrides).
@@ -434,6 +443,8 @@ func Load() (*Config, error) {
AxiomQueryToken: os.Getenv("AXIOM_QUERY_TOKEN"),
AxiomDataset: envOrDefault("AXIOM_DATASET", "oc-sandbox-logs"),
+ VMDOEdgeURL: os.Getenv("OPENSANDBOX_VMDO_EDGE_URL"),
+
SecretsARN: os.Getenv("OPENSANDBOX_SECRETS_ARN"),
SecretEncryptionKey: os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY"),
diff --git a/internal/worker/dodialer.go b/internal/worker/dodialer.go
new file mode 100644
index 00000000..9323c49f
--- /dev/null
+++ b/internal/worker/dodialer.go
@@ -0,0 +1,509 @@
+package worker
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "fmt"
+ "log"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// dodialer.go — the QEMU worker HOST side of the VM-DO exec data plane
+// (vm_do_datapane_validation). For each customer-usable sandbox on this worker
+// the host opens a persistent outbound WebSocket to the sandbox's VmSession
+// Durable Object on the edge (wss://<edge>/internal/vms/<id>/connect). The DO
+// relays exec requests over that socket as protobuf frames; the host runs them
+// against the in-guest agent (via the same manager.Exec the tunnel path uses)
+// and replies with a result frame keyed by requestId.
+//
+// This re-homes the internal/wsgateway broker concept as a host→edge dial. It is
+// host-dialed (not guest-dialed): the credential never enters the untrusted
+// guest, egress allowlists don't sever it, and it is torn down/re-established on
+// the box's lifecycle transitions rather than dying with a guest process.
+//
+// Auth is a per-sandbox connect token (auth.MintVMDOConnectToken), minted by the
+// CP and delivered to the worker over the already-authenticated create/claim/wake
+// gRPC. The worker holds no signing secret — only the token for the boxes it
+// hosts — and presents it as the 2nd WS subprotocol; the edge re-derives and
+// compares. A box with no token simply doesn't dial (exec stays on the tunnel).
+//
+// Scope is deliberately narrow — one-shot buffered exec, which is all the TTI
+// benchmark (create→node -v→destroy) exercises. Files/PTY/streaming stay on the
+// tunnel; the edge falls back to it automatically whenever the DO reports the
+// channel isn't live, so a dialer that never connects only costs a fallback, not
+// a failure.
+
+const (
+ // Keepalive matches the POC's validated cadence: an app-level ping every
+ // 30s, and terminate+reconnect if no pong lands within ~2.5 intervals. A
+ // silent half-open (DO evicted, FIN lost) otherwise looks OPEN forever.
+ doPingPeriod = 30 * time.Second
+ doPongWait = 75 * time.Second
+
+ doHandshakeTimeout = 10 * time.Second
+ doDialBackoffMin = 250 * time.Millisecond
+ doDialBackoffMax = 10 * time.Second
+
+ // A single result frame must stay under the Workers WebSocket message cap
+ // (~1 MiB). Larger buffered output is truncated to this combined budget —
+ // parity with the tunnel path's 1 MB scrollback ring. Commands that need
+ // unbounded/streaming output aren't served here anyway (they attach over the
+ // tunnel); this only bounds the run-async buffered result.
+ doMaxOutputBytes = 900 * 1024
+
+ // wsSubprotocol marks the binary exec wire format; the connect secret rides
+ // as the 2nd subprotocol (mirrors the edge's socketSecret parsing).
+ wsSubprotocol = "oc-protobuf-v1"
+)
+
+// doExecFn runs one buffered command against a sandbox's in-guest agent. It is
+// s.manager.Exec — the exact one-shot path (with transport-error redial
+// recovery) the tunnel exec uses, so DO-served and tunnel-served execs are
+// byte-for-byte equivalent.
+type doExecFn func(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error)
+
+// doDialerRegistry owns the per-sandbox host dialers. Inert (start/stop no-op)
+// unless an edge URL is configured; per-sandbox it also needs a connect token.
+type doDialerRegistry struct {
+ edgeWSBase string // e.g. wss://opensandbox-edge-dev.example
+ execFn doExecFn
+
+ mu sync.Mutex
+ dialers map[string]*doDialer
+}
+
+func newDoDialerRegistry(edgeURL string, execFn doExecFn) *doDialerRegistry {
+ // Accept an https:// base for convenience and normalize to wss:// (the
+ // gorilla dialer requires a ws/wss scheme).
+ base := strings.TrimRight(edgeURL, "/")
+ switch {
+ case strings.HasPrefix(base, "https://"):
+ base = "wss://" + strings.TrimPrefix(base, "https://")
+ case strings.HasPrefix(base, "http://"):
+ base = "ws://" + strings.TrimPrefix(base, "http://")
+ }
+ return &doDialerRegistry{
+ edgeWSBase: base,
+ execFn: execFn,
+ dialers: make(map[string]*doDialer),
+ }
+}
+
+func (r *doDialerRegistry) enabled() bool {
+ return r != nil && r.edgeWSBase != ""
+}
+
+// start begins (or leaves running) the host dialer for a sandbox, using the
+// per-sandbox connect token the CP delivered. Idempotent: a second call for a
+// live sandbox is a no-op. An empty token means the VM-DO plane isn't provisioned
+// for this box → no dial (exec stays on the tunnel). Safe to call from any
+// lifecycle success tail (claim, create, warm-fork, wake).
+func (r *doDialerRegistry) start(sandboxID, token string) {
+ if !r.enabled() || token == "" {
+ return
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if _, ok := r.dialers[sandboxID]; ok {
+ return
+ }
+ url := fmt.Sprintf("%s/internal/vms/%s/connect", r.edgeWSBase, sandboxID)
+ d := newDoDialer(url, token, sandboxID, r.execFn)
+ r.dialers[sandboxID] = d
+ d.run()
+}
+
+// stop tears the dialer down deterministically so a reaped/hibernated box can't
+// keep serving a stale channel. Idempotent.
+func (r *doDialerRegistry) stop(sandboxID string) {
+ if r == nil {
+ return
+ }
+ r.mu.Lock()
+ d := r.dialers[sandboxID]
+ delete(r.dialers, sandboxID)
+ r.mu.Unlock()
+ if d != nil {
+ d.close()
+ }
+}
+
+// doDialer is one sandbox's reconnecting host→DO WebSocket. A single background
+// goroutine owns the dial/serve/backoff loop until close() cancels it.
+type doDialer struct {
+ url string
+ token string // per-sandbox connect token, presented as the 2nd WS subprotocol
+ sandboxID string
+ execFn doExecFn
+
+ ctx context.Context
+ cancel context.CancelFunc
+ wg sync.WaitGroup
+}
+
+func newDoDialer(url, token, sandboxID string, execFn doExecFn) *doDialer {
+ ctx, cancel := context.WithCancel(context.Background())
+ return &doDialer{url: url, token: token, sandboxID: sandboxID, execFn: execFn, ctx: ctx, cancel: cancel}
+}
+
+func (d *doDialer) run() {
+ d.wg.Add(1)
+ go d.loop()
+}
+
+func (d *doDialer) close() {
+ d.cancel()
+ // Don't Wait() here: close() is called on the gRPC hot path (destroy /
+ // hibernate) and the loop unwinds on its own once ctx is cancelled. The
+ // blocked ReadMessage returns when the deferred conn.Close fires.
+}
+
+func (d *doDialer) loop() {
+ defer d.wg.Done()
+ backoff := doDialBackoffMin
+ for {
+ if d.ctx.Err() != nil {
+ return
+ }
+ if d.serveOnce() {
+ backoff = doDialBackoffMin // clean connection resets the ladder
+ }
+ if d.ctx.Err() != nil {
+ return
+ }
+ select {
+ case <-d.ctx.Done():
+ return
+ case <-time.After(backoff):
+ }
+ backoff *= 2
+ if backoff > doDialBackoffMax {
+ backoff = doDialBackoffMax
+ }
+ }
+}
+
+// serveOnce dials, serves the read loop until the socket drops, and returns true
+// if the connection was established (so the caller can reset backoff).
+func (d *doDialer) serveOnce() (connected bool) {
+ dialer := websocket.Dialer{
+ HandshakeTimeout: doHandshakeTimeout,
+ // The DO echoes "oc-protobuf-v1"; offering the per-sandbox token as the
+ // 2nd subprotocol carries the credential without a custom header (which
+ // the CF edge upgrade wouldn't forward).
+ Subprotocols: []string{wsSubprotocol, d.token},
+ }
+ conn, resp, err := dialer.DialContext(d.ctx, d.url, nil)
+ if err != nil {
+ status := 0
+ if resp != nil {
+ status = resp.StatusCode
+ }
+ // Quiet on shutdown; a canceled ctx surfaces as a dial error.
+ if d.ctx.Err() == nil {
+ log.Printf("vmdo: dial %s failed (status=%d): %v", d.sandboxID, status, err)
+ }
+ return false
+ }
+ defer conn.Close()
+ log.Printf("vmdo: connected %s", d.sandboxID)
+
+ // Read deadline is the pong watchdog: every pong (and every inbound frame)
+ // pushes it out; if pongs stop landing it fires and ReadMessage errors,
+ // dropping us into the reconnect loop.
+ _ = conn.SetReadDeadline(time.Now().Add(doPongWait))
+ conn.SetPongHandler(func(string) error {
+ return conn.SetReadDeadline(time.Now().Add(doPongWait))
+ })
+
+ // gorilla permits one concurrent writer; execs reply from per-request
+ // goroutines, so serialize data writes. Ping uses WriteControl, which
+ // gorilla documents as safe alongside other methods.
+ var writeMu sync.Mutex
+
+ pingCtx, stopPing := context.WithCancel(d.ctx)
+ defer stopPing()
+ go func() {
+ ticker := time.NewTicker(doPingPeriod)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-pingCtx.Done():
+ return
+ case <-ticker.C:
+ if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil {
+ return
+ }
+ }
+ }
+ }()
+
+ // Close the conn when the dialer is cancelled so a blocked ReadMessage
+ // unwinds promptly on destroy/hibernate.
+ go func() {
+ <-pingCtx.Done()
+ _ = conn.Close()
+ }()
+
+ for {
+ msgType, data, err := conn.ReadMessage()
+ if err != nil {
+ if d.ctx.Err() == nil {
+ log.Printf("vmdo: read %s: %v", d.sandboxID, err)
+ }
+ return true
+ }
+ if msgType != websocket.BinaryMessage {
+ continue
+ }
+ _ = conn.SetReadDeadline(time.Now().Add(doPongWait))
+ req, derr := decodeExecRequest(data)
+ if derr != nil {
+ log.Printf("vmdo: bad exec frame %s: %v", d.sandboxID, derr)
+ continue
+ }
+ go d.handleExec(conn, &writeMu, req)
+ }
+}
+
+// handleExec runs one decoded request against the agent and writes the result
+// frame back. Any agent/transport failure is returned as the frame's error
+// field, which the DO turns into a 409 so the edge retries via the tunnel.
+func (d *doDialer) handleExec(conn *websocket.Conn, writeMu *sync.Mutex, req execRequest) {
+ timeoutSec := int((req.timeoutMs + 999) / 1000)
+ if timeoutSec <= 0 {
+ timeoutSec = 60
+ }
+ // Cap the RPC a little past the command's own timeout so a wedged agent
+ // call can't leak the goroutine.
+ ctx, cancel := context.WithTimeout(d.ctx, time.Duration(timeoutSec)*time.Second+5*time.Second)
+ defer cancel()
+
+ started := time.Now()
+ res, err := d.execFn(ctx, d.sandboxID, types.ProcessConfig{
+ Command: req.command, // flattened shell string; manager.Exec wraps it in /bin/sh -c
+ Env: req.env,
+ Cwd: req.cwd,
+ Timeout: timeoutSec,
+ })
+ durMs := uint32(time.Since(started).Milliseconds())
+
+ var frame []byte
+ if err != nil {
+ frame = encodeExecResult(req.requestID, 1, durMs, "", "", err.Error())
+ } else {
+ stdout, stderr := capOutput(res.Stdout, res.Stderr)
+ frame = encodeExecResult(req.requestID, int32(res.ExitCode), durMs, stdout, stderr, "")
+ }
+
+ writeMu.Lock()
+ _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
+ werr := conn.WriteMessage(websocket.BinaryMessage, frame)
+ writeMu.Unlock()
+ if werr != nil && d.ctx.Err() == nil {
+ log.Printf("vmdo: write result %s: %v", d.sandboxID, werr)
+ }
+}
+
+// capOutput bounds the combined stdout+stderr so the result frame stays under
+// the WebSocket message cap. stdout is favored (it carries the command result);
+// stderr gets whatever budget remains. Truncation keeps the head of each stream,
+// matching the tunnel scrollback's behavior for parity.
+func capOutput(stdout, stderr string) (string, string) {
+ if len(stdout)+len(stderr) <= doMaxOutputBytes {
+ return stdout, stderr
+ }
+ if len(stdout) >= doMaxOutputBytes {
+ return stdout[:doMaxOutputBytes], ""
+ }
+ remaining := doMaxOutputBytes - len(stdout)
+ if len(stderr) > remaining {
+ stderr = stderr[:remaining]
+ }
+ return stdout, stderr
+}
+
+// ── protobuf codec (opencomputer.edge.v1 ExecRequest/ExecResult) ────────────
+// Hand-rolled to match cloudflare-workers/api-edge/src/protocol.ts byte-for-byte
+// without pulling in a generated stub. ExecRequest is decoded (DO→host);
+// ExecResult is encoded (host→DO).
+
+type execRequest struct {
+ requestID uint32
+ command string
+ cwd string
+ timeoutMs uint32
+ env map[string]string
+}
+
+func decodeExecRequest(buf []byte) (execRequest, error) {
+ r := execRequest{env: map[string]string{}}
+ i := 0
+ for i < len(buf) {
+ tag, n := binary.Uvarint(buf[i:])
+ if n <= 0 {
+ return r, fmt.Errorf("bad tag varint")
+ }
+ i += n
+ field := tag >> 3
+ wire := tag & 7
+ switch {
+ case field == 1 && wire == 0:
+ v, m, err := readUvarint(buf, i)
+ if err != nil {
+ return r, err
+ }
+ r.requestID = uint32(v)
+ i = m
+ case field == 2 && wire == 2:
+ v, m, err := readBytes(buf, i)
+ if err != nil {
+ return r, err
+ }
+ r.command = string(v)
+ i = m
+ case field == 3 && wire == 2:
+ v, m, err := readBytes(buf, i)
+ if err != nil {
+ return r, err
+ }
+ r.cwd = string(v)
+ i = m
+ case field == 4 && wire == 0:
+ v, m, err := readUvarint(buf, i)
+ if err != nil {
+ return r, err
+ }
+ r.timeoutMs = uint32(v)
+ i = m
+ case field == 5 && wire == 2:
+ v, m, err := readBytes(buf, i)
+ if err != nil {
+ return r, err
+ }
+ k, val := decodeEnvEntry(v)
+ r.env[k] = val
+ i = m
+ default:
+ m, err := skipField(buf, i, wire)
+ if err != nil {
+ return r, err
+ }
+ i = m
+ }
+ }
+ if r.requestID == 0 || r.command == "" {
+ return r, fmt.Errorf("request_id and command are required")
+ }
+ return r, nil
+}
+
+// decodeEnvEntry parses a map<string,string> entry message ({1:key, 2:value}).
+func decodeEnvEntry(buf []byte) (key, value string) {
+ i := 0
+ for i < len(buf) {
+ tag, n := binary.Uvarint(buf[i:])
+ if n <= 0 {
+ return
+ }
+ i += n
+ field := tag >> 3
+ wire := tag & 7
+ if wire != 2 {
+ m, err := skipField(buf, i, wire)
+ if err != nil {
+ return
+ }
+ i = m
+ continue
+ }
+ v, m, err := readBytes(buf, i)
+ if err != nil {
+ return
+ }
+ if field == 1 {
+ key = string(v)
+ } else if field == 2 {
+ value = string(v)
+ }
+ i = m
+ }
+ return
+}
+
+func readUvarint(buf []byte, i int) (uint64, int, error) {
+ v, n := binary.Uvarint(buf[i:])
+ if n <= 0 {
+ return 0, i, fmt.Errorf("truncated varint")
+ }
+ return v, i + n, nil
+}
+
+func readBytes(buf []byte, i int) ([]byte, int, error) {
+ l, n := binary.Uvarint(buf[i:])
+ if n <= 0 {
+ return nil, i, fmt.Errorf("truncated length")
+ }
+ i += n
+ end := i + int(l)
+ if end > len(buf) || end < i {
+ return nil, i, fmt.Errorf("truncated bytes")
+ }
+ return buf[i:end], end, nil
+}
+
+func skipField(buf []byte, i int, wire uint64) (int, error) {
+ switch wire {
+ case 0:
+ _, n := binary.Uvarint(buf[i:])
+ if n <= 0 {
+ return i, fmt.Errorf("truncated varint")
+ }
+ return i + n, nil
+ case 2:
+ _, m, err := readBytes(buf, i)
+ return m, err
+ default:
+ return i, fmt.Errorf("unsupported wire type %d", wire)
+ }
+}
+
+func encodeExecResult(requestID uint32, exitCode int32, durationMs uint32, stdout, stderr, errStr string) []byte {
+ var b bytes.Buffer
+ writeVarintField(&b, 1, uint64(requestID))
+ writeVarintField(&b, 2, uint64(zigzag32(exitCode)))
+ writeVarintField(&b, 3, uint64(durationMs))
+ writeBytesField(&b, 4, []byte(stdout))
+ writeBytesField(&b, 5, []byte(stderr))
+ if errStr != "" {
+ writeBytesField(&b, 6, []byte(errStr))
+ }
+ return b.Bytes()
+}
+
+func writeVarintField(b *bytes.Buffer, field int, v uint64) {
+ writeUvarint(b, uint64(field)<<3|0)
+ writeUvarint(b, v)
+}
+
+func writeBytesField(b *bytes.Buffer, field int, v []byte) {
+ writeUvarint(b, uint64(field)<<3|2)
+ writeUvarint(b, uint64(len(v)))
+ b.Write(v)
+}
+
+func writeUvarint(b *bytes.Buffer, v uint64) {
+ var tmp [binary.MaxVarintLen64]byte
+ n := binary.PutUvarint(tmp[:], v)
+ b.Write(tmp[:n])
+}
+
+func zigzag32(v int32) uint32 {
+ return uint32((v << 1) ^ (v >> 31))
+}
diff --git a/internal/worker/dodialer_test.go b/internal/worker/dodialer_test.go
new file mode 100644
index 00000000..d638f58b
--- /dev/null
+++ b/internal/worker/dodialer_test.go
@@ -0,0 +1,268 @@
+package worker
+
+import (
+ "bytes"
+ "encoding/binary"
+ "testing"
+)
+
+// These tests pin the Go host codec to the TypeScript wire format in
+// cloudflare-workers/api-edge/src/protocol.ts. tsEncodeExec / tsDecodeResult are
+// faithful Go transcriptions of that file's encodeExec / decodeResult, so a pass
+// means the DO (encoder of ExecRequest, decoder of ExecResult) and the host
+// (decoder of ExecRequest, encoder of ExecResult) agree byte-for-byte.
+
+// tsEncodeExec mirrors protocol.ts encodeExec.
+func tsEncodeExec(requestID uint32, command, cwd string, timeoutMs uint32, env map[string]string) []byte {
+ var b bytes.Buffer
+ putVarintField := func(field int, v uint64) {
+ putUvarint(&b, uint64(field)<<3|0)
+ putUvarint(&b, v)
+ }
+ putBytesField := func(field int, v []byte) {
+ putUvarint(&b, uint64(field)<<3|2)
+ putUvarint(&b, uint64(len(v)))
+ b.Write(v)
+ }
+ putStringField := func(field int, v string) {
+ if v != "" {
+ putBytesField(field, []byte(v))
+ }
+ }
+ putVarintField(1, uint64(requestID))
+ putStringField(2, command)
+ putStringField(3, cwd)
+ putVarintField(4, uint64(timeoutMs))
+ for k, v := range env {
+ var entry bytes.Buffer
+ // entry = {field1: key, field2: value}
+ putUvarint(&entry, 1<<3|2)
+ putUvarint(&entry, uint64(len(k)))
+ entry.WriteString(k)
+ putUvarint(&entry, 2<<3|2)
+ putUvarint(&entry, uint64(len(v)))
+ entry.WriteString(v)
+ putBytesField(5, entry.Bytes())
+ }
+ return b.Bytes()
+}
+
+func putUvarint(b *bytes.Buffer, v uint64) {
+ var tmp [binary.MaxVarintLen64]byte
+ n := binary.PutUvarint(tmp[:], v)
+ b.Write(tmp[:n])
+}
+
+// tsDecodeResult mirrors protocol.ts decodeResult (incl. zigzag on field 2).
+func tsDecodeResult(t *testing.T, buf []byte) (requestID uint32, exitCode int32, durationMs uint32, stdout, stderr, errStr string) {
+ i := 0
+ for i < len(buf) {
+ tag, n := binary.Uvarint(buf[i:])
+ if n <= 0 {
+ t.Fatalf("bad tag")
+ }
+ i += n
+ field := tag >> 3
+ wire := tag & 7
+ switch {
+ case field == 1 && wire == 0:
+ v, m := binary.Uvarint(buf[i:])
+ requestID = uint32(v)
+ i += m
+ case field == 2 && wire == 0:
+ v, m := binary.Uvarint(buf[i:])
+ exitCode = int32(v>>1) ^ -int32(v&1) // zigzag decode
+ i += m
+ case field == 3 && wire == 0:
+ v, m := binary.Uvarint(buf[i:])
+ durationMs = uint32(v)
+ i += m
+ case field == 4 && wire == 2:
+ l, m := binary.Uvarint(buf[i:])
+ i += m
+ stdout = string(buf[i : i+int(l)])
+ i += int(l)
+ case field == 5 && wire == 2:
+ l, m := binary.Uvarint(buf[i:])
+ i += m
+ stderr = string(buf[i : i+int(l)])
+ i += int(l)
+ case field == 6 && wire == 2:
+ l, m := binary.Uvarint(buf[i:])
+ i += m
+ errStr = string(buf[i : i+int(l)])
+ i += int(l)
+ default:
+ t.Fatalf("unexpected field=%d wire=%d", field, wire)
+ }
+ }
+ return
+}
+
+func TestDecodeExecRequest(t *testing.T) {
+ frame := tsEncodeExec(42, "node -v", "/work", 30000, map[string]string{"FOO": "bar"})
+ req, err := decodeExecRequest(frame)
+ if err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if req.requestID != 42 {
+ t.Errorf("requestID = %d, want 42", req.requestID)
+ }
+ if req.command != "node -v" {
+ t.Errorf("command = %q, want %q", req.command, "node -v")
+ }
+ if req.cwd != "/work" {
+ t.Errorf("cwd = %q, want %q", req.cwd, "/work")
+ }
+ if req.timeoutMs != 30000 {
+ t.Errorf("timeoutMs = %d, want 30000", req.timeoutMs)
+ }
+ if req.env["FOO"] != "bar" {
+ t.Errorf("env[FOO] = %q, want bar", req.env["FOO"])
+ }
+}
+
+func TestDecodeExecRequestOmitsEmptyStrings(t *testing.T) {
+ // TS encodeExec omits empty cwd (stringField no-op); decode must default it.
+ frame := tsEncodeExec(7, "ls", "", 0, nil)
+ req, err := decodeExecRequest(frame)
+ if err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if req.cwd != "" {
+ t.Errorf("cwd = %q, want empty", req.cwd)
+ }
+ if req.requestID != 7 || req.command != "ls" {
+ t.Errorf("got id=%d cmd=%q", req.requestID, req.command)
+ }
+}
+
+func TestDecodeExecRequestRejectsIncomplete(t *testing.T) {
+ // Missing command must be rejected (mirrors the guest agent's guard).
+ frame := tsEncodeExec(1, "", "", 0, nil)
+ if _, err := decodeExecRequest(frame); err == nil {
+ t.Fatal("expected error for missing command")
+ }
+}
+
+func TestEncodeExecResultRoundTrip(t *testing.T) {
+ cases := []struct {
+ name string
+ exitCode int32
+ errStr string
+ }{
+ {"zero", 0, ""},
+ {"one", 1, ""},
+ {"negative", -1, ""},
+ {"timeout", -1, "command timed out"},
+ {"big", 137, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ frame := encodeExecResult(99, tc.exitCode, 1234, "out", "err", tc.errStr)
+ id, code, dur, so, se, es := tsDecodeResult(t, frame)
+ if id != 99 {
+ t.Errorf("requestID = %d, want 99", id)
+ }
+ if code != tc.exitCode {
+ t.Errorf("exitCode = %d, want %d", code, tc.exitCode)
+ }
+ if dur != 1234 {
+ t.Errorf("durationMs = %d, want 1234", dur)
+ }
+ if so != "out" || se != "err" {
+ t.Errorf("stdout/stderr = %q/%q", so, se)
+ }
+ if es != tc.errStr {
+ t.Errorf("error = %q, want %q", es, tc.errStr)
+ }
+ })
+ }
+}
+
+func TestEncodeExecResultOmitsEmptyError(t *testing.T) {
+ // error field (6) must be absent when empty so the DO doesn't reject a
+ // success as a failure.
+ frame := encodeExecResult(1, 0, 0, "", "", "")
+ for i := 0; i < len(frame); {
+ tag, n := binary.Uvarint(frame[i:])
+ i += n
+ field := tag >> 3
+ wire := tag & 7
+ if field == 6 {
+ t.Fatal("error field present for empty error")
+ }
+ if wire == 2 {
+ l, m := binary.Uvarint(frame[i:])
+ i += m + int(l)
+ }
+ }
+}
+
+func TestRegistryDisabledWhenUnconfigured(t *testing.T) {
+ r := newDoDialerRegistry("", nil)
+ if r.enabled() {
+ t.Fatal("registry with empty url should be disabled")
+ }
+ // start/stop on a disabled registry must be safe no-ops.
+ r.start("sbx-1", "tok")
+ r.stop("sbx-1")
+
+ var nilReg *doDialerRegistry
+ nilReg.start("sbx-2", "tok") // must not panic
+ nilReg.stop("sbx-2")
+ if nilReg.enabled() {
+ t.Fatal("nil registry should be disabled")
+ }
+}
+
+func TestRegistryStartRequiresToken(t *testing.T) {
+ // An enabled registry with an empty token must not dial (no token → tunnel).
+ r := newDoDialerRegistry("wss://edge.example", nil)
+ r.start("sbx-1", "")
+ r.mu.Lock()
+ n := len(r.dialers)
+ r.mu.Unlock()
+ if n != 0 {
+ t.Errorf("empty token should not start a dialer, got %d", n)
+ }
+}
+
+func TestCapOutput(t *testing.T) {
+ // Small output passes through untouched.
+ so, se := capOutput("hello", "world")
+ if so != "hello" || se != "world" {
+ t.Errorf("small output altered: %q/%q", so, se)
+ }
+
+ // Combined over budget: stdout kept (head), stderr gets the remainder.
+ bigOut := string(bytes.Repeat([]byte("a"), doMaxOutputBytes-10))
+ bigErr := string(bytes.Repeat([]byte("b"), 100))
+ so, se = capOutput(bigOut, bigErr)
+ if len(so)+len(se) > doMaxOutputBytes {
+ t.Errorf("capped total %d exceeds budget %d", len(so)+len(se), doMaxOutputBytes)
+ }
+ if len(so) != len(bigOut) {
+ t.Errorf("stdout should be preserved when under budget alone, got %d", len(so))
+ }
+ if len(se) != 10 {
+ t.Errorf("stderr should be trimmed to remaining 10, got %d", len(se))
+ }
+
+ // stdout alone over budget: stderr dropped, stdout truncated to budget.
+ hugeOut := string(bytes.Repeat([]byte("a"), doMaxOutputBytes*2))
+ so, se = capOutput(hugeOut, "x")
+ if len(so) != doMaxOutputBytes || se != "" {
+ t.Errorf("huge stdout: got len(so)=%d se=%q", len(so), se)
+ }
+}
+
+func TestRegistryNormalizesScheme(t *testing.T) {
+ r := newDoDialerRegistry("https://edge.example/", nil)
+ if r.edgeWSBase != "wss://edge.example" {
+ t.Errorf("edgeWSBase = %q, want wss://edge.example", r.edgeWSBase)
+ }
+ if !r.enabled() {
+ t.Fatal("registry with url should be enabled")
+ }
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 2101641d..e7487205 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -91,6 +91,11 @@ type GRPCServer struct {
// Set via SetRegion at startup. Empty = "unknown".
region string
+ // doDialers owns the per-sandbox host→edge WebSocket dialers for the VM-DO
+ // exec data plane. nil (or a disabled registry) means every exec takes the
+ // tunnel path. Wired via SetVMDialer at startup. See dodialer.go.
+ doDialers *doDialerRegistry
+
// checkpointFetchSF collapses concurrent forks of the same checkpoint that
// all miss the local cache into a single S3 download+extract; the rest wait
// and reuse it. Keyed by checkpoint id. See ensureFullCheckpointCached.
@@ -110,6 +115,17 @@ func (s *GRPCServer) SetAxiomConfig(ingestToken, dataset string) {
s.axiomDataset = dataset
}
+// SetVMDialer wires the VM-DO exec data plane. When edgeURL is non-empty, the
+// worker host dials a per-sandbox VmSession Durable Object on the edge and serves
+// exec over it (edge→DO→host→agent), bypassing the tunnel hop — but only for
+// boxes the CP hands a connect token (delivered per-sandbox on create/claim/wake;
+// the worker holds no signing secret). Empty edgeURL leaves the registry disabled
+// — every exec takes the tunnel path (also the edge's automatic fallback). Uses
+// the manager's one-shot Exec so DO- and tunnel-served execs are identical.
+func (s *GRPCServer) SetVMDialer(edgeURL string) {
+ s.doDialers = newDoDialerRegistry(edgeURL, s.manager.Exec)
+}
+
// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.
// If OPENSANDBOX_GRPC_TLS_* env vars are set, the server uses mTLS.
func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder interface{}, store *db.Store) *GRPCServer {
@@ -263,6 +279,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
s.initSandboxDB(sb.ID, cfg.Template)
s.recordInitialScaleEvent(ctx, sb.ID, cfg)
s.configureLogshipForSandbox(ctx, sb.ID)
+ s.doDialers.start(sb.ID, req.VmdoConnectToken)
return &pb.CreateSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
@@ -318,6 +335,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
s.initSandboxDB(sb.ID, cfg.Template)
s.recordInitialScaleEvent(ctx, sb.ID, cfg)
s.configureLogshipForSandbox(ctx, sb.ID)
+ s.doDialers.start(sb.ID, req.VmdoConnectToken)
return &pb.CreateSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
@@ -399,6 +417,8 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
s.configureLogshipForSandbox(ctx, sb.ID)
+ s.doDialers.start(sb.ID, req.VmdoConnectToken)
+
return &pb.CreateSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
@@ -523,6 +543,10 @@ func (s *GRPCServer) ClaimSandbox(ctx context.Context, req *pb.ClaimSandboxReque
go s.recordInitialScaleEvent(context.Background(), sb.ID, cfg)
go s.configureLogshipForSandbox(context.Background(), sb.ID)
+ // Open the VM-DO exec channel now the box is customer-usable. no-op if the
+ // dialer is unconfigured; the box still execs fine over the tunnel.
+ s.doDialers.start(sb.ID, req.VmdoConnectToken)
+
log.Printf("grpc: claimed pool box %s (template=%s)", sb.ID, sb.Template)
return &pb.ClaimSandboxResponse{
SandboxId: sb.ID,
@@ -532,6 +556,10 @@ func (s *GRPCServer) ClaimSandbox(ctx context.Context, req *pb.ClaimSandboxReque
}
func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxRequest) (*pb.DestroySandboxResponse, error) {
+ // Tear the VM-DO exec channel down first so an in-flight exec can't land on
+ // a box we're about to kill (it falls back to the tunnel, which 404s cleanly).
+ s.doDialers.stop(req.SandboxId)
+
// End billing scale event before destroying
if s.store != nil {
if err := s.store.EndScaleEvent(ctx, req.SandboxId); err != nil {
@@ -978,6 +1006,9 @@ func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSand
return nil, fmt.Errorf("hibernation not configured on this worker")
}
+ // Drop the VM-DO exec channel: the box is leaving RAM. Wake re-establishes it.
+ s.doDialers.stop(req.SandboxId)
+
// End billing scale event (sandbox going to sleep)
if s.store != nil {
if err := s.store.EndScaleEvent(ctx, req.SandboxId); err != nil {
@@ -1120,6 +1151,9 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest
}
}
+ // Re-open the VM-DO exec channel the hibernate teardown dropped.
+ s.doDialers.start(sb.ID, req.VmdoConnectToken)
+
return &pb.WakeSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 73287308..52f65ead 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -96,9 +96,15 @@ type CreateSandboxRequest struct {
// immediately pause (RAM-resident) and park under the pool org. Skips the
// customer bindings (no scale_event, no D1 created, exempt from promote-to-deep).
// The box is later bound to a customer via ClaimSandbox.
- Pooled bool `protobuf:"varint,17,opt,name=pooled,proto3" json:"pooled,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ Pooled bool `protobuf:"varint,17,opt,name=pooled,proto3" json:"pooled,omitempty"`
+ // Per-sandbox VM-DO connect token = HMAC(SESSION_JWT_SECRET, "vmdo:"+id),
+ // minted by the CP (which holds the shared secret) and presented by the worker
+ // host when it dials the sandbox's VmSession DO on the edge. The worker never
+ // holds the signing secret — only this per-box token. Empty = VM-DO exec plane
+ // not provisioned; the host doesn't dial and exec stays on the tunnel.
+ VmdoConnectToken string `protobuf:"bytes,18,opt,name=vmdo_connect_token,json=vmdoConnectToken,proto3" json:"vmdo_connect_token,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *CreateSandboxRequest) Reset() {
@@ -250,6 +256,13 @@ func (x *CreateSandboxRequest) GetPooled() bool {
return false
}
+func (x *CreateSandboxRequest) GetVmdoConnectToken() string {
+ if x != nil {
+ return x.VmdoConnectToken
+ }
+ return ""
+}
+
type CreateSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -337,6 +350,7 @@ type ClaimSandboxRequest struct {
SecretAllowedHosts map[string]string `protobuf:"bytes,6,rep,name=secret_allowed_hosts,json=secretAllowedHosts,proto3" json:"secret_allowed_hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
MemoryMb int32 `protobuf:"varint,7,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"` // grow target via virtio-mem (0 = leave as-is)
CpuCount int32 `protobuf:"varint,8,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`
+ VmdoConnectToken string `protobuf:"bytes,9,opt,name=vmdo_connect_token,json=vmdoConnectToken,proto3" json:"vmdo_connect_token,omitempty"` // per-sandbox VM-DO connect token (see CreateSandboxRequest)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -427,6 +441,13 @@ func (x *ClaimSandboxRequest) GetCpuCount() int32 {
return 0
}
+func (x *ClaimSandboxRequest) GetVmdoConnectToken() string {
+ if x != nil {
+ return x.VmdoConnectToken
+ }
+ return ""
+}
+
type ClaimSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -1910,12 +1931,13 @@ func (x *HibernateSandboxResponse) GetSizeBytes() int64 {
}
type WakeSandboxRequest struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
- CheckpointKey string `protobuf:"bytes,2,opt,name=checkpoint_key,json=checkpointKey,proto3" json:"checkpoint_key,omitempty"`
- Timeout int32 `protobuf:"varint,3,opt,name=timeout,proto3" json:"timeout,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ CheckpointKey string `protobuf:"bytes,2,opt,name=checkpoint_key,json=checkpointKey,proto3" json:"checkpoint_key,omitempty"`
+ Timeout int32 `protobuf:"varint,3,opt,name=timeout,proto3" json:"timeout,omitempty"`
+ VmdoConnectToken string `protobuf:"bytes,4,opt,name=vmdo_connect_token,json=vmdoConnectToken,proto3" json:"vmdo_connect_token,omitempty"` // per-sandbox VM-DO connect token (see CreateSandboxRequest)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *WakeSandboxRequest) Reset() {
@@ -1969,6 +1991,13 @@ func (x *WakeSandboxRequest) GetTimeout() int32 {
return 0
}
+func (x *WakeSandboxRequest) GetVmdoConnectToken() string {
+ if x != nil {
+ return x.VmdoConnectToken
+ }
+ return ""
+}
+
type WakeSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -4459,7 +4488,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
"\n" +
- "\x19proto/worker/worker.proto\x12\x06worker\"\x98\a\n" +
+ "\x19proto/worker/worker.proto\x12\x06worker\"\xc6\a\n" +
"\x14CreateSandboxRequest\x12\x1a\n" +
"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +
"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +
@@ -4480,7 +4509,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\vsecret_envs\x18\x0f \x03(\v2,.worker.CreateSandboxRequest.SecretEnvsEntryR\n" +
"secretEnvs\x12\x17\n" +
"\adisk_mb\x18\x10 \x01(\x05R\x06diskMb\x12\x16\n" +
- "\x06pooled\x18\x11 \x01(\bR\x06pooled\x1a7\n" +
+ "\x06pooled\x18\x11 \x01(\bR\x06pooled\x12,\n" +
+ "\x12vmdo_connect_token\x18\x12 \x01(\tR\x10vmdoConnectToken\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aE\n" +
@@ -4495,7 +4525,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" +
"\x06status\x18\x02 \x01(\tR\x06status\x12\x1b\n" +
"\tmemory_mb\x18\x03 \x01(\x05R\bmemoryMb\x12%\n" +
- "\x0egolden_version\x18\x04 \x01(\tR\rgoldenVersion\"\xe2\x04\n" +
+ "\x0egolden_version\x18\x04 \x01(\tR\rgoldenVersion\"\x90\x05\n" +
"\x13ClaimSandboxRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x18\n" +
@@ -4506,7 +4536,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x10egress_allowlist\x18\x05 \x03(\tR\x0fegressAllowlist\x12e\n" +
"\x14secret_allowed_hosts\x18\x06 \x03(\v23.worker.ClaimSandboxRequest.SecretAllowedHostsEntryR\x12secretAllowedHosts\x12\x1b\n" +
"\tmemory_mb\x18\a \x01(\x05R\bmemoryMb\x12\x1b\n" +
- "\tcpu_count\x18\b \x01(\x05R\bcpuCount\x1a7\n" +
+ "\tcpu_count\x18\b \x01(\x05R\bcpuCount\x12,\n" +
+ "\x12vmdo_connect_token\x18\t \x01(\tR\x10vmdoConnectToken\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a=\n" +
@@ -4625,12 +4656,13 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12%\n" +
"\x0echeckpoint_key\x18\x02 \x01(\tR\rcheckpointKey\x12\x1d\n" +
"\n" +
- "size_bytes\x18\x03 \x01(\x03R\tsizeBytes\"t\n" +
+ "size_bytes\x18\x03 \x01(\x03R\tsizeBytes\"\xa2\x01\n" +
"\x12WakeSandboxRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12%\n" +
"\x0echeckpoint_key\x18\x02 \x01(\tR\rcheckpointKey\x12\x18\n" +
- "\atimeout\x18\x03 \x01(\x05R\atimeout\"L\n" +
+ "\atimeout\x18\x03 \x01(\x05R\atimeout\x12,\n" +
+ "\x12vmdo_connect_token\x18\x04 \x01(\tR\x10vmdoConnectToken\"L\n" +
"\x13WakeSandboxResponse\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 34400170..717127a5 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -120,6 +120,12 @@ message CreateSandboxRequest {
// customer bindings (no scale_event, no D1 created, exempt from promote-to-deep).
// The box is later bound to a customer via ClaimSandbox.
bool pooled = 17;
+ // Per-sandbox VM-DO connect token = HMAC(SESSION_JWT_SECRET, "vmdo:"+id),
+ // minted by the CP (which holds the shared secret) and presented by the worker
+ // host when it dials the sandbox's VmSession DO on the edge. The worker never
+ // holds the signing secret — only this per-box token. Empty = VM-DO exec plane
+ // not provisioned; the host doesn't dial and exec stays on the tunnel.
+ string vmdo_connect_token = 18;
}
message CreateSandboxResponse {
@@ -147,6 +153,7 @@ message ClaimSandboxRequest {
map<string, string> secret_allowed_hosts = 6;
int32 memory_mb = 7; // grow target via virtio-mem (0 = leave as-is)
int32 cpu_count = 8;
+ string vmdo_connect_token = 9; // per-sandbox VM-DO connect token (see CreateSandboxRequest)
}
message ClaimSandboxResponse {
@@ -298,6 +305,7 @@ message WakeSandboxRequest {
string sandbox_id = 1;
string checkpoint_key = 2;
int32 timeout = 3;
+ string vmdo_connect_token = 4; // per-sandbox VM-DO connect token (see CreateSandboxRequest)
}
message WakeSandboxResponse {