|
| 1 | +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +/** |
| 5 | + * Pre-backup audit (NC-2227-04) treatment of multiply-linked regular files. |
| 6 | + * |
| 7 | + * Package managers hard-link installed files out of their cache, so a Hermes |
| 8 | + * sandbox that lazily installed a dependency carries hundreds of them under |
| 9 | + * `lazy-packages`. Rejecting those aborted the whole pre-upgrade backup |
| 10 | + * (#9314). They are now recorded and archived; symlink and special-file |
| 11 | + * rejection is unchanged. |
| 12 | + */ |
| 13 | + |
| 14 | +import fs from "node:fs"; |
| 15 | +import { spawnSync } from "node:child_process"; |
| 16 | +import os from "node:os"; |
| 17 | +import path from "node:path"; |
| 18 | +import { pathToFileURL } from "node:url"; |
| 19 | +import { afterAll, describe, expect, it } from "vitest"; |
| 20 | + |
| 21 | +const ORIGINAL_HOME = process.env.HOME; |
| 22 | +const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-backup-audit-hardlinks-")); |
| 23 | +process.env.HOME = TMP_HOME; |
| 24 | +const tarHelp = spawnSync("tar", ["--help"], { encoding: "utf8" }); |
| 25 | +const supportsHardDereference = `${tarHelp.stdout}${tarHelp.stderr}`.includes("--hard-dereference"); |
| 26 | +// Production executes GNU tar inside the Linux sandbox. Skip only this |
| 27 | +// archive-behavior case on hosts such as macOS whose BSD tar lacks that flag. |
| 28 | +const hardDereferenceTest = supportsHardDereference ? it : it.skip; |
| 29 | + |
| 30 | +const REPO_ROOT = path.join(import.meta.dirname, ".."); |
| 31 | +type SandboxStateModule = typeof import("../src/lib/state/sandbox.js"); |
| 32 | +const sandboxState = (await import( |
| 33 | + pathToFileURL(path.join(REPO_ROOT, "src", "lib", "state", "sandbox.ts")).href |
| 34 | +)) as SandboxStateModule; |
| 35 | + |
| 36 | +function writeExecutable(filePath: string, source: string): void { |
| 37 | + fs.writeFileSync(filePath, source, { mode: 0o755 }); |
| 38 | +} |
| 39 | + |
| 40 | +/** Restore an env var without branching, mirroring the sibling snapshot tests. */ |
| 41 | +function restoreEnv(name: string, value: string | undefined): void { |
| 42 | + value === undefined |
| 43 | + ? Reflect.deleteProperty(process.env, name) |
| 44 | + : Reflect.set(process.env, name, value); |
| 45 | +} |
| 46 | + |
| 47 | +function writeRegistry(sandboxName: string): void { |
| 48 | + fs.mkdirSync(path.join(TMP_HOME, ".nemoclaw"), { recursive: true }); |
| 49 | + fs.writeFileSync( |
| 50 | + path.join(TMP_HOME, ".nemoclaw", "sandboxes.json"), |
| 51 | + JSON.stringify({ |
| 52 | + defaultSandbox: sandboxName, |
| 53 | + sandboxes: { |
| 54 | + [sandboxName]: { |
| 55 | + name: sandboxName, |
| 56 | + model: "m", |
| 57 | + provider: "p", |
| 58 | + gpuEnabled: false, |
| 59 | + policies: [], |
| 60 | + agent: null, |
| 61 | + }, |
| 62 | + }, |
| 63 | + }), |
| 64 | + ); |
| 65 | +} |
| 66 | + |
| 67 | +function writeFakeOpenshell(binDir: string): string { |
| 68 | + const openshell = path.join(binDir, "openshell"); |
| 69 | + writeExecutable( |
| 70 | + openshell, |
| 71 | + `#!/usr/bin/env node |
| 72 | +const args = process.argv.slice(2); |
| 73 | +if (args[0] === "sandbox" && args[1] === "ssh-config") { |
| 74 | + process.stdout.write("Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"); |
| 75 | + process.exit(0); |
| 76 | +} |
| 77 | +process.exit(0); |
| 78 | +`, |
| 79 | + ); |
| 80 | + return openshell; |
| 81 | +} |
| 82 | + |
| 83 | +/** |
| 84 | + * Run `backupSandboxState` against a fake sandbox whose pre-backup audit |
| 85 | + * reports `auditLines` (raw `find -printf "%y\t%p\t%l\n"` rows). |
| 86 | + */ |
| 87 | +function backupWithAuditOutput( |
| 88 | + auditLines: string, |
| 89 | +): ReturnType<SandboxStateModule["backupSandboxState"]> { |
| 90 | + const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-fixture-")); |
| 91 | + const oldPath = process.env.PATH; |
| 92 | + const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; |
| 93 | + try { |
| 94 | + const binDir = path.join(fixture, "bin"); |
| 95 | + const stateRoot = path.join(fixture, "sandbox-root", ".openclaw"); |
| 96 | + const existingDirs = ["workspace"]; |
| 97 | + fs.mkdirSync(binDir, { recursive: true }); |
| 98 | + for (const d of existingDirs) fs.mkdirSync(path.join(stateRoot, d), { recursive: true }); |
| 99 | + fs.writeFileSync(path.join(stateRoot, "workspace", "note.txt"), "content\n"); |
| 100 | + // A real multiply-linked pair inside the archived tree, the shape a package |
| 101 | + // manager leaves behind. `tar` would otherwise emit a hard-link record for |
| 102 | + // the second path and `safeTarExtract` would reject the archive. |
| 103 | + const linkedDir = path.join(stateRoot, "workspace", "lazy-packages"); |
| 104 | + fs.mkdirSync(linkedDir, { recursive: true }); |
| 105 | + fs.writeFileSync(path.join(linkedDir, "impl.py"), "package payload\n"); |
| 106 | + fs.linkSync(path.join(linkedDir, "impl.py"), path.join(linkedDir, "alias.py")); |
| 107 | + |
| 108 | + const openshell = writeFakeOpenshell(binDir); |
| 109 | + writeExecutable( |
| 110 | + path.join(binDir, "ssh"), |
| 111 | + `#!/usr/bin/env node |
| 112 | +const { spawnSync } = require("node:child_process"); |
| 113 | +const fs = require("node:fs"); |
| 114 | +const cmd = process.argv[process.argv.length - 1] || ""; |
| 115 | +const existingDirs = ${JSON.stringify(existingDirs)}; |
| 116 | +if (cmd.includes("[ -d ")) { |
| 117 | + process.stdout.write(existingDirs.join("\\n") + "\\n"); |
| 118 | + process.exit(0); |
| 119 | +} |
| 120 | +if (cmd.includes("find ")) { |
| 121 | + process.stdout.write(${JSON.stringify(auditLines)} + (${JSON.stringify(auditLines)} ? "\\n" : "")); |
| 122 | + process.exit(0); |
| 123 | +} |
| 124 | +if (cmd.includes("tar ") && cmd.includes("-cf -")) { |
| 125 | + // Run the archive command the product actually issued, with the sandbox |
| 126 | + // state path mapped onto the fixture, so tar flags are exercised for real. |
| 127 | + const real = cmd.split("/sandbox/.openclaw").join(${JSON.stringify(stateRoot)}); |
| 128 | + const r = spawnSync("sh", ["-c", real], { stdio: ["ignore", "pipe", "pipe"] }); |
| 129 | + if (r.stdout) fs.writeSync(1, r.stdout); |
| 130 | + process.exit(r.status || 0); |
| 131 | +} |
| 132 | +process.exit(0); |
| 133 | +`, |
| 134 | + ); |
| 135 | + |
| 136 | + writeRegistry("alpha"); |
| 137 | + process.env.NEMOCLAW_OPENSHELL_BIN = openshell; |
| 138 | + process.env.PATH = `${binDir}:${oldPath || ""}`; |
| 139 | + return sandboxState.backupSandboxState("alpha"); |
| 140 | + } finally { |
| 141 | + restoreEnv("NEMOCLAW_OPENSHELL_BIN", oldOpenshell); |
| 142 | + restoreEnv("PATH", oldPath); |
| 143 | + fs.rmSync(fixture, { recursive: true, force: true }); |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +afterAll(() => { |
| 148 | + restoreEnv("HOME", ORIGINAL_HOME); |
| 149 | + fs.rmSync(TMP_HOME, { recursive: true, force: true }); |
| 150 | +}); |
| 151 | + |
| 152 | +describe("pre-backup audit — multiply-linked regular files (#9314)", () => { |
| 153 | + hardDereferenceTest( |
| 154 | + "backs up a sandbox whose state dirs contain hard-linked package files", |
| 155 | + () => { |
| 156 | + // Shape emitted by `find -type f -a -links +1`: type `f`, empty link |
| 157 | + // target. A lazily installed dependency hard-links out of the package |
| 158 | + // manager cache, so every installed file looks like this. |
| 159 | + const auditLines = [ |
| 160 | + "f\t/sandbox/.openclaw/workspace/lazy-packages/aiohappyeyeballs/impl.py\t", |
| 161 | + "f\t/sandbox/.openclaw/workspace/lazy-packages/aiohappyeyeballs/utils.py\t", |
| 162 | + "f\t/sandbox/.openclaw/workspace/lazy-packages/edge_tts/__init__.py\t", |
| 163 | + ].join("\n"); |
| 164 | + |
| 165 | + const backup = backupWithAuditOutput(auditLines); |
| 166 | + |
| 167 | + expect(backup.success, backup.error).toBe(true); |
| 168 | + expect(backup.error).toBeUndefined(); |
| 169 | + expect(backup.backedUpDirs).toEqual(["workspace"]); |
| 170 | + |
| 171 | + // Both linked paths must survive as independent regular files: the archive |
| 172 | + // is unpacked through safeTarExtract, which rejects hard-link records. |
| 173 | + const linked = path.join(String(backup.manifest?.backupPath), "workspace", "lazy-packages"); |
| 174 | + expect(fs.readFileSync(path.join(linked, "impl.py"), "utf8")).toBe("package payload\n"); |
| 175 | + expect(fs.readFileSync(path.join(linked, "alias.py"), "utf8")).toBe("package payload\n"); |
| 176 | + expect(fs.lstatSync(path.join(linked, "alias.py")).nlink).toBe(1); |
| 177 | + }, |
| 178 | + ); |
| 179 | + |
| 180 | + it("still rejects an unsafe symlink alongside hard-linked files", () => { |
| 181 | + // Regression lock: accepting hard links must not weaken symlink rejection. |
| 182 | + const auditLines = [ |
| 183 | + "f\t/sandbox/.openclaw/workspace/lazy-packages/edge_tts/__init__.py\t", |
| 184 | + "l\t/sandbox/.openclaw/workspace/escape\t../openclaw.json", |
| 185 | + ].join("\n"); |
| 186 | + |
| 187 | + const backup = backupWithAuditOutput(auditLines); |
| 188 | + |
| 189 | + expect(backup.success).toBe(false); |
| 190 | + expect(backup.error).toMatch(/Pre-backup audit rejected/); |
| 191 | + expect(backup.error).toContain("workspace/escape"); |
| 192 | + }); |
| 193 | + |
| 194 | + it("still rejects special files", () => { |
| 195 | + // Regression lock: sockets/fifos/devices remain violations. |
| 196 | + const backup = backupWithAuditOutput("s\t/sandbox/.openclaw/workspace/agent.sock\t"); |
| 197 | + |
| 198 | + expect(backup.success).toBe(false); |
| 199 | + expect(backup.error).toMatch(/Pre-backup audit rejected/); |
| 200 | + expect(backup.error).toContain("agent.sock"); |
| 201 | + }); |
| 202 | +}); |
0 commit comments