Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(bot-box): refuse multiply-linked read-only files
Sebastian Ba9855bb06035
diff --git a/server/bot-box/hardlink.linux.test.ts b/server/bot-box/hardlink.linux.test.tsnew file mode 100644index 0000000000..e08b5c6183--- /dev/null+++ b/server/bot-box/hardlink.linux.test.ts@@ -0,0 +1,44 @@+import { spawnSync } from "node:child_process";+import { linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { detectBox } from "./detect.ts";+import { bwrapArgs, planBox } from "./plan.ts";++const detection = detectBox({ env: { ...process.env, OMB_BOT_BOX: "1" } });+const roots: string[] = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });++describe.skipIf(detection.box !== "bwrap")("read-only file hardlinks in real bubblewrap", () => {+ it.each([false, true])("protects an explicit read-only file from a writable HOME alias (hardlink: %s)", (hardlink) => {+ const root = mkdtempSync(join(tmpdir(), "omb-ro-hardlink-"));+ roots.push(root);+ const home = join(root, "home"), dataDir = join(root, "data");+ mkdirSync(home);+ mkdirSync(dataDir);+ const file = join(dataDir, "mcp.json"), alias = join(home, "mcp-alias.json");+ writeFileSync(file, "original");+ if (hardlink) linkSync(file, alias);+ else writeFileSync(alias, "separate file");+ const makePlan = () => planBox({ home, dataDir, codeRoots: [], engineRoots: [], bridges: [] }, {+ command: "/bin/sh", args: [], env: { HOME: home }, net: "shared", ro: [file],+ });+ let args: string[];+ try { args = bwrapArgs(makePlan()); } catch (error) {+ expect(hardlink).toBe(true);+ expect((error as Error).message).toMatch(/multiply-linked read-only file/);+ expect(readFileSync(file, "utf8")).toBe("original");+ return;+ }+ const probe = spawnSync(detection.tools!.bwrap, [...args, "--", "/bin/sh", "-c",+ 'if (echo direct > "$1") 2>/dev/null; then echo writable; else echo read-only; fi; echo changed > "$2"; cat "$1"',+ "probe", file, alias,+ ], { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8", timeout: 10_000 });+ expect(probe.status, probe.stderr).toBe(0);+ expect(probe.stdout).toBe("read-only\noriginal");+ expect(readFileSync(file, "utf8")).toBe("original");+ expect(readFileSync(alias, "utf8")).toBe("changed\n");+ });+});diff --git a/server/bot-box/hardlink.test.ts b/server/bot-box/hardlink.test.tsnew file mode 100644index 0000000000..1d60569fab--- /dev/null+++ b/server/bot-box/hardlink.test.ts@@ -0,0 +1,47 @@+import { linkSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { bwrapArgs, planBox, type BoxPlan, type Mount } from "./plan.ts";++const roots: string[] = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });+const plan = (mounts: Mount[]): BoxPlan => ({ mounts, options: [], net: "shared", writable: [], botId: null });++function fixture() {+ const root = mkdtempSync(join(tmpdir(), "omb-hardlink-"));+ roots.push(root);+ const home = join(root, "home"), dataDir = join(home, "data");+ mkdirSync(dataDir, { recursive: true });+ const file = join(dataDir, "mcp.json"), alias = join(home, "alias.json");+ writeFileSync(file, "original");+ return { home, dataDir, file, alias, codeRoots: [], engineRoots: [], bridges: [] };+}++describe.skipIf(process.platform === "win32")("read-only file hardlinks", () => {+ it.each([false, true])("refuses multiply-linked read-only files, including optional grants (%s)", (optional) => {+ const f = fixture();+ linkSync(f.file, f.alias);+ expect(() => bwrapArgs(plan([{ kind: "ro", source: f.file, target: f.file, optional }]))).toThrow(/multiply-linked read-only file/);+ });++ it.each(["file", "alias"] as const)("refuses an explicit read-only %s with a writable HOME alias", (source) => {+ const f = fixture();+ linkSync(f.file, f.alias);+ expect(() => planBox(f, { command: "/bin/sh", args: [], env: {}, ro: [f[source]] })).toThrow(/multiply-linked read-only file/);+ });++ it("refuses a read-only source hardlinked after planning", () => {+ const f = fixture();+ const given = planBox(f, { command: "/bin/sh", args: ["--mcp-config", f.file], env: {} });+ linkSync(f.file, f.alias);+ expect(() => bwrapArgs(given)).toThrow(/multiply-linked read-only file/);+ });++ it("preserves writable file grants", () => {+ const f = fixture();+ linkSync(f.file, f.alias);+ expect(bwrapArgs(plan([{ kind: "bind", source: f.file, target: f.file }]))).toEqual(["--bind", f.file, f.file]);+ });+});diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex 7cd260c4b0..24472e649c 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -1,5 +1,4 @@-// The bot box's plan: what one boxed process sees, as a list of mounts and the bubblewrap argv that makes it. Pure, so-// tests can check the list itself (and that removing a line opens exactly the hole it guards).+// The bot box's plan: what one boxed process sees, as a list of mounts and the bubblewrap argv that makes it.//// What the box sees:// - the image's code read-only: /usr (with /bin, /lib, /lib64 and /sbin as the links a merged-/usr Debian has), /etc,@@ -16,6 +15,7 @@// - a network namespace with loopback only. Two loopback ports inside are bridged to unix sockets bound in from outside:// the egress gate (every connection to the internet goes through it) and the harness gate (only /api/internal/// routes of this server). Nothing else on the server's loopback is reachable.+import { statSync } from "node:fs";import { isAbsolute, join, relative, resolve, sep } from "node:path";export type BoxNet = "isolated" | "shared";@@ -115,6 +115,17 @@ export const PATH_ENV_NAMES = ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "XDG_CONFIG_HO/** Folders the box always has its own copy of, so no setting may put the host's back. */const PRIVATE_INSIDE = ["/tmp", "/var/tmp", "/run", "/dev", "/proc"];+function assertReadOnlySource(source: string): void {+ try {+ const stat = statSync(source);+ if (stat.isFile() && stat.nlink > 1) {+ throw new Error(`The bot box refuses a multiply-linked read-only file: ${source}`);+ }+ } catch (error) {+ if (!["ENOENT", "EACCES", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;+ }+}+export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {const mutate = setup.mutate ?? new Set<BoxMutation>();const dataDir = resolve(setup.dataDir), home = resolve(setup.home);@@ -190,6 +201,7 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {const readOnly = new Set<string>();for (const path of [...(request.ro ?? []), ...argvPaths(request.args), ...(botId && ID.test(botId) ? [join(dataDir, "bots", botId, "SOUL.md")] : [])]) {const full = resolve(path);+ if (request.ro?.includes(path)) assertReadOnlySource(full);// Code and the system are already there; a file under HOME or /tmp the command line names is put back read-only.if (covered(full) || readOnly.has(full)) continue;if (["/usr", "/etc", "/opt", "/var/lib", ...setup.codeRoots, ...setup.engineRoots].some((base) => under(full, resolve(base)))) continue;@@ -214,7 +226,7 @@ export function bwrapArgs(plan: BoxPlan): string[] {const args: string[] = [];for (const mount of plan.mounts) {switch (mount.kind) {- case "ro": args.push(mount.optional ? "--ro-bind-try" : "--ro-bind", mount.source, mount.target); break;+ case "ro": assertReadOnlySource(mount.source); args.push(mount.optional ? "--ro-bind-try" : "--ro-bind", mount.source, mount.target); break;case "bind": args.push(mount.optional ? "--bind-try" : "--bind", mount.source, mount.target); break;case "tmpfs": args.push("--tmpfs", mount.target); break;case "proc": args.push("--proc", mount.target); break;