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.mts b/scripts/checks/legacy-sandbox-transports.mts new file mode 100644 index 00000000000..d86c1f61f87 --- /dev/null +++ b/scripts/checks/legacy-sandbox-transports.mts @@ -0,0 +1,360 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * 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"; +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)), "../.."); +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", +]); + +/** 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"], + ["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 SHELL_COMMAND_CALLS = new Set(["exec", "execSync"]); + +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; +} + +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, + bindings: ConstBindings, +): string | null { + if (!argument) return null; + const resolved = resolveAlias(argument, bindings); + const direct = literalText(resolved); + if (direct) return direct; + if (!ts.isArrayLiteralExpression(resolved)) return null; + const first = resolved.elements[0]; + 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, +) { + 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(); + const bindings = collectConstBindings(sourceFile); + + 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 = 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], 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], bindings); + 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"); + } + 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); + } + + 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[] = loadReviewedLegacySandboxTransportSites( + repoRoot, + ), +): 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.mts b/scripts/checks/run.mts index 278e466dc8f..2e8cddec95d 100644 --- a/scripts/checks/run.mts +++ b/scripts/checks/run.mts @@ -48,6 +48,11 @@ export const CHECKS: readonly CheckCommand[] = [ command: TSX, args: ["scripts/checks/hermes-light-skin-boundary.mts"], }, + { + name: "legacy-sandbox-transports", + command: TSX, + args: ["scripts/checks/legacy-sandbox-transports.mts"], + }, { 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..358bd385bd3 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -0,0 +1,192 @@ +// 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, + 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" }); + expectValidationIssue([""], { kind: "empty-command" }); + expectValidationIssue([" \t"], { 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("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"], + ["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 () => { + 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, + timeoutMs: 30_000, + }); + + expect(capture).toHaveBeenCalledWith( + ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], + { ignoreError: true, includeStreams: true, maxBuffer: 4096, timeout: 30_000 }, + ); + 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", + }); + }); + + 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( + (_args: readonly string[]): 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, + ]); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts new file mode 100644 index 00000000000..de3b8053eb3 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -0,0 +1,202 @@ +// 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; + timeoutMs?: number; +} + +export interface SandboxExecResult { + status: number | null; + stdout: string; + stderr: string; + error?: Error; + signal?: NodeJS.Signals | null; +} + +export interface OpenShellSandboxControl { + exec(request: SandboxExecRequest): Promise; +} + +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; + 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; +const OPENSHELL_V0072_MAX_ASSEMBLED_COMMAND_BYTES = 256 * 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 "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": + return issue.character === "nul" + ? `command argument ${String(issue.index)} contains null bytes` + : `command argument ${String(issue.index)} contains newline or carriage return characters`; + } +} + +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[], +): OpenShellExecRequestValidationError | null { + if (command.length === 0 || command[0]?.trim().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", + }); + } + } + + 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; +} + +export function openShellExecRequestValidationFailure( + error: OpenShellExecRequestValidationError, +): SandboxExecResult { + return { status: null, stdout: "", stderr: "", error }; +} + +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 validationError = validateOpenShellExecCommand(request.command); + if (validationError) return openShellExecRequestValidationFailure(validationError); + + const result = capture( + ["sandbox", "exec", "--name", request.sandboxName, "--", ...request.command], + { + ignoreError: true, + includeStreams: true, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + }, + ); + 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..ed46a7870fd --- /dev/null +++ b/test/legacy-sandbox-transports.test.ts @@ -0,0 +1,134 @@ +// 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, + loadReviewedLegacySandboxTransportSites, +} from "../scripts/checks/legacy-sandbox-transports.mts"; + +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"]);', + '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: 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: 4 }, + { relativePath: "src/transport.ts", kind: "ssh-temp-config", calls: 1 }, + { relativePath: "src/transport.ts", kind: "sshfs-command", calls: 2 }, + ]); + }); + + 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": [ + '// 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)", + ]); + }); + + 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"); + }); +});