bash-cmd-readonly-policy.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. CoreErrorType,
  7. SessionEventType,
  8. createSessionId,
  9. createToolCallId,
  10. type ExecutionShellSelection,
  11. type SessionEvent,
  12. type ToolCallStartedPayload,
  13. } from "@zcode/contracts";
  14. import { PermissionService } from "../src/permission/service.js";
  15. import { createToolExecutor } from "../src/tool/executor.js";
  16. import { resolveRuntimePermissionCapability } from "../src/tool/executor/permission-capability.js";
  17. import { createToolRegistry } from "../src/tool/registry.js";
  18. import {
  19. isCmdExecutedShellSelection,
  20. isDriveQualifiedWindowsPathEntry,
  21. setCmdReadonlyHostForTest,
  22. } from "../src/tool/handlers/bash-cmd-readonly-policy.js";
  23. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  24. const CMD_PATH = String.raw`C:\Windows\System32\cmd.exe`;
  25. const SYSTEM_ROOT = String.raw`C:\Windows`;
  26. const WINDOWS_ENV = {
  27. ComSpec: CMD_PATH,
  28. SystemRoot: SYSTEM_ROOT,
  29. PATH: String.raw`C:\Windows\System32;C:\Program Files\Git\cmd`,
  30. PATHEXT: ".COM;.EXE;.BAT;.CMD;.PY",
  31. };
  32. // 模拟 Windows 文件系统里 shell 相关的 realpath:键按不区分大小写匹配,值是解析后的真实路径。
  33. const FAKE_REALPATHS = new Map(
  34. [
  35. [SYSTEM_ROOT, SYSTEM_ROOT],
  36. [CMD_PATH, CMD_PATH],
  37. [String.raw`C:\Windows\SysWOW64\cmd.exe`, String.raw`C:\Windows\SysWOW64\cmd.exe`],
  38. [String.raw`C:\Links\system-cmd\cmd.exe`, CMD_PATH],
  39. [String.raw`C:\ws\cmd.exe`, String.raw`C:\ws\cmd.exe`],
  40. [String.raw`C:\Links\ws-cmd\cmd.exe`, String.raw`C:\ws\cmd.exe`],
  41. [String.raw`C:\x\pwsh.exe`, String.raw`C:\x\pwsh.exe`],
  42. ].map(([path, real]) => [path!.toLowerCase(), real!]),
  43. );
  44. function fakeRealpath(path: string): string | undefined {
  45. return FAKE_REALPATHS.get(path.toLowerCase());
  46. }
  47. function windowsHost(env: NodeJS.ProcessEnv = {}) {
  48. return { platform: "win32", env: { ...WINDOWS_ENV, ...env }, realpath: fakeRealpath };
  49. }
  50. const CMD_SELECTION: ExecutionShellSelection = {
  51. dialect: "cmd",
  52. display: { name: "CMD" },
  53. id: "cmd",
  54. path: CMD_PATH,
  55. source: "user-config",
  56. };
  57. const LEGACY_SELECTION: ExecutionShellSelection = {
  58. dialect: "legacy-shell",
  59. display: { name: "system shell" },
  60. source: "legacy-fallback",
  61. };
  62. const READ_ONLY_COMMANDS = [
  63. "dir",
  64. "dir /b /s src",
  65. "DIR",
  66. "type README.md",
  67. String.raw`findstr /n /i foo src\a.ts`,
  68. "where node",
  69. "where.exe git",
  70. "git status",
  71. "git log --oneline -10",
  72. "git diff",
  73. ];
  74. const NOT_READ_ONLY_COMMANDS = [
  75. String.raw`type # & python x.py`,
  76. "dir & del x",
  77. "dir && del x",
  78. "dir | findstr a",
  79. "findstr a b > out.txt",
  80. String.raw`type %USERPROFILE%\x`,
  81. "dir ^& calc",
  82. 'type "a" & calc',
  83. String.raw`type \\server\share\x`,
  84. "type //server/share/x",
  85. String.raw`type \??\UNC\server\share\x`,
  86. String.raw`dir \\?\C:\x`,
  87. "type con",
  88. "TYPE Con.txt",
  89. String.raw`type src\nul.txt`,
  90. "findstr /g:con a",
  91. String.raw`git -C D:\x status`,
  92. "git --git-dir x status",
  93. "git -c core.pager=calc log",
  94. "git push",
  95. "git status *",
  96. String.raw`C:\tools\findstr.exe a b`,
  97. String.raw`.\findstr a b`,
  98. "dir\ndel x",
  99. "dir\r\ndel x",
  100. "dir\u000bx",
  101. "@dir",
  102. "dir/b",
  103. "dir;x",
  104. "dir,x",
  105. "dir x=y",
  106. "(dir)",
  107. "type !x!",
  108. "type a`b",
  109. "findstr "a" b",
  110. "where 中文",
  111. "del x",
  112. "echo hi",
  113. "cmd /c dir",
  114. "",
  115. ];
  116. let workingDirectory: string;
  117. beforeEach(() => {
  118. workingDirectory = mkdtempSync(join(tmpdir(), "zcode-cmd-readonly-"));
  119. setCmdReadonlyHostForTest(windowsHost());
  120. });
  121. afterEach(() => {
  122. setCmdReadonlyHostForTest(undefined);
  123. rmSync(workingDirectory, { force: true, recursive: true });
  124. });
  125. function capabilityFor(command: string, bashShellSelection: ExecutionShellSelection) {
  126. return resolveRuntimePermissionCapability(
  127. bashToolEntry,
  128. { command },
  129. { bashShellSelection, workingDirectory, workspaceRoot: workingDirectory },
  130. );
  131. }
  132. function decisionFor(
  133. command: string,
  134. bashShellSelection: ExecutionShellSelection,
  135. mode: "build" | "plan",
  136. ) {
  137. const capability = capabilityFor(command, bashShellSelection);
  138. return new PermissionService().checkPermission(
  139. { input: { command }, mode, riskLevel: capability.riskLevel, toolName: "Bash" },
  140. capability,
  141. ).decision;
  142. }
  143. describe("CMD read-only Bash policy", () => {
  144. describe.each([
  145. ["cmd", CMD_SELECTION],
  146. ["legacy-shell on Windows", LEGACY_SELECTION],
  147. ] as const)("%s", (_label, selection) => {
  148. it.each(READ_ONLY_COMMANDS)("treats %j as read-only", (command) => {
  149. expect(capabilityFor(command, selection)).toMatchObject({
  150. needsApproval: false,
  151. readOnly: true,
  152. sideEffectScope: "none",
  153. });
  154. expect(decisionFor(command, selection, "plan")).toBe("allow");
  155. expect(decisionFor(command, selection, "build")).toBe("allow");
  156. });
  157. it.each(NOT_READ_ONLY_COMMANDS)("keeps %j gated", (command) => {
  158. expect(capabilityFor(command, selection)).toMatchObject({
  159. needsApproval: true,
  160. readOnly: false,
  161. sideEffectScope: "system",
  162. });
  163. expect(decisionFor(command, selection, "plan")).toBe("deny");
  164. expect(decisionFor(command, selection, "build")).toBe("ask");
  165. });
  166. });
  167. it.each([
  168. ["where node", "where.bat"],
  169. ["where node", "where.com"],
  170. ["where.exe git", "where.exe.bat"],
  171. ["git status", "git.cmd"],
  172. ["git status", "git.py"],
  173. [String.raw`findstr /n foo src\a.ts`, "findstr.exe"],
  174. [String.raw`findstr /n foo src\a.ts`, "findstr"],
  175. ])("rejects %j when the working directory contains %s", (command, fileName) => {
  176. expect(capabilityFor(command, CMD_SELECTION)).toMatchObject({ readOnly: true });
  177. writeFileSync(join(workingDirectory, fileName), "@echo off\r\ncalc\r\n");
  178. expect(capabilityFor(command, CMD_SELECTION)).toMatchObject({ readOnly: false });
  179. expect(decisionFor(command, CMD_SELECTION, "plan")).toBe("deny");
  180. expect(decisionFor(command, CMD_SELECTION, "build")).toBe("ask");
  181. });
  182. it("does not let same-named programs affect the CMD built-ins", () => {
  183. writeFileSync(join(workingDirectory, "dir.bat"), "calc\r\n");
  184. writeFileSync(join(workingDirectory, "type.exe"), "");
  185. expect(capabilityFor("dir", CMD_SELECTION)).toMatchObject({ readOnly: true });
  186. expect(capabilityFor("type README.md", CMD_SELECTION)).toMatchObject({ readOnly: true });
  187. });
  188. it("only looks for the program name with PATHEXT extensions and ignores directories", () => {
  189. mkdirSync(join(workingDirectory, "git"));
  190. mkdirSync(join(workingDirectory, "git.exe"));
  191. writeFileSync(join(workingDirectory, "git.md"), "");
  192. expect(capabilityFor("git status", CMD_SELECTION)).toMatchObject({ readOnly: true });
  193. });
  194. describe("PATH directories the agent can write", () => {
  195. let outside: string;
  196. beforeEach(() => {
  197. outside = mkdtempSync(join(tmpdir(), "zcode-cmd-outside-"));
  198. });
  199. afterEach(() => {
  200. rmSync(outside, { force: true, recursive: true });
  201. });
  202. function usePath(...entries: string[]) {
  203. setCmdReadonlyHostForTest(windowsHost({ PATH: [...entries, WINDOWS_ENV.PATH].join(";") }));
  204. }
  205. it("rejects a same-named program in a workspace directory on PATH", () => {
  206. const bin = join(workingDirectory, "node_modules", ".bin");
  207. mkdirSync(bin, { recursive: true });
  208. usePath(bin);
  209. expect(capabilityFor("git status", CMD_SELECTION)).toMatchObject({ readOnly: true });
  210. writeFileSync(join(bin, "git.cmd"), "@echo off\r\ncalc\r\n");
  211. expect(capabilityFor("git status", CMD_SELECTION)).toMatchObject({ readOnly: false });
  212. expect(decisionFor("git status", CMD_SELECTION, "plan")).toBe("deny");
  213. expect(decisionFor("git status", CMD_SELECTION, "build")).toBe("ask");
  214. expect(capabilityFor("where node", CMD_SELECTION)).toMatchObject({ readOnly: true });
  215. });
  216. it("checks PATH directories under the workspace root, not only under the working directory", () => {
  217. const scripts = join(workingDirectory, ".venv", "Scripts");
  218. const subdirectory = join(workingDirectory, "packages", "app");
  219. mkdirSync(scripts, { recursive: true });
  220. mkdirSync(subdirectory, { recursive: true });
  221. writeFileSync(join(scripts, "where.exe"), "");
  222. usePath(scripts);
  223. const capability = resolveRuntimePermissionCapability(
  224. bashToolEntry,
  225. { command: "where node" },
  226. {
  227. bashShellSelection: CMD_SELECTION,
  228. workingDirectory: subdirectory,
  229. workspaceRoot: workingDirectory,
  230. },
  231. );
  232. expect(capability).toMatchObject({ readOnly: false });
  233. });
  234. it("resolves links that point into the workspace", () => {
  235. const bin = join(workingDirectory, "bin");
  236. mkdirSync(bin);
  237. writeFileSync(join(bin, "findstr.bat"), "calc\r\n");
  238. const link = join(outside, "linked-bin");
  239. symlinkSync(bin, link, "dir");
  240. usePath(link);
  241. expect(capabilityFor("findstr a b", CMD_SELECTION)).toMatchObject({ readOnly: false });
  242. });
  243. it("trusts absolute PATH directories outside the workspace", () => {
  244. writeFileSync(join(outside, "git.cmd"), "@echo off\r\n");
  245. usePath(outside);
  246. expect(capabilityFor("git status", CMD_SELECTION)).toMatchObject({ readOnly: true });
  247. });
  248. });
  249. it("rejects external programs when PATH has entries that depend on the working directory or drive", () => {
  250. for (const pathValue of [
  251. String.raw`.\bin;C:\Windows\System32`,
  252. "C:tools;C:\\Windows",
  253. // 根相对条目由 cmd.exe 按执行目录的盘符解析,可能与本进程的当前盘符不同。
  254. String.raw`\workspace\bin;C:\Windows\System32`,
  255. String.raw`%SystemRoot%\system32;C:\Windows`,
  256. // 双斜杠开头的条目(UNC、设备命名空间、localhost 别名)可能指回工作区,又不能为了证明不在而访问网络。
  257. String.raw`\\server\share\bin;C:\Windows`,
  258. String.raw`\\?\C:\ws\.venv\Scripts;C:\Windows`,
  259. String.raw`\\.\C:\ws\bin;C:\Windows`,
  260. String.raw`\\localhost\C$\ws\node_modules\.bin;C:\Windows`,
  261. ]) {
  262. setCmdReadonlyHostForTest({
  263. platform: "win32",
  264. env: { ComSpec: CMD_PATH, SystemRoot: SYSTEM_ROOT, Path: pathValue },
  265. realpath: fakeRealpath,
  266. });
  267. expect(capabilityFor("where node", CMD_SELECTION)).toMatchObject({ readOnly: false });
  268. expect(capabilityFor("dir", CMD_SELECTION)).toMatchObject({ readOnly: true });
  269. }
  270. });
  271. it("only accepts drive-qualified PATH entries", () => {
  272. for (const entry of [String.raw`C:\Windows`, "D:/tools"]) {
  273. expect(isDriveQualifiedWindowsPathEntry(entry)).toBe(true);
  274. }
  275. for (const entry of [
  276. String.raw`\workspace\bin`,
  277. "/workspace/bin",
  278. "C:tools",
  279. String.raw`.\bin`,
  280. "bin",
  281. String.raw`%SystemRoot%\system32`,
  282. String.raw`\\server\share\bin`,
  283. String.raw`\\?\C:\ws\bin`,
  284. String.raw`\\.\C:\ws\bin`,
  285. String.raw`\\localhost\C$\ws\bin`,
  286. "//server/share/bin",
  287. ]) {
  288. expect(isDriveQualifiedWindowsPathEntry(entry)).toBe(false);
  289. }
  290. });
  291. it("rejects external programs without a known working directory", () => {
  292. const capability = resolveRuntimePermissionCapability(
  293. bashToolEntry,
  294. { command: "where node" },
  295. { bashShellSelection: CMD_SELECTION },
  296. );
  297. expect(capability).toMatchObject({ readOnly: false });
  298. });
  299. it("applies the git runtime safety check", () => {
  300. writeFileSync(join(workingDirectory, "HEAD"), "ref: refs/heads/main\n");
  301. expect(capabilityFor("git status", CMD_SELECTION)).toMatchObject({ readOnly: false });
  302. expect(capabilityFor("dir", CMD_SELECTION)).toMatchObject({ readOnly: true });
  303. });
  304. it("only applies when the executor is the system cmd.exe", () => {
  305. for (const path of [
  306. CMD_PATH,
  307. String.raw`C:\WINDOWS\system32\cmd.exe`,
  308. String.raw`C:\Windows\SysWOW64\cmd.exe`,
  309. String.raw`C:\Links\system-cmd\cmd.exe`,
  310. ]) {
  311. expect(isCmdExecutedShellSelection({ ...CMD_SELECTION, path })).toBe(true);
  312. }
  313. for (const path of [
  314. undefined,
  315. // 裸名由 libuv 先在子进程 cwd(工作区)里查找。
  316. "cmd.exe",
  317. // Node 不会对正斜杠路径用 /d /s /c。
  318. "C:/Windows/System32/cmd.exe",
  319. String.raw`C:\x\pwsh.exe`,
  320. // 文件名是 cmd.exe,但不在系统目录,或经链接指向工作区。
  321. String.raw`C:\ws\cmd.exe`,
  322. String.raw`C:\Links\ws-cmd\cmd.exe`,
  323. String.raw`C:\Missing\cmd.exe`,
  324. ]) {
  325. const selection = { ...CMD_SELECTION, path };
  326. expect(isCmdExecutedShellSelection(selection)).toBe(false);
  327. expect(capabilityFor("dir", selection)).toMatchObject({ readOnly: false });
  328. expect(decisionFor("dir", selection, "plan")).toBe("deny");
  329. }
  330. for (const env of [
  331. { ComSpec: String.raw`C:\x\pwsh.exe` },
  332. { ComSpec: String.raw`C:\ws\cmd.exe` },
  333. { ComSpec: undefined },
  334. { SystemRoot: undefined },
  335. { SystemRoot: String.raw`C:\ws` },
  336. ]) {
  337. setCmdReadonlyHostForTest(windowsHost(env));
  338. expect(capabilityFor("dir", LEGACY_SELECTION)).toMatchObject({ readOnly: false });
  339. }
  340. setCmdReadonlyHostForTest(windowsHost({ SystemRoot: undefined, windir: SYSTEM_ROOT }));
  341. expect(capabilityFor("dir", LEGACY_SELECTION)).toMatchObject({ readOnly: true });
  342. });
  343. it("keeps POSIX legacy-shell (/bin/sh) without read-only grants", () => {
  344. setCmdReadonlyHostForTest({ platform: "linux", env: { PATH: "/usr/bin:/bin" } });
  345. for (const command of ["dir", "type README.md", "git status", "cat README.md", "ls"]) {
  346. expect(capabilityFor(command, LEGACY_SELECTION)).toMatchObject({ readOnly: false });
  347. expect(capabilityFor(command, CMD_SELECTION)).toMatchObject({ readOnly: false });
  348. expect(decisionFor(command, LEGACY_SELECTION, "plan")).toBe("deny");
  349. }
  350. });
  351. it.each(["posix", "git-bash"] as const)("leaves %s on the Bash AST rules", (dialect) => {
  352. const selection: ExecutionShellSelection = {
  353. dialect,
  354. display: { name: dialect },
  355. path: "/bin/bash",
  356. source: "auto-detected",
  357. };
  358. expect(capabilityFor("cat README.md", selection)).toMatchObject({ readOnly: true });
  359. expect(capabilityFor("ls -la", selection)).toMatchObject({ readOnly: true });
  360. expect(capabilityFor("rm -rf x", selection)).toMatchObject({ readOnly: false });
  361. });
  362. it("keeps project deny and ask rules ahead of the read-only grant", () => {
  363. const capability = capabilityFor("git status", CMD_SELECTION);
  364. for (const behavior of ["deny", "ask"] as const) {
  365. const decision = new PermissionService().checkPermission(
  366. {
  367. input: { command: "git status" },
  368. mode: "plan",
  369. riskLevel: capability.riskLevel,
  370. toolName: "Bash",
  371. },
  372. capability,
  373. { version: 1, [behavior]: [{ toolName: "Bash", ruleContent: "git status" }] },
  374. );
  375. expect(decision.decision).toBe(behavior);
  376. }
  377. });
  378. });
  379. describe("CMD read-only Bash policy through the tool executor", () => {
  380. async function execute(command: string, mode: "build" | "plan") {
  381. const registry = createToolRegistry();
  382. const handler = vi.fn(async () => ({}));
  383. registry.register({ ...bashToolEntry, handler });
  384. const requestPermission = vi.fn(async () => ({ decision: "deny" as const }));
  385. const events: SessionEvent[] = [];
  386. const executor = createToolExecutor({
  387. registry,
  388. permissionService: new PermissionService(),
  389. permissionBroker: { requestPermission },
  390. mode,
  391. emitEvent: async (event) => {
  392. events.push(event);
  393. },
  394. bashShellSelection: CMD_SELECTION,
  395. workingDirectory,
  396. sessionId: createSessionId(`cmd-readonly-${mode}`),
  397. });
  398. const result = await executor.execute({
  399. id: createToolCallId(`cmd-readonly-${mode}`),
  400. name: "Bash",
  401. input: { command },
  402. });
  403. const started = events.find((event) => event.type === SessionEventType.ToolCallStarted);
  404. return {
  405. handler,
  406. requestPermission,
  407. result,
  408. started: started?.payload as ToolCallStartedPayload | undefined,
  409. };
  410. }
  411. it.each(["build", "plan"] as const)(
  412. "runs read-only CMD commands without approval in %s and reports readOnly",
  413. async (mode) => {
  414. const { handler, requestPermission, started } = await execute("type README.md", mode);
  415. // handler 是桩,输出过不了 Bash 的输出 schema;这里只关心权限放行和能力事件。
  416. expect(requestPermission).not.toHaveBeenCalled();
  417. expect(handler).toHaveBeenCalledTimes(1);
  418. expect(started).toMatchObject({ readOnly: true, sideEffectScope: "none" });
  419. },
  420. );
  421. it.each(["build", "plan"] as const)("never runs the CMD comment mismatch in %s", async (mode) => {
  422. const { handler, requestPermission, result } = await execute(
  423. String.raw`type # & python x.py`,
  424. mode,
  425. );
  426. expect(result).toMatchObject({
  427. success: false,
  428. error: { type: CoreErrorType.PermissionDenied },
  429. });
  430. expect(requestPermission).toHaveBeenCalledTimes(mode === "plan" ? 0 : 1);
  431. expect(handler).not.toHaveBeenCalled();
  432. });
  433. });