tests/workspace-safety.test.ts
// Regression tests for security review findings C5 (planted instruction/config files), C6 (workspace
// fallback) and C7 (Windows 8.3 short names). Temporary folders only; nothing else is written.
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { mkdtempSync, writeFileSync, mkdirSync, readdirSync, readFileSync, rmSync, existsSync } from "node:fs";
import { tmpdir, homedir } from "node:os";
import { join, dirname } from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import agentModule from "../src/index.js";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import { workspaceRoot, normalizeRel, checkWritableName, PROJECT_MARKERS } from "../src/fsguard.js";
const agent: any = agentModule;
const AGENT_DIR = fileURLToPath(new URL("..", import.meta.url));
const IS_WIN = process.platform === "win32";
const NOW = new Date("2026-11-26T15:00:00Z");
let ws = "";
beforeEach(() => {
ws = mkdtempSync(join(tmpdir(), "wfa-safety-"));
process.env.AGENTROVE_WORKFLOW_ROOT = ws;
});
afterEach(() => {
delete process.env.AGENTROVE_WORKFLOW_ROOT;
rmSync(ws, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
const plan = (recipe: any) => agent.call("plan_recipe", { recipe }, { now: () => NOW });
const run = (recipe: any) => agent.call("run_recipe", { recipe, confirm: true }, { now: () => NOW });
const codeOf = async (p: Promise<unknown>) => {
try {
await p;
return "ok";
} catch (e: any) {
return e.code;
}
};
describe("C5: recipes cannot plant instruction, configuration or tool files", () => {
it("write_file to a protected name is a conflict, so run_recipe writes nothing", async () => {
for (const path of ["CLAUDE.md", "docs/AGENTS.md", "package.json", "src/vite.config.ts", "notes/review.instructions.md", "node_modules/x/README.md", "{{vars.name}}"]) {
const recipe = { vars: { name: "Claude.md" }, steps: [{ id: "w", type: "write_file", content: "planted assistant instructions", path, escape: "none" }] };
const p = await plan(recipe);
expect(p.operations.find((o: any) => o.op === "write_file"), path).toMatchObject({ status: "conflict", reason: expect.stringMatching(/instructions, configuration or code|read as configuration/) });
expect(p.ready).toBe(false);
expect(await codeOf(run(recipe))).toBe("plan_has_conflicts");
}
expect(readdirSync(ws)).toEqual([]);
});
it("move_files and copy_files skip protected destination names and leave the file where it is", async () => {
mkdirSync(join(ws, "inbox"));
writeFileSync(join(ws, "inbox", "CLAUDE.md"), "downloaded instructions");
writeFileSync(join(ws, "inbox", "notes.md"), "ok");
const recipe = { steps: [{ id: "f", type: "list_files", folder: "inbox" }, { id: "m", type: "move_files", to: "project/{{name}}" }] };
const r = await run(recipe);
expect(r.operations.filter((o: any) => o.op === "move_file").map((o: any) => [o.from, o.status])).toEqual([["inbox/CLAUDE.md", "skip"], ["inbox/notes.md", "planned"]]);
expect(readFileSync(join(ws, "inbox", "CLAUDE.md"), "utf8")).toBe("downloaded instructions");
expect(existsSync(join(ws, "project", "CLAUDE.md"))).toBe(false);
expect(readFileSync(join(ws, "project", "notes.md"), "utf8")).toBe("ok");
const copy = await plan({ steps: [{ id: "l", type: "literal", value: [{ path: "project/notes.md" }] }, { id: "c", type: "copy_files", to: "pkg/package.json" }] });
expect(copy.operations[0]).toMatchObject({ op: "copy_file", status: "skip", reason: expect.stringMatching(/package\.json/) });
});
});
describe("C7: Windows 8.3 short names are refused", () => {
it("refuses segments such as ENV~1 or PROGRA~1", () => {
for (const p of ["ENV~1", "data/GITCON~1", "PROGRA~1/x.csv", "LONGFI~12.TXT"]) expect(() => normalizeRel(p, "p"), p).toThrow(/8\.3 short name/);
expect(normalizeRel("notes/v1~draft.md", "p")).toBe("notes/v1~draft.md");
});
});
describe("C6: workspace choice", () => {
it("refuses the home folder itself, the folder holding home folders, and system folders, even when set explicitly", () => {
expect(() => workspaceRoot(homedir())).toThrow(/your home folder itself/);
expect(() => workspaceRoot(dirname(homedir()))).toThrow(/holds the users' home folders|shared system location/);
const sys = IS_WIN ? process.env.SystemRoot || "C:\\Windows" : "/etc";
expect(() => workspaceRoot(sys)).toThrow(/system folder/);
const sub = IS_WIN ? join(process.env.SystemRoot || "C:\\Windows", "System32") : "/usr/bin";
if (existsSync(sub)) expect(() => workspaceRoot(sub)).toThrow(/system folder/);
expect(workspaceRoot(ws)).toBeTruthy();
});
it("uses the start folder only when it looks like a project", () => {
expect(() => workspaceRoot(ws, { explicit: false, envName: "AGENTROVE_WORKFLOW_ROOT" })).toThrow(/does not look like a project folder.*AGENTROVE_WORKFLOW_ROOT/);
for (const m of [".agentrove-workspace", "pyproject.toml", ".git"]) {
const d = mkdtempSync(join(ws, "p-"));
if (m === ".git") mkdirSync(join(d, m));
else writeFileSync(join(d, m), "");
expect(workspaceRoot(d, { explicit: false }), m).toBeTruthy();
}
expect(PROJECT_MARKERS).toContain(".agentrove-workspace");
});
it("the CLI refuses a start folder that is not a project, unless the variable names it", () => {
const env = { ...process.env };
delete env.AGENTROVE_WORKFLOW_ROOT;
const cli = join(AGENT_DIR, "bin", "cli.js");
const input = JSON.stringify({ recipe: { steps: [{ id: "a", type: "literal", value: 1 }] } });
let err = "";
try {
execFileSync(process.execPath, [cli, "plan_recipe", "--json", input], { cwd: ws, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
} catch (e: any) {
err = String(e.stderr);
}
expect(err).toMatch(/workspace_not_chosen/);
const out = execFileSync(process.execPath, [cli, "plan_recipe", "--json", input], { cwd: ws, env: { ...env, AGENTROVE_WORKFLOW_ROOT: ws }, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
expect(JSON.parse(out).ready).toBe(true);
});
});
describe("protected-name list", () => {
it("covers instruction, MCP and tool configuration names and leaves ordinary names alone", () => {
for (const p of ["CLAUDE.md", "x/AGENTS.md", "package-lock.json", "a/.vscode/tasks.json", "pyproject.toml", "conftest.py", "Dockerfile", "jest.config.js", "eslint.config.mjs", "app.code-workspace"]) expect(() => checkWritableName(p, "p"), p).toThrow();
for (const p of ["reports/summary.md", "config.json", "notes/agents-overview.md", "claude-notes.md", "readme.md"]) expect(() => checkWritableName(p, "p"), p).not.toThrow();
});
});