From 9fb747ada690b04881273adba7e013fb0add9f08 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 13:22:20 -0700 Subject: [PATCH 1/7] refactor(openshell): establish sandbox control boundary Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 265 ++++++++++++++++++ scripts/checks/run.ts | 5 + .../actions/sandbox/sessions/passthrough.ts | 20 +- .../openshell/sandbox-control.test.ts | 58 ++++ src/lib/adapters/openshell/sandbox-control.ts | 56 ++++ test/legacy-sandbox-transports.test.ts | 85 ++++++ 6 files changed, 479 insertions(+), 10 deletions(-) create mode 100644 scripts/checks/legacy-sandbox-transports.ts create mode 100644 src/lib/adapters/openshell/sandbox-control.test.ts create mode 100644 src/lib/adapters/openshell/sandbox-control.ts create mode 100644 test/legacy-sandbox-transports.test.ts diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts new file mode 100644 index 00000000000..f41ca728cbd --- /dev/null +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Freezes the direct host-to-sandbox transport surface while NemoClaw moves to + * OpenShell's gRPC API. Every reviewed site must be removed or re-reviewed + * explicitly; new SSH, SSHFS, or Docker-exec bypasses fail repository checks. + */ + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; + +export type LegacySandboxTransportKind = + | "docker-exec-command" + | "docker-exec-builder" + | "openshell-ssh-config" + | "privileged-sandbox-exec" + | "ssh-command" + | "ssh-temp-config" + | "sshfs-command"; + +export interface LegacySandboxTransportSite { + relativePath: string; + kind: LegacySandboxTransportKind; + calls: number; +} + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); + +type ReviewedSiteTuple = readonly [string, LegacySandboxTransportKind, number]; + +const REVIEWED_SITE_TUPLES = [ + ["src/lib/actions/dns/index.ts", "docker-exec-command", 4], + ["src/lib/actions/sandbox/host-aliases.ts", "docker-exec-command", 1], + ["src/lib/actions/sandbox/process-recovery.ts", "openshell-ssh-config", 1], + ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], + ["src/lib/actions/sandbox/process-recovery.ts", "ssh-command", 1], + ["src/lib/actions/sandbox/process-recovery.ts", "ssh-temp-config", 1], + ["src/lib/actions/sandbox/skill-install.ts", "openshell-ssh-config", 2], + ["src/lib/actions/sandbox/skill-install.ts", "ssh-temp-config", 2], + ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], + ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], + ["src/lib/adapters/openshell/client.ts", "openshell-ssh-config", 1], + ["src/lib/adapters/openshell/runtime.ts", "openshell-ssh-config", 1], + ["src/lib/diagnostics/debug.ts", "openshell-ssh-config", 1], + ["src/lib/diagnostics/debug.ts", "ssh-command", 4], + ["src/lib/onboard.ts", "docker-exec-builder", 1], + ["src/lib/resources-cmd.ts", "docker-exec-command", 1], + ["src/lib/sandbox/config.ts", "privileged-sandbox-exec", 2], + ["src/lib/sandbox/version.ts", "openshell-ssh-config", 1], + ["src/lib/sandbox/version.ts", "ssh-command", 1], + ["src/lib/sandbox/version.ts", "ssh-temp-config", 1], + ["src/lib/share-command-deps.ts", "openshell-ssh-config", 1], + ["src/lib/share-command.ts", "sshfs-command", 1], + ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], + ["src/lib/shields/mutable-config-repair.ts", "privileged-sandbox-exec", 2], + ["src/lib/skill-remote.ts", "ssh-command", 1], + ["src/lib/state/openclaw-config-restore-input.ts", "ssh-command", 1], + ["src/lib/state/openclaw-plugin-restore.ts", "ssh-command", 2], + ["src/lib/state/openclaw-plugin-restore.ts", "ssh-temp-config", 1], + ["src/lib/state/sandbox.ts", "openshell-ssh-config", 1], + ["src/lib/state/sandbox.ts", "ssh-command", 8], + ["src/lib/state/sandbox.ts", "ssh-temp-config", 2], + ["src/lib/state/state-file-restore.ts", "ssh-command", 1], + ["src/lib/state/user-managed-files-probe.ts", "ssh-command", 1], + ["src/lib/state/user-managed-files-probe.ts", "ssh-temp-config", 1], + ["src/lib/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], +] as const satisfies readonly ReviewedSiteTuple[]; + +export const REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES: readonly LegacySandboxTransportSite[] = + REVIEWED_SITE_TUPLES.map(([relativePath, kind, calls]) => ({ relativePath, kind, calls })); + +const HELPER_KINDS = new Map([ + ["captureSandboxSshConfig", "openshell-ssh-config"], + ["captureSandboxSshConfigCommand", "openshell-ssh-config"], + ["createTempSshConfig", "ssh-temp-config"], + ["dockerExecArgv", "docker-exec-builder"], + ["privilegedSandboxExecArgv", "privileged-sandbox-exec"], +]); + +const COMMAND_CALLS = new Set([ + "execFile", + "execFileSync", + "run", + "runCapture", + "runCaptureImpl", + "runSync", + "spawn", + "spawnSync", +]); + +const DOCKER_COMMAND_CALLS = new Set([ + "dockerCapture", + "dockerExecFileSync", + "dockerRun", + "dockerSpawn", + "dockerSpawnSync", + "runDocker", +]); + +const NON_SANDBOX_SSH_ROOTS = ["src/lib/actions/dns/", "src/lib/deploy/"] as const; + +function productionTypeScriptFiles(directory: string): string[] { + if (!existsSync(directory)) return []; + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const entryPath = path.join(directory, entry.name); + if (entry.isDirectory()) return productionTypeScriptFiles(entryPath); + if ( + !entry.isFile() || + !/\.[cm]?ts$/u.test(entry.name) || + /\.(?:test|spec)\.[cm]?ts$/u.test(entry.name) + ) { + return []; + } + return [entryPath]; + }); +} + +function repoPath(repoRoot: string, sourcePath: string): string { + return path.relative(repoRoot, sourcePath).split(path.sep).join("/"); +} + +function expressionName(expression: ts.Expression): string | null { + if (ts.isIdentifier(expression)) return expression.text; + if (ts.isPropertyAccessExpression(expression)) return expression.name.text; + return null; +} + +function literalText(node: ts.Node | undefined): string | null { + if (!node) return null; + if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text; + return null; +} + +function commandFromArgument(argument: ts.Expression | undefined): string | null { + if (!argument) return null; + const direct = literalText(argument); + if (direct) return direct; + if (!ts.isArrayLiteralExpression(argument)) return null; + return literalText(argument.elements[0]); +} + +function increment( + counts: Map, + kind: LegacySandboxTransportKind, +) { + counts.set(kind, (counts.get(kind) ?? 0) + 1); +} + +function scanSource( + relativePath: string, + sourceText: string, +): Map { + const sourceFile = ts.createSourceFile( + relativePath, + sourceText, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, + ); + const counts = new Map(); + + function visit(node: ts.Node): void { + if (ts.isArrayLiteralExpression(node)) { + const first = literalText(node.elements[0]); + const second = literalText(node.elements[1]); + if (first === "docker" && second === "exec") { + increment(counts, "docker-exec-command"); + } + if (first === "sandbox" && second === "ssh-config") { + increment(counts, "openshell-ssh-config"); + } + } + + if (ts.isCallExpression(node)) { + const name = expressionName(node.expression); + const helperKind = name ? HELPER_KINDS.get(name) : undefined; + if (helperKind) increment(counts, helperKind); + if (name !== null && DOCKER_COMMAND_CALLS.has(name)) { + const firstDockerArg = commandFromArgument(node.arguments[0]); + if (firstDockerArg === "exec") increment(counts, "docker-exec-command"); + } + + const commandArgumentIndex = name === "collect" ? 2 : 0; + if (name === "collect" || (name !== null && COMMAND_CALLS.has(name))) { + const command = commandFromArgument(node.arguments[commandArgumentIndex]); + const scansSandboxSsh = !NON_SANDBOX_SSH_ROOTS.some((root) => + relativePath.startsWith(root), + ); + if (scansSandboxSsh && command === "ssh") increment(counts, "ssh-command"); + if (command === "sshfs") increment(counts, "sshfs-command"); + } + } + + ts.forEachChild(node, visit); + } + + visit(sourceFile); + return counts; +} + +export function discoverLegacySandboxTransportSites( + repoRoot: string, +): LegacySandboxTransportSite[] { + return ["src", "nemoclaw/src"] + .flatMap((sourceRoot) => productionTypeScriptFiles(path.join(repoRoot, sourceRoot))) + .flatMap((sourcePath) => { + const relativePath = repoPath(repoRoot, sourcePath); + return [...scanSource(relativePath, readFileSync(sourcePath, "utf8"))].map( + ([kind, calls]) => ({ relativePath, kind, calls }), + ); + }) + .sort( + (left, right) => + left.relativePath.localeCompare(right.relativePath) || left.kind.localeCompare(right.kind), + ); +} + +function siteKey(site: Pick): string { + return `${site.relativePath}:${site.kind}`; +} + +export function auditLegacySandboxTransports( + repoRoot = REPO_ROOT, + reviewedSites: readonly LegacySandboxTransportSite[] = REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES, +): string[] { + const violations: string[] = []; + const discovered = new Map( + discoverLegacySandboxTransportSites(repoRoot).map((site) => [siteKey(site), site]), + ); + + for (const reviewed of reviewedSites) { + const key = siteKey(reviewed); + const current = discovered.get(key); + if (!current) { + violations.push(`${key}: reviewed legacy transport is gone; remove this allowlist entry`); + } else if (current.calls !== reviewed.calls) { + violations.push( + `${key}: expected ${reviewed.calls} reviewed call(s), found ${current.calls}`, + ); + } + discovered.delete(key); + } + + for (const site of discovered.values()) { + violations.push(`${siteKey(site)}: found ${site.calls} unreviewed legacy transport call(s)`); + } + + return violations; +} + +const isEntrypoint = + typeof process.argv[1] === "string" && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isEntrypoint) { + const violations = auditLegacySandboxTransports(); + if (violations.length > 0) { + console.error(violations.join("\n")); + process.exit(1); + } + + console.log("Legacy sandbox SSH, SSHFS, and Docker-exec sites match the reviewed inventory."); +} diff --git a/scripts/checks/run.ts b/scripts/checks/run.ts index 5a9fc95a89d..0c899dc6ba6 100644 --- a/scripts/checks/run.ts +++ b/scripts/checks/run.ts @@ -36,6 +36,11 @@ const CHECKS: readonly CheckCommand[] = [ command: TSX, args: ["scripts/checks/hermes-light-skin-boundary.ts"], }, + { + name: "legacy-sandbox-transports", + command: TSX, + args: ["scripts/checks/legacy-sandbox-transports.ts"], + }, { name: "dependency-pins", command: TSX, diff --git a/src/lib/actions/sandbox/sessions/passthrough.ts b/src/lib/actions/sandbox/sessions/passthrough.ts index 825382097ef..36f4ee5935f 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { captureOpenshell } from "../../../adapters/openshell/runtime"; +import { openShellSandboxControl } from "../../../adapters/openshell/sandbox-control"; import { CLI_NAME } from "../../../cli/branding"; import * as registry from "../../../state/registry"; -import { buildOpenshellExecArgs, computeExitCode, execSandbox } from "../exec"; +import { computeExitCode, execSandbox } from "../exec"; import { ensureLiveSandboxOrExit } from "../gateway-state"; import { isWarmupSessionId, WARMUP_SESSION_ID_PREFIX } from "../warmup-session"; import { balancedJsonCandidates, parseSessionIndex } from "./session-index"; @@ -132,12 +132,12 @@ function writeWithTrailingNewline(stream: NodeJS.WriteStream, value: string | un stream.write(value.endsWith("\n") ? value : `${value}\n`); } -function capturedStdout(result: { output: string; stdout?: string }): string { - return typeof result.stdout === "string" ? result.stdout.trim() : result.output; +function capturedStdout(result: { stdout: string }): string { + return result.stdout.trim(); } -function capturedStderr(result: { stderr?: string }): string { - return typeof result.stderr === "string" ? result.stderr.trim() : ""; +function capturedStderr(result: { stderr: string }): string { + return result.stderr.trim(); } function printJsonParseFailure(): void { @@ -230,10 +230,10 @@ export async function runSessionsPassthrough( else if (inSandboxBinary === "hermes") command.push("list"); for (const arg of extraArgs) command.push(arg); if (isFilterableListPassthrough(verb) && inSandboxBinary === "openclaw") { - const result = captureOpenshell(buildOpenshellExecArgs(sandboxName, command), { - ignoreError: true, - includeStreams: true, - maxBuffer: SESSIONS_LIST_CAPTURE_MAX_BUFFER_BYTES, + const result = await openShellSandboxControl.exec({ + sandboxName, + command, + maxOutputBytes: SESSIONS_LIST_CAPTURE_MAX_BUFFER_BYTES, }); const { code, errorMessage } = computeExitCode(result); const capturedOutput = capturedStdout(result); diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts new file mode 100644 index 00000000000..9bca623a1fc --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import type { CaptureOpenshellResult } from "./client"; +import { createCliOpenShellSandboxControl } from "./sandbox-control"; + +describe("CLI OpenShell sandbox control", () => { + it("maps a typed exec request to the existing CLI contract", async () => { + const capture = vi.fn( + (): CaptureOpenshellResult => ({ + status: 0, + output: "hello", + stdout: "hello\n", + stderr: "warning\n", + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["openclaw", "sessions", "list", "--json"], + maxOutputBytes: 4096, + }); + + expect(capture).toHaveBeenCalledWith( + ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], + { ignoreError: true, includeStreams: true, maxBuffer: 4096 }, + ); + expect(result).toEqual({ + status: 0, + stdout: "hello\n", + stderr: "warning\n", + }); + }); + + it("preserves transport failures without throwing", async () => { + const error = Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }); + const capture = vi.fn( + (): CaptureOpenshellResult => ({ + status: null, + output: "partial", + error, + signal: "SIGTERM", + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect(control.exec({ sandboxName: "alpha", command: ["true"] })).resolves.toEqual({ + status: null, + stdout: "partial", + stderr: "", + error, + signal: "SIGTERM", + }); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts new file mode 100644 index 00000000000..52008a5aa5c --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { CaptureOpenshellResult } from "./client"; +import { captureOpenshell } from "./runtime"; + +export interface SandboxExecRequest { + sandboxName: string; + command: readonly string[]; + maxOutputBytes?: number; +} + +export interface SandboxExecResult { + status: number | null; + stdout: string; + stderr: string; + error?: Error; + signal?: NodeJS.Signals | null; +} + +export interface OpenShellSandboxControl { + exec(request: SandboxExecRequest): Promise; +} + +type CaptureOpenShell = typeof captureOpenshell; + +function normalizeExecResult(result: CaptureOpenshellResult): SandboxExecResult { + const normalized: SandboxExecResult = { + status: result.status, + stdout: result.stdout ?? result.output, + stderr: result.stderr ?? "", + }; + if (result.error) normalized.error = result.error; + if (result.signal !== undefined) normalized.signal = result.signal; + return normalized; +} + +export function createCliOpenShellSandboxControl( + capture: CaptureOpenShell = captureOpenshell, +): OpenShellSandboxControl { + return { + async exec(request): Promise { + const result = capture( + ["sandbox", "exec", "--name", request.sandboxName, "--", ...request.command], + { + ignoreError: true, + includeStreams: true, + maxBuffer: request.maxOutputBytes, + }, + ); + return normalizeExecResult(result); + }, + }; +} + +export const openShellSandboxControl = createCliOpenShellSandboxControl(); diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts new file mode 100644 index 00000000000..252d0f1e492 --- /dev/null +++ b/test/legacy-sandbox-transports.test.ts @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { + auditLegacySandboxTransports, + discoverLegacySandboxTransportSites, +} from "../scripts/checks/legacy-sandbox-transports"; + +const fixtures: string[] = []; + +function fixtureRepo(files: Readonly>): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-legacy-transports-")); + fixtures.push(root); + for (const [relativePath, source] of Object.entries(files)) { + const filePath = path.join(root, relativePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, source); + } + return root; +} + +afterEach(() => { + for (const fixture of fixtures.splice(0)) { + fs.rmSync(fixture, { force: true, recursive: true }); + } +}); + +describe("legacy sandbox transport inventory", () => { + it("discovers the direct sandbox transport shapes that the migration must remove", () => { + const root = fixtureRepo({ + "src/transport.ts": [ + 'spawnSync("ssh", ["sandbox"]);', + 'run(["ssh", "sandbox"]);', + 'collect(root, "probe", "ssh", ["sandbox"]);', + 'deps.run("sshfs", ["sandbox:/", "/mnt"]);', + 'captureOpenshell(["sandbox", "ssh-config", "alpha"]);', + 'captureSandboxSshConfig("alpha");', + 'createTempSshConfig(config, "prefix-");', + 'privilegedSandboxExecArgv("alpha", ["true"]);', + 'dockerExecArgv("openshell-cluster-nemoclaw", ["true"]);', + 'dockerSpawnSync(["exec", "openshell-cluster-nemoclaw", "true"]);', + ].join("\n"), + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([ + { relativePath: "src/transport.ts", kind: "docker-exec-builder", calls: 1 }, + { relativePath: "src/transport.ts", kind: "docker-exec-command", calls: 1 }, + { relativePath: "src/transport.ts", kind: "openshell-ssh-config", calls: 2 }, + { relativePath: "src/transport.ts", kind: "privileged-sandbox-exec", calls: 1 }, + { relativePath: "src/transport.ts", kind: "ssh-command", calls: 3 }, + { relativePath: "src/transport.ts", kind: "ssh-temp-config", calls: 1 }, + { relativePath: "src/transport.ts", kind: "sshfs-command", calls: 1 }, + ]); + }); + + it("ignores comments, inert strings, tests, and non-sandbox SSH workflows", () => { + const root = fixtureRepo({ + "src/safe.ts": [ + '// spawnSync("ssh", ["sandbox"]);', + 'const example = "ssh";', + 'log("ssh");', + ].join("\n"), + "src/safe.test.ts": 'spawnSync("ssh", ["sandbox"]);', + "src/lib/deploy/remote.ts": 'spawnSync("ssh", ["host"]);', + "src/lib/actions/dns/colima.ts": 'run(["ssh", "vm"]);', + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([]); + }); + + it("fails closed when a production site is not in the reviewed inventory", () => { + const root = fixtureRepo({ + "src/new-path.ts": 'spawnSync("ssh", ["sandbox"]);', + }); + + expect(auditLegacySandboxTransports(root, [])).toEqual([ + "src/new-path.ts:ssh-command: found 1 unreviewed legacy transport call(s)", + ]); + }); +}); From a1e75391d8893ccd4cfd227634d3430f1c28dc12 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 21:02:55 -0700 Subject: [PATCH 2/7] fix(openshell): detect aliased legacy transports Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 66 +++++++++++++++++---- test/legacy-sandbox-transports.test.ts | 26 ++++++++ 2 files changed, 82 insertions(+), 10 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index f41ca728cbd..afcf4fb9278 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -2,9 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 /** - * Freezes the direct host-to-sandbox transport surface while NemoClaw moves to - * OpenShell's gRPC API. Every reviewed site must be removed or re-reviewed - * explicitly; new SSH, SSHFS, or Docker-exec bypasses fail repository checks. + * Freezes the statically recognizable direct host-to-sandbox transport surface + * while NemoClaw moves to OpenShell's gRPC API. Literal calls and same-file + * immutable aliases must be removed or re-reviewed explicitly. This check is a + * review tripwire, not a general-purpose data-flow analysis. */ import { existsSync, readdirSync, readFileSync } from "node:fs"; @@ -128,18 +129,62 @@ function expressionName(expression: ts.Expression): string | null { return null; } +type ConstBindings = ReadonlyMap; + +function collectConstBindings(sourceFile: ts.SourceFile): ConstBindings { + const bindings = new Map(); + + function visit(node: ts.Node): void { + if ( + ts.isVariableDeclaration(node) && + ts.isIdentifier(node.name) && + node.initializer && + ts.isVariableDeclarationList(node.parent) && + (node.parent.flags & ts.NodeFlags.Const) !== 0 + ) { + const name = node.name.text; + bindings.set(name, bindings.has(name) ? null : node.initializer); + } + ts.forEachChild(node, visit); + } + + visit(sourceFile); + return bindings; +} + +function resolveAlias( + expression: ts.Expression, + bindings: ConstBindings, + seen = new Set(), +): ts.Expression { + if (!ts.isIdentifier(expression) || seen.has(expression.text)) return expression; + const binding = bindings.get(expression.text); + if (!binding) return expression; + seen.add(expression.text); + return resolveAlias(binding, bindings, seen); +} + +function resolvedExpressionName(expression: ts.Expression, bindings: ConstBindings): string | null { + return expressionName(resolveAlias(expression, bindings)); +} + function literalText(node: ts.Node | undefined): string | null { if (!node) return null; if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text; return null; } -function commandFromArgument(argument: ts.Expression | undefined): string | null { +function commandFromArgument( + argument: ts.Expression | undefined, + bindings: ConstBindings, +): string | null { if (!argument) return null; - const direct = literalText(argument); + const resolved = resolveAlias(argument, bindings); + const direct = literalText(resolved); if (direct) return direct; - if (!ts.isArrayLiteralExpression(argument)) return null; - return literalText(argument.elements[0]); + if (!ts.isArrayLiteralExpression(resolved)) return null; + const first = resolved.elements[0]; + return first && ts.isExpression(first) ? literalText(resolveAlias(first, bindings)) : null; } function increment( @@ -161,6 +206,7 @@ function scanSource( ts.ScriptKind.TS, ); const counts = new Map(); + const bindings = collectConstBindings(sourceFile); function visit(node: ts.Node): void { if (ts.isArrayLiteralExpression(node)) { @@ -175,17 +221,17 @@ function scanSource( } if (ts.isCallExpression(node)) { - const name = expressionName(node.expression); + const name = resolvedExpressionName(node.expression, bindings); const helperKind = name ? HELPER_KINDS.get(name) : undefined; if (helperKind) increment(counts, helperKind); if (name !== null && DOCKER_COMMAND_CALLS.has(name)) { - const firstDockerArg = commandFromArgument(node.arguments[0]); + const firstDockerArg = commandFromArgument(node.arguments[0], bindings); if (firstDockerArg === "exec") increment(counts, "docker-exec-command"); } const commandArgumentIndex = name === "collect" ? 2 : 0; if (name === "collect" || (name !== null && COMMAND_CALLS.has(name))) { - const command = commandFromArgument(node.arguments[commandArgumentIndex]); + const command = commandFromArgument(node.arguments[commandArgumentIndex], bindings); const scansSandboxSsh = !NON_SANDBOX_SSH_ROOTS.some((root) => relativePath.startsWith(root), ); diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index 252d0f1e492..fb5adaa76e6 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -58,6 +58,32 @@ describe("legacy sandbox transport inventory", () => { ]); }); + it("discovers immutable command and callee aliases without claiming general data flow", () => { + const root = fixtureRepo({ + "src/aliased-transport.ts": [ + 'const sshCommand = "ssh";', + "const invokeSsh = spawnSync;", + "invokeSsh(sshCommand, [\"sandbox\"]);", + 'const sshfsCommand = ["sshfs", "sandbox:/", "/mnt"];', + "const invokeSshfs = run;", + "invokeSshfs(sshfsCommand);", + 'const dockerArgs = ["exec", "openshell-cluster-nemoclaw", "true"];', + "const invokeDocker = dockerSpawnSync;", + "invokeDocker(dockerArgs);", + ].join("\n"), + }); + + expect(discoverLegacySandboxTransportSites(root)).toEqual([ + { + relativePath: "src/aliased-transport.ts", + kind: "docker-exec-command", + calls: 1, + }, + { relativePath: "src/aliased-transport.ts", kind: "ssh-command", calls: 1 }, + { relativePath: "src/aliased-transport.ts", kind: "sshfs-command", calls: 1 }, + ]); + }); + it("ignores comments, inert strings, tests, and non-sandbox SSH workflows", () => { const root = fixtureRepo({ "src/safe.ts": [ From 75661db808b37407cd0d61f13beda4f08a275433 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 21:14:04 -0700 Subject: [PATCH 3/7] test(openshell): format alias transport fixture Signed-off-by: Aaron Erickson --- test/legacy-sandbox-transports.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index fb5adaa76e6..efecf82b062 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -63,7 +63,7 @@ describe("legacy sandbox transport inventory", () => { "src/aliased-transport.ts": [ 'const sshCommand = "ssh";', "const invokeSsh = spawnSync;", - "invokeSsh(sshCommand, [\"sandbox\"]);", + 'invokeSsh(sshCommand, ["sandbox"]);', 'const sshfsCommand = ["sshfs", "sandbox:/", "/mnt"];', "const invokeSshfs = run;", "invokeSshfs(sshfsCommand);", From 2b7457be46099c8b2a2bbc340c81d8b27f867701 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 03:10:57 -0700 Subject: [PATCH 4/7] fix(openshell): validate exec commands before dispatch Signed-off-by: Aaron Erickson --- .../openshell/sandbox-control.test.ts | 107 +++++++++++++++++- src/lib/adapters/openshell/sandbox-control.ts | 99 ++++++++++++++++ 2 files changed, 205 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 9bca623a1fc..a31cb60c3e9 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -4,7 +4,74 @@ import { describe, expect, it, vi } from "vitest"; import type { CaptureOpenshellResult } from "./client"; -import { createCliOpenShellSandboxControl } from "./sandbox-control"; +import { + createCliOpenShellSandboxControl, + OpenShellExecRequestValidationError, + validateOpenShellExecCommand, +} from "./sandbox-control"; + +function expectValidationIssue( + command: readonly string[], + issue: OpenShellExecRequestValidationError["issue"], +): void { + const error = validateOpenShellExecCommand(command); + expect(error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect(error?.issue).toEqual(issue); +} + +describe("OpenShell exec command validation", () => { + it("requires a command", () => { + expectValidationIssue([], { kind: "empty-command" }); + }); + + it("allows 1024 arguments and rejects 1025", () => { + expect(validateOpenShellExecCommand(Array.from({ length: 1024 }, () => "x"))).toBeNull(); + expectValidationIssue( + Array.from({ length: 1025 }, () => "x"), + { + kind: "too-many-arguments", + actual: 1025, + max: 1024, + }, + ); + }); + + it("measures ASCII arguments in UTF-8 bytes", () => { + expect(validateOpenShellExecCommand(["x".repeat(32 * 1024)])).toBeNull(); + expectValidationIssue(["x".repeat(32 * 1024 + 1)], { + kind: "argument-too-large", + index: 0, + actualBytes: 32 * 1024 + 1, + maxBytes: 32 * 1024, + }); + }); + + it("measures multibyte arguments in UTF-8 bytes", () => { + expect(validateOpenShellExecCommand(["é".repeat(16 * 1024)])).toBeNull(); + expectValidationIssue(["é".repeat(16 * 1024 + 1)], { + kind: "argument-too-large", + index: 0, + actualBytes: 32 * 1024 + 2, + maxBytes: 32 * 1024, + }); + }); + + it.each([ + ["nul", "\0"], + ["lf", "\n"], + ["cr", "\r"], + ] as const)("rejects %s characters", (character, value) => { + expectValidationIssue(["sh", `bad${value}argument`], { + kind: "argument-control-character", + index: 1, + character, + }); + }); + + it("allows tabs, shell metacharacters, and empty non-command arguments", () => { + expect(validateOpenShellExecCommand(["sh", "", "\t; | & $() <> * ?"])).toBeNull(); + }); +}); describe("CLI OpenShell sandbox control", () => { it("maps a typed exec request to the existing CLI contract", async () => { @@ -55,4 +122,42 @@ describe("CLI OpenShell sandbox control", () => { signal: "SIGTERM", }); }); + + it("returns a standard failure without capture for invalid commands", async () => { + const capture = vi.fn<() => CaptureOpenshellResult>(); + const control = createCliOpenShellSandboxControl(capture); + + const result = await control.exec({ sandboxName: "alpha", command: ["bad\ncommand"] }); + + expect(capture).not.toHaveBeenCalled(); + expect(result).toMatchObject({ status: null, stdout: "", stderr: "" }); + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect((result.error as OpenShellExecRequestValidationError).issue).toEqual({ + kind: "argument-control-character", + index: 0, + character: "lf", + }); + }); + + it("forwards an exact-boundary argument unchanged", async () => { + const capture = vi.fn( + (): CaptureOpenshellResult => ({ status: 0, output: "", stdout: "", stderr: "" }), + ); + const control = createCliOpenShellSandboxControl(capture); + const boundaryArgument = "é".repeat(16 * 1024); + + await control.exec({ sandboxName: "alpha", command: ["printf", boundaryArgument] }); + + expect(capture).toHaveBeenCalledOnce(); + expect(capture.mock.calls[0]?.[0]).toEqual([ + "sandbox", + "exec", + "--name", + "alpha", + "--", + "printf", + boundaryArgument, + ]); + expect(capture.mock.calls[0]?.[0]?.at(-1)).toBe(boundaryArgument); + }); }); diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index 52008a5aa5c..afc3e68e068 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -22,8 +22,104 @@ export interface OpenShellSandboxControl { exec(request: SandboxExecRequest): Promise; } +export type OpenShellExecRequestValidationIssue = + | { kind: "empty-command" } + | { kind: "too-many-arguments"; actual: number; max: number } + | { + kind: "argument-too-large"; + index: number; + actualBytes: number; + maxBytes: number; + } + | { + kind: "argument-control-character"; + index: number; + character: "nul" | "lf" | "cr"; + }; + +export const OPENSHELL_EXEC_INVALID_ARGUMENT = "OPENSHELL_EXEC_INVALID_ARGUMENT"; + +/** A command OpenShell v0.0.72 will reject before attempting sandbox execution. */ +export class OpenShellExecRequestValidationError extends Error { + readonly code = OPENSHELL_EXEC_INVALID_ARGUMENT; + + constructor(readonly issue: OpenShellExecRequestValidationIssue) { + super(openShellExecRequestValidationMessage(issue)); + this.name = "OpenShellExecRequestValidationError"; + } +} + type CaptureOpenShell = typeof captureOpenshell; +const OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS = 1024; +const OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES = 32 * 1024; + +function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValidationIssue): string { + switch (issue.kind) { + case "empty-command": + return "command is required"; + case "too-many-arguments": + return `command array exceeds ${String(issue.max)} argument limit`; + case "argument-too-large": + return `command argument ${String(issue.index)} exceeds ${String(issue.maxBytes)} byte limit`; + case "argument-control-character": + return issue.character === "nul" + ? `command argument ${String(issue.index)} contains null bytes` + : `command argument ${String(issue.index)} contains newline or carriage return characters`; + } +} + +/** Match OpenShell v0.0.72's pre-dispatch command validation. */ +export function validateOpenShellExecCommand( + command: readonly string[], +): OpenShellExecRequestValidationError | null { + if (command.length === 0) { + return new OpenShellExecRequestValidationError({ kind: "empty-command" }); + } + if (command.length > OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS) { + return new OpenShellExecRequestValidationError({ + kind: "too-many-arguments", + actual: command.length, + max: OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS, + }); + } + + for (const [index, argument] of command.entries()) { + const actualBytes = Buffer.byteLength(argument, "utf8"); + if (actualBytes > OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES) { + return new OpenShellExecRequestValidationError({ + kind: "argument-too-large", + index, + actualBytes, + maxBytes: OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES, + }); + } + if (argument.includes("\0")) { + return new OpenShellExecRequestValidationError({ + kind: "argument-control-character", + index, + character: "nul", + }); + } + const newlineIndex = argument.search(/[\n\r]/); + if (newlineIndex !== -1) { + return new OpenShellExecRequestValidationError({ + kind: "argument-control-character", + index, + character: argument[newlineIndex] === "\n" ? "lf" : "cr", + }); + } + } + + return null; +} + +export function openShellExecRequestValidationFailure( + error: OpenShellExecRequestValidationError, +): SandboxExecResult { + return { status: null, stdout: "", stderr: "", error }; +} + function normalizeExecResult(result: CaptureOpenshellResult): SandboxExecResult { const normalized: SandboxExecResult = { status: result.status, @@ -40,6 +136,9 @@ export function createCliOpenShellSandboxControl( ): OpenShellSandboxControl { return { async exec(request): Promise { + const validationError = validateOpenShellExecCommand(request.command); + if (validationError) return openShellExecRequestValidationFailure(validationError); + const result = capture( ["sandbox", "exec", "--name", request.sandboxName, "--", ...request.command], { From a56d36b22b923afcda4ba2a3f2a204185892471e Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 03:19:15 -0700 Subject: [PATCH 5/7] test(openshell): type exec boundary capture Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/sandbox-control.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index a31cb60c3e9..41467f58773 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -141,7 +141,12 @@ describe("CLI OpenShell sandbox control", () => { it("forwards an exact-boundary argument unchanged", async () => { const capture = vi.fn( - (): CaptureOpenshellResult => ({ status: 0, output: "", stdout: "", stderr: "" }), + (_args: readonly string[]): CaptureOpenshellResult => ({ + status: 0, + output: "", + stdout: "", + stderr: "", + }), ); const control = createCliOpenShellSandboxControl(capture); const boundaryArgument = "é".repeat(16 * 1024); @@ -158,6 +163,5 @@ describe("CLI OpenShell sandbox control", () => { "printf", boundaryArgument, ]); - expect(capture.mock.calls[0]?.[0]?.at(-1)).toBe(boundaryArgument); }); }); From c50e57a4f641b00bb9bb6b291719404421b77416 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 03:29:32 -0700 Subject: [PATCH 6/7] fix(openshell): bound assembled exec commands Signed-off-by: Aaron Erickson --- .../openshell/sandbox-control.test.ts | 22 +++++++++ src/lib/adapters/openshell/sandbox-control.ts | 45 +++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 41467f58773..8e00a79cae6 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -56,6 +56,28 @@ describe("OpenShell exec command validation", () => { }); }); + it("allows the exact assembled command boundary and rejects one byte more", () => { + const prefix = Array.from({ length: 7 }, () => "x".repeat(32 * 1024)); + const exactBoundary = [...prefix, "x".repeat(32 * 1024 - 7)]; + + expect(validateOpenShellExecCommand(exactBoundary)).toBeNull(); + expectValidationIssue([...prefix, "x".repeat(32 * 1024 - 6)], { + kind: "assembled-command-too-large", + actualBytes: 256 * 1024 + 1, + maxBytes: 256 * 1024, + }); + }); + + it("accounts for OpenShell single-quote expansion in the assembled command", () => { + const quotedArgument = "'".repeat(32 * 1024); + + expectValidationIssue([quotedArgument, quotedArgument], { + kind: "assembled-command-too-large", + actualBytes: 10 * 32 * 1024 + 5, + maxBytes: 256 * 1024, + }); + }); + it.each([ ["nul", "\0"], ["lf", "\n"], diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index afc3e68e068..5d9e9930aa0 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -25,6 +25,7 @@ export interface OpenShellSandboxControl { export type OpenShellExecRequestValidationIssue = | { kind: "empty-command" } | { kind: "too-many-arguments"; actual: number; max: number } + | { kind: "assembled-command-too-large"; actualBytes: number; maxBytes: number } | { kind: "argument-too-large"; index: number; @@ -53,6 +54,7 @@ type CaptureOpenShell = typeof captureOpenshell; const OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS = 1024; const OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES = 32 * 1024; +const OPENSHELL_V0072_MAX_ASSEMBLED_COMMAND_BYTES = 256 * 1024; function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValidationIssue): string { switch (issue.kind) { @@ -60,6 +62,8 @@ function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValida return "command is required"; case "too-many-arguments": return `command array exceeds ${String(issue.max)} argument limit`; + case "assembled-command-too-large": + return `assembled command string exceeds ${String(issue.maxBytes)} byte limit`; case "argument-too-large": return `command argument ${String(issue.index)} exceeds ${String(issue.maxBytes)} byte limit`; case "argument-control-character": @@ -69,6 +73,35 @@ function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValida } } +function openShellEscapedArgumentByteLength(argument: string): number { + const bytes = Buffer.from(argument, "utf8"); + if (bytes.length === 0) return 2; + + let safe = true; + let singleQuotes = 0; + for (const byte of bytes) { + if (byte === 0x27) singleQuotes += 1; + if ( + !( + (byte >= 0x30 && byte <= 0x39) || + (byte >= 0x41 && byte <= 0x5a) || + (byte >= 0x61 && byte <= 0x7a) || + byte === 0x2e || + byte === 0x2f || + byte === 0x2d || + byte === 0x5f + ) + ) { + safe = false; + } + } + if (safe) return bytes.length; + + // OpenShell wraps unsafe arguments in single quotes and expands each + // embedded quote from one byte to the five-byte '\"'\"' sequence. + return bytes.length + 2 + singleQuotes * 4; +} + /** Match OpenShell v0.0.72's pre-dispatch command validation. */ export function validateOpenShellExecCommand( command: readonly string[], @@ -111,6 +144,18 @@ export function validateOpenShellExecCommand( } } + const assembledBytes = + command.reduce((total, argument) => total + openShellEscapedArgumentByteLength(argument), 0) + + command.length - + 1; + if (assembledBytes > OPENSHELL_V0072_MAX_ASSEMBLED_COMMAND_BYTES) { + return new OpenShellExecRequestValidationError({ + kind: "assembled-command-too-large", + actualBytes: assembledBytes, + maxBytes: OPENSHELL_V0072_MAX_ASSEMBLED_COMMAND_BYTES, + }); + } + return null; } From eb5c79f9414a97f64651ee9fbbb9ebc45e3503c9 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 04:38:03 -0700 Subject: [PATCH 7/7] fix(openshell): close control boundary review gaps Co-authored-by: Aaron Erickson Signed-off-by: Apurv Kumaria --- ci/legacy-sandbox-transports.json | 37 +++++ ...ports.ts => legacy-sandbox-transports.mts} | 135 ++++++++++++------ scripts/checks/run.mts | 2 +- .../openshell/sandbox-control.test.ts | 5 +- src/lib/adapters/openshell/sandbox-control.ts | 4 +- test/legacy-sandbox-transports.test.ts | 31 +++- 6 files changed, 164 insertions(+), 50 deletions(-) create mode 100644 ci/legacy-sandbox-transports.json rename scripts/checks/{legacy-sandbox-transports.ts => legacy-sandbox-transports.mts} (70%) diff --git a/ci/legacy-sandbox-transports.json b/ci/legacy-sandbox-transports.json new file mode 100644 index 00000000000..aee4d7cecb0 --- /dev/null +++ b/ci/legacy-sandbox-transports.json @@ -0,0 +1,37 @@ +[ + { "relativePath": "src/lib/actions/dns/index.ts", "kind": "docker-exec-command", "calls": 4 }, + { "relativePath": "src/lib/actions/sandbox/host-aliases.ts", "kind": "docker-exec-command", "calls": 1 }, + { "relativePath": "src/lib/actions/sandbox/process-recovery.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/actions/sandbox/process-recovery.ts", "kind": "privileged-sandbox-exec", "calls": 2 }, + { "relativePath": "src/lib/actions/sandbox/process-recovery.ts", "kind": "ssh-command", "calls": 1 }, + { "relativePath": "src/lib/actions/sandbox/process-recovery.ts", "kind": "ssh-temp-config", "calls": 1 }, + { "relativePath": "src/lib/actions/sandbox/skill-install.ts", "kind": "openshell-ssh-config", "calls": 2 }, + { "relativePath": "src/lib/actions/sandbox/skill-install.ts", "kind": "ssh-temp-config", "calls": 2 }, + { "relativePath": "src/lib/actions/sandbox/snapshot.ts", "kind": "docker-exec-command", "calls": 1 }, + { "relativePath": "src/lib/adapters/docker/container.ts", "kind": "docker-exec-command", "calls": 1 }, + { "relativePath": "src/lib/adapters/openshell/client.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/adapters/openshell/runtime.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/diagnostics/debug.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/diagnostics/debug.ts", "kind": "ssh-command", "calls": 4 }, + { "relativePath": "src/lib/onboard.ts", "kind": "docker-exec-builder", "calls": 1 }, + { "relativePath": "src/lib/resources-cmd.ts", "kind": "docker-exec-command", "calls": 1 }, + { "relativePath": "src/lib/sandbox/config.ts", "kind": "privileged-sandbox-exec", "calls": 2 }, + { "relativePath": "src/lib/sandbox/version.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/sandbox/version.ts", "kind": "ssh-command", "calls": 1 }, + { "relativePath": "src/lib/sandbox/version.ts", "kind": "ssh-temp-config", "calls": 1 }, + { "relativePath": "src/lib/share-command-deps.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/share-command.ts", "kind": "sshfs-command", "calls": 1 }, + { "relativePath": "src/lib/shields/index.ts", "kind": "privileged-sandbox-exec", "calls": 4 }, + { "relativePath": "src/lib/shields/mutable-config-repair.ts", "kind": "privileged-sandbox-exec", "calls": 2 }, + { "relativePath": "src/lib/skill-remote.ts", "kind": "ssh-command", "calls": 1 }, + { "relativePath": "src/lib/state/openclaw-config-restore-input.ts", "kind": "ssh-command", "calls": 1 }, + { "relativePath": "src/lib/state/openclaw-plugin-restore.ts", "kind": "ssh-command", "calls": 2 }, + { "relativePath": "src/lib/state/openclaw-plugin-restore.ts", "kind": "ssh-temp-config", "calls": 1 }, + { "relativePath": "src/lib/state/sandbox.ts", "kind": "openshell-ssh-config", "calls": 1 }, + { "relativePath": "src/lib/state/sandbox.ts", "kind": "ssh-command", "calls": 8 }, + { "relativePath": "src/lib/state/sandbox.ts", "kind": "ssh-temp-config", "calls": 2 }, + { "relativePath": "src/lib/state/state-file-restore.ts", "kind": "ssh-command", "calls": 1 }, + { "relativePath": "src/lib/state/user-managed-files-probe.ts", "kind": "ssh-command", "calls": 1 }, + { "relativePath": "src/lib/state/user-managed-files-probe.ts", "kind": "ssh-temp-config", "calls": 1 }, + { "relativePath": "src/lib/tunnel/sandbox-gateway-stop.ts", "kind": "docker-exec-command", "calls": 2 } +] diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.mts similarity index 70% rename from scripts/checks/legacy-sandbox-transports.ts rename to scripts/checks/legacy-sandbox-transports.mts index afcf4fb9278..d86c1f61f87 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.mts @@ -29,49 +29,71 @@ export interface LegacySandboxTransportSite { } const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const REVIEWED_INVENTORY_PATH = "ci/legacy-sandbox-transports.json"; +const LEGACY_SANDBOX_TRANSPORT_KINDS = new Set([ + "docker-exec-command", + "docker-exec-builder", + "openshell-ssh-config", + "privileged-sandbox-exec", + "ssh-command", + "ssh-temp-config", + "sshfs-command", +]); -type ReviewedSiteTuple = readonly [string, LegacySandboxTransportKind, number]; - -const REVIEWED_SITE_TUPLES = [ - ["src/lib/actions/dns/index.ts", "docker-exec-command", 4], - ["src/lib/actions/sandbox/host-aliases.ts", "docker-exec-command", 1], - ["src/lib/actions/sandbox/process-recovery.ts", "openshell-ssh-config", 1], - ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], - ["src/lib/actions/sandbox/process-recovery.ts", "ssh-command", 1], - ["src/lib/actions/sandbox/process-recovery.ts", "ssh-temp-config", 1], - ["src/lib/actions/sandbox/skill-install.ts", "openshell-ssh-config", 2], - ["src/lib/actions/sandbox/skill-install.ts", "ssh-temp-config", 2], - ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], - ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], - ["src/lib/adapters/openshell/client.ts", "openshell-ssh-config", 1], - ["src/lib/adapters/openshell/runtime.ts", "openshell-ssh-config", 1], - ["src/lib/diagnostics/debug.ts", "openshell-ssh-config", 1], - ["src/lib/diagnostics/debug.ts", "ssh-command", 4], - ["src/lib/onboard.ts", "docker-exec-builder", 1], - ["src/lib/resources-cmd.ts", "docker-exec-command", 1], - ["src/lib/sandbox/config.ts", "privileged-sandbox-exec", 2], - ["src/lib/sandbox/version.ts", "openshell-ssh-config", 1], - ["src/lib/sandbox/version.ts", "ssh-command", 1], - ["src/lib/sandbox/version.ts", "ssh-temp-config", 1], - ["src/lib/share-command-deps.ts", "openshell-ssh-config", 1], - ["src/lib/share-command.ts", "sshfs-command", 1], - ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], - ["src/lib/shields/mutable-config-repair.ts", "privileged-sandbox-exec", 2], - ["src/lib/skill-remote.ts", "ssh-command", 1], - ["src/lib/state/openclaw-config-restore-input.ts", "ssh-command", 1], - ["src/lib/state/openclaw-plugin-restore.ts", "ssh-command", 2], - ["src/lib/state/openclaw-plugin-restore.ts", "ssh-temp-config", 1], - ["src/lib/state/sandbox.ts", "openshell-ssh-config", 1], - ["src/lib/state/sandbox.ts", "ssh-command", 8], - ["src/lib/state/sandbox.ts", "ssh-temp-config", 2], - ["src/lib/state/state-file-restore.ts", "ssh-command", 1], - ["src/lib/state/user-managed-files-probe.ts", "ssh-command", 1], - ["src/lib/state/user-managed-files-probe.ts", "ssh-temp-config", 1], - ["src/lib/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], -] as const satisfies readonly ReviewedSiteTuple[]; - -export const REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES: readonly LegacySandboxTransportSite[] = - REVIEWED_SITE_TUPLES.map(([relativePath, kind, calls]) => ({ relativePath, kind, calls })); +/** Load the reviewed baseline from the CODEOWNERS-protected CI inventory. */ +export function loadReviewedLegacySandboxTransportSites( + repoRoot = REPO_ROOT, +): readonly LegacySandboxTransportSite[] { + const inventoryPath = path.join(repoRoot, REVIEWED_INVENTORY_PATH); + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(inventoryPath, "utf8")); + } catch (error) { + throw new Error( + `Failed to read reviewed legacy sandbox transport inventory ${inventoryPath}: ${(error as Error).message}`, + ); + } + if (!Array.isArray(parsed)) { + throw new Error(`${REVIEWED_INVENTORY_PATH} must contain an array`); + } + + const seen = new Set(); + return parsed.map((entry, index) => { + if (typeof entry !== "object" || entry === null || Array.isArray(entry)) { + throw new Error(`${REVIEWED_INVENTORY_PATH}[${String(index)}] must be an object`); + } + const { relativePath, kind, calls } = entry as Record; + if ( + typeof relativePath !== "string" || + !relativePath || + path.isAbsolute(relativePath) || + relativePath.includes("\\") || + relativePath.split("/").includes("..") + ) { + throw new Error( + `${REVIEWED_INVENTORY_PATH}[${String(index)}].relativePath must be a safe repository-relative path`, + ); + } + if ( + typeof kind !== "string" || + !LEGACY_SANDBOX_TRANSPORT_KINDS.has(kind as LegacySandboxTransportKind) + ) { + throw new Error(`${REVIEWED_INVENTORY_PATH}[${String(index)}].kind is invalid`); + } + if (!Number.isSafeInteger(calls) || (calls as number) < 1) { + throw new Error(`${REVIEWED_INVENTORY_PATH}[${String(index)}].calls must be positive`); + } + const site = { + relativePath, + kind: kind as LegacySandboxTransportKind, + calls: calls as number, + }; + const key = `${site.relativePath}:${site.kind}`; + if (seen.has(key)) throw new Error(`${REVIEWED_INVENTORY_PATH} contains duplicate ${key}`); + seen.add(key); + return site; + }); +} const HELPER_KINDS = new Map([ ["captureSandboxSshConfig", "openshell-ssh-config"], @@ -92,6 +114,8 @@ const COMMAND_CALLS = new Set([ "spawnSync", ]); +const SHELL_COMMAND_CALLS = new Set(["exec", "execSync"]); + const DOCKER_COMMAND_CALLS = new Set([ "dockerCapture", "dockerExecFileSync", @@ -187,6 +211,18 @@ function commandFromArgument( return first && ts.isExpression(first) ? literalText(resolveAlias(first, bindings)) : null; } +function shellCommandPrefix( + argument: ts.Expression | undefined, + bindings: ConstBindings, +): readonly [string, string | undefined] | null { + if (!argument) return null; + const command = literalText(resolveAlias(argument, bindings)); + if (command === null) return null; + const [executable, subcommand] = command.trimStart().split(/\s+/u, 2); + if (!executable) return null; + return [path.posix.basename(executable), subcommand]; +} + function increment( counts: Map, kind: LegacySandboxTransportKind, @@ -238,6 +274,17 @@ function scanSource( if (scansSandboxSsh && command === "ssh") increment(counts, "ssh-command"); if (command === "sshfs") increment(counts, "sshfs-command"); } + if (name !== null && SHELL_COMMAND_CALLS.has(name)) { + const prefix = shellCommandPrefix(node.arguments[0], bindings); + const scansSandboxSsh = !NON_SANDBOX_SSH_ROOTS.some((root) => + relativePath.startsWith(root), + ); + if (scansSandboxSsh && prefix?.[0] === "ssh") increment(counts, "ssh-command"); + if (prefix?.[0] === "sshfs") increment(counts, "sshfs-command"); + if (prefix?.[0] === "docker" && prefix[1] === "exec") { + increment(counts, "docker-exec-command"); + } + } } ts.forEachChild(node, visit); @@ -270,7 +317,9 @@ function siteKey(site: Pick export function auditLegacySandboxTransports( repoRoot = REPO_ROOT, - reviewedSites: readonly LegacySandboxTransportSite[] = REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES, + reviewedSites: readonly LegacySandboxTransportSite[] = loadReviewedLegacySandboxTransportSites( + repoRoot, + ), ): string[] { const violations: string[] = []; const discovered = new Map( diff --git a/scripts/checks/run.mts b/scripts/checks/run.mts index 30a29542f15..2e8cddec95d 100644 --- a/scripts/checks/run.mts +++ b/scripts/checks/run.mts @@ -51,7 +51,7 @@ export const CHECKS: readonly CheckCommand[] = [ { name: "legacy-sandbox-transports", command: TSX, - args: ["scripts/checks/legacy-sandbox-transports.ts"], + args: ["scripts/checks/legacy-sandbox-transports.mts"], }, { name: "dependency-pins", diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 8e00a79cae6..358bd385bd3 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -22,6 +22,8 @@ function expectValidationIssue( describe("OpenShell exec command validation", () => { it("requires a command", () => { expectValidationIssue([], { kind: "empty-command" }); + expectValidationIssue([""], { kind: "empty-command" }); + expectValidationIssue([" \t"], { kind: "empty-command" }); }); it("allows 1024 arguments and rejects 1025", () => { @@ -111,11 +113,12 @@ describe("CLI OpenShell sandbox control", () => { sandboxName: "alpha", command: ["openclaw", "sessions", "list", "--json"], maxOutputBytes: 4096, + timeoutMs: 30_000, }); expect(capture).toHaveBeenCalledWith( ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], - { ignoreError: true, includeStreams: true, maxBuffer: 4096 }, + { ignoreError: true, includeStreams: true, maxBuffer: 4096, timeout: 30_000 }, ); expect(result).toEqual({ status: 0, diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index 5d9e9930aa0..de3b8053eb3 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -8,6 +8,7 @@ export interface SandboxExecRequest { sandboxName: string; command: readonly string[]; maxOutputBytes?: number; + timeoutMs?: number; } export interface SandboxExecResult { @@ -106,7 +107,7 @@ function openShellEscapedArgumentByteLength(argument: string): number { export function validateOpenShellExecCommand( command: readonly string[], ): OpenShellExecRequestValidationError | null { - if (command.length === 0) { + if (command.length === 0 || command[0]?.trim().length === 0) { return new OpenShellExecRequestValidationError({ kind: "empty-command" }); } if (command.length > OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS) { @@ -190,6 +191,7 @@ export function createCliOpenShellSandboxControl( ignoreError: true, includeStreams: true, maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, }, ); return normalizeExecResult(result); diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index efecf82b062..ed46a7870fd 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -9,7 +9,8 @@ import { afterEach, describe, expect, it } from "vitest"; import { auditLegacySandboxTransports, discoverLegacySandboxTransportSites, -} from "../scripts/checks/legacy-sandbox-transports"; + loadReviewedLegacySandboxTransportSites, +} from "../scripts/checks/legacy-sandbox-transports.mts"; const fixtures: string[] = []; @@ -44,17 +45,20 @@ describe("legacy sandbox transport inventory", () => { 'privilegedSandboxExecArgv("alpha", ["true"]);', 'dockerExecArgv("openshell-cluster-nemoclaw", ["true"]);', 'dockerSpawnSync(["exec", "openshell-cluster-nemoclaw", "true"]);', + 'exec("ssh sandbox");', + 'execSync("sshfs sandbox:/ /mnt");', + 'exec("docker exec openshell-cluster-nemoclaw true");', ].join("\n"), }); expect(discoverLegacySandboxTransportSites(root)).toEqual([ { relativePath: "src/transport.ts", kind: "docker-exec-builder", calls: 1 }, - { relativePath: "src/transport.ts", kind: "docker-exec-command", calls: 1 }, + { relativePath: "src/transport.ts", kind: "docker-exec-command", calls: 2 }, { relativePath: "src/transport.ts", kind: "openshell-ssh-config", calls: 2 }, { relativePath: "src/transport.ts", kind: "privileged-sandbox-exec", calls: 1 }, - { relativePath: "src/transport.ts", kind: "ssh-command", calls: 3 }, + { relativePath: "src/transport.ts", kind: "ssh-command", calls: 4 }, { relativePath: "src/transport.ts", kind: "ssh-temp-config", calls: 1 }, - { relativePath: "src/transport.ts", kind: "sshfs-command", calls: 1 }, + { relativePath: "src/transport.ts", kind: "sshfs-command", calls: 2 }, ]); }); @@ -108,4 +112,23 @@ describe("legacy sandbox transport inventory", () => { "src/new-path.ts:ssh-command: found 1 unreviewed legacy transport call(s)", ]); }); + + it("loads the reviewed baseline from the separate CI inventory", () => { + const reviewed = [{ relativePath: "src/reviewed.ts", kind: "ssh-command", calls: 1 }] as const; + const root = fixtureRepo({ + "ci/legacy-sandbox-transports.json": JSON.stringify(reviewed), + "src/reviewed.ts": 'spawnSync("ssh", ["sandbox"]);', + }); + + expect(loadReviewedLegacySandboxTransportSites(root)).toEqual(reviewed); + expect(auditLegacySandboxTransports(root)).toEqual([]); + }); + + it("fails closed when the separate CI inventory is malformed", () => { + const root = fixtureRepo({ + "ci/legacy-sandbox-transports.json": JSON.stringify({ reviewed: [] }), + }); + + expect(() => loadReviewedLegacySandboxTransportSites(root)).toThrow("must contain an array"); + }); });