Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(bot-box): release resources when read-only grants are refused

Sebastian B8d662cb51196
diff --git a/server/bot-box/box-cleanup.linux.test.ts b/server/bot-box/box-cleanup.linux.test.ts
new file mode 100644
index 0000000000..7b47963854
--- /dev/null
+++ b/server/bot-box/box-cleanup.linux.test.ts
@@ -0,0 +1,57 @@
+import { closeSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { BoxRunner } from "./box.ts";
+import { openCredentialBroker, type CredentialBroker } from "./broker.ts";
+
+function descriptorsFor(file: string): number[] {
+ return readdirSync("/proc/self/fd").flatMap((fd) => {
+ try { return readlinkSync(`/proc/self/fd/${fd}`) === file ? [Number(fd)] : []; } catch { return []; }
+ });
+}
+
+describe.skipIf(process.platform !== "linux")("BoxRunner refusal cleanup", () => {
+ it.each(["explicit", "argv"] as const)("releases seccomp descriptors and broker grants on %s read-only refusal", async (source) => {
+ const root = mkdtempSync(join(tmpdir(), "omb-wrap-cleanup-"));
+ const home = join(root, "home"), dataDir = join(root, "data");
+ const file = join(dataDir, "mcp.json"), filter = join(root, "seccomp.bpf");
+ let broker: CredentialBroker | undefined;
+ try {
+ mkdirSync(home);
+ mkdirSync(dataDir);
+ writeFileSync(file, "fixture");
+ writeFileSync(filter, "filter");
+ broker = await openCredentialBroker({ socketPath: join(root, "b.sock") });
+ const runner = new BoxRunner({
+ bwrap: "/usr/bin/bwrap",
+ bridge: { socat: "/usr/bin/socat", bridgeScript: "/fixture/bridge", node: process.execPath },
+ setup: { home, dataDir, codeRoots: [], engineRoots: [], bridges: [] },
+ denyEnv: new Set(), seccompFile: filter,
+ broker: { port: 18080, mintForProcess: broker.mintForProcess, revoke: broker.revoke },
+ });
+ const request = {
+ command: "/bin/sh", args: source === "argv" ? ["--mcp-config", file] : [],
+ env: { ANTHROPIC_API_KEY: "synthetic" }, ...(source === "explicit" ? { ro: [file] } : {}),
+ };
+ const wrapped = runner.wrap(request);
+ try {
+ expect(descriptorsFor(filter)).toHaveLength(1);
+ expect(broker.stats().tokens).toBe(1);
+ } finally {
+ for (const fd of wrapped.extraFds) closeSync(fd);
+ wrapped.release();
+ }
+ linkSync(file, join(home, "alias"));
+ for (let attempt = 0; attempt < 3; attempt++) {
+ expect(() => runner.wrap(request)).toThrow(/multiply-linked read-only file/);
+ }
+ expect({ seccompFds: descriptorsFor(filter).length, grants: broker.stats().tokens }).toEqual({ seccompFds: 0, grants: 0 });
+ } finally {
+ for (const fd of descriptorsFor(filter)) closeSync(fd);
+ await broker?.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/server/bot-box/box.ts b/server/bot-box/box.ts
index 782817df24..16bf5600b8 100644
--- a/server/bot-box/box.ts
+++ b/server/bot-box/box.ts
@@ -2,7 +2,7 @@
// boxes reach through unix sockets (egress-gate.ts, harness-gate.ts), and wraps each bot spawn (server/procs.ts spawnCli
// with owner "bot") in bubblewrap by the plan (plan.ts). Nothing here changes a spawn when the box is off: the command,
// its arguments and its environment go through untouched, so every host that is not a Cloud home behaves as before.
-import { existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { engineInstallRoots } from "../engine-roots.ts";
@@ -87,7 +87,6 @@ export class BoxRunner {
const request: BoxRequest = lent.length ? { ...given, rw: [...(given.rw ?? []), ...lent] } : given;
const extraFds: number[] = [];
const seccomp = this.options.seccompFile && !this.options.setup.mutate?.has("no-seccomp") ? this.options.seccompFile : null;
- if (seccomp) extraFds.push(openSync(seccomp, "r"));
const plan = planBox({ ...this.options.setup, seccompFd: seccomp ? BOX_SECCOMP_FD : undefined }, request);
const mutate = this.options.setup.mutate;
const env = mutate?.has("env-all")
@@ -102,9 +101,16 @@ export class BoxRunner {
const bridges = plan.net === "isolated" ? this.options.setup.bridges : [];
const inner = bridgedCommand(this.options.bridge, bridges, request.command, request.args);
const brokered = this.broker(env, plan, request);
- const vouched = (request.allowEnv ?? []).filter((name) => /(?:KEY|TOKEN|SECRET)$/.test(name) && brokered.env[name] !== undefined && brokered.env[name] === request.env[name]);
- const unbrokered = [...new Set([...brokered.unbrokered, ...vouched])];
- return { command: this.options.bwrap, args: [...bwrapArgs(plan), "--", inner.command, ...inner.args], env: brokered.env, plan, token: brokered.token, release: brokered.release, unbrokered, extraFds };
+ try {
+ const vouched = (request.allowEnv ?? []).filter((name) => /(?:KEY|TOKEN|SECRET)$/.test(name) && brokered.env[name] !== undefined && brokered.env[name] === request.env[name]);
+ const unbrokered = [...new Set([...brokered.unbrokered, ...vouched])];
+ if (seccomp) extraFds.push(openSync(seccomp, "r"));
+ return { command: this.options.bwrap, args: [...bwrapArgs(plan), "--", inner.command, ...inner.args], env: brokered.env, plan, token: brokered.token, release: brokered.release, unbrokered, extraFds };
+ } catch (error) {
+ for (const fd of extraFds) { try { closeSync(fd); } catch {} }
+ brokered.release();
+ throw error;
+ }
}
/** Keys become a per-process token when the broker is on and the box has its own network (the bridge to the broker). */
diff --git a/server/bot-box/hardlink.linux.test.ts b/server/bot-box/hardlink.linux.test.ts
index e08b5c6183..36662ce850 100644
--- a/server/bot-box/hardlink.linux.test.ts
+++ b/server/bot-box/hardlink.linux.test.ts
@@ -28,7 +28,7 @@ describe.skipIf(detection.box !== "bwrap")("read-only file hardlinks in real bub
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((error as Error).message).toMatch(/multiply-linked read-only file: .*; grant a separate single-link copy instead\./);
expect(readFileSync(file, "utf8")).toBe("original");
return;
}
diff --git a/server/bot-box/hardlink.test.ts b/server/bot-box/hardlink.test.ts
index 1d60569fab..8a3534e3fe 100644
--- a/server/bot-box/hardlink.test.ts
+++ b/server/bot-box/hardlink.test.ts
@@ -23,20 +23,20 @@ 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/);
+ expect(() => bwrapArgs(plan([{ kind: "ro", source: f.file, target: f.file, optional }]))).toThrow(/multiply-linked read-only file: .*; grant a separate single-link copy instead\./);
});
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/);
+ expect(() => planBox(f, { command: "/bin/sh", args: [], env: {}, ro: [f[source]] })).toThrow(/multiply-linked read-only file: .*; grant a separate single-link copy instead\./);
});
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/);
+ expect(() => bwrapArgs(given)).toThrow(/multiply-linked read-only file: .*; grant a separate single-link copy instead\./);
});
it("preserves writable file grants", () => {
diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.ts
index 24472e649c..d073ba8e11 100644
--- a/server/bot-box/plan.ts
+++ b/server/bot-box/plan.ts
@@ -119,7 +119,7 @@ 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}`);
+ throw new Error(`The bot box refuses a multiply-linked read-only file: ${source}; grant a separate single-link copy instead.`);
}
} catch (error) {
if (!["ENOENT", "EACCES", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;