diff --git a/docs/concepts/mantis.md b/docs/concepts/mantis.md index 35e19691b68..99ab42f1abd 100644 --- a/docs/concepts/mantis.md +++ b/docs/concepts/mantis.md @@ -420,6 +420,12 @@ noVNC, Node 22.22.3+, 24.15+, or 25.9+ and pnpm, an OpenClaw checkout, and outbound access to the target transport, GitHub, model providers, and the credential broker. +The Telegram Desktop proof workflow runs on Ubuntu. Its lease fence requires +Bash, util-linux `setsid`, and coreutils; the agent wrapper also uses GNU +`timeout` and configured `sudo`. Setup uses Linux account tools, and cleanup +inspects `/proc`. See the [focused Linux fence tests](/reference/test#linux-shell-integrations) +for prerequisites and the local proof command. + Credential and environment names used across Mantis commands and workflows: - `OPENCLAW_QA_DISCORD_MANTIS_BOT_TOKEN` diff --git a/docs/gateway/openshell.md b/docs/gateway/openshell.md index f640b0a2220..f134c420a68 100644 --- a/docs/gateway/openshell.md +++ b/docs/gateway/openshell.md @@ -437,8 +437,8 @@ Custom images used with the OpenClaw filesystem bridge must provide: - `/bin/sh` - `sleep` for the persistent sandbox main process on current OpenShell releases -- `python3` or `python` for pinned write, edit, rename, and remove operations -- GNU-compatible `stat` and `find` +- `python3` for pinned remote filesystem reads and mutations +- GNU-compatible `stat` (`-c`), `readlink` (`-f`), and `find` - standard `mkdir`, `mv`, `rm`, and `rmdir` utilities When the agent workspace differs from the sandbox workspace, the sandbox user diff --git a/docs/gateway/sandboxing.md b/docs/gateway/sandboxing.md index 77b124c5b7a..dad45e9b16a 100644 --- a/docs/gateway/sandboxing.md +++ b/docs/gateway/sandboxing.md @@ -213,6 +213,13 @@ A containerized Gateway creates sibling sandboxes through the host's local Podma Use `backend: "ssh"` to sandbox `exec`, file tools, and media reads on an arbitrary SSH-accessible machine. +The remote environment must provide `/bin/sh`, `python3`, and GNU-compatible +`stat` (`-c`) and `readlink` (`-f`) for the filesystem bridge. These utilities +must be available to the non-interactive SSH command, not just an interactive +login shell. The Gateway host does not need these remote utilities: a macOS or +Windows Gateway can use an SSH target that supplies them. This is a remote +utility contract, not a Linux-only Gateway requirement. + ```json5 { agents: { diff --git a/docs/reference/test.md b/docs/reference/test.md index 1cffd2ad09e..60a513cb564 100644 --- a/docs/reference/test.md +++ b/docs/reference/test.md @@ -98,6 +98,29 @@ Test wrapper runs end with a short `[test] passed|failed|skipped ... in ...` sum | `pnpm changed:lanes` | Shows the architectural lanes triggered by the diff against `origin/main`. | | `pnpm check:changed` | Classifies and runs the local changed formatting/typecheck/lint/guard plan. Does not run Vitest; use `pnpm test:changed` or `pnpm test ` for test proof. | +## Linux shell integrations + +The Mantis Telegram lease-fence integration tests require Linux, Bash, +util-linux `setsid`, and coreutils (`sleep`, `cat`, and `true`). On Ubuntu, +install the prerequisites with `sudo apt-get install bash util-linux coreutils`. +With repository dependencies ready, run the focused proof on Linux: + +```bash +node scripts/run-vitest.mjs test/scripts/run-with-lease-fence.test.ts +``` + +All three tests must pass: lease loss removes the command's process group, +clean exit propagates, and stdin reaches the fenced command. Missing `setsid` +fails the Linux suite with prerequisite guidance; it does not skip the tests. +macOS and Windows skip this Linux workflow integration. Use Linux CI or an +isolated Linux environment for that proof. See [Mantis](/concepts/mantis). + +Remote filesystem fixtures that execute GNU `stat` and `readlink` run locally +only on Linux. The shared leading-`@` file-tool scenario +also runs against a portable remote-only bridge on every platform. Native +Python helper coverage remains separate, including macOS; these fixture gates +do not restrict the [SSH backend's Gateway host](/gateway/sandboxing#ssh-backend). + ## Shared test state and process helpers - `src/test-utils/openclaw-test-state.ts`: use from Vitest when a test needs an isolated `HOME`, `OPENCLAW_STATE_DIR`, `OPENCLAW_CONFIG_PATH`, config fixture, workspace, agent dir, or auth-profile store. diff --git a/src/agents/agent-tools.at-prefixed-remote-paths.test.ts b/src/agents/agent-tools.at-prefixed-remote-paths.test.ts index 415ca0bba04..022b7f750d5 100644 --- a/src/agents/agent-tools.at-prefixed-remote-paths.test.ts +++ b/src/agents/agent-tools.at-prefixed-remote-paths.test.ts @@ -1,6 +1,6 @@ import fs from "node:fs/promises"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js"; import { createSandboxedEditTool, @@ -13,16 +13,20 @@ import { createApplyPatchTool } from "./apply-patch.js"; import { createRemoteShellSandboxFsBridge } from "./sandbox/remote-fs-bridge.js"; import { createLocalRemoteShellScriptRunner } from "./sandbox/remote-fs-bridge.test-helpers.js"; import { createSandboxTestContext } from "./sandbox/test-fixtures.js"; +import { createSandboxFsBridgeFromResolver } from "./test-helpers/host-sandbox-fs-bridge.js"; const tempDirs = useAutoCleanupTempDirTracker(afterEach); -describe("leading-@ paths on a real remote sandbox filesystem bridge", () => { - it.runIf(process.platform !== "win32")( - "preserves remote-only literal files, shorthand, journal authority, and patch targets", +describe.each(["portable", "Linux shell"] as const)("leading-@ remote paths (%s)", (fixture) => { + // The shell fixture runs remote GNU utilities locally; the portable fixture + // exercises the same tool scenario without requiring that local environment. + it.runIf(fixture === "portable" || process.platform === "linux")( + "preserves literal files, shorthand, journal authority, patch targets, and stat failures", async () => { - const stateDir = tempDirs.make("openclaw-at-remote-"); + const stateDir = await fs.realpath(tempDirs.make("openclaw-at-remote-")); const hostRoot = path.join(stateDir, "host"); const remoteRoot = path.join(stateDir, "remote"); + const containerWorkdir = fixture === "portable" ? "/remote-workspace" : remoteRoot; await fs.mkdir(hostRoot); await fs.mkdir(remoteRoot); await fs.writeFile(path.join(remoteRoot, "@notes.md"), "literal original", "utf8"); @@ -36,27 +40,66 @@ describe("leading-@ paths on a real remote sandbox filesystem bridge", () => { overrides: { workspaceDir: hostRoot, agentWorkspaceDir: hostRoot, - containerWorkdir: remoteRoot, + containerWorkdir, workspaceAccess: "rw", }, }); - const bridge = createRemoteShellSandboxFsBridge({ + const remoteBridge = createRemoteShellSandboxFsBridge({ sandbox, runtime: { - remoteWorkspaceDir: remoteRoot, - remoteAgentWorkspaceDir: remoteRoot, + remoteWorkspaceDir: containerWorkdir, + remoteAgentWorkspaceDir: containerWorkdir, runRemoteShellScript: createLocalRemoteShellScriptRunner(), }, }); + const resolvePath = remoteBridge.resolvePath.bind(remoteBridge); + const bridge = + fixture === "portable" + ? { + ...createSandboxFsBridgeFromResolver((filePath, cwd) => { + const resolved = resolvePath({ filePath, cwd }); + return { ...resolved, hostPath: path.join(remoteRoot, resolved.relativePath) }; + }), + // Only backing operations see hostPath. Public resolution must keep + // path policy on asynchronous remote stat, including on Windows. + resolvePath, + } + : remoteBridge; const guard = (tool: ReturnType) => wrapToolWorkspaceRootGuardWithOptions(tool, hostRoot, { - containerWorkdir: remoteRoot, + containerWorkdir, bridge, }); const readTool = guard(createSandboxedReadTool({ root: hostRoot, bridge })); const writeTool = guard(createSandboxedWriteTool({ root: hostRoot, bridge })); const editTool = guard(createSandboxedEditTool({ root: hostRoot, bridge })); + const statError = new Error("remote stat unavailable"); + const stat = bridge.stat.bind(bridge); + const statFailure = vi + .spyOn(bridge, "stat") + .mockImplementation((params) => + resolvePath(params).relativePath === "@notes.md" + ? Promise.reject(statError) + : stat(params), + ); + try { + await expect( + writeTool.execute("remote-at-stat-error", { + path: "@notes.md", + content: "must not replace either file", + }), + ).rejects.toBe(statError); + await expect(fs.readFile(path.join(remoteRoot, "@notes.md"), "utf8")).resolves.toBe( + "literal original", + ); + await expect(fs.readFile(path.join(remoteRoot, "notes.md"), "utf8")).resolves.toBe( + "sibling original", + ); + } finally { + statFailure.mockRestore(); + } + await expect(readTool.execute("remote-at-read", { path: "@notes.md" })).resolves.toEqual( expect.objectContaining({ content: expect.arrayContaining([ @@ -132,6 +175,7 @@ describe("leading-@ paths on a real remote sandbox filesystem bridge", () => { await expect(fs.stat(path.join(hostRoot, "@notes.md"))).rejects.toMatchObject({ code: "ENOENT", }); + await expect(fs.readdir(hostRoot)).resolves.toEqual([]); }, ); }); diff --git a/src/agents/sandbox/remote-fs-bridge.test-helpers.ts b/src/agents/sandbox/remote-fs-bridge.test-helpers.ts index 0ac7fbb02c4..dcf762053e2 100644 --- a/src/agents/sandbox/remote-fs-bridge.test-helpers.ts +++ b/src/agents/sandbox/remote-fs-bridge.test-helpers.ts @@ -1,9 +1,6 @@ // Local subprocess-backed remote bridge fixtures shared by focused sandbox tests. import { spawnSync } from "node:child_process"; -import { - SANDBOX_CREATE_EXISTS_EXIT_CODE, - SANDBOX_PINNED_MUTATION_PYTHON, -} from "./fs-bridge-mutation-helper.js"; +import { SANDBOX_CREATE_EXISTS_EXIT_CODE } from "./fs-bridge-mutation-helper.js"; import type { RemoteShellSandboxHandle } from "./remote-fs-bridge.types.js"; export type LocalRemoteShellSpawnResult = { @@ -39,22 +36,13 @@ export function createLocalRemoteShellScriptRunner(params?: { params?.onCommand?.(command); const runsPinnedMutation = command.script.includes(PINNED_MUTATION_MARKER); const spawn = params?.spawn ?? spawnLocalRemoteShell; - const result = runsPinnedMutation - ? spawn( - "python3", - ["-c", SANDBOX_PINNED_MUTATION_PYTHON, ...(command.args ?? [])], - command.stdin, - ) - : spawn( - "sh", - [ - "-c", - command.script, - params?.shellArg0 ?? "openclaw-sandbox-fs", - ...(command.args ?? []), - ], - command.stdin, - ); + // Linux integration executes the remote command unchanged, including its + // fd 3 heredoc, while stdin remains available for mutation payloads. + const result = spawn( + "/bin/sh", + ["-c", command.script, params?.shellArg0 ?? "openclaw-sandbox-fs", ...(command.args ?? [])], + command.stdin, + ); const stdout = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(result.stdout ?? []); diff --git a/src/agents/sandbox/remote-fs-bridge.test.ts b/src/agents/sandbox/remote-fs-bridge.test.ts index 4e024bb2793..ea713c5fbb7 100644 --- a/src/agents/sandbox/remote-fs-bridge.test.ts +++ b/src/agents/sandbox/remote-fs-bridge.test.ts @@ -105,87 +105,6 @@ describe("remote sandbox fs bridge", () => { ).resolves.toMatchObject({ code: SANDBOX_CREATE_EXISTS_EXIT_CODE }); }); - it.runIf(process.platform !== "win32")( - "orders sandbox tools through one remote alias identity", - async () => { - await withTempDir("openclaw-remote-fs-queue-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "host-workspace"); - const remoteWorkspaceDir = path.join(stateDir, "remote-workspace"); - await fs.mkdir(workspaceDir); - await fs.mkdir(remoteWorkspaceDir); - const sandbox = createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }); - const { runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir, - remoteAgentWorkspaceDir: remoteWorkspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ sandbox, runtime }); - const remotePath = path.join(remoteWorkspaceDir, "race-target.txt"); - const hostPath = path.join(workspaceDir, "race-target.txt"); - const aliasIdentity = await resolveSandboxFileMutationQueueKey({ - bridge, - root: workspaceDir, - filePath: remotePath, - cwd: workspaceDir, - }); - await expect( - resolveSandboxFileMutationQueueKey({ - bridge, - root: workspaceDir, - filePath: hostPath, - cwd: workspaceDir, - }), - ).resolves.toBe(aliasIdentity); - - const writeIdentityStarted = createDeferred(); - const releaseWriteIdentity = createDeferred(); - const readIdentityResolved = createDeferred(); - const runRemoteShellScript = runtime.runRemoteShellScript.bind(runtime); - let identityCallCount = 0; - runtime.runRemoteShellScript = async (command) => { - const isTargetIdentity = - command.script.includes('target="$1"') && command.args?.[0] === remotePath; - if (!isTargetIdentity) { - return await runRemoteShellScript(command); - } - const identityCall = ++identityCallCount; - if (identityCall === 1) { - writeIdentityStarted.resolve(); - await releaseWriteIdentity.promise; - } - const result = await runRemoteShellScript(command); - if (identityCall === 2) { - readIdentityResolved.resolve(); - } - return result; - }; - const statSpy = vi.spyOn(bridge, "stat"); - const writeTool = createSandboxedWriteTool({ root: workspaceDir, bridge }); - const readTool = createSandboxedReadTool({ root: workspaceDir, bridge }); - const writeResult = writeTool.execute("write", { - path: remotePath, - content: "remote snapshot", - }); - await writeIdentityStarted.promise; - const readResult = readTool.execute("read", { path: hostPath }); - void readResult.catch(() => {}); - await readIdentityResolved.promise; - await new Promise((resolve) => { - setImmediate(resolve); - }); - expect(statSpy).not.toHaveBeenCalled(); - - releaseWriteIdentity.resolve(); - const [, result] = await Promise.all([writeResult, readResult]); - expect(statSpy).toHaveBeenCalled(); - expect(result.content).toEqual( - expect.arrayContaining([ - expect.objectContaining({ type: "text", text: "remote snapshot" }), - ]), - ); - }); - }, - ); - it.each([ { name: "an unrecognized script", @@ -245,310 +164,30 @@ describe("remote sandbox fs bridge", () => { ).rejects.toBe(spawnError); }); - it.runIf(process.platform !== "win32")( - "creates files exclusively and preserves existing entries", - async () => { - await withTempDir("openclaw-remote-fs-create-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - const { runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: workspaceDir, - remoteAgentWorkspaceDir: workspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), - runtime, - }); - const createFileExclusive = bridge.createFileExclusive?.bind(bridge); - expect(createFileExclusive).toBeTypeOf("function"); - - await expect( - createFileExclusive!({ filePath: "nested/note.txt", data: "first" }), - ).resolves.toBe("created"); - await expect( - createFileExclusive!({ filePath: "nested/note.txt", data: "replacement" }), - ).resolves.toBe("exists"); - await expect( - fs.readFile(path.join(workspaceDir, "nested", "note.txt"), "utf8"), - ).resolves.toBe("first"); - - const outcomes = await Promise.all([ - createFileExclusive!({ filePath: "race.txt", data: "one" }), - createFileExclusive!({ filePath: "race.txt", data: "two" }), - ]); - expect(outcomes.toSorted()).toEqual(["created", "exists"]); - await expect(fs.readFile(path.join(workspaceDir, "race.txt"), "utf8")).resolves.toMatch( - /^(one|two)$/u, - ); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "treats a symlink destination as existing without changing its target", - async () => { - await withTempDir("openclaw-remote-fs-create-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - await fs.writeFile(path.join(workspaceDir, "target.txt"), "keep", "utf8"); - await fs.symlink("target.txt", path.join(workspaceDir, "link.txt")); - const { runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: workspaceDir, - remoteAgentWorkspaceDir: workspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), - runtime, - }); - const createFileExclusive = bridge.createFileExclusive?.bind(bridge); - expect(createFileExclusive).toBeTypeOf("function"); - - await expect( - createFileExclusive!({ filePath: "link.txt", data: Buffer.alloc(1_048_576) }), - ).resolves.toBe("exists"); - await expect(fs.readFile(path.join(workspaceDir, "target.txt"), "utf8")).resolves.toBe( - "keep", - ); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "accepts a symlinked mount root while rejecting escapes through it", - async () => { - await withTempDir("openclaw-remote-fs-linked-root-", async (stateDir) => { - const realWorkspaceDir = path.join(stateDir, "real-workspace"); - const linkedWorkspaceDir = path.join(stateDir, "linked-workspace"); - const outsideDir = path.join(stateDir, "outside"); - await fs.mkdir(realWorkspaceDir); - await fs.mkdir(outsideDir); - await fs.symlink(realWorkspaceDir, linkedWorkspaceDir, "dir"); - await fs.symlink(outsideDir, path.join(realWorkspaceDir, "escape"), "dir"); - const { runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: linkedWorkspaceDir, - remoteAgentWorkspaceDir: linkedWorkspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ - workspaceDir: linkedWorkspaceDir, - agentWorkspaceDir: linkedWorkspaceDir, - }), - runtime, - }); - const createFileExclusive = bridge.createFileExclusive?.bind(bridge); - expect(createFileExclusive).toBeTypeOf("function"); - - await expect( - createFileExclusive!({ filePath: "inside.txt", data: "inside" }), - ).resolves.toBe("created"); - await expect(bridge.readFile({ filePath: "inside.txt" })).resolves.toEqual( - Buffer.from("inside"), - ); - await expect(bridge.mkdirp({ filePath: "nested/dir" })).resolves.toBeUndefined(); - await expect(fs.readFile(path.join(realWorkspaceDir, "inside.txt"), "utf8")).resolves.toBe( - "inside", - ); - await expect( - fs - .stat(path.join(realWorkspaceDir, "nested", "dir")) - .then((entry) => entry.isDirectory()), - ).resolves.toBe(true); - await expect( - createFileExclusive!({ filePath: "escape/outside.txt", data: "blocked" }), - ).rejects.toThrow(/escapes allowed mounts/); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "reads files with the pinned mutation helper", - async () => { - await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { - const workspacePath = path.join(stateDir, "workspace"); - await fs.mkdir(workspacePath, { recursive: true }); - const workspaceDir = await fs.realpath(workspacePath); - await fs.writeFile(path.join(workspaceDir, "note.txt"), "hello", "utf8"); - - const { calls, runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: workspaceDir, - remoteAgentWorkspaceDir: workspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ - workspaceDir, - agentWorkspaceDir: workspaceDir, - }), - runtime, - }); - - await expect(bridge.readFile({ filePath: "note.txt" })).resolves.toEqual( - Buffer.from("hello"), - ); - expect(calls).toHaveLength(2); - const readCall = calls.find((call) => call.args?.[0] === "read"); - expect(readCall?.script).toContain("python3 /dev/fd/3 \"$@\" 3<<'PY'"); - expect(readCall?.script).toContain("read_file(parent_fd, basename)"); - expect(readCall?.script).not.toContain('cat -- "$1"'); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "forwards and enforces bounded pinned file reads", - async () => { - await withTempDir("openclaw-remote-fs-bounded-read-", async (stateDir) => { - const workspacePath = path.join(stateDir, "workspace"); - await fs.mkdir(workspacePath, { recursive: true }); - const workspaceDir = await fs.realpath(workspacePath); - await fs.writeFile(path.join(workspaceDir, "note.txt"), "hello", "utf8"); - - const { calls, runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: workspaceDir, - remoteAgentWorkspaceDir: workspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), - runtime, - }); - - await expect(bridge.readFile({ filePath: "note.txt", maxBytes: 5 })).resolves.toEqual( - Buffer.from("hello"), - ); - expect(calls.find((call) => call.args?.[0] === "read")?.args).toEqual([ - "read", - workspaceDir, - "", - "note.txt", - "5", - ]); - await expect(bridge.readFile({ filePath: "note.txt", maxBytes: 4 })).rejects.toThrow( - /bounded read limit/i, - ); - await expect(bridge.readFile({ filePath: "note.txt", maxBytes: -1 })).rejects.toThrow( - /non-negative safe integer/i, - ); - expect(calls).toHaveLength(4); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "streams file copies with the pinned mutation helper", - async () => { - await withTempDir("openclaw-remote-fs-copy-", async (stateDir) => { - const workspacePath = path.join(stateDir, "workspace"); - await fs.mkdir(workspacePath, { recursive: true }); - const workspaceDir = await fs.realpath(workspacePath); - await fs.writeFile(path.join(workspaceDir, "source.txt"), "streamed", "utf8"); - const { calls, runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: workspaceDir, - remoteAgentWorkspaceDir: workspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), - runtime, - }); - - const copyFile = bridge.copyFile?.bind(bridge); - expect(copyFile).toBeTypeOf("function"); - await copyFile!({ - sourcePath: "source.txt", - destinationPath: "nested/copy.txt", - }); - - await expect( - fs.readFile(path.join(workspaceDir, "nested", "copy.txt"), "utf8"), - ).resolves.toBe("streamed"); - expect(calls.some((call) => call.args?.[0] === "copy")).toBe(true); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "rejects mount-root reads before invoking the mutation helper", - async () => { - await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - - const { calls, runtime } = createLocalRemoteRuntime({ - remoteWorkspaceDir: workspaceDir, - remoteAgentWorkspaceDir: workspaceDir, - }); - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ - workspaceDir, - agentWorkspaceDir: workspaceDir, - }), - runtime, - }); - - await expect(bridge.readFile({ filePath: "." })).rejects.toThrow( - /Invalid sandbox entry target/, - ); - expect(calls).toHaveLength(0); - }); - }, - ); - - it.runIf(process.platform !== "win32")( - "reads dot-dot-prefixed filenames inside the workspace", - async () => { - await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - await fs.writeFile(path.join(workspaceDir, "..note.txt"), "hidden", "utf8"); - - const bridge = createWorkspaceReadBridge(workspaceDir); - - expect(bridge.resolvePath({ filePath: "..note.txt" })).toMatchObject({ - relativePath: "..note.txt", - containerPath: `${workspaceDir}/..note.txt`, - }); - await expect(bridge.readFile({ filePath: "..note.txt" })).resolves.toEqual( - Buffer.from("hidden"), - ); - }); - }, - ); - - it.runIf(process.platform !== "win32")("rejects symlink escapes while reading", async () => { - // The remote helper uses no-follow file opens; symlinked final components - // must fail even when the local caller cannot inspect the remote inode. + it("rejects mount-root reads before invoking the mutation helper", async () => { await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { const workspaceDir = path.join(stateDir, "workspace"); - const outsideDir = path.join(stateDir, "outside"); await fs.mkdir(workspaceDir, { recursive: true }); - await fs.mkdir(outsideDir, { recursive: true }); - await fs.writeFile(path.join(outsideDir, "secret.txt"), "classified", "utf8"); - await fs.symlink(path.join(outsideDir, "secret.txt"), path.join(workspaceDir, "link.txt")); - const bridge = createWorkspaceReadBridge(workspaceDir); + const { calls, runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: workspaceDir, + remoteAgentWorkspaceDir: workspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ + workspaceDir, + agentWorkspaceDir: workspaceDir, + }), + runtime, + }); - await expect(bridge.readFile({ filePath: "link.txt" })).rejects.toThrow( - /symbolic links|too many levels|ELOOP/i, + await expect(bridge.readFile({ filePath: "." })).rejects.toThrow( + /Invalid sandbox entry target/, ); + expect(calls).toHaveLength(0); }); }); - it.runIf(process.platform !== "win32")( - "rejects final-component symlinks even when they stay inside the workspace", - async () => { - await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - await fs.writeFile(path.join(workspaceDir, "note.txt"), "hello", "utf8"); - await fs.symlink("note.txt", path.join(workspaceDir, "link.txt")); - - const bridge = createWorkspaceReadBridge(workspaceDir); - - await expect(bridge.readFile({ filePath: "link.txt" })).rejects.toThrow( - /symbolic links|too many levels|ELOOP/i, - ); - }); - }, - ); - it("normalizes stat output locale and saturates unsafe sizes", async () => { // Remote stat output is untrusted shell text; unsafe numeric fields should // clamp to deterministic values instead of leaking NaN into callers. @@ -621,6 +260,339 @@ describe("remote sandbox fs bridge", () => { }); }); +// These fixtures execute remote GNU stat/readlink and the fd 3 Python launcher +// locally. Portable Python behavior stays in fs-bridge-mutation-helper.test.ts. +describe.runIf(process.platform === "linux")("remote sandbox fs bridge (GNU shell)", () => { + it("orders sandbox tools through one remote alias identity", async () => { + await withTempDir("openclaw-remote-fs-queue-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "host-workspace"); + const remoteWorkspaceDir = path.join(stateDir, "remote-workspace"); + await fs.mkdir(workspaceDir); + await fs.mkdir(remoteWorkspaceDir); + const sandbox = createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }); + const { runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir, + remoteAgentWorkspaceDir: remoteWorkspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ sandbox, runtime }); + const remotePath = path.join(remoteWorkspaceDir, "race-target.txt"); + const hostPath = path.join(workspaceDir, "race-target.txt"); + const aliasIdentity = await resolveSandboxFileMutationQueueKey({ + bridge, + root: workspaceDir, + filePath: remotePath, + cwd: workspaceDir, + }); + await expect( + resolveSandboxFileMutationQueueKey({ + bridge, + root: workspaceDir, + filePath: hostPath, + cwd: workspaceDir, + }), + ).resolves.toBe(aliasIdentity); + + const writeIdentityStarted = createDeferred(); + const releaseWriteIdentity = createDeferred(); + const readIdentityResolved = createDeferred(); + const runRemoteShellScript = runtime.runRemoteShellScript.bind(runtime); + let identityCallCount = 0; + runtime.runRemoteShellScript = async (command) => { + const isTargetIdentity = + command.script.includes('target="$1"') && command.args?.[0] === remotePath; + if (!isTargetIdentity) { + return await runRemoteShellScript(command); + } + const identityCall = ++identityCallCount; + if (identityCall === 1) { + writeIdentityStarted.resolve(); + await releaseWriteIdentity.promise; + } + const result = await runRemoteShellScript(command); + if (identityCall === 2) { + readIdentityResolved.resolve(); + } + return result; + }; + const statSpy = vi.spyOn(bridge, "stat"); + const writeTool = createSandboxedWriteTool({ root: workspaceDir, bridge }); + const readTool = createSandboxedReadTool({ root: workspaceDir, bridge }); + const writeResult = writeTool.execute("write", { + path: remotePath, + content: "remote snapshot", + }); + await writeIdentityStarted.promise; + const readResult = readTool.execute("read", { path: hostPath }); + void readResult.catch(() => {}); + await readIdentityResolved.promise; + await new Promise((resolve) => { + setImmediate(resolve); + }); + expect(statSpy).not.toHaveBeenCalled(); + + releaseWriteIdentity.resolve(); + const [, result] = await Promise.all([writeResult, readResult]); + expect(statSpy).toHaveBeenCalled(); + expect(result.content).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "text", text: "remote snapshot" }), + ]), + ); + }); + }); + + it("creates files exclusively and preserves existing entries", async () => { + await withTempDir("openclaw-remote-fs-create-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + await fs.mkdir(workspaceDir, { recursive: true }); + const { runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: workspaceDir, + remoteAgentWorkspaceDir: workspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), + runtime, + }); + const createFileExclusive = bridge.createFileExclusive?.bind(bridge); + expect(createFileExclusive).toBeTypeOf("function"); + + await expect( + createFileExclusive!({ filePath: "nested/note.txt", data: "first" }), + ).resolves.toBe("created"); + await expect( + createFileExclusive!({ filePath: "nested/note.txt", data: "replacement" }), + ).resolves.toBe("exists"); + await expect( + fs.readFile(path.join(workspaceDir, "nested", "note.txt"), "utf8"), + ).resolves.toBe("first"); + + const outcomes = await Promise.all([ + createFileExclusive!({ filePath: "race.txt", data: "one" }), + createFileExclusive!({ filePath: "race.txt", data: "two" }), + ]); + expect(outcomes.toSorted()).toEqual(["created", "exists"]); + await expect(fs.readFile(path.join(workspaceDir, "race.txt"), "utf8")).resolves.toMatch( + /^(one|two)$/u, + ); + }); + }); + + it("treats a symlink destination as existing without changing its target", async () => { + await withTempDir("openclaw-remote-fs-create-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + await fs.mkdir(workspaceDir, { recursive: true }); + await fs.writeFile(path.join(workspaceDir, "target.txt"), "keep", "utf8"); + await fs.symlink("target.txt", path.join(workspaceDir, "link.txt")); + const { runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: workspaceDir, + remoteAgentWorkspaceDir: workspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), + runtime, + }); + const createFileExclusive = bridge.createFileExclusive?.bind(bridge); + expect(createFileExclusive).toBeTypeOf("function"); + + await expect( + createFileExclusive!({ filePath: "link.txt", data: Buffer.alloc(1_048_576) }), + ).resolves.toBe("exists"); + await expect(fs.readFile(path.join(workspaceDir, "target.txt"), "utf8")).resolves.toBe( + "keep", + ); + }); + }); + + it("accepts a symlinked mount root while rejecting escapes through it", async () => { + await withTempDir("openclaw-remote-fs-linked-root-", async (stateDir) => { + const realWorkspaceDir = path.join(stateDir, "real-workspace"); + const linkedWorkspaceDir = path.join(stateDir, "linked-workspace"); + const outsideDir = path.join(stateDir, "outside"); + await fs.mkdir(realWorkspaceDir); + await fs.mkdir(outsideDir); + await fs.symlink(realWorkspaceDir, linkedWorkspaceDir, "dir"); + await fs.symlink(outsideDir, path.join(realWorkspaceDir, "escape"), "dir"); + const { runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: linkedWorkspaceDir, + remoteAgentWorkspaceDir: linkedWorkspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ + workspaceDir: linkedWorkspaceDir, + agentWorkspaceDir: linkedWorkspaceDir, + }), + runtime, + }); + const createFileExclusive = bridge.createFileExclusive?.bind(bridge); + expect(createFileExclusive).toBeTypeOf("function"); + + await expect(createFileExclusive!({ filePath: "inside.txt", data: "inside" })).resolves.toBe( + "created", + ); + await expect(bridge.readFile({ filePath: "inside.txt" })).resolves.toEqual( + Buffer.from("inside"), + ); + await expect(bridge.mkdirp({ filePath: "nested/dir" })).resolves.toBeUndefined(); + await expect(fs.readFile(path.join(realWorkspaceDir, "inside.txt"), "utf8")).resolves.toBe( + "inside", + ); + await expect( + fs.stat(path.join(realWorkspaceDir, "nested", "dir")).then((entry) => entry.isDirectory()), + ).resolves.toBe(true); + await expect( + createFileExclusive!({ filePath: "escape/outside.txt", data: "blocked" }), + ).rejects.toThrow(/escapes allowed mounts/); + }); + }); + + it("reads files with the pinned mutation helper", async () => { + await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { + const workspacePath = path.join(stateDir, "workspace"); + await fs.mkdir(workspacePath, { recursive: true }); + const workspaceDir = await fs.realpath(workspacePath); + await fs.writeFile(path.join(workspaceDir, "note.txt"), "hello", "utf8"); + + const { calls, runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: workspaceDir, + remoteAgentWorkspaceDir: workspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ + workspaceDir, + agentWorkspaceDir: workspaceDir, + }), + runtime, + }); + + await expect(bridge.readFile({ filePath: "note.txt" })).resolves.toEqual( + Buffer.from("hello"), + ); + expect(calls).toHaveLength(2); + const readCall = calls.find((call) => call.args?.[0] === "read"); + expect(readCall?.script).toContain("python3 /dev/fd/3 \"$@\" 3<<'PY'"); + expect(readCall?.script).toContain("read_file(parent_fd, basename)"); + expect(readCall?.script).not.toContain('cat -- "$1"'); + }); + }); + + it("forwards and enforces bounded pinned file reads", async () => { + await withTempDir("openclaw-remote-fs-bounded-read-", async (stateDir) => { + const workspacePath = path.join(stateDir, "workspace"); + await fs.mkdir(workspacePath, { recursive: true }); + const workspaceDir = await fs.realpath(workspacePath); + await fs.writeFile(path.join(workspaceDir, "note.txt"), "hello", "utf8"); + + const { calls, runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: workspaceDir, + remoteAgentWorkspaceDir: workspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), + runtime, + }); + + await expect(bridge.readFile({ filePath: "note.txt", maxBytes: 5 })).resolves.toEqual( + Buffer.from("hello"), + ); + expect(calls.find((call) => call.args?.[0] === "read")?.args).toEqual([ + "read", + workspaceDir, + "", + "note.txt", + "5", + ]); + await expect(bridge.readFile({ filePath: "note.txt", maxBytes: 4 })).rejects.toThrow( + /bounded read limit/i, + ); + await expect(bridge.readFile({ filePath: "note.txt", maxBytes: -1 })).rejects.toThrow( + /non-negative safe integer/i, + ); + expect(calls).toHaveLength(4); + }); + }); + + it("streams file copies with the pinned mutation helper", async () => { + await withTempDir("openclaw-remote-fs-copy-", async (stateDir) => { + const workspacePath = path.join(stateDir, "workspace"); + await fs.mkdir(workspacePath, { recursive: true }); + const workspaceDir = await fs.realpath(workspacePath); + await fs.writeFile(path.join(workspaceDir, "source.txt"), "streamed", "utf8"); + const { calls, runtime } = createLocalRemoteRuntime({ + remoteWorkspaceDir: workspaceDir, + remoteAgentWorkspaceDir: workspaceDir, + }); + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ workspaceDir, agentWorkspaceDir: workspaceDir }), + runtime, + }); + + const copyFile = bridge.copyFile?.bind(bridge); + expect(copyFile).toBeTypeOf("function"); + await copyFile!({ + sourcePath: "source.txt", + destinationPath: "nested/copy.txt", + }); + + await expect( + fs.readFile(path.join(workspaceDir, "nested", "copy.txt"), "utf8"), + ).resolves.toBe("streamed"); + expect(calls.some((call) => call.args?.[0] === "copy")).toBe(true); + }); + }); + + it("reads dot-dot-prefixed filenames inside the workspace", async () => { + await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + await fs.mkdir(workspaceDir, { recursive: true }); + await fs.writeFile(path.join(workspaceDir, "..note.txt"), "hidden", "utf8"); + + const bridge = createWorkspaceReadBridge(workspaceDir); + + expect(bridge.resolvePath({ filePath: "..note.txt" })).toMatchObject({ + relativePath: "..note.txt", + containerPath: `${workspaceDir}/..note.txt`, + }); + await expect(bridge.readFile({ filePath: "..note.txt" })).resolves.toEqual( + Buffer.from("hidden"), + ); + }); + }); + + it("rejects symlink escapes while reading", async () => { + // The remote helper uses no-follow file opens; symlinked final components + // must fail even when the local caller cannot inspect the remote inode. + await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + const outsideDir = path.join(stateDir, "outside"); + await fs.mkdir(workspaceDir, { recursive: true }); + await fs.mkdir(outsideDir, { recursive: true }); + await fs.writeFile(path.join(outsideDir, "secret.txt"), "classified", "utf8"); + await fs.symlink(path.join(outsideDir, "secret.txt"), path.join(workspaceDir, "link.txt")); + + const bridge = createWorkspaceReadBridge(workspaceDir); + + await expect(bridge.readFile({ filePath: "link.txt" })).rejects.toThrow( + /symbolic links|too many levels|ELOOP/i, + ); + }); + }); + + it("rejects final-component symlinks even when they stay inside the workspace", async () => { + await withTempDir("openclaw-remote-fs-bridge-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + await fs.mkdir(workspaceDir, { recursive: true }); + await fs.writeFile(path.join(workspaceDir, "note.txt"), "hello", "utf8"); + await fs.symlink("note.txt", path.join(workspaceDir, "link.txt")); + + const bridge = createWorkspaceReadBridge(workspaceDir); + + await expect(bridge.readFile({ filePath: "link.txt" })).rejects.toThrow( + /symbolic links|too many levels|ELOOP/i, + ); + }); + }); +}); + async function withTempDir(prefix: string, run: (stateDir: string) => Promise): Promise { const stateDir = await fs.mkdtemp(path.join(process.env.TMPDIR ?? "/tmp", prefix)); try { diff --git a/src/agents/sandbox/workspace-skills-bridge-readonly.test.ts b/src/agents/sandbox/workspace-skills-bridge-readonly.test.ts index 997f08d902c..eff22050280 100644 --- a/src/agents/sandbox/workspace-skills-bridge-readonly.test.ts +++ b/src/agents/sandbox/workspace-skills-bridge-readonly.test.ts @@ -54,34 +54,6 @@ describe("workspace skills bridge mount policy", () => { }); }); - it.runIf(process.platform !== "win32")( - "allows remote bridge writes under absent skill roots", - async () => { - await withTempDir("openclaw-skills-remote-absent-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - const canonicalWorkspaceDir = await fs.realpath(workspaceDir); - - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ - workspaceDir: canonicalWorkspaceDir, - agentWorkspaceDir: canonicalWorkspaceDir, - }), - runtime: { - remoteWorkspaceDir: canonicalWorkspaceDir, - remoteAgentWorkspaceDir: canonicalWorkspaceDir, - runRemoteShellScript, - }, - }); - - await bridge.writeFile({ filePath: "skills/new.txt", data: "created" }); - await expect( - fs.readFile(path.join(canonicalWorkspaceDir, "skills", "new.txt"), "utf8"), - ).resolves.toBe("created"); - }); - }, - ); - it.runIf(process.platform !== "win32")( "rejects remote bridge writes under remote-only skill roots", async () => { @@ -143,46 +115,6 @@ describe("workspace skills bridge mount policy", () => { }, ); - it.runIf(process.platform !== "win32")( - "rejects remote bridge writes through symlinks into skill roots", - async () => { - // Symlink resolution must happen on the remote side too; otherwise writes - // can bypass read-only skill root detection. - await withTempDir("openclaw-skills-remote-link-", async (stateDir) => { - const workspaceDir = path.join(stateDir, "workspace"); - const remoteWorkspaceDir = path.join(stateDir, "remote-workspace"); - await fs.mkdir(workspaceDir, { recursive: true }); - await fs.mkdir(path.join(remoteWorkspaceDir, "skills", "demo"), { recursive: true }); - await fs.symlink("skills", path.join(remoteWorkspaceDir, "link"), "dir"); - const canonicalWorkspaceDir = await fs.realpath(workspaceDir); - const canonicalRemoteWorkspaceDir = await fs.realpath(remoteWorkspaceDir); - - const bridge = createRemoteShellSandboxFsBridge({ - sandbox: createSandbox({ - workspaceDir: canonicalWorkspaceDir, - agentWorkspaceDir: canonicalWorkspaceDir, - }), - runtime: { - remoteWorkspaceDir: canonicalRemoteWorkspaceDir, - remoteAgentWorkspaceDir: canonicalRemoteWorkspaceDir, - runRemoteShellScript, - }, - }); - - await expect( - bridge.writeFile({ - filePath: "link/demo/SKILL.md", - cwd: canonicalRemoteWorkspaceDir, - data: "# Demo\n", - }), - ).rejects.toThrow(/read-only/); - await expect( - fs.stat(path.join(canonicalRemoteWorkspaceDir, "skills", "demo", "SKILL.md")), - ).rejects.toMatchObject({ code: "ENOENT" }); - }); - }, - ); - it.runIf(process.platform !== "win32")( "rejects remote bridge mkdirp under skill roots from container cwd", async () => { @@ -216,3 +148,68 @@ describe("workspace skills bridge mount policy", () => { }, ); }); + +// Canonical path checks invoke GNU readlink/stat on the local fixture host. +describe.runIf(process.platform === "linux")("workspace skills bridge (GNU shell)", () => { + it("allows remote bridge writes under absent skill roots", async () => { + await withTempDir("openclaw-skills-remote-absent-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + await fs.mkdir(workspaceDir, { recursive: true }); + const canonicalWorkspaceDir = await fs.realpath(workspaceDir); + + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ + workspaceDir: canonicalWorkspaceDir, + agentWorkspaceDir: canonicalWorkspaceDir, + }), + runtime: { + remoteWorkspaceDir: canonicalWorkspaceDir, + remoteAgentWorkspaceDir: canonicalWorkspaceDir, + runRemoteShellScript, + }, + }); + + await bridge.writeFile({ filePath: "skills/new.txt", data: "created" }); + await expect( + fs.readFile(path.join(canonicalWorkspaceDir, "skills", "new.txt"), "utf8"), + ).resolves.toBe("created"); + }); + }); + + it("rejects remote bridge writes through symlinks into skill roots", async () => { + // Symlink resolution must happen on the remote side too; otherwise writes + // can bypass read-only skill root detection. + await withTempDir("openclaw-skills-remote-link-", async (stateDir) => { + const workspaceDir = path.join(stateDir, "workspace"); + const remoteWorkspaceDir = path.join(stateDir, "remote-workspace"); + await fs.mkdir(workspaceDir, { recursive: true }); + await fs.mkdir(path.join(remoteWorkspaceDir, "skills", "demo"), { recursive: true }); + await fs.symlink("skills", path.join(remoteWorkspaceDir, "link"), "dir"); + const canonicalWorkspaceDir = await fs.realpath(workspaceDir); + const canonicalRemoteWorkspaceDir = await fs.realpath(remoteWorkspaceDir); + + const bridge = createRemoteShellSandboxFsBridge({ + sandbox: createSandbox({ + workspaceDir: canonicalWorkspaceDir, + agentWorkspaceDir: canonicalWorkspaceDir, + }), + runtime: { + remoteWorkspaceDir: canonicalRemoteWorkspaceDir, + remoteAgentWorkspaceDir: canonicalRemoteWorkspaceDir, + runRemoteShellScript, + }, + }); + + await expect( + bridge.writeFile({ + filePath: "link/demo/SKILL.md", + cwd: canonicalRemoteWorkspaceDir, + data: "# Demo\n", + }), + ).rejects.toThrow(/read-only/); + await expect( + fs.stat(path.join(canonicalRemoteWorkspaceDir, "skills", "demo", "SKILL.md")), + ).rejects.toMatchObject({ code: "ENOENT" }); + }); + }); +}); diff --git a/test/scripts/run-with-lease-fence.test.ts b/test/scripts/run-with-lease-fence.test.ts index c429f92d0ba..2025d8eaddd 100644 --- a/test/scripts/run-with-lease-fence.test.ts +++ b/test/scripts/run-with-lease-fence.test.ts @@ -1,70 +1,103 @@ import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { waitForChildClose, waitForFile, waitForPidFile } from "../helpers/process-wait.js"; import { useAutoCleanupTempDirTracker } from "../helpers/temp-dir.js"; const SCRIPT = "scripts/mantis/run-with-lease-fence.sh"; const tempDirs = useAutoCleanupTempDirTracker(afterEach); -// Mantis runs on Ubuntu and requires util-linux's setsid for process-group fencing. -const linuxIt = process.platform === "linux" ? it : it.skip; +// The Telegram Desktop workflow owns this Linux fence: util-linux setsid, +// Linux account setup, and /proc cleanup are not an arbitrary POSIX contract. +describe.runIf(process.platform === "linux")("run-with-lease-fence", () => { + beforeAll(() => { + const result = spawnSync("setsid", ["--version"], { encoding: "utf8" }); + expect( + result.status, + "Linux lease-fence tests require util-linux setsid on PATH; install bash, util-linux, and coreutils.", + ).toBe(0); + }); -describe("run-with-lease-fence", () => { - linuxIt( - "stops the active process group after terminal lease loss", - async () => { - const root = tempDirs.make("openclaw-lease-fence-"); - const lostMarker = path.join(root, "lease.lost"); - const commandPidFile = path.join(root, "command.pid"); - const ticksFile = path.join(root, "ticks.log"); - let stderr = ""; - const child = spawn( - SCRIPT, - [ - lostMarker, - "--", - "/bin/bash", - "-c", - 'trap "exit 0" TERM; printf "%s\\n" "$$" >"$1"; while :; do printf "tick\\n" >>"$2"; sleep 1; done', - "lease-fence-command", - commandPidFile, - ticksFile, - ], - { stdio: ["ignore", "ignore", "pipe"] }, - ); - child.stderr.setEncoding("utf8"); - child.stderr.on("data", (chunk: string) => { - stderr += chunk; - }); + it("stops the active process group after terminal lease loss", async () => { + const root = tempDirs.make("openclaw-lease-fence-"); + const lostMarker = path.join(root, "lease.lost"); + const commandPidFile = path.join(root, "command.pid"); + const ticksFile = path.join(root, "ticks.log"); + let stderr = ""; + const child = spawn( + SCRIPT, + [ + lostMarker, + "--", + "/bin/bash", + "-c", + 'trap "exit 0" TERM; printf "%s\\n" "$$" >"$1"; while :; do printf "tick\\n" >>"$2"; sleep 1; done', + "lease-fence-command", + commandPidFile, + ticksFile, + ], + { stdio: ["ignore", "ignore", "pipe"] }, + ); + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderr += chunk; + }); + // Readiness can fail after the command starts. Keep it under cleanup, and + // handle a child that already exited before a close waiter is attached. + const waitForFenceClose = () => + child.exitCode !== null || child.signalCode !== null + ? Promise.resolve({ code: child.exitCode, signal: child.signalCode }) + : waitForChildClose(child); + let cleanupPid: number | undefined; + try { const commandPid = await waitForPidFile(commandPidFile, 2_000); + cleanupPid = commandPid; await waitForFile(ticksFile, 2_000); + const closed = waitForFenceClose(); + fs.writeFileSync(lostMarker, "lost\n"); + await expect(closed).resolves.toEqual({ + code: 97, + signal: null, + }); + expect(() => process.kill(-commandPid, 0)).toThrow( + expect.objectContaining({ code: "ESRCH" }), + ); + expect(stderr).toContain("::error::Telegram QA lease lost mid-run; fencing proof"); + } finally { + // Let the fence reap its group even if readiness failed before we read + // the PID; recover a late PID for forced cleanup if fencing also fails. + const closed = waitForFenceClose(); fs.writeFileSync(lostMarker, "lost\n"); - try { - await expect(waitForChildClose(child)).resolves.toEqual({ - code: 97, - signal: null, - }); - expect(() => process.kill(-commandPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); - expect(stderr).toContain("::error::Telegram QA lease lost mid-run; fencing proof"); + await closed; } finally { - if (child.exitCode === null) { + const forcedClose = + child.exitCode === null && child.signalCode === null + ? waitForChildClose(child) + : undefined; + if (forcedClose) { child.kill("SIGKILL"); } - try { - process.kill(-commandPid, "SIGKILL"); - } catch {} + if (cleanupPid === undefined && fs.existsSync(commandPidFile)) { + cleanupPid = Number.parseInt(fs.readFileSync(commandPidFile, "utf8"), 10); + } + if (cleanupPid !== undefined && Number.isInteger(cleanupPid) && cleanupPid > 0) { + try { + process.kill(-cleanupPid, "SIGKILL"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") { + throw error; + } + } + } + await forcedClose; } - }, - 20_000, - ); + } + }, 20_000); - linuxIt("propagates a clean command exit", () => { + it("propagates a clean command exit", () => { const root = tempDirs.make("openclaw-lease-fence-clean-"); const result = spawnSync(SCRIPT, [path.join(root, "lease.lost"), "--", "/bin/true"], { encoding: "utf8", @@ -74,7 +107,7 @@ describe("run-with-lease-fence", () => { expect(result.stderr).toBe(""); }); - linuxIt("passes the caller's stdin through to the fenced command", () => { + it("passes the caller's stdin through to the fenced command", () => { // The workflow pipes the agent prompt into the fenced Codex process; a // backgrounded child otherwise defaults its stdin to /dev/null, which // made the agent fail with an empty prompt.