bash-permission.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 } from "vitest";
  5. import { PermissionService, type PermissionToolCapability } from "../src/permission/service.js";
  6. import {
  7. bashToolEntry,
  8. isBashInputConcurrencySafe,
  9. isBashInputReadOnly,
  10. prepareBashPermissionMatcher,
  11. } from "../src/tool/handlers/bash.js";
  12. describe("bash runtime permission capability", () => {
  13. it("keeps display classification separate from read-only and concurrency helpers", () => {
  14. expect(isBashInputReadOnly({ command: "ls" })).toBe(true);
  15. expect(isBashInputConcurrencySafe({ command: "ls" })).toBe(true);
  16. expect(isBashInputReadOnly({ command: "ls > out.txt" })).toBe(false);
  17. expect(isBashInputConcurrencySafe({ command: "ls > out.txt" })).toBe(false);
  18. expect(isBashInputReadOnly({ command: "find . -exec rm {} \\;" })).toBe(false);
  19. expect(isBashInputReadOnly({ command: "ls $(touch out.txt)" })).toBe(false);
  20. expect(isBashInputConcurrencySafe({ command: "ls $(touch out.txt)" })).toBe(false);
  21. expect(isBashInputReadOnly({ command: "ls `touch out.txt`" })).toBe(false);
  22. });
  23. it("uses command safe flags for tree read-only permission", () => {
  24. expect(isBashInputReadOnly({ command: "tree" })).toBe(true);
  25. expect(isBashInputReadOnly({ command: "tree -a" })).toBe(true);
  26. expect(isBashInputReadOnly({ command: "tree -L 2" })).toBe(true);
  27. expect(isBashInputReadOnly({ command: "tree --charset utf-8 src" })).toBe(true);
  28. expect(isBashInputReadOnly({ command: "tree -o out.txt" })).toBe(false);
  29. expect(isBashInputConcurrencySafe({ command: "tree -o out.txt" })).toBe(false);
  30. expect(isBashInputReadOnly({ command: "tree --bogus" })).toBe(false);
  31. });
  32. it("allows a minimal set of simple read-only file and search commands", () => {
  33. const service = new PermissionService();
  34. const commands = [
  35. "pwd",
  36. "whoami",
  37. "echo hello",
  38. "printf '%s\\n' hello",
  39. "cat README.md",
  40. "cat < README.md",
  41. "cat -n README.md",
  42. "fd --hidden foo src",
  43. "fdfind -e ts foo src",
  44. "head -n 20 README.md",
  45. "tail --lines=50 README.md",
  46. "wc -l README.md",
  47. "stat README.md",
  48. "file README.md",
  49. "base64 -d fixture.txt",
  50. "sha256sum package.json",
  51. "date +%F",
  52. "hostname -f",
  53. "man ls",
  54. "netstat -an",
  55. "ps -ef",
  56. "lsof -n -i",
  57. "pgrep -fl node",
  58. "pyright --outputjson",
  59. "ss -tuln",
  60. "test -f package.json",
  61. "tput cols",
  62. "strings fixture.bin",
  63. "sed -n '1,20p' README.md",
  64. "jq '.scripts' package.json",
  65. "xargs grep -n foo",
  66. "sort README.md",
  67. "uniq README.md",
  68. "cut -d: -f1 README.md",
  69. "tr a-z A-Z README.md",
  70. "diff -u before.txt after.txt",
  71. "du -sh .",
  72. "docker ps --format '{{.Names}}'",
  73. "docker logs --tail 20 container",
  74. "gh pr view 123 --json title --repo owner/repo",
  75. "gh run list --limit 10 --json databaseId",
  76. "rg -n foo src",
  77. "rg --files src",
  78. "rg -g '*.ts' foo src",
  79. "grep -R -n foo src",
  80. "grep -R -n foo src 2>&1",
  81. "grep -R -n foo src 2>/dev/null",
  82. "grep --include '*.ts' foo src",
  83. "LC_ALL=C grep -R -n foo src",
  84. "command grep -R -n foo src",
  85. "noglob grep -R -n foo src",
  86. ];
  87. for (const command of commands) {
  88. expect(isBashInputReadOnly({ command }), command).toBe(true);
  89. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  90. const decision = service.checkPermission(
  91. {
  92. input: { command },
  93. mode: "build",
  94. riskLevel: bashToolEntry.metadata.riskLevel,
  95. toolName: "Bash",
  96. },
  97. withRuntimeCapability({ command }),
  98. );
  99. expect(decision.decision, command).toBe("allow");
  100. expect(decision.ruleId, command).toBe("mode.build.readOnly");
  101. }
  102. });
  103. it("keeps risky flags, redirects, and dynamic words out of the read-only Bash allowlist", () => {
  104. const commands = [
  105. "cat README.md > out.txt",
  106. "rg --pre ./filter foo src",
  107. "rg --pre=./filter foo src",
  108. "grep foo src > out.txt",
  109. "cat < /dev/tcp/example.com/80",
  110. "cat < //server/share",
  111. "sed -n '1w out.txt' README.md",
  112. "jq -f filter.jq package.json",
  113. "jq 'env' package.json",
  114. "xargs rm -rf",
  115. "docker ps --context prod",
  116. "docker logs --host tcp://example.com container",
  117. "gh pr view 123 --repo https://example.com/repo",
  118. "date tomorrow",
  119. "lsof -iTCP@example.com",
  120. "man ./local.1",
  121. "pyright --watch",
  122. "ss dst example.com",
  123. "test -v PATH",
  124. "tput clear",
  125. "rg foo src $(touch out.txt)",
  126. "FOO=bar grep foo src",
  127. ];
  128. for (const command of commands) {
  129. expect(isBashInputReadOnly({ command }), command).toBe(false);
  130. expect(isBashInputConcurrencySafe({ command }), command).toBe(false);
  131. }
  132. });
  133. it("allows common read-only inspection Bash commands in plan mode", () => {
  134. const service = new PermissionService();
  135. const commands = [
  136. "rg -n foo src",
  137. 'grep -R -n "already referenced\\|destination physical cluster" src/metaoscpp || true',
  138. "grep -R -n foo src | head -20",
  139. "grep -R -n foo src 2>/dev/null",
  140. "cat < README.md",
  141. 'find src -name "*.ts" -maxdepth 3',
  142. "find src -type f -name '*.ts'",
  143. "git status --short",
  144. "git status --porcelain --branch --untracked-files=all",
  145. "git diff --name-only --",
  146. "git diff --exit-code -- src/index.ts",
  147. "git log --oneline -n 5",
  148. "git log --oneline -8 -- tests/xxx.ts",
  149. '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',
  150. "git show --stat HEAD",
  151. "git ls-files --others --exclude-standard",
  152. "git rev-parse --show-toplevel",
  153. "git grep -n foo -- src",
  154. "git branch --show-current",
  155. 'cd "/workspace/project" && grep -R -n "foo" src',
  156. 'LC_ALL=C cd "/workspace/project" && grep -R -n "foo" src',
  157. ];
  158. for (const command of commands) {
  159. expect(isBashInputReadOnly({ command })).toBe(true);
  160. expect(isBashInputConcurrencySafe({ command })).toBe(true);
  161. const readOnlyDecision = service.checkPermission(
  162. {
  163. input: { command },
  164. mode: "plan",
  165. riskLevel: bashToolEntry.metadata.riskLevel,
  166. toolName: "Bash",
  167. },
  168. withRuntimeCapability({ command }),
  169. );
  170. expect(readOnlyDecision.decision).toBe("allow");
  171. expect(readOnlyDecision.ruleId).toBe("mode.plan.readOnly");
  172. }
  173. const writeDecision = service.checkPermission(
  174. {
  175. input: { command: "cat README.md > out.txt" },
  176. mode: "plan",
  177. riskLevel: bashToolEntry.metadata.riskLevel,
  178. toolName: "Bash",
  179. },
  180. withRuntimeCapability({ command: "cat README.md > out.txt" }),
  181. );
  182. expect(writeDecision.decision).toBe("deny");
  183. expect(writeDecision.ruleId).toBe("mode.plan.nonReadOnly");
  184. });
  185. it("allows the grep and fd readonly safe flags", () => {
  186. const commands = [
  187. "grep -c foo README.md",
  188. "grep --count foo README.md",
  189. "grep --color=never -n foo README.md",
  190. "grep --colour=never -n foo README.md",
  191. "grep --silent foo README.md",
  192. "grep -b foo README.md",
  193. "grep --byte-offset foo README.md",
  194. "grep --label stdin foo -",
  195. "grep -T foo README.md",
  196. "grep --initial-tab foo README.md",
  197. "grep -u foo README.md",
  198. "grep --unix-byte-offsets foo README.md",
  199. "grep -Z foo README.md",
  200. "grep --null foo README.md",
  201. "grep -z foo README.md",
  202. "grep --null-data foo README.md",
  203. "grep --group-separator='--' -A 1 foo README.md",
  204. "grep --no-group-separator -A 1 foo README.md",
  205. "grep -D read foo README.md",
  206. "grep --devices=read foo README.md",
  207. "grep -d skip foo README.md",
  208. "grep --line-buffered foo README.md",
  209. "grep -U foo README.md",
  210. "grep --binary foo README.md",
  211. "grep --help",
  212. "grep -V",
  213. "grep --version",
  214. "fd --ignore-case foo src",
  215. "fdfind --ignore-case foo src",
  216. ];
  217. for (const command of commands) {
  218. expect(isBashInputReadOnly({ command }), command).toBe(true);
  219. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  220. }
  221. });
  222. it("allows the direct readonly argv branches", () => {
  223. const commands = [
  224. "node -v",
  225. "node --version",
  226. "python --version",
  227. "python3 --version",
  228. "ip addr",
  229. "history",
  230. "history 20",
  231. "arch",
  232. "arch --help",
  233. "ifconfig en0",
  234. "printf '%d\\n' 42",
  235. "printf -- '%s\\n' hello",
  236. "find . -name package.json",
  237. "find . -newer marker -type f",
  238. "cal -3",
  239. "uptime",
  240. "type grep",
  241. "unexpand README.md",
  242. "tsort graph.txt",
  243. "pr README.md",
  244. ];
  245. for (const command of commands) {
  246. expect(isBashInputReadOnly({ command }), command).toBe(true);
  247. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  248. }
  249. });
  250. it("rejects direct readonly argv negative branches", () => {
  251. const commands = [
  252. "node -e 'console.log(1)'",
  253. "python -c 'print(1)'",
  254. "history abc",
  255. "arch -x",
  256. "printf -v name value",
  257. "printf '%d\\n' not-a-number",
  258. "printf '%s\\n' $(touch out.txt)",
  259. "find . -exec rm {} \\;",
  260. "find . -files0-from list",
  261. "ifconfig -a",
  262. ];
  263. for (const command of commands) {
  264. expect(isBashInputReadOnly({ command }), command).toBe(false);
  265. expect(isBashInputConcurrencySafe({ command }), command).toBe(false);
  266. }
  267. });
  268. it("requires approval for git runtime guard conditions", async () => {
  269. const service = new PermissionService();
  270. const testRoot = await mkdtemp(join(tmpdir(), "zcode-bash-git-guard-"));
  271. try {
  272. const normalRepo = join(testRoot, "normal-repo");
  273. await writeMinimalGitDir(normalRepo);
  274. expect(withRuntimeCapability({ command: "git status --short" }, normalRepo)?.readOnly).toBe(
  275. true,
  276. );
  277. const bareLike = join(testRoot, "bare-like");
  278. await writeGitIndicators(bareLike);
  279. expect(withRuntimeCapability({ command: "git status --short" }, bareLike).readOnly).toBe(
  280. false,
  281. );
  282. const redirected = join(testRoot, "redirected");
  283. const redirectedTarget = join(testRoot, "external.git");
  284. await mkdir(redirected, { recursive: true });
  285. await writeGitIndicators(redirectedTarget);
  286. await writeFile(join(redirected, ".git"), `gitdir: ${redirectedTarget}\n`);
  287. expect(withRuntimeCapability({ command: "git status --short" }, redirected).readOnly).toBe(
  288. false,
  289. );
  290. const decision = service.checkPermission(
  291. {
  292. input: { command: "git status --short" },
  293. mode: "plan",
  294. riskLevel: bashToolEntry.metadata.riskLevel,
  295. toolName: "Bash",
  296. },
  297. withRuntimeCapability({ command: "git status --short" }, bareLike),
  298. );
  299. expect(decision.decision).toBe("deny");
  300. expect(decision.ruleId).toBe("mode.plan.nonReadOnly");
  301. } finally {
  302. await rm(testRoot, { force: true, recursive: true });
  303. }
  304. });
  305. it("keeps mutating Bash commands denied in plan mode", () => {
  306. const service = new PermissionService();
  307. const commands = [
  308. "grep foo src > out.txt",
  309. "find . -exec rm {} \\;",
  310. "find . -delete",
  311. "find . -fprint out.txt",
  312. "git -c core.pager=cat status",
  313. "git -C . status --short",
  314. "git -C/tmp status --short",
  315. "git --exec-path=/tmp status",
  316. "git checkout main",
  317. 'cd "/workspace/project" && git status --short',
  318. "git status && rm out.txt",
  319. "FOO=bar grep foo src",
  320. ];
  321. for (const command of commands) {
  322. const decision = service.checkPermission(
  323. {
  324. input: { command },
  325. mode: "plan",
  326. riskLevel: bashToolEntry.metadata.riskLevel,
  327. toolName: "Bash",
  328. },
  329. withRuntimeCapability({ command }),
  330. );
  331. expect(decision.decision, command).toBe("deny");
  332. expect(decision.ruleId, command).toBe("mode.plan.nonReadOnly");
  333. }
  334. });
  335. it("allows read-only Bash commands through the real permission policy", () => {
  336. const service = new PermissionService();
  337. const lsDecision = service.checkPermission(
  338. {
  339. input: { command: "ls" },
  340. mode: "build",
  341. riskLevel: bashToolEntry.metadata.riskLevel,
  342. toolName: "Bash",
  343. },
  344. withRuntimeCapability({ command: "ls" }),
  345. );
  346. expect(lsDecision.decision).toBe("allow");
  347. expect(lsDecision.ruleId).toBe("mode.build.readOnly");
  348. const redirectDecision = service.checkPermission(
  349. {
  350. input: { command: "ls > out.txt" },
  351. mode: "build",
  352. riskLevel: bashToolEntry.metadata.riskLevel,
  353. toolName: "Bash",
  354. },
  355. withRuntimeCapability({ command: "ls > out.txt" }),
  356. );
  357. expect(redirectDecision.decision).toBe("ask");
  358. const sedDecision = service.checkPermission(
  359. {
  360. input: { command: "sed -i 's/a/b/' file.txt" },
  361. mode: "build",
  362. riskLevel: bashToolEntry.metadata.riskLevel,
  363. toolName: "Bash",
  364. },
  365. withRuntimeCapability({ command: "sed -i 's/a/b/' file.txt" }),
  366. );
  367. expect(sedDecision.decision).toBe("ask");
  368. const findExecDecision = service.checkPermission(
  369. {
  370. input: { command: "find . -exec rm {} \\;" },
  371. mode: "build",
  372. riskLevel: bashToolEntry.metadata.riskLevel,
  373. toolName: "Bash",
  374. },
  375. withRuntimeCapability({ command: "find . -exec rm {} \\;" }),
  376. );
  377. expect(findExecDecision.decision).toBe("ask");
  378. const treeOutputDecision = service.checkPermission(
  379. {
  380. input: { command: "tree -o out.txt" },
  381. mode: "build",
  382. riskLevel: bashToolEntry.metadata.riskLevel,
  383. toolName: "Bash",
  384. },
  385. withRuntimeCapability({ command: "tree -o out.txt" }),
  386. );
  387. expect(treeOutputDecision.decision).toBe("ask");
  388. const treeSafeFlagDecision = service.checkPermission(
  389. {
  390. input: { command: "tree -L 2" },
  391. mode: "build",
  392. riskLevel: bashToolEntry.metadata.riskLevel,
  393. toolName: "Bash",
  394. },
  395. withRuntimeCapability({ command: "tree -L 2" }),
  396. );
  397. expect(treeSafeFlagDecision.decision).toBe("allow");
  398. expect(treeSafeFlagDecision.ruleId).toBe("mode.build.readOnly");
  399. const multilineDecision = service.checkPermission(
  400. {
  401. input: { command: "ls\nrm file.txt" },
  402. mode: "build",
  403. riskLevel: bashToolEntry.metadata.riskLevel,
  404. toolName: "Bash",
  405. },
  406. withRuntimeCapability({ command: "ls\nrm file.txt" }),
  407. );
  408. expect(multilineDecision.decision).toBe("ask");
  409. const commandSubstitutionDecision = service.checkPermission(
  410. {
  411. input: { command: "ls $(touch out.txt)" },
  412. mode: "build",
  413. riskLevel: bashToolEntry.metadata.riskLevel,
  414. toolName: "Bash",
  415. },
  416. withRuntimeCapability({ command: "ls $(touch out.txt)" }),
  417. );
  418. expect(commandSubstitutionDecision.decision).toBe("ask");
  419. });
  420. it("prepares a conservative matcher when Bash security parsing is unavailable", () => {
  421. const envMatcher = prepareBashPermissionMatcher({
  422. command: "FOO=bar git push origin main",
  423. });
  424. expect(envMatcher?.("git push")).toBe(true);
  425. expect(envMatcher?.("git push:*")).toBe(true);
  426. expect(envMatcher?.("npm *")).toBe(true);
  427. const compoundMatcher = prepareBashPermissionMatcher({
  428. command: "ls && git status",
  429. });
  430. expect(compoundMatcher?.("ls")).toBe(true);
  431. expect(compoundMatcher?.("git status")).toBe(true);
  432. expect(compoundMatcher?.("git:*")).toBe(true);
  433. expect(compoundMatcher?.("rm *")).toBe(true);
  434. const commandSubstitutionMatcher = prepareBashPermissionMatcher({
  435. command: "ls $(touch out.txt)",
  436. });
  437. expect(commandSubstitutionMatcher?.("ls")).toBe(true);
  438. expect(commandSubstitutionMatcher?.("rm *")).toBe(true);
  439. const emptyMatcher = prepareBashPermissionMatcher({ command: "" });
  440. expect(emptyMatcher?.("anything")).toBe(false);
  441. });
  442. });
  443. function withRuntimeCapability(input: unknown, cwd = process.cwd()): PermissionToolCapability {
  444. const runtimeCapability = bashToolEntry.resolvePermissionCapability?.(input, {
  445. workingDirectory: cwd,
  446. workspaceRoot: cwd,
  447. } as never);
  448. return {
  449. ...bashToolEntry.metadata,
  450. ...runtimeCapability,
  451. permission: bashToolEntry.permission,
  452. ...(runtimeCapability?.permission
  453. ? { permission: { ...bashToolEntry.permission, ...runtimeCapability.permission } }
  454. : undefined),
  455. };
  456. }
  457. async function writeMinimalGitDir(repoPath: string): Promise<void> {
  458. await mkdir(join(repoPath, ".git", "objects"), { recursive: true });
  459. await mkdir(join(repoPath, ".git", "refs"), { recursive: true });
  460. await writeFile(join(repoPath, ".git", "HEAD"), "ref: refs/heads/main\n");
  461. }
  462. async function writeGitIndicators(repoPath: string): Promise<void> {
  463. await mkdir(join(repoPath, "objects"), { recursive: true });
  464. await mkdir(join(repoPath, "refs"), { recursive: true });
  465. await writeFile(join(repoPath, "HEAD"), "ref: refs/heads/main\n");
  466. }