bash-permission.test.ts 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import {
  6. CoreErrorType,
  7. SessionEventType,
  8. createSessionId,
  9. createToolCallId,
  10. type ExecutionPort,
  11. type ExecutionShellSelection,
  12. type SessionEvent,
  13. } from "@zcode/contracts";
  14. import {
  15. defaultPermissionConfig,
  16. PermissionService,
  17. type PermissionToolCapability,
  18. } from "../src/permission/service.js";
  19. import { createToolExecutor } from "../src/tool/executor.js";
  20. import { createToolRegistry } from "../src/tool/registry.js";
  21. import { resolveRuntimePermissionCapability } from "../src/tool/executor/permission-capability.js";
  22. import {
  23. bashToolEntry,
  24. isBashInputConcurrencySafe,
  25. isBashInputReadOnly,
  26. prepareBashPermissionMatcher,
  27. } from "../src/tool/handlers/bash.js";
  28. describe("bash runtime permission capability", () => {
  29. it.each(["cmd", "legacy-shell"] as const)(
  30. "does not grant Bash read-only capability to %s commands",
  31. (dialect) => {
  32. const bashShellSelection: ExecutionShellSelection = {
  33. dialect,
  34. source: "legacy-fallback",
  35. display: { name: dialect },
  36. };
  37. for (const command of [String.raw`type # & python G:\temp\hello.py`, "type README.md"]) {
  38. const input = { command };
  39. const capability = resolveRuntimePermissionCapability(bashToolEntry, input, {
  40. bashShellSelection,
  41. });
  42. expect(capability).toMatchObject({ readOnly: false, needsApproval: true });
  43. for (const mode of ["build", "edit", "plan"] as const) {
  44. const decision = new PermissionService().checkPermission(
  45. { input, mode, riskLevel: capability.riskLevel, toolName: "Bash" },
  46. capability,
  47. );
  48. expect(decision.decision).toBe(mode === "plan" ? "deny" : "ask");
  49. }
  50. expect(
  51. new PermissionService().checkPermission(
  52. {
  53. input,
  54. mode: "build",
  55. planEnabled: true,
  56. riskLevel: capability.riskLevel,
  57. toolName: "Bash",
  58. },
  59. capability,
  60. { version: 1, allow: [{ toolName: "Bash", ruleContent: command }] },
  61. ).decision,
  62. ).toBe("deny");
  63. }
  64. },
  65. );
  66. it.each(["posix", "git-bash"] as const)("preserves read-only capability for %s", (dialect) => {
  67. expect(
  68. resolveRuntimePermissionCapability(
  69. bashToolEntry,
  70. { command: "cat README.md" },
  71. {
  72. bashShellSelection: { dialect, source: "legacy-fallback", display: { name: dialect } },
  73. },
  74. ),
  75. ).toMatchObject({ readOnly: true, needsApproval: false });
  76. });
  77. it.each(["build", "edit", "plan"] as const)(
  78. "never executes the CMD comment mismatch when denied in %s",
  79. async (mode) => {
  80. const registry = createToolRegistry();
  81. registry.register(bashToolEntry);
  82. const run = vi.fn<ExecutionPort["run"]>(async () => {
  83. throw new Error("Denied commands must not reach execution");
  84. });
  85. const requestPermission = vi.fn(async () => ({ decision: "deny" as const }));
  86. const executor = createToolExecutor({
  87. registry,
  88. permissionService: new PermissionService(),
  89. permissionBroker: { requestPermission },
  90. executionPort: { run },
  91. mode,
  92. emitEvent: async () => {},
  93. bashShellSelection: { dialect: "cmd", source: "user-config", display: { name: "CMD" } },
  94. workingDirectory: process.cwd(),
  95. sessionId: createSessionId(`cmd-${mode}`),
  96. });
  97. const result = await executor.execute({
  98. id: createToolCallId(`cmd-${mode}`),
  99. name: "Bash",
  100. input: { command: String.raw`type # & python G:\temp\hello.py` },
  101. });
  102. expect(result).toMatchObject({
  103. success: false,
  104. error: { type: CoreErrorType.PermissionDenied },
  105. });
  106. expect(requestPermission).toHaveBeenCalledTimes(mode === "plan" ? 0 : 1);
  107. expect(run).not.toHaveBeenCalled();
  108. },
  109. );
  110. it("keeps display classification separate from read-only and concurrency helpers", () => {
  111. expect(isBashInputReadOnly({ command: "ls" })).toBe(true);
  112. expect(isBashInputConcurrencySafe({ command: "ls" })).toBe(true);
  113. expect(isBashInputReadOnly({ command: "ls > out.txt" })).toBe(false);
  114. expect(isBashInputConcurrencySafe({ command: "ls > out.txt" })).toBe(false);
  115. expect(isBashInputReadOnly({ command: "find . -exec rm {} \\;" })).toBe(false);
  116. expect(isBashInputReadOnly({ command: "ls $(touch out.txt)" })).toBe(false);
  117. expect(isBashInputConcurrencySafe({ command: "ls $(touch out.txt)" })).toBe(false);
  118. expect(isBashInputReadOnly({ command: "ls `touch out.txt`" })).toBe(false);
  119. });
  120. it("uses command safe flags for tree read-only permission", () => {
  121. expect(isBashInputReadOnly({ command: "tree" })).toBe(true);
  122. expect(isBashInputReadOnly({ command: "tree -a" })).toBe(true);
  123. expect(isBashInputReadOnly({ command: "tree -L 2" })).toBe(true);
  124. expect(isBashInputReadOnly({ command: "tree --charset utf-8 src" })).toBe(true);
  125. expect(isBashInputReadOnly({ command: "tree -o out.txt" })).toBe(false);
  126. expect(isBashInputConcurrencySafe({ command: "tree -o out.txt" })).toBe(false);
  127. expect(isBashInputReadOnly({ command: "tree --bogus" })).toBe(false);
  128. });
  129. it("allows a minimal set of simple read-only file and search commands", () => {
  130. const service = new PermissionService();
  131. const commands = [
  132. "pwd",
  133. "whoami",
  134. "echo hello",
  135. "printf '%s\\n' hello",
  136. "cat README.md",
  137. "cat < README.md",
  138. "cat -n README.md",
  139. "fd --hidden foo src",
  140. "fdfind -e ts foo src",
  141. "head -n 20 README.md",
  142. "tail --lines=50 README.md",
  143. "wc -l README.md",
  144. "stat README.md",
  145. "file README.md",
  146. "base64 -d fixture.txt",
  147. "sha256sum package.json",
  148. "date +%F",
  149. "hostname -f",
  150. "man ls",
  151. "netstat -an",
  152. "ps -ef",
  153. "lsof -n -i",
  154. "pgrep -fl node",
  155. "pyright --outputjson",
  156. "ss -tuln",
  157. "test -f package.json",
  158. "tput cols",
  159. "strings fixture.bin",
  160. "jq '.scripts' package.json",
  161. "xargs grep -n foo",
  162. "sort README.md",
  163. "uniq README.md",
  164. "cut -d: -f1 README.md",
  165. "tr a-z A-Z README.md",
  166. "diff -u before.txt after.txt",
  167. "du -sh .",
  168. "docker ps --format '{{.Names}}'",
  169. "docker logs --tail 20 container",
  170. "gh pr view 123 --json title --repo owner/repo",
  171. "gh run list --limit 10 --json databaseId",
  172. "rg -n foo src",
  173. "rg --files src",
  174. "rg -g '*.ts' foo src",
  175. "grep -R -n foo src",
  176. "grep -R -n foo src 2>&1",
  177. "grep -R -n foo src 2>/dev/null",
  178. "grep --include '*.ts' foo src",
  179. "LC_ALL=C grep -R -n foo src",
  180. "command grep -R -n foo src",
  181. "noglob grep -R -n foo src",
  182. ];
  183. for (const command of commands) {
  184. expect(isBashInputReadOnly({ command }), command).toBe(true);
  185. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  186. const decision = service.checkPermission(
  187. {
  188. input: { command },
  189. mode: "build",
  190. riskLevel: bashToolEntry.metadata.riskLevel,
  191. toolName: "Bash",
  192. },
  193. withRuntimeCapability({ command }),
  194. );
  195. expect(decision.decision, command).toBe("allow");
  196. expect(decision.ruleId, command).toBe("mode.build.readOnly");
  197. }
  198. });
  199. it("keeps risky flags, redirects, and dynamic words out of the read-only Bash allowlist", () => {
  200. const commands = [
  201. "cat README.md > out.txt",
  202. "rg --pre ./filter foo src",
  203. "rg --pre=./filter foo src",
  204. "grep foo src > out.txt",
  205. "cat < /dev/tcp/example.com/80",
  206. "cat < //server/share",
  207. "sed -n '1w out.txt' README.md",
  208. "jq -f filter.jq package.json",
  209. "jq 'env' package.json",
  210. "xargs rm -rf",
  211. "docker ps --context prod",
  212. "docker logs --host tcp://example.com container",
  213. "gh pr view 123 --repo https://example.com/repo",
  214. "date tomorrow",
  215. "lsof -iTCP@example.com",
  216. "man ./local.1",
  217. "pyright --watch",
  218. "ss dst example.com",
  219. "test -v PATH",
  220. "tput clear",
  221. "rg foo src $(touch out.txt)",
  222. "FOO=bar grep foo src",
  223. ];
  224. for (const command of commands) {
  225. expect(isBashInputReadOnly({ command }), command).toBe(false);
  226. expect(isBashInputConcurrencySafe({ command }), command).toBe(false);
  227. }
  228. });
  229. it.each([
  230. "sed -n '1,20p' README.md",
  231. "sed -n 'p' README.md",
  232. "sed -n '1p; 3p' README.md",
  233. "sed -nE '1p' README.md",
  234. "sed -En '1p' README.md",
  235. "sed --quiet '1p' README.md",
  236. "sed --silent '1p' README.md",
  237. "sed -nz '1p' README.md",
  238. "sed --quiet --regexp-extended --zero-terminated '1p' README.md",
  239. "sed --posix -n '1p' README.md",
  240. "sed -n -- '1p' README.md",
  241. "sed -n '1p' -",
  242. "sed 's/foo/bar/g'",
  243. "sed -- 's/foo/bar/g'",
  244. "sed -E 's/(foo)/\\1/g'",
  245. "sed -r 's/foo/bar/2gp'",
  246. "sed --posix 's/foo/bar/'",
  247. "sed 's/a\\/b/c/'",
  248. "sed 's/a/b\\/c/'",
  249. "sed 's/\\\\/x/'",
  250. "sed 's/foo/\\& bar/g'",
  251. "command sed -n '1p' README.md",
  252. "LC_ALL=C sed -n '1p' README.md",
  253. "cat README.md | sed -n '1p'",
  254. "cat README.md | sed 's/foo/bar/g'",
  255. "sed -n '1p' README.md && cat README.md",
  256. ])("allows only the bounded sed read-only grammar: %s", (command) => {
  257. const input = { command };
  258. const capability = withRuntimeCapability(input);
  259. const service = new PermissionService();
  260. expect(isBashInputReadOnly(input)).toBe(true);
  261. expect(isBashInputConcurrencySafe(input)).toBe(true);
  262. expect(capability).toMatchObject({
  263. readOnly: true,
  264. needsApproval: false,
  265. sideEffectScope: "none",
  266. });
  267. for (const context of [
  268. { mode: "plan" },
  269. { mode: "build", planEnabled: true },
  270. { mode: "yolo", planEnabled: true },
  271. { mode: "guarded", planEnabled: true },
  272. { mode: "build" },
  273. ] as const) {
  274. expect(
  275. service.checkPermission(
  276. { input, ...context, riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  277. capability,
  278. ).decision,
  279. ).toBe("allow");
  280. }
  281. });
  282. it.each([
  283. "sed -n -e 'e printf sed-probe' README.md",
  284. "sed --expression='e printf sed-probe' README.md",
  285. "sed 'e printf sed-probe' README.md",
  286. "sed -n 's/.*/printf sed-probe/e' README.md",
  287. "sed -n 's/.*/probe/w out.txt' README.md",
  288. "sed 's/foo/printf sed-probe/e'",
  289. "sed 's/foo/bar/w out.txt'",
  290. "sed -e 's/foo/bar/' README.md",
  291. "sed -n -e '1p' README.md",
  292. "sed -ne '1p' README.md",
  293. "sed --expression='1p' README.md",
  294. "sed -f script.sed README.md",
  295. "sed --file=script.sed README.md",
  296. "sed -in '1p' README.md",
  297. "sed --in-place -n '1p' README.md",
  298. "sed -n '1p' README.md -e 'e printf sed-probe'",
  299. "sed -n -- '1p' -e 'e printf sed-probe'",
  300. "sed -n '1p' -- README.md",
  301. "sed -n '1p; e printf sed-probe' README.md",
  302. "sed -n '1p\ne printf sed-probe' README.md",
  303. "sed -n '1p\r' README.md",
  304. "sed -n '1p\0' README.md",
  305. "sed -n '0p' README.md",
  306. "sed -n '$p' README.md",
  307. "sed -n '/foo/p' README.md",
  308. "sed -n '1p;' README.md",
  309. "sed -n '' README.md",
  310. "sed -n",
  311. "sed -n --",
  312. "sed 's/foo/bar/g' README.md",
  313. "sed -n 's/foo/bar/p'",
  314. "sed -z 's/foo/bar/g'",
  315. "sed 's/foo/bar/10'",
  316. "sed 's/foo/bar/0'",
  317. "sed 's/foo/bar/;e printf sed-probe'",
  318. "sed 's/foo/bar/\ne printf sed-probe'",
  319. "sed 's#foo#bar#g'",
  320. "sed 's/foo/bar'",
  321. "sed 's/foo/bar\\/'",
  322. "sed 's/foo/\\x0a/g'",
  323. "sed 's/foo/\\cA/g'",
  324. "sed -n '1p' README.md > out.txt",
  325. "cat README.md | sed 'e printf sed-probe'",
  326. "sed -n '1p' README.md && sed 's/.*/printf sed-probe/e'",
  327. "sed --version",
  328. "/usr/bin/sed -n '1p' README.md",
  329. ])("rejects sed outside the bounded read-only grammar: %s", (command) => {
  330. const input = { command };
  331. const capability = withRuntimeCapability(input);
  332. const service = new PermissionService();
  333. expect(isBashInputReadOnly(input)).toBe(false);
  334. expect(isBashInputConcurrencySafe(input)).toBe(false);
  335. expect(capability.readOnly).toBe(false);
  336. for (const context of [
  337. { mode: "plan" },
  338. { mode: "build", planEnabled: true },
  339. { mode: "edit", planEnabled: true },
  340. { mode: "yolo", planEnabled: true },
  341. { mode: "guarded", planEnabled: true },
  342. ] as const) {
  343. expect(
  344. service.checkPermission(
  345. { input, ...context, riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  346. capability,
  347. ),
  348. ).toMatchObject({ allowed: false, decision: "deny", ruleId: "mode.plan.nonReadOnly" });
  349. }
  350. expect(
  351. service.checkPermission(
  352. { input, mode: "build", riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  353. capability,
  354. ).decision,
  355. ).toBe("ask");
  356. });
  357. it("keeps sed authorizations subject to Plan while preserving normal execution permissions", () => {
  358. const input = { command: "sed 'e printf sed-probe' README.md" };
  359. const capability = withRuntimeCapability(input);
  360. const service = new PermissionService({
  361. ...defaultPermissionConfig,
  362. allowedTools: new Set(["Bash"]),
  363. });
  364. const projectRules = { version: 1 as const, allow: [{ toolName: "Bash" }] };
  365. for (const context of [
  366. { mode: "plan" },
  367. { mode: "build", planEnabled: true },
  368. { mode: "yolo", planEnabled: true },
  369. { mode: "guarded", planEnabled: true },
  370. ] as const) {
  371. expect(
  372. service.checkPermission(
  373. { input, ...context, riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  374. capability,
  375. projectRules,
  376. ),
  377. ).toMatchObject({ decision: "deny", ruleId: "mode.plan.nonReadOnly" });
  378. }
  379. for (const mode of ["build", "yolo", "guarded"] as const) {
  380. expect(
  381. service.checkPermission(
  382. {
  383. input,
  384. mode,
  385. planEnabled: false,
  386. riskLevel: bashToolEntry.metadata.riskLevel,
  387. toolName: "Bash",
  388. },
  389. capability,
  390. projectRules,
  391. ).decision,
  392. ).toBe("allow");
  393. }
  394. });
  395. it("denies sed before execution and emits a denial without requesting approval", async () => {
  396. const registry = createToolRegistry();
  397. registry.register(bashToolEntry);
  398. const events: SessionEvent[] = [];
  399. const run = vi.fn<ExecutionPort["run"]>(async () => {
  400. throw new Error("Plan must not reach the execution port");
  401. });
  402. const requestPermission = vi.fn(async () => ({
  403. decision: "allow" as const,
  404. resolvedAt: new Date(),
  405. }));
  406. const executor = createToolExecutor({
  407. registry,
  408. permissionService: new PermissionService(),
  409. permissionBroker: { requestPermission },
  410. executionPort: { run },
  411. mode: "plan",
  412. workingDirectory: process.cwd(),
  413. workspaceRoot: process.cwd(),
  414. sessionId: createSessionId("sed-plan-denial"),
  415. emitEvent: async (event) => {
  416. events.push(event);
  417. },
  418. });
  419. const toolCallId = createToolCallId("sed-plan-call");
  420. const result = await executor.execute({
  421. id: toolCallId,
  422. name: "Bash",
  423. input: { command: "sed -n -e 'e printf sed-probe' README.md" },
  424. });
  425. expect(run).not.toHaveBeenCalled();
  426. expect(result).toMatchObject({
  427. success: false,
  428. error: { type: CoreErrorType.PermissionDenied },
  429. });
  430. expect(requestPermission).not.toHaveBeenCalled();
  431. expect(
  432. events.filter((event) => event.type === SessionEventType.PermissionDenied),
  433. ).toMatchObject([{ payload: { toolCallId, toolName: "Bash" } }]);
  434. expect(events.some((event) => event.type === SessionEventType.PermissionRequested)).toBe(false);
  435. });
  436. it("allows common read-only inspection Bash commands in plan mode", () => {
  437. const service = new PermissionService();
  438. const commands = [
  439. "rg -n foo src",
  440. 'grep -R -n "already referenced\\|destination physical cluster" src/metaoscpp || true',
  441. "grep -R -n foo src | head -20",
  442. "grep -R -n foo src 2>/dev/null",
  443. "cat < README.md",
  444. 'find src -name "*.ts" -maxdepth 3',
  445. "find src -type f -name '*.ts'",
  446. "git status --short",
  447. "git status --porcelain --branch --untracked-files=all",
  448. "git diff --name-only --",
  449. "git diff --exit-code -- src/index.ts",
  450. "git log --oneline -n 5",
  451. "git log --oneline -8 -- tests/xxx.ts",
  452. 'grep -rn "minScore" /Users/xxxxx.test.ts; echo "=== check git blame for this test ==="; git log -1 --format="%H %s" -S "uses candidate score only" -- tests/xxx.test.ts',
  453. "git show --stat HEAD",
  454. "git ls-files --others --exclude-standard",
  455. "git rev-parse --show-toplevel",
  456. "git grep -n foo -- src",
  457. "git branch --show-current",
  458. 'cd "/workspace/project" && grep -R -n "foo" src',
  459. 'LC_ALL=C cd "/workspace/project" && grep -R -n "foo" src',
  460. ];
  461. for (const command of commands) {
  462. expect(isBashInputReadOnly({ command })).toBe(true);
  463. expect(isBashInputConcurrencySafe({ command })).toBe(true);
  464. const readOnlyDecision = service.checkPermission(
  465. {
  466. input: { command },
  467. mode: "plan",
  468. riskLevel: bashToolEntry.metadata.riskLevel,
  469. toolName: "Bash",
  470. },
  471. withRuntimeCapability({ command }),
  472. );
  473. expect(readOnlyDecision.decision).toBe("allow");
  474. expect(readOnlyDecision.ruleId).toBe("mode.plan.readOnly");
  475. }
  476. const writeDecision = service.checkPermission(
  477. {
  478. input: { command: "cat README.md > out.txt" },
  479. mode: "plan",
  480. riskLevel: bashToolEntry.metadata.riskLevel,
  481. toolName: "Bash",
  482. },
  483. withRuntimeCapability({ command: "cat README.md > out.txt" }),
  484. );
  485. expect(writeDecision.decision).toBe("deny");
  486. expect(writeDecision.ruleId).toBe("mode.plan.nonReadOnly");
  487. });
  488. it("allows the grep and fd readonly safe flags", () => {
  489. const commands = [
  490. "grep -c foo README.md",
  491. "grep --count foo README.md",
  492. "grep --color=never -n foo README.md",
  493. "grep --colour=never -n foo README.md",
  494. "grep --silent foo README.md",
  495. "grep -b foo README.md",
  496. "grep --byte-offset foo README.md",
  497. "grep --label stdin foo -",
  498. "grep -T foo README.md",
  499. "grep --initial-tab foo README.md",
  500. "grep -u foo README.md",
  501. "grep --unix-byte-offsets foo README.md",
  502. "grep -Z foo README.md",
  503. "grep --null foo README.md",
  504. "grep -z foo README.md",
  505. "grep --null-data foo README.md",
  506. "grep --group-separator='--' -A 1 foo README.md",
  507. "grep --no-group-separator -A 1 foo README.md",
  508. "grep -D read foo README.md",
  509. "grep --devices=read foo README.md",
  510. "grep -d skip foo README.md",
  511. "grep --line-buffered foo README.md",
  512. "grep -U foo README.md",
  513. "grep --binary foo README.md",
  514. "grep --help",
  515. "grep -V",
  516. "grep --version",
  517. "fd --ignore-case foo src",
  518. "fdfind --ignore-case foo src",
  519. ];
  520. for (const command of commands) {
  521. expect(isBashInputReadOnly({ command }), command).toBe(true);
  522. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  523. }
  524. });
  525. it("allows the direct readonly argv branches", () => {
  526. const commands = [
  527. "node -v",
  528. "node --version",
  529. "python --version",
  530. "python3 --version",
  531. "ip addr",
  532. "history",
  533. "history 20",
  534. "arch",
  535. "arch --help",
  536. "ifconfig en0",
  537. "printf '%d\\n' 42",
  538. "printf -- '%s\\n' hello",
  539. "find . -name package.json",
  540. "find . -newer marker -type f",
  541. "cal -3",
  542. "uptime",
  543. "type grep",
  544. "unexpand README.md",
  545. "tsort graph.txt",
  546. "pr README.md",
  547. ];
  548. for (const command of commands) {
  549. expect(isBashInputReadOnly({ command }), command).toBe(true);
  550. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  551. }
  552. });
  553. it("rejects direct readonly argv negative branches", () => {
  554. const commands = [
  555. "node -e 'console.log(1)'",
  556. "python -c 'print(1)'",
  557. "history abc",
  558. "arch -x",
  559. "printf -v name value",
  560. "printf '%d\\n' not-a-number",
  561. "printf '%s\\n' $(touch out.txt)",
  562. "find . -exec rm {} \\;",
  563. "find . -files0-from list",
  564. "ifconfig -a",
  565. ];
  566. for (const command of commands) {
  567. expect(isBashInputReadOnly({ command }), command).toBe(false);
  568. expect(isBashInputConcurrencySafe({ command }), command).toBe(false);
  569. }
  570. });
  571. it("allows list-only archive, Windows lookup, and git history commands in plan mode", () => {
  572. const service = new PermissionService();
  573. const commands = [
  574. "git --version",
  575. "command -p git --version",
  576. "git log --oneline --follow -10 -- src/a.sql",
  577. "git log --oneline --follow -15 -- mod/a.cpp | head -20",
  578. "git log -L 10,20:src/a.ts",
  579. "git log -L10,20:src/a.ts --oneline",
  580. "git log --all --oneline -i --grep=fix",
  581. "git log --oneline --grep=fix --regexp-ignore-case --invert-grep",
  582. "git log feature/a --oneline --not main",
  583. "git ls-tree origin/v4 --name-only",
  584. "git ls-tree -r --name-only HEAD | head -50",
  585. "git ls-tree -r -t -l --full-name --abbrev HEAD src",
  586. "git ls-tree --abbrev=8 --format='%(objectname) %(path)' -z HEAD",
  587. "git ls-tree --name-only origin/main:src/lib",
  588. 'git grep -rn "needle" -- src',
  589. 'git grep -I -l -i "needle" origin/v4',
  590. 'git grep -c "needle" -- src/a.sql',
  591. 'git grep -n -A15 "needle" -- src/a.js',
  592. 'git grep -m 3 -p -W --column "needle"',
  593. "git blame -C src/a.ts",
  594. "git diff -C --stat HEAD~1",
  595. String.raw`dir /b "D:\Repos\proj"`,
  596. String.raw`dir /s /b /ad /o-n "C:\work\proj\src"`,
  597. "dir",
  598. String.raw`findstr /R "^frontend/" "C:\Users\u\AppData\Local\Temp\list.txt"`,
  599. 'findstr /S /I /N "foo" *.java',
  600. String.raw`findstr /spin "Manager" D:\proj\src\*.cs`,
  601. String.raw`findstr /s /m /c:"missing slot" "C:\work\proj\*.java"`,
  602. 'findstr /F:list.txt /G:patterns.txt "/D:src;tests" "foo"',
  603. "findstr /?",
  604. "git grep -n foo -- src/a.py | findstr /v test",
  605. "where node",
  606. "where bash sh git",
  607. String.raw`where /r "D:\work\proj" *.java`,
  608. "where /q /f /t node",
  609. "whereis git",
  610. "whereis -b -B /usr/bin -f git",
  611. "unzip -l /Users/u/.gradle/caches/a.jar",
  612. "unzip -l a.zip | head -20",
  613. "unzip -lv a.zip '*.class'",
  614. "unzip -t a.zip",
  615. "unzip -v",
  616. "unzip -O GBK -l a.zip",
  617. "unzip -Z -1 a.zip",
  618. "unzip -Z a.zip",
  619. 'zipinfo -1 "docs/设计书.docx"',
  620. "zipinfo -l -T a.jar",
  621. "tar -tzf a.tar.gz | head",
  622. "tar -tf a.tar",
  623. "tar tzf a.tar.gz",
  624. "tar -tf a.tar '*.md'",
  625. String.raw`xxd a\*`,
  626. "tar tvf a.tar member.txt",
  627. "tar --list --file=a.tar --verbose",
  628. "tar -t -v -j -f a.tar.bz2 --wildcards '*.md'",
  629. "tar -tfa.tar",
  630. String.raw`tar --force-local -tf "E:\docs\design.zip"`,
  631. "tar -tf host:/a.tar --force-local",
  632. "tar --version",
  633. String.raw`iconv -f GB18030 -t UTF-8 "E:\data\a.txt"`,
  634. "iconv -f UTF-16LE -t UTF-8 -c a.xls | head",
  635. "iconv --from-code=GBK --to-code=UTF-8 a.txt",
  636. "iconv -l",
  637. "command -v unzip; command -v awk",
  638. "command -v R Rscript python3",
  639. "command -V git",
  640. "xxd a.bin",
  641. "xxd -l 120 a.bin",
  642. "xxd -s 0x10 -l16 -c 8 -g 1 a.bin",
  643. "xxd -p a.bin | head",
  644. "xxd -v",
  645. "head -c 64 a.bin | xxd",
  646. ];
  647. for (const command of commands) {
  648. expect(isBashInputReadOnly({ command }), command).toBe(true);
  649. const decision = service.checkPermission(
  650. {
  651. input: { command },
  652. mode: "plan",
  653. riskLevel: bashToolEntry.metadata.riskLevel,
  654. toolName: "Bash",
  655. },
  656. withRuntimeCapability({ command }),
  657. );
  658. expect(decision.decision, command).toBe("allow");
  659. expect(decision.ruleId, command).toBe("mode.plan.readOnly");
  660. }
  661. });
  662. it("keeps extracting, writing, and program-running forms of the new allowlist denied", () => {
  663. const service = new PermissionService();
  664. const commands = [
  665. // 有意禁止的 git 目录切换,保持不变。
  666. "git -C /repo log --oneline -5",
  667. "cd /repo && git log --oneline -8",
  668. "git --no-pager -C /repo log --oneline -5",
  669. "git -c core.pager=cat grep -c foo",
  670. "git --version --build-options",
  671. "git --version -C /repo",
  672. "git grep -O foo",
  673. "git grep --open-files-in-pager=vim foo",
  674. "git grep --textconv foo",
  675. // unzip:没有列表/测试参数就是解压模式;-d/-o/-p/-x/-T 都不放行。
  676. "unzip a.zip",
  677. "unzip -o a.zip -d out",
  678. "unzip -l a.zip -d out",
  679. "unzip -l a.zip -- -d out",
  680. "unzip -p a.zip word/document.xml",
  681. "unzip -Olatin1 a.zip",
  682. "unzip -O GBK a.zip",
  683. "unzip -T -l a.zip",
  684. "unzip -l a.zip -x skip.txt",
  685. "unzip -lZ a.zip",
  686. "unzip -Z -M a.zip",
  687. "zipinfo -M a.zip",
  688. // Info-ZIP 的 `--` 是否定标记:`-l -- -l` 会取消列表模式并解压。
  689. "unzip -l -- -l a.zip",
  690. "unzip -t -- -t a.zip",
  691. "unzip -l -- -- -l a.zip",
  692. "unzip --l a.zip",
  693. "unzip -l-l a.zip",
  694. "unzip -lv- a.zip",
  695. "unzip -Z -- -M a.zip",
  696. "zipinfo -- -M a.zip",
  697. // 第二个字符不是字母数字的词(`-:`、`-^`)通用参数表不当选项检查,Info-ZIP 却会照常解析:
  698. // `-:-l` 是「开启 :(允许 ../ 路径)再取消 -l」,实际解压。
  699. "unzip -:-l a.zip",
  700. "unzip -:-lo a.zip",
  701. "unzip -^-l a.zip",
  702. "unzip -l -:- a.zip",
  703. "unzip -l -$ a.zip",
  704. "unzip -l - a.zip",
  705. "unzip -Z -:-1 a.zip",
  706. "zipinfo -^-1 a.zip",
  707. "xxd -:-r a.hex",
  708. // tar:只放行列表模式;冒号归档名必须配 --force-local。
  709. "tar -xf a.tar",
  710. "tar xf a.tar",
  711. "tar -xOf a.docx word/document.xml",
  712. "tar -cf a.tar src",
  713. "tar -tf a.tar --to-command=sh",
  714. 'tar -t -I "sh -c x" -f a.tar',
  715. "tar -tf a.tar --use-compress-program=sh",
  716. "tar -tf a.tar --checkpoint-action=exec=sh",
  717. "tar -tf a.tar -F script.sh",
  718. "tar -tf a.tar --info-script=script.sh",
  719. "tar -tf a.tar --rsh-command=/bin/sh",
  720. "tar -tf a.tar --new-volume-script=script.sh",
  721. "tar -tf a.tar --delete member",
  722. "tar -tf a.tar -C /",
  723. "tar -tf host:/a.tar",
  724. String.raw`tar -tf "E:\docs\design.zip"`,
  725. "tar -tzf D:/docs/a.tgz",
  726. "tar --file=host:a.tar --list",
  727. String.raw`tar -tf '\\host\share\a.tar' --force-local`,
  728. "tar -t",
  729. "tar -tf",
  730. "tar -tf --to-command=sh",
  731. "tar --li -f a.tar",
  732. "tar archive",
  733. // 未引用的通配符在执行前展开成文件名:`--checkpoint-action=exec=...` 这样的文件名会变成 tar 选项,
  734. // 多出来的文件会被 xxd 当成输出文件。策略只看得到展开前的 argv,所以这些命令带通配符一律拒绝。
  735. "tar -tf - *",
  736. "tar -tf *.tar",
  737. "tar -tf a.tar *",
  738. "unzip -l *.zip",
  739. "unzip -Z -1 *.jar",
  740. "zipinfo -1 *.jar",
  741. "iconv -f GBK -t UTF-8 *",
  742. "xxd *.bin",
  743. "xxd a?",
  744. "xxd [ab]",
  745. "command -p xxd *.bin",
  746. // iconv:-o/--output 写文件。
  747. "iconv -f GBK -t UTF-8 a.txt -o b.txt",
  748. "iconv --output=b.txt -f GBK -t UTF-8 a.txt",
  749. "iconv -co b.txt -f GBK -t UTF-8 a.txt",
  750. "iconv -f GBK -t UTF-8 -ob.txt a.txt",
  751. // command:`command <程序>` 会执行程序。
  752. "command rm -rf x",
  753. "command python a.py",
  754. "command -x foo",
  755. "command",
  756. // xxd:第二个位置参数是输出文件;-r 是还原模式。
  757. "xxd -r a.hex b.bin",
  758. "xxd -r a.hex",
  759. "xxd -revert a.hex",
  760. "xxd a b",
  761. "xxd a.bin -l 16",
  762. "xxd -- a.bin out.txt",
  763. "xxd -s -16 a.bin",
  764. // findstr / where:值或参数是 UNC 路径会访问网络共享。
  765. String.raw`findstr '/F:\\host\share\list.txt' foo`,
  766. "findstr /G://host/share/patterns.txt foo a.txt",
  767. String.raw`findstr '/D:src;\\host\share' foo *.c`,
  768. String.raw`findstr foo '\\host\share\a.txt'`,
  769. "findstr -i foo a.txt",
  770. String.raw`where /r '\\host\share' node`,
  771. "where /x node",
  772. "where -p node",
  773. // printenv 会把环境变量(含密钥)带进模型上下文,与 `echo $TOKEN`、`env` 一样需要审批。
  774. "printenv",
  775. "printenv PATH",
  776. "printenv GITHUB_TOKEN",
  777. "whereis -X git",
  778. // 本次不处理的命令保持拒绝。
  779. "awk '{print $1}' f",
  780. 'python -c "print(1)"',
  781. 'powershell -Command "Get-ChildItem"',
  782. "dir > out.txt",
  783. ];
  784. for (const command of commands) {
  785. expect(isBashInputReadOnly({ command }), command).toBe(false);
  786. const decision = service.checkPermission(
  787. {
  788. input: { command },
  789. mode: "plan",
  790. riskLevel: bashToolEntry.metadata.riskLevel,
  791. toolName: "Bash",
  792. },
  793. withRuntimeCapability({ command }),
  794. );
  795. expect(decision.decision, command).toBe("deny");
  796. expect(decision.ruleId, command).toBe("mode.plan.nonReadOnly");
  797. }
  798. });
  799. it("auto-approves the new allowlist commands in build mode and still asks for unsafe forms", () => {
  800. // 同一份名单也决定 build 模式是否免审批:新增的只读形态在 build 下直接执行,危险形态照常询问。
  801. const service = new PermissionService();
  802. const decide = (command: string) =>
  803. service.checkPermission(
  804. {
  805. input: { command },
  806. mode: "build",
  807. riskLevel: bashToolEntry.metadata.riskLevel,
  808. toolName: "Bash",
  809. },
  810. withRuntimeCapability({ command }),
  811. );
  812. for (const command of [
  813. "unzip -l a.zip",
  814. "tar -tzf a.tgz",
  815. 'findstr /S /I "foo" *.java',
  816. "where node",
  817. "git ls-tree -r --name-only HEAD",
  818. 'git grep -c "foo" -- src',
  819. "git --version",
  820. "iconv -f GBK -t UTF-8 a.txt",
  821. "xxd -l 64 a.bin",
  822. ]) {
  823. const decision = decide(command);
  824. expect(decision.decision, command).toBe("allow");
  825. expect(decision.ruleId, command).toBe("mode.build.readOnly");
  826. }
  827. for (const command of [
  828. "unzip a.zip",
  829. "tar -xf a.tar",
  830. String.raw`tar -tf "E:\docs\design.zip"`,
  831. "iconv -f GBK -t UTF-8 a.txt -o b.txt",
  832. "xxd -r a.hex b.bin",
  833. "command python a.py",
  834. "tar -tf - *",
  835. "xxd *.bin",
  836. "unzip -l -- -l a.zip",
  837. "unzip -:-l a.zip",
  838. ]) {
  839. expect(decide(command).decision, command).toBe("ask");
  840. }
  841. });
  842. it("requires approval for git runtime guard conditions", async () => {
  843. const service = new PermissionService();
  844. const testRoot = await mkdtemp(join(tmpdir(), "zcode-bash-git-guard-"));
  845. try {
  846. const normalRepo = join(testRoot, "normal-repo");
  847. await writeMinimalGitDir(normalRepo);
  848. expect(withRuntimeCapability({ command: "git status --short" }, normalRepo)?.readOnly).toBe(
  849. true,
  850. );
  851. const bareLike = join(testRoot, "bare-like");
  852. await writeGitIndicators(bareLike);
  853. expect(withRuntimeCapability({ command: "git status --short" }, bareLike).readOnly).toBe(
  854. false,
  855. );
  856. const redirected = join(testRoot, "redirected");
  857. const redirectedTarget = join(testRoot, "external.git");
  858. await mkdir(redirected, { recursive: true });
  859. await writeGitIndicators(redirectedTarget);
  860. await writeFile(join(redirected, ".git"), `gitdir: ${redirectedTarget}\n`);
  861. expect(withRuntimeCapability({ command: "git status --short" }, redirected).readOnly).toBe(
  862. false,
  863. );
  864. const decision = service.checkPermission(
  865. {
  866. input: { command: "git status --short" },
  867. mode: "plan",
  868. riskLevel: bashToolEntry.metadata.riskLevel,
  869. toolName: "Bash",
  870. },
  871. withRuntimeCapability({ command: "git status --short" }, bareLike),
  872. );
  873. expect(decision.decision).toBe("deny");
  874. expect(decision.ruleId).toBe("mode.plan.nonReadOnly");
  875. } finally {
  876. await rm(testRoot, { force: true, recursive: true });
  877. }
  878. });
  879. it("keeps mutating Bash commands denied in plan mode", () => {
  880. const service = new PermissionService();
  881. const commands = [
  882. "grep foo src > out.txt",
  883. "find . -exec rm {} \\;",
  884. "find . -delete",
  885. "find . -fprint out.txt",
  886. "git -c core.pager=cat status",
  887. "git -C . status --short",
  888. "git -C/tmp status --short",
  889. "git --exec-path=/tmp status",
  890. "git checkout main",
  891. 'cd "/workspace/project" && git status --short',
  892. "git status && rm out.txt",
  893. "FOO=bar grep foo src",
  894. ];
  895. for (const command of commands) {
  896. const decision = service.checkPermission(
  897. {
  898. input: { command },
  899. mode: "plan",
  900. riskLevel: bashToolEntry.metadata.riskLevel,
  901. toolName: "Bash",
  902. },
  903. withRuntimeCapability({ command }),
  904. );
  905. expect(decision.decision, command).toBe("deny");
  906. expect(decision.ruleId, command).toBe("mode.plan.nonReadOnly");
  907. }
  908. });
  909. it("allows read-only Bash commands through the real permission policy", () => {
  910. const service = new PermissionService();
  911. const lsDecision = service.checkPermission(
  912. {
  913. input: { command: "ls" },
  914. mode: "build",
  915. riskLevel: bashToolEntry.metadata.riskLevel,
  916. toolName: "Bash",
  917. },
  918. withRuntimeCapability({ command: "ls" }),
  919. );
  920. expect(lsDecision.decision).toBe("allow");
  921. expect(lsDecision.ruleId).toBe("mode.build.readOnly");
  922. const redirectDecision = service.checkPermission(
  923. {
  924. input: { command: "ls > out.txt" },
  925. mode: "build",
  926. riskLevel: bashToolEntry.metadata.riskLevel,
  927. toolName: "Bash",
  928. },
  929. withRuntimeCapability({ command: "ls > out.txt" }),
  930. );
  931. expect(redirectDecision.decision).toBe("ask");
  932. const sedDecision = service.checkPermission(
  933. {
  934. input: { command: "sed -i 's/a/b/' file.txt" },
  935. mode: "build",
  936. riskLevel: bashToolEntry.metadata.riskLevel,
  937. toolName: "Bash",
  938. },
  939. withRuntimeCapability({ command: "sed -i 's/a/b/' file.txt" }),
  940. );
  941. expect(sedDecision.decision).toBe("ask");
  942. const findExecDecision = service.checkPermission(
  943. {
  944. input: { command: "find . -exec rm {} \\;" },
  945. mode: "build",
  946. riskLevel: bashToolEntry.metadata.riskLevel,
  947. toolName: "Bash",
  948. },
  949. withRuntimeCapability({ command: "find . -exec rm {} \\;" }),
  950. );
  951. expect(findExecDecision.decision).toBe("ask");
  952. const treeOutputDecision = service.checkPermission(
  953. {
  954. input: { command: "tree -o out.txt" },
  955. mode: "build",
  956. riskLevel: bashToolEntry.metadata.riskLevel,
  957. toolName: "Bash",
  958. },
  959. withRuntimeCapability({ command: "tree -o out.txt" }),
  960. );
  961. expect(treeOutputDecision.decision).toBe("ask");
  962. const treeSafeFlagDecision = service.checkPermission(
  963. {
  964. input: { command: "tree -L 2" },
  965. mode: "build",
  966. riskLevel: bashToolEntry.metadata.riskLevel,
  967. toolName: "Bash",
  968. },
  969. withRuntimeCapability({ command: "tree -L 2" }),
  970. );
  971. expect(treeSafeFlagDecision.decision).toBe("allow");
  972. expect(treeSafeFlagDecision.ruleId).toBe("mode.build.readOnly");
  973. const multilineDecision = service.checkPermission(
  974. {
  975. input: { command: "ls\nrm file.txt" },
  976. mode: "build",
  977. riskLevel: bashToolEntry.metadata.riskLevel,
  978. toolName: "Bash",
  979. },
  980. withRuntimeCapability({ command: "ls\nrm file.txt" }),
  981. );
  982. expect(multilineDecision.decision).toBe("ask");
  983. const commandSubstitutionDecision = service.checkPermission(
  984. {
  985. input: { command: "ls $(touch out.txt)" },
  986. mode: "build",
  987. riskLevel: bashToolEntry.metadata.riskLevel,
  988. toolName: "Bash",
  989. },
  990. withRuntimeCapability({ command: "ls $(touch out.txt)" }),
  991. );
  992. expect(commandSubstitutionDecision.decision).toBe("ask");
  993. });
  994. it("prepares a conservative matcher when Bash security parsing is unavailable", () => {
  995. const envMatcher = prepareBashPermissionMatcher({
  996. command: "FOO=bar git push origin main",
  997. });
  998. expect(envMatcher?.("git push")).toBe(true);
  999. expect(envMatcher?.("git push:*")).toBe(true);
  1000. expect(envMatcher?.("npm *")).toBe(true);
  1001. const compoundMatcher = prepareBashPermissionMatcher({
  1002. command: "ls && git status",
  1003. });
  1004. expect(compoundMatcher?.("ls")).toBe(true);
  1005. expect(compoundMatcher?.("git status")).toBe(true);
  1006. expect(compoundMatcher?.("git:*")).toBe(true);
  1007. expect(compoundMatcher?.("rm *")).toBe(true);
  1008. const commandSubstitutionMatcher = prepareBashPermissionMatcher({
  1009. command: "ls $(touch out.txt)",
  1010. });
  1011. expect(commandSubstitutionMatcher?.("ls")).toBe(true);
  1012. expect(commandSubstitutionMatcher?.("rm *")).toBe(true);
  1013. const emptyMatcher = prepareBashPermissionMatcher({ command: "" });
  1014. expect(emptyMatcher?.("anything")).toBe(false);
  1015. });
  1016. });
  1017. function withRuntimeCapability(input: unknown, cwd = process.cwd()): PermissionToolCapability {
  1018. const runtimeCapability = bashToolEntry.resolvePermissionCapability?.(input, {
  1019. workingDirectory: cwd,
  1020. workspaceRoot: cwd,
  1021. } as never);
  1022. return {
  1023. ...bashToolEntry.metadata,
  1024. ...runtimeCapability,
  1025. permission: bashToolEntry.permission,
  1026. ...(runtimeCapability?.permission
  1027. ? { permission: { ...bashToolEntry.permission, ...runtimeCapability.permission } }
  1028. : undefined),
  1029. };
  1030. }
  1031. async function writeMinimalGitDir(repoPath: string): Promise<void> {
  1032. await mkdir(join(repoPath, ".git", "objects"), { recursive: true });
  1033. await mkdir(join(repoPath, ".git", "refs"), { recursive: true });
  1034. await writeFile(join(repoPath, ".git", "HEAD"), "ref: refs/heads/main\n");
  1035. }
  1036. async function writeGitIndicators(repoPath: string): Promise<void> {
  1037. await mkdir(join(repoPath, "objects"), { recursive: true });
  1038. await mkdir(join(repoPath, "refs"), { recursive: true });
  1039. await writeFile(join(repoPath, "HEAD"), "ref: refs/heads/main\n");
  1040. }