bash-permission.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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("requires approval for git runtime guard conditions", async () => {
  572. const service = new PermissionService();
  573. const testRoot = await mkdtemp(join(tmpdir(), "zcode-bash-git-guard-"));
  574. try {
  575. const normalRepo = join(testRoot, "normal-repo");
  576. await writeMinimalGitDir(normalRepo);
  577. expect(withRuntimeCapability({ command: "git status --short" }, normalRepo)?.readOnly).toBe(
  578. true,
  579. );
  580. const bareLike = join(testRoot, "bare-like");
  581. await writeGitIndicators(bareLike);
  582. expect(withRuntimeCapability({ command: "git status --short" }, bareLike).readOnly).toBe(
  583. false,
  584. );
  585. const redirected = join(testRoot, "redirected");
  586. const redirectedTarget = join(testRoot, "external.git");
  587. await mkdir(redirected, { recursive: true });
  588. await writeGitIndicators(redirectedTarget);
  589. await writeFile(join(redirected, ".git"), `gitdir: ${redirectedTarget}\n`);
  590. expect(withRuntimeCapability({ command: "git status --short" }, redirected).readOnly).toBe(
  591. false,
  592. );
  593. const decision = service.checkPermission(
  594. {
  595. input: { command: "git status --short" },
  596. mode: "plan",
  597. riskLevel: bashToolEntry.metadata.riskLevel,
  598. toolName: "Bash",
  599. },
  600. withRuntimeCapability({ command: "git status --short" }, bareLike),
  601. );
  602. expect(decision.decision).toBe("deny");
  603. expect(decision.ruleId).toBe("mode.plan.nonReadOnly");
  604. } finally {
  605. await rm(testRoot, { force: true, recursive: true });
  606. }
  607. });
  608. it("keeps mutating Bash commands denied in plan mode", () => {
  609. const service = new PermissionService();
  610. const commands = [
  611. "grep foo src > out.txt",
  612. "find . -exec rm {} \\;",
  613. "find . -delete",
  614. "find . -fprint out.txt",
  615. "git -c core.pager=cat status",
  616. "git -C . status --short",
  617. "git -C/tmp status --short",
  618. "git --exec-path=/tmp status",
  619. "git checkout main",
  620. 'cd "/workspace/project" && git status --short',
  621. "git status && rm out.txt",
  622. "FOO=bar grep foo src",
  623. ];
  624. for (const command of commands) {
  625. const decision = service.checkPermission(
  626. {
  627. input: { command },
  628. mode: "plan",
  629. riskLevel: bashToolEntry.metadata.riskLevel,
  630. toolName: "Bash",
  631. },
  632. withRuntimeCapability({ command }),
  633. );
  634. expect(decision.decision, command).toBe("deny");
  635. expect(decision.ruleId, command).toBe("mode.plan.nonReadOnly");
  636. }
  637. });
  638. it("allows read-only Bash commands through the real permission policy", () => {
  639. const service = new PermissionService();
  640. const lsDecision = service.checkPermission(
  641. {
  642. input: { command: "ls" },
  643. mode: "build",
  644. riskLevel: bashToolEntry.metadata.riskLevel,
  645. toolName: "Bash",
  646. },
  647. withRuntimeCapability({ command: "ls" }),
  648. );
  649. expect(lsDecision.decision).toBe("allow");
  650. expect(lsDecision.ruleId).toBe("mode.build.readOnly");
  651. const redirectDecision = service.checkPermission(
  652. {
  653. input: { command: "ls > out.txt" },
  654. mode: "build",
  655. riskLevel: bashToolEntry.metadata.riskLevel,
  656. toolName: "Bash",
  657. },
  658. withRuntimeCapability({ command: "ls > out.txt" }),
  659. );
  660. expect(redirectDecision.decision).toBe("ask");
  661. const sedDecision = service.checkPermission(
  662. {
  663. input: { command: "sed -i 's/a/b/' file.txt" },
  664. mode: "build",
  665. riskLevel: bashToolEntry.metadata.riskLevel,
  666. toolName: "Bash",
  667. },
  668. withRuntimeCapability({ command: "sed -i 's/a/b/' file.txt" }),
  669. );
  670. expect(sedDecision.decision).toBe("ask");
  671. const findExecDecision = service.checkPermission(
  672. {
  673. input: { command: "find . -exec rm {} \\;" },
  674. mode: "build",
  675. riskLevel: bashToolEntry.metadata.riskLevel,
  676. toolName: "Bash",
  677. },
  678. withRuntimeCapability({ command: "find . -exec rm {} \\;" }),
  679. );
  680. expect(findExecDecision.decision).toBe("ask");
  681. const treeOutputDecision = service.checkPermission(
  682. {
  683. input: { command: "tree -o out.txt" },
  684. mode: "build",
  685. riskLevel: bashToolEntry.metadata.riskLevel,
  686. toolName: "Bash",
  687. },
  688. withRuntimeCapability({ command: "tree -o out.txt" }),
  689. );
  690. expect(treeOutputDecision.decision).toBe("ask");
  691. const treeSafeFlagDecision = service.checkPermission(
  692. {
  693. input: { command: "tree -L 2" },
  694. mode: "build",
  695. riskLevel: bashToolEntry.metadata.riskLevel,
  696. toolName: "Bash",
  697. },
  698. withRuntimeCapability({ command: "tree -L 2" }),
  699. );
  700. expect(treeSafeFlagDecision.decision).toBe("allow");
  701. expect(treeSafeFlagDecision.ruleId).toBe("mode.build.readOnly");
  702. const multilineDecision = service.checkPermission(
  703. {
  704. input: { command: "ls\nrm file.txt" },
  705. mode: "build",
  706. riskLevel: bashToolEntry.metadata.riskLevel,
  707. toolName: "Bash",
  708. },
  709. withRuntimeCapability({ command: "ls\nrm file.txt" }),
  710. );
  711. expect(multilineDecision.decision).toBe("ask");
  712. const commandSubstitutionDecision = service.checkPermission(
  713. {
  714. input: { command: "ls $(touch out.txt)" },
  715. mode: "build",
  716. riskLevel: bashToolEntry.metadata.riskLevel,
  717. toolName: "Bash",
  718. },
  719. withRuntimeCapability({ command: "ls $(touch out.txt)" }),
  720. );
  721. expect(commandSubstitutionDecision.decision).toBe("ask");
  722. });
  723. it("prepares a conservative matcher when Bash security parsing is unavailable", () => {
  724. const envMatcher = prepareBashPermissionMatcher({
  725. command: "FOO=bar git push origin main",
  726. });
  727. expect(envMatcher?.("git push")).toBe(true);
  728. expect(envMatcher?.("git push:*")).toBe(true);
  729. expect(envMatcher?.("npm *")).toBe(true);
  730. const compoundMatcher = prepareBashPermissionMatcher({
  731. command: "ls && git status",
  732. });
  733. expect(compoundMatcher?.("ls")).toBe(true);
  734. expect(compoundMatcher?.("git status")).toBe(true);
  735. expect(compoundMatcher?.("git:*")).toBe(true);
  736. expect(compoundMatcher?.("rm *")).toBe(true);
  737. const commandSubstitutionMatcher = prepareBashPermissionMatcher({
  738. command: "ls $(touch out.txt)",
  739. });
  740. expect(commandSubstitutionMatcher?.("ls")).toBe(true);
  741. expect(commandSubstitutionMatcher?.("rm *")).toBe(true);
  742. const emptyMatcher = prepareBashPermissionMatcher({ command: "" });
  743. expect(emptyMatcher?.("anything")).toBe(false);
  744. });
  745. });
  746. function withRuntimeCapability(input: unknown, cwd = process.cwd()): PermissionToolCapability {
  747. const runtimeCapability = bashToolEntry.resolvePermissionCapability?.(input, {
  748. workingDirectory: cwd,
  749. workspaceRoot: cwd,
  750. } as never);
  751. return {
  752. ...bashToolEntry.metadata,
  753. ...runtimeCapability,
  754. permission: bashToolEntry.permission,
  755. ...(runtimeCapability?.permission
  756. ? { permission: { ...bashToolEntry.permission, ...runtimeCapability.permission } }
  757. : undefined),
  758. };
  759. }
  760. async function writeMinimalGitDir(repoPath: string): Promise<void> {
  761. await mkdir(join(repoPath, ".git", "objects"), { recursive: true });
  762. await mkdir(join(repoPath, ".git", "refs"), { recursive: true });
  763. await writeFile(join(repoPath, ".git", "HEAD"), "ref: refs/heads/main\n");
  764. }
  765. async function writeGitIndicators(repoPath: string): Promise<void> {
  766. await mkdir(join(repoPath, "objects"), { recursive: true });
  767. await mkdir(join(repoPath, "refs"), { recursive: true });
  768. await writeFile(join(repoPath, "HEAD"), "ref: refs/heads/main\n");
  769. }