diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index de4ee8c9fcc..b928cd56c99 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -21,14 +21,15 @@ const { isIP } = require("node:net"); const { validateName } = require("../runner"); const { shellQuote } = require("../core/shell-quote"); const { dockerExecFileSync } = require("../adapters/docker/exec"); -const { dockerCapture } = require("../adapters/docker/run"); const credentialFilter: typeof import("../security/credential-filter") = require("../security/credential-filter"); const { stripCredentials, isConfigObject, isConfigValue, isCredentialField } = credentialFilter; const { appendAuditEntry } = require("../shields/audit"); const { isPrivateHostname, isPrivateIp } = require("../private-networks"); -const registry = require("../state/registry") as { - getSandbox?: (name: string) => { openshellDriver?: string | null } | null; -}; +const { + selectPrivilegedSandboxContainer, + resolvePrivilegedSandboxContainer, + buildPrivilegedExecArgv, +}: typeof import("./privileged-container") = require("./privileged-container"); type ConfigObject = import("../security/credential-filter").ConfigObject; type ConfigValue = import("../security/credential-filter").ConfigValue; @@ -38,8 +39,6 @@ function parseJson(text: string): T { return JSON.parse(text); } -const K3S_CONTAINER = "openshell-cluster-nemoclaw"; - // --------------------------------------------------------------------------- // Agent-aware config resolution // @@ -117,61 +116,32 @@ const DEFAULT_AGENT_CONFIG: AgentConfigTarget = { const HERMES_STRICT_HASH_FILE = "/etc/nemoclaw/hermes.config-hash"; // Privileged sandbox exec bypasses the sandbox process's Landlock domain for -// host-initiated config writes. Legacy OpenShell gateways expose the pod via -// K3s/kubectl; Docker-driver gateways expose a sandbox container directly. +// host-initiated config writes. Legacy k3s gateways expose the pod via +// kubectl through `openshell-cluster-`; direct-container drivers +// (`docker`, `vm`) expose the sandbox container directly on the local Docker +// engine. Resolution is delegated to a shared helper so shields and config +// stay consistent (see `./privileged-container`). function selectDockerDriverSandboxContainer( sandboxName: string, openshellDriver: string | null | undefined, containerNames: string, + knownSandboxNames: readonly string[] = [], ): string | null { - if (openshellDriver !== "docker") return null; - const prefix = `openshell-${sandboxName}-`; - const exact = `openshell-${sandboxName}`; - return ( - containerNames - .split("\n") - .map((line: string) => line.trim()) - .find((name: string) => name === exact || name.startsWith(prefix)) || null + return selectPrivilegedSandboxContainer( + sandboxName, + openshellDriver, + containerNames, + knownSandboxNames, ); } function resolveDockerDriverSandboxContainer(sandboxName: string): string | null { - let openshellDriver: string | null | undefined; - try { - openshellDriver = registry.getSandbox?.(sandboxName)?.openshellDriver; - } catch { - return null; - } - - const output = dockerCapture(["ps", "--format", "{{.Names}}"], { ignoreError: true }); - return selectDockerDriverSandboxContainer(sandboxName, openshellDriver, output); -} - -function kubectlExecArgv(sandboxName: string, cmd: string[], stdin = false): string[] { - const args = [ - "exec", - ...(stdin ? ["-i"] : []), - K3S_CONTAINER, - "kubectl", - "exec", - "-n", - "openshell", - sandboxName, - "-c", - "agent", - ...(stdin ? ["-i"] : []), - "--", - ...cmd, - ]; - return args; + return resolvePrivilegedSandboxContainer(sandboxName); } function privilegedSandboxExecArgv(sandboxName: string, cmd: string[], stdin = false): string[] { - const dockerDriverContainer = resolveDockerDriverSandboxContainer(sandboxName); - if (dockerDriverContainer) { - return ["exec", ...(stdin ? ["-i"] : []), "--user", "root", dockerDriverContainer, ...cmd]; - } - return kubectlExecArgv(sandboxName, cmd, stdin); + const directContainer = resolveDockerDriverSandboxContainer(sandboxName); + return buildPrivilegedExecArgv(sandboxName, cmd, directContainer, { stdin }); } function privilegedSandboxExec( diff --git a/src/lib/sandbox/privileged-container.ts b/src/lib/sandbox/privileged-container.ts new file mode 100644 index 00000000000..bc1d016b55f --- /dev/null +++ b/src/lib/sandbox/privileged-container.ts @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Shared resolver and argv builders for privileged host-initiated execs +// (shields up/down, host-side config writes). The same code is consumed by +// `shields/index.ts` and `sandbox/config.ts` so the two callers cannot +// drift on how they pick the target sandbox container. +// +// Drivers that route privileged execs through a k3s cluster container still +// fall through to the legacy `openshell-cluster-` kubectl path. +// Drivers that run the sandbox directly on the local Docker engine +// (`docker`, `vm`) get a `docker exec --user root ...` argv so +// callers can bypass the sandbox's Landlock domain without depending on a +// non-existent cluster container. See #4245 for the macOS VM-driver case. + +import { dockerCapture } from "../adapters/docker/run"; +import * as registry from "../state/registry"; + +const DIRECT_CONTAINER_DRIVERS: ReadonlySet = new Set(["docker", "vm"]); +const LEGACY_K3S_CONTAINER = "openshell-cluster-nemoclaw"; + +export interface PrivilegedExecArgvOptions { + /** Include `-i` so the exec inherits stdin (used by config writes). */ + stdin?: boolean; +} + +export function isDirectContainerDriver( + openshellDriver: string | null | undefined, +): boolean { + return ( + typeof openshellDriver === "string" && + DIRECT_CONTAINER_DRIVERS.has(openshellDriver) + ); +} + +/** + * Pure selector: given the openshell driver and the output of + * `docker ps --format {{.Names}}`, return the sandbox container we should + * exec into, or null when the driver is not a direct-container driver or no + * matching container is present. + * + * `knownSandboxNames` is used to disambiguate when a sandbox name is a prefix + * of another sandbox's name (`my` vs `my-assistant`) so that looking up the + * shorter name does not steal the longer sandbox's container. + */ +export function selectPrivilegedSandboxContainer( + sandboxName: string, + openshellDriver: string | null | undefined, + containerNames: string, + knownSandboxNames: readonly string[] = [], +): string | null { + if (!isDirectContainerDriver(openshellDriver)) return null; + + const ourPrefix = `openshell-${sandboxName}-`; + const ourExact = `openshell-${sandboxName}`; + const knownSandboxes = new Set(knownSandboxNames); + knownSandboxes.add(sandboxName); + const candidates = containerNames + .split("\n") + .map((line) => line.trim()) + .filter((line) => line === ourExact || line.startsWith(ourPrefix)); + + // Prefer the exact-name container before considering suffixed ones, so a + // stale `openshell--` from an earlier OpenShell run cannot win + // the longest-known-name heuristic over the live exact container. + if (candidates.includes(ourExact)) return ourExact; + + for (const candidate of candidates) { + const stripped = candidate.replace(/^openshell-/, ""); + const owner = [...knownSandboxes] + .filter((name) => stripped === name || stripped.startsWith(`${name}-`)) + .sort((a, b) => b.length - a.length)[0]; + if (owner === sandboxName) return candidate; + } + return null; +} + +/** + * Runtime resolver: queries the local registry for the sandbox's openshell + * driver and known sandbox names, and the local Docker engine for live + * container names, then defers to the pure selector above. + * + * Returns null when the driver is not a direct-container driver, when the + * registry/Docker lookup fails, or when no matching container is found. + */ +export function resolvePrivilegedSandboxContainer( + sandboxName: string, +): string | null { + let openshellDriver: string | null | undefined; + let knownSandboxNames: string[] = []; + try { + openshellDriver = registry.getSandbox(sandboxName)?.openshellDriver; + if (!isDirectContainerDriver(openshellDriver)) return null; + try { + knownSandboxNames = registry + .listSandboxes() + .sandboxes.map((entry) => entry.name); + } catch { + knownSandboxNames = []; + } + } catch { + return null; + } + const output = dockerCapture(["ps", "--format", "{{.Names}}"], { + ignoreError: true, + }); + return selectPrivilegedSandboxContainer( + sandboxName, + openshellDriver, + output, + knownSandboxNames, + ); +} + +/** `docker exec --user root [-i] ` for direct-container drivers. */ +export function buildDirectContainerExecArgv( + container: string, + cmd: readonly string[], + opts: PrivilegedExecArgvOptions = {}, +): string[] { + return [ + "exec", + ...(opts.stdin ? ["-i"] : []), + "--user", + "root", + container, + ...cmd, + ]; +} + +/** + * Legacy k3s gateway path: + * `docker exec [-i] openshell-cluster-nemoclaw kubectl exec -n openshell -c agent [-i] -- ` + * + * When `opts.stdin` is true, `-i` is threaded into both the outer `docker exec` + * and the inner `kubectl exec` so stdin reaches the in-pod process. + */ +export function buildKubectlExecArgv( + sandboxName: string, + cmd: readonly string[], + opts: PrivilegedExecArgvOptions = {}, +): string[] { + const stdinFlag = opts.stdin ? ["-i"] : []; + return [ + "exec", + ...stdinFlag, + LEGACY_K3S_CONTAINER, + "kubectl", + "exec", + "-n", + "openshell", + sandboxName, + "-c", + "agent", + ...stdinFlag, + "--", + ...cmd, + ]; +} + +/** + * Choose the privileged-exec argv given an already-resolved direct container + * (or null to force the legacy k3s/kubectl fallback). Kept as a pure helper + * so shields and host-side config writes both go through the same dispatcher + * and so the argv is unit-testable without poking at registry/docker. + */ +export function buildPrivilegedExecArgv( + sandboxName: string, + cmd: readonly string[], + directContainer: string | null, + opts: PrivilegedExecArgvOptions = {}, +): string[] { + if (directContainer) return buildDirectContainerExecArgv(directContainer, cmd, opts); + return buildKubectlExecArgv(sandboxName, cmd, opts); +} + +/** Exposed so callers and tests can reference the legacy gateway container name. */ +export const LEGACY_K3S_GATEWAY_CONTAINER = LEGACY_K3S_CONTAINER; diff --git a/src/lib/shields/index.ts b/src/lib/shields/index.ts index d9de3700f3d..d8af96afad2 100644 --- a/src/lib/shields/index.ts +++ b/src/lib/shields/index.ts @@ -16,10 +16,10 @@ const { fork } = require("child_process"); const { randomBytes } = require("crypto"); const { run, runCapture, validateName } = require("../runner"); const { dockerExecFileSync } = require("../adapters/docker/exec"); -const { dockerCapture } = require("../adapters/docker/run"); -const registry = require("../state/registry") as { - getSandbox?: (name: string) => { openshellDriver?: string | null } | null; -}; +const { + resolvePrivilegedSandboxContainer, + buildPrivilegedExecArgv, +}: typeof import("../sandbox/privileged-container") = require("../sandbox/privileged-container"); const { buildPolicyGetCommand, buildPolicySetCommand, @@ -55,62 +55,19 @@ const STATE_DIR = resolveNemoclawStateDir(); // openshell sandbox exec runs commands INSIDE the Landlock domain, so it // can't modify read_only paths or change chattr flags. kubectl exec starts // a new process in the pod that does NOT inherit the Landlock ruleset. -// On the legacy gateway we reach kubectl via the K3s container. On the -// Docker-driver gateway there is no K3s container, so we exec into the -// sandbox Docker container directly as root. +// On the legacy k3s gateway we reach kubectl via the K3s container. On +// direct-container drivers (`docker`, `vm`) there is no K3s container, so +// we exec into the sandbox Docker container directly as root. Resolution +// is delegated to a shared helper shared with sandbox/config.ts so the two +// privileged-exec callers stay in sync (see #4245). // --------------------------------------------------------------------------- -const K3S_CONTAINER = "openshell-cluster-nemoclaw"; - -function resolveDockerDriverSandboxContainer( - sandboxName: string, -): string | null { - try { - if (registry.getSandbox?.(sandboxName)?.openshellDriver !== "docker") { - return null; - } - } catch { - return null; - } - const prefix = `openshell-${sandboxName}-`; - const exact = `openshell-${sandboxName}`; - const output = dockerCapture(["ps", "--format", "{{.Names}}"], { - ignoreError: true, - }); - return ( - output - .split("\n") - .map((line: string) => line.trim()) - .find((name: string) => name === exact || name.startsWith(prefix)) || null - ); -} - -function kubectlExecArgv(sandboxName: string, cmd: string[]): string[] { - return [ - "exec", - K3S_CONTAINER, - "kubectl", - "exec", - "-n", - "openshell", - sandboxName, - "-c", - "agent", - "--", - ...cmd, - ]; -} - function privilegedSandboxExecArgv( sandboxName: string, cmd: string[], ): string[] { - const dockerDriverContainer = - resolveDockerDriverSandboxContainer(sandboxName); - if (dockerDriverContainer) { - return ["exec", "--user", "root", dockerDriverContainer, ...cmd]; - } - return kubectlExecArgv(sandboxName, cmd); + const directContainer = resolvePrivilegedSandboxContainer(sandboxName); + return buildPrivilegedExecArgv(sandboxName, cmd, directContainer); } function privilegedSandboxExec(sandboxName: string, cmd: string[]): void { @@ -1368,6 +1325,7 @@ export { parseDuration, lockAgentConfig, unlockAgentConfig, + privilegedSandboxExecArgv, MAX_TIMEOUT_SECONDS, DEFAULT_TIMEOUT_SECONDS, }; diff --git a/test/config-set.test.ts b/test/config-set.test.ts index 5aa24f9e0c3..2a380b7ce46 100644 --- a/test/config-set.test.ts +++ b/test/config-set.test.ts @@ -120,6 +120,33 @@ describe("selectDockerDriverSandboxContainer", () => { selectDockerDriverSandboxContainer("demo", "kubernetes", "openshell-demo\n"), ).toBeNull(); }); + + it("resolves the VM-driver sandbox container instead of falling back to k3s (#4245)", () => { + // macOS Docker Desktop with the OpenShell VM driver: there is no + // openshell-cluster-* container, but the sandbox container is still + // exposed on the host docker engine. Host-initiated config writes must + // exec into it directly instead of hitting kubectl through a container + // that does not exist. + expect( + selectDockerDriverSandboxContainer( + "my-assistant", + "vm", + "openshell-my-assistant\n", + ["my-assistant"], + ), + ).toBe("openshell-my-assistant"); + }); + + it("disambiguates VM-driver sandbox names with shared prefixes", () => { + expect( + selectDockerDriverSandboxContainer( + "my", + "vm", + "openshell-my-assistant-12ab\n", + ["my", "my-assistant"], + ), + ).toBeNull(); + }); }); describe("config set helpers", () => { diff --git a/test/privileged-container.test.ts b/test/privileged-container.test.ts new file mode 100644 index 00000000000..cc480eaab5e --- /dev/null +++ b/test/privileged-container.test.ts @@ -0,0 +1,250 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createRequire } from "node:module"; +import { describe, it, expect } from "vitest"; + +// Build must run before these tests (imports from dist/) +const require = createRequire(import.meta.url); +const { + isDirectContainerDriver, + selectPrivilegedSandboxContainer, + buildPrivilegedExecArgv, + buildDirectContainerExecArgv, + buildKubectlExecArgv, + LEGACY_K3S_GATEWAY_CONTAINER, +} = require("../dist/lib/sandbox/privileged-container"); + +describe("isDirectContainerDriver", () => { + it("recognizes the docker and vm drivers", () => { + expect(isDirectContainerDriver("docker")).toBe(true); + expect(isDirectContainerDriver("vm")).toBe(true); + }); + + it("rejects legacy k3s/kubernetes and unknown drivers", () => { + expect(isDirectContainerDriver("kubernetes")).toBe(false); + expect(isDirectContainerDriver("k3s")).toBe(false); + expect(isDirectContainerDriver("podman")).toBe(false); + }); + + it("treats null/undefined/empty as not direct-container", () => { + expect(isDirectContainerDriver(null)).toBe(false); + expect(isDirectContainerDriver(undefined)).toBe(false); + expect(isDirectContainerDriver("")).toBe(false); + }); +}); + +describe("selectPrivilegedSandboxContainer", () => { + it("resolves the exact `openshell-` container for the docker driver", () => { + expect( + selectPrivilegedSandboxContainer( + "demo", + "docker", + "openshell-demo\nopenshell-other-aa11", + ), + ).toBe("openshell-demo"); + }); + + it("resolves the exact `openshell-` container for the vm driver (#4245)", () => { + // macOS Docker Desktop with the OpenShell VM driver: no k3s container + // exists, but the sandbox container shows up on the host docker engine. + expect( + selectPrivilegedSandboxContainer( + "my-assistant", + "vm", + "openshell-my-assistant\n", + ["my-assistant"], + ), + ).toBe("openshell-my-assistant"); + }); + + it("falls back to a suffixed `openshell--` container for the vm driver", () => { + expect( + selectPrivilegedSandboxContainer( + "my-assistant", + "vm", + "openshell-my-assistant-12ab\n", + ["my-assistant"], + ), + ).toBe("openshell-my-assistant-12ab"); + }); + + it("returns null for legacy kubernetes-driver sandboxes so callers fall back to kubectl", () => { + expect( + selectPrivilegedSandboxContainer( + "demo", + "kubernetes", + "openshell-demo\nopenshell-cluster-nemoclaw\n", + ), + ).toBeNull(); + }); + + it("returns null when the driver is null/undefined", () => { + expect( + selectPrivilegedSandboxContainer("demo", null, "openshell-demo\n"), + ).toBeNull(); + expect( + selectPrivilegedSandboxContainer("demo", undefined, "openshell-demo\n"), + ).toBeNull(); + }); + + it("returns null when no matching container is present", () => { + expect( + selectPrivilegedSandboxContainer( + "demo", + "docker", + "openshell-other\nopenshell-cluster-nemoclaw\n", + ), + ).toBeNull(); + }); + + it("does not steal another sandbox's container when its name is a prefix", () => { + // Looking up `my` must not match `openshell-my-assistant-12ab`. + expect( + selectPrivilegedSandboxContainer( + "my", + "vm", + "openshell-my-assistant-12ab\n", + ["my", "my-assistant"], + ), + ).toBeNull(); + }); + + it("does not steal a hyphenated sandbox's container when its name is a prefix and the suffix is hyphen-free", () => { + expect( + selectPrivilegedSandboxContainer( + "my-assistant", + "vm", + "openshell-my-assistant-prod\n", + ["my-assistant", "my-assistant-prod"], + ), + ).toBeNull(); + }); + + it("prefers the exact-name container over a docker-runtime-suffixed sibling", () => { + // openshell-my-12ab is a stale same-sandbox alternate container; only + // `my` is registered, so the longest-known-name heuristic alone would + // still resolve the suffixed candidate to `my`. The exact name must + // always win. + expect( + selectPrivilegedSandboxContainer( + "my", + "vm", + "openshell-my-12ab\nopenshell-my\n", + ["my"], + ), + ).toBe("openshell-my"); + }); + + it("attributes a hyphenated container to the longest registered sandbox name", () => { + expect( + selectPrivilegedSandboxContainer( + "my-assistant", + "vm", + "openshell-my-assistant-prod-abc\n", + ["my-assistant", "my-assistant-prod"], + ), + ).toBeNull(); + }); +}); + +describe("buildPrivilegedExecArgv", () => { + it("uses `docker exec --user root ` for direct-container drivers (#4245)", () => { + expect( + buildPrivilegedExecArgv( + "my-assistant", + ["chmod", "444", "/sandbox/.openclaw/openclaw.json"], + "openshell-my-assistant", + ), + ).toEqual([ + "exec", + "--user", + "root", + "openshell-my-assistant", + "chmod", + "444", + "/sandbox/.openclaw/openclaw.json", + ]); + }); + + it("falls back to the legacy k3s/kubectl path when no direct container is resolved", () => { + expect( + buildPrivilegedExecArgv( + "my-assistant", + ["chmod", "444", "/sandbox/.openclaw/openclaw.json"], + null, + ), + ).toEqual([ + "exec", + "openshell-cluster-nemoclaw", + "kubectl", + "exec", + "-n", + "openshell", + "my-assistant", + "-c", + "agent", + "--", + "chmod", + "444", + "/sandbox/.openclaw/openclaw.json", + ]); + }); + + it("threads -i into both docker exec and kubectl exec on the legacy path", () => { + const argv = buildPrivilegedExecArgv( + "demo", + ["sh", "-c", "cat > /tmp/out"], + null, + { stdin: true }, + ); + + // -i must appear once for `docker exec -i ...` and once for the inner + // `kubectl exec -i ...` so stdin reaches the in-pod process. + expect(argv[0]).toBe("exec"); + expect(argv[1]).toBe("-i"); + expect(argv).toContain("kubectl"); + const kubectlIdx = argv.indexOf("kubectl"); + expect(argv.slice(kubectlIdx).filter((arg: string) => arg === "-i")).toHaveLength(1); + }); + + it("threads -i into the direct-container path for config writes", () => { + expect( + buildPrivilegedExecArgv( + "demo", + ["sh", "-c", "cat > /tmp/out"], + "openshell-demo", + { stdin: true }, + ), + ).toEqual([ + "exec", + "-i", + "--user", + "root", + "openshell-demo", + "sh", + "-c", + "cat > /tmp/out", + ]); + }); +}); + +describe("buildDirectContainerExecArgv / buildKubectlExecArgv", () => { + it("buildDirectContainerExecArgv emits a `docker exec --user root` argv", () => { + expect( + buildDirectContainerExecArgv("openshell-demo", ["whoami"]), + ).toEqual(["exec", "--user", "root", "openshell-demo", "whoami"]); + }); + + it("buildKubectlExecArgv targets the legacy gateway container", () => { + expect(buildKubectlExecArgv("demo", ["whoami"]).slice(0, 3)).toEqual([ + "exec", + LEGACY_K3S_GATEWAY_CONTAINER, + "kubectl", + ]); + }); + + it("LEGACY_K3S_GATEWAY_CONTAINER pins the legacy container name", () => { + expect(LEGACY_K3S_GATEWAY_CONTAINER).toBe("openshell-cluster-nemoclaw"); + }); +}); diff --git a/test/shields-vm-driver-argv.test.ts b/test/shields-vm-driver-argv.test.ts new file mode 100644 index 00000000000..a1ad3f1b711 --- /dev/null +++ b/test/shields-vm-driver-argv.test.ts @@ -0,0 +1,218 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Issue #4245: `nemoclaw shields up/down` on macOS Docker Desktop +// with the OpenShell VM driver was routing privileged execs through +// `docker exec openshell-cluster-nemoclaw kubectl exec ...`, which fails +// because no k3s container exists in VM-driver gateways. Both shields and +// the host-side config writer must instead exec directly into the +// `openshell-` container. + +import { createRequire } from "node:module"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +// Build must run before these tests (imports from dist/). +const require = createRequire(import.meta.url); + +type SandboxEntry = { + name: string; + openshellDriver?: string | null; +}; + +const registry = require("../dist/lib/state/registry") as { + getSandbox: (name: string) => SandboxEntry | null; + listSandboxes: () => { sandboxes: SandboxEntry[]; defaultSandbox: string | null }; +}; + +const dockerRun = require("../dist/lib/adapters/docker/run") as { + dockerCapture: (args: readonly string[], opts?: unknown) => string; +}; + +const shields = require("../dist/lib/shields") as { + privilegedSandboxExecArgv: (sandboxName: string, cmd: string[]) => string[]; +}; + +const config = require("../dist/lib/sandbox/config") as { + privilegedSandboxExecArgv: ( + sandboxName: string, + cmd: string[], + stdin?: boolean, + ) => string[]; +}; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function stubRegistry(opts: { + driver: string | null; + sandboxNames?: string[]; + containerNames: string; +}): void { + // Every name passed in sandboxNames (plus the canonical "my-assistant") must + // resolve through getSandbox so the prefix-collision test actually exercises + // selectPrivilegedSandboxContainer's longest-known-name disambiguation rather + // than falling out of resolvePrivilegedSandboxContainer's `driver == null` + // short-circuit (CodeRabbit #4290). + const canonicalName = "my-assistant"; + const knownSandboxNames = opts.sandboxNames ?? [canonicalName]; + vi.spyOn(registry, "getSandbox").mockImplementation((name) => { + if (knownSandboxNames.includes(name)) { + return { name, openshellDriver: opts.driver }; + } + return null; + }); + vi.spyOn(registry, "listSandboxes").mockReturnValue({ + sandboxes: knownSandboxNames.map((name) => ({ + name, + openshellDriver: opts.driver, + })), + defaultSandbox: canonicalName, + }); + vi.spyOn(dockerRun, "dockerCapture").mockReturnValue(opts.containerNames); +} + +describe("shields privilegedSandboxExecArgv (#4245)", () => { + it("targets the direct VM-driver sandbox container instead of the legacy k3s gateway", () => { + stubRegistry({ + driver: "vm", + containerNames: "openshell-my-assistant\nopenshell-other\n", + }); + + const argv = shields.privilegedSandboxExecArgv("my-assistant", [ + "chmod", + "444", + "/sandbox/.openclaw/openclaw.json", + ]); + + expect(argv).toEqual([ + "exec", + "--user", + "root", + "openshell-my-assistant", + "chmod", + "444", + "/sandbox/.openclaw/openclaw.json", + ]); + // Defensive regression check: the legacy k3s container must not appear. + expect(argv).not.toContain("openshell-cluster-nemoclaw"); + }); + + it("still uses the direct container for the docker driver", () => { + stubRegistry({ + driver: "docker", + containerNames: "openshell-my-assistant-12ab\n", + }); + + const argv = shields.privilegedSandboxExecArgv("my-assistant", ["whoami"]); + + expect(argv).toEqual([ + "exec", + "--user", + "root", + "openshell-my-assistant-12ab", + "whoami", + ]); + }); + + it("falls back to the legacy k3s/kubectl path for non-direct drivers", () => { + stubRegistry({ + driver: "kubernetes", + containerNames: "openshell-cluster-nemoclaw\nopenshell-my-assistant\n", + }); + + const argv = shields.privilegedSandboxExecArgv("my-assistant", ["whoami"]); + + expect(argv).toEqual([ + "exec", + "openshell-cluster-nemoclaw", + "kubectl", + "exec", + "-n", + "openshell", + "my-assistant", + "-c", + "agent", + "--", + "whoami", + ]); + }); + + it("does not steal another sandbox's container when its name is a prefix (#4245 disambiguation)", () => { + // Only `openshell-my-assistant-12ab` is live; looking up the shorter + // `my` must fall back to kubectl rather than mis-execing into + // `my-assistant`'s container. + stubRegistry({ + driver: "vm", + sandboxNames: ["my", "my-assistant"], + containerNames: "openshell-my-assistant-12ab\n", + }); + + const argv = shields.privilegedSandboxExecArgv("my", ["whoami"]); + + expect(argv).not.toContain("openshell-my-assistant-12ab"); + // Falls back to kubectl because no openshell-my[-id] container exists. + expect(argv.slice(0, 3)).toEqual([ + "exec", + "openshell-cluster-nemoclaw", + "kubectl", + ]); + }); +}); + +describe("sandbox config privilegedSandboxExecArgv (#4245)", () => { + it("targets the direct VM-driver container for host-initiated config writes", () => { + stubRegistry({ + driver: "vm", + containerNames: "openshell-my-assistant\n", + }); + + const argv = config.privilegedSandboxExecArgv( + "my-assistant", + ["sh", "-c", "cat > /sandbox/.openclaw/openclaw.json"], + true, + ); + + expect(argv).toEqual([ + "exec", + "-i", + "--user", + "root", + "openshell-my-assistant", + "sh", + "-c", + "cat > /sandbox/.openclaw/openclaw.json", + ]); + }); + + it("preserves the kubectl `-i` thread-through for legacy gateways", () => { + stubRegistry({ + driver: "kubernetes", + containerNames: "openshell-cluster-nemoclaw\n", + }); + + const argv = config.privilegedSandboxExecArgv( + "my-assistant", + ["sh", "-c", "cat > /tmp/foo"], + true, + ); + + expect(argv).toEqual([ + "exec", + "-i", + "openshell-cluster-nemoclaw", + "kubectl", + "exec", + "-n", + "openshell", + "my-assistant", + "-c", + "agent", + "-i", + "--", + "sh", + "-c", + "cat > /tmp/foo", + ]); + }); +});