bash-permission.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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 SessionEvent,
  12. } from "@zcode/contracts";
  13. import {
  14. defaultPermissionConfig,
  15. PermissionService,
  16. type PermissionToolCapability,
  17. } from "../src/permission/service.js";
  18. import { createToolExecutor } from "../src/tool/executor.js";
  19. import { createToolRegistry } from "../src/tool/registry.js";
  20. import {
  21. bashToolEntry,
  22. isBashInputConcurrencySafe,
  23. isBashInputReadOnly,
  24. prepareBashPermissionMatcher,
  25. } from "../src/tool/handlers/bash.js";
  26. describe("bash runtime permission capability", () => {
  27. it("keeps display classification separate from read-only and concurrency helpers", () => {
  28. expect(isBashInputReadOnly({ command: "ls" })).toBe(true);
  29. expect(isBashInputConcurrencySafe({ command: "ls" })).toBe(true);
  30. expect(isBashInputReadOnly({ command: "ls > out.txt" })).toBe(false);
  31. expect(isBashInputConcurrencySafe({ command: "ls > out.txt" })).toBe(false);
  32. expect(isBashInputReadOnly({ command: "find . -exec rm {} \\;" })).toBe(false);
  33. expect(isBashInputReadOnly({ command: "ls $(touch out.txt)" })).toBe(false);
  34. expect(isBashInputConcurrencySafe({ command: "ls $(touch out.txt)" })).toBe(false);
  35. expect(isBashInputReadOnly({ command: "ls `touch out.txt`" })).toBe(false);
  36. });
  37. it("uses command safe flags for tree read-only permission", () => {
  38. expect(isBashInputReadOnly({ command: "tree" })).toBe(true);
  39. expect(isBashInputReadOnly({ command: "tree -a" })).toBe(true);
  40. expect(isBashInputReadOnly({ command: "tree -L 2" })).toBe(true);
  41. expect(isBashInputReadOnly({ command: "tree --charset utf-8 src" })).toBe(true);
  42. expect(isBashInputReadOnly({ command: "tree -o out.txt" })).toBe(false);
  43. expect(isBashInputConcurrencySafe({ command: "tree -o out.txt" })).toBe(false);
  44. expect(isBashInputReadOnly({ command: "tree --bogus" })).toBe(false);
  45. });
  46. it("allows a minimal set of simple read-only file and search commands", () => {
  47. const service = new PermissionService();
  48. const commands = [
  49. "pwd",
  50. "whoami",
  51. "echo hello",
  52. "printf '%s\\n' hello",
  53. "cat README.md",
  54. "cat < README.md",
  55. "cat -n README.md",
  56. "fd --hidden foo src",
  57. "fdfind -e ts foo src",
  58. "head -n 20 README.md",
  59. "tail --lines=50 README.md",
  60. "wc -l README.md",
  61. "stat README.md",
  62. "file README.md",
  63. "base64 -d fixture.txt",
  64. "sha256sum package.json",
  65. "date +%F",
  66. "hostname -f",
  67. "man ls",
  68. "netstat -an",
  69. "ps -ef",
  70. "lsof -n -i",
  71. "pgrep -fl node",
  72. "pyright --outputjson",
  73. "ss -tuln",
  74. "test -f package.json",
  75. "tput cols",
  76. "strings fixture.bin",
  77. "jq '.scripts' package.json",
  78. "xargs grep -n foo",
  79. "sort README.md",
  80. "uniq README.md",
  81. "cut -d: -f1 README.md",
  82. "tr a-z A-Z README.md",
  83. "diff -u before.txt after.txt",
  84. "du -sh .",
  85. "docker ps --format '{{.Names}}'",
  86. "docker logs --tail 20 container",
  87. "gh pr view 123 --json title --repo owner/repo",
  88. "gh run list --limit 10 --json databaseId",
  89. "rg -n foo src",
  90. "rg --files src",
  91. "rg -g '*.ts' foo src",
  92. "grep -R -n foo src",
  93. "grep -R -n foo src 2>&1",
  94. "grep -R -n foo src 2>/dev/null",
  95. "grep --include '*.ts' foo src",
  96. "LC_ALL=C grep -R -n foo src",
  97. "command grep -R -n foo src",
  98. "noglob grep -R -n foo src",
  99. ];
  100. for (const command of commands) {
  101. expect(isBashInputReadOnly({ command }), command).toBe(true);
  102. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  103. const decision = service.checkPermission(
  104. {
  105. input: { command },
  106. mode: "build",
  107. riskLevel: bashToolEntry.metadata.riskLevel,
  108. toolName: "Bash",
  109. },
  110. withRuntimeCapability({ command }),
  111. );
  112. expect(decision.decision, command).toBe("allow");
  113. expect(decision.ruleId, command).toBe("mode.build.readOnly");
  114. }
  115. });
  116. it("keeps risky flags, redirects, and dynamic words out of the read-only Bash allowlist", () => {
  117. const commands = [
  118. "cat README.md > out.txt",
  119. "rg --pre ./filter foo src",
  120. "rg --pre=./filter foo src",
  121. "grep foo src > out.txt",
  122. "cat < /dev/tcp/example.com/80",
  123. "cat < //server/share",
  124. "sed -n '1w out.txt' README.md",
  125. "jq -f filter.jq package.json",
  126. "jq 'env' package.json",
  127. "xargs rm -rf",
  128. "docker ps --context prod",
  129. "docker logs --host tcp://example.com container",
  130. "gh pr view 123 --repo https://example.com/repo",
  131. "date tomorrow",
  132. "lsof -iTCP@example.com",
  133. "man ./local.1",
  134. "pyright --watch",
  135. "ss dst example.com",
  136. "test -v PATH",
  137. "tput clear",
  138. "rg foo src $(touch out.txt)",
  139. "FOO=bar grep foo src",
  140. ];
  141. for (const command of commands) {
  142. expect(isBashInputReadOnly({ command }), command).toBe(false);
  143. expect(isBashInputConcurrencySafe({ command }), command).toBe(false);
  144. }
  145. });
  146. it.each([
  147. "sed -n '1,20p' README.md",
  148. "sed -n 'p' README.md",
  149. "sed -n '1p; 3p' README.md",
  150. "sed -nE '1p' README.md",
  151. "sed -En '1p' README.md",
  152. "sed --quiet '1p' README.md",
  153. "sed --silent '1p' README.md",
  154. "sed -nz '1p' README.md",
  155. "sed --quiet --regexp-extended --zero-terminated '1p' README.md",
  156. "sed --posix -n '1p' README.md",
  157. "sed -n -- '1p' README.md",
  158. "sed -n '1p' -",
  159. "sed 's/foo/bar/g'",
  160. "sed -- 's/foo/bar/g'",
  161. "sed -E 's/(foo)/\\1/g'",
  162. "sed -r 's/foo/bar/2gp'",
  163. "sed --posix 's/foo/bar/'",
  164. "sed 's/a\\/b/c/'",
  165. "sed 's/a/b\\/c/'",
  166. "sed 's/\\\\/x/'",
  167. "sed 's/foo/\\& bar/g'",
  168. "command sed -n '1p' README.md",
  169. "LC_ALL=C sed -n '1p' README.md",
  170. "cat README.md | sed -n '1p'",
  171. "cat README.md | sed 's/foo/bar/g'",
  172. "sed -n '1p' README.md && cat README.md",
  173. ])("allows only the bounded sed read-only grammar: %s", (command) => {
  174. const input = { command };
  175. const capability = withRuntimeCapability(input);
  176. const service = new PermissionService();
  177. expect(isBashInputReadOnly(input)).toBe(true);
  178. expect(isBashInputConcurrencySafe(input)).toBe(true);
  179. expect(capability).toMatchObject({
  180. readOnly: true,
  181. needsApproval: false,
  182. sideEffectScope: "none",
  183. });
  184. for (const context of [
  185. { mode: "plan" },
  186. { mode: "build", planEnabled: true },
  187. { mode: "yolo", planEnabled: true },
  188. { mode: "guarded", planEnabled: true },
  189. { mode: "build" },
  190. ] as const) {
  191. expect(
  192. service.checkPermission(
  193. { input, ...context, riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  194. capability,
  195. ).decision,
  196. ).toBe("allow");
  197. }
  198. });
  199. it.each([
  200. "sed -n -e 'e printf sed-probe' README.md",
  201. "sed --expression='e printf sed-probe' README.md",
  202. "sed 'e printf sed-probe' README.md",
  203. "sed -n 's/.*/printf sed-probe/e' README.md",
  204. "sed -n 's/.*/probe/w out.txt' README.md",
  205. "sed 's/foo/printf sed-probe/e'",
  206. "sed 's/foo/bar/w out.txt'",
  207. "sed -e 's/foo/bar/' README.md",
  208. "sed -n -e '1p' README.md",
  209. "sed -ne '1p' README.md",
  210. "sed --expression='1p' README.md",
  211. "sed -f script.sed README.md",
  212. "sed --file=script.sed README.md",
  213. "sed -in '1p' README.md",
  214. "sed --in-place -n '1p' README.md",
  215. "sed -n '1p' README.md -e 'e printf sed-probe'",
  216. "sed -n -- '1p' -e 'e printf sed-probe'",
  217. "sed -n '1p' -- README.md",
  218. "sed -n '1p; e printf sed-probe' README.md",
  219. "sed -n '1p\ne printf sed-probe' README.md",
  220. "sed -n '1p\r' README.md",
  221. "sed -n '1p\0' README.md",
  222. "sed -n '0p' README.md",
  223. "sed -n '$p' README.md",
  224. "sed -n '/foo/p' README.md",
  225. "sed -n '1p;' README.md",
  226. "sed -n '' README.md",
  227. "sed -n",
  228. "sed -n --",
  229. "sed 's/foo/bar/g' README.md",
  230. "sed -n 's/foo/bar/p'",
  231. "sed -z 's/foo/bar/g'",
  232. "sed 's/foo/bar/10'",
  233. "sed 's/foo/bar/0'",
  234. "sed 's/foo/bar/;e printf sed-probe'",
  235. "sed 's/foo/bar/\ne printf sed-probe'",
  236. "sed 's#foo#bar#g'",
  237. "sed 's/foo/bar'",
  238. "sed 's/foo/bar\\/'",
  239. "sed 's/foo/\\x0a/g'",
  240. "sed 's/foo/\\cA/g'",
  241. "sed -n '1p' README.md > out.txt",
  242. "cat README.md | sed 'e printf sed-probe'",
  243. "sed -n '1p' README.md && sed 's/.*/printf sed-probe/e'",
  244. "sed --version",
  245. "/usr/bin/sed -n '1p' README.md",
  246. ])("rejects sed outside the bounded read-only grammar: %s", (command) => {
  247. const input = { command };
  248. const capability = withRuntimeCapability(input);
  249. const service = new PermissionService();
  250. expect(isBashInputReadOnly(input)).toBe(false);
  251. expect(isBashInputConcurrencySafe(input)).toBe(false);
  252. expect(capability.readOnly).toBe(false);
  253. for (const context of [
  254. { mode: "plan" },
  255. { mode: "build", planEnabled: true },
  256. { mode: "edit", planEnabled: true },
  257. { mode: "yolo", planEnabled: true },
  258. { mode: "guarded", planEnabled: true },
  259. ] as const) {
  260. expect(
  261. service.checkPermission(
  262. { input, ...context, riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  263. capability,
  264. ),
  265. ).toMatchObject({ allowed: false, decision: "deny", ruleId: "mode.plan.nonReadOnly" });
  266. }
  267. expect(
  268. service.checkPermission(
  269. { input, mode: "build", riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  270. capability,
  271. ).decision,
  272. ).toBe("ask");
  273. });
  274. it("keeps sed authorizations subject to Plan while preserving normal execution permissions", () => {
  275. const input = { command: "sed 'e printf sed-probe' README.md" };
  276. const capability = withRuntimeCapability(input);
  277. const service = new PermissionService({
  278. ...defaultPermissionConfig,
  279. allowedTools: new Set(["Bash"]),
  280. });
  281. const projectRules = { version: 1 as const, allow: [{ toolName: "Bash" }] };
  282. for (const context of [
  283. { mode: "plan" },
  284. { mode: "build", planEnabled: true },
  285. { mode: "yolo", planEnabled: true },
  286. { mode: "guarded", planEnabled: true },
  287. ] as const) {
  288. expect(
  289. service.checkPermission(
  290. { input, ...context, riskLevel: bashToolEntry.metadata.riskLevel, toolName: "Bash" },
  291. capability,
  292. projectRules,
  293. ),
  294. ).toMatchObject({ decision: "deny", ruleId: "mode.plan.nonReadOnly" });
  295. }
  296. for (const mode of ["build", "yolo", "guarded"] as const) {
  297. expect(
  298. service.checkPermission(
  299. {
  300. input,
  301. mode,
  302. planEnabled: false,
  303. riskLevel: bashToolEntry.metadata.riskLevel,
  304. toolName: "Bash",
  305. },
  306. capability,
  307. projectRules,
  308. ).decision,
  309. ).toBe("allow");
  310. }
  311. });
  312. it("denies sed before execution and emits a denial without requesting approval", async () => {
  313. const registry = createToolRegistry();
  314. registry.register(bashToolEntry);
  315. const events: SessionEvent[] = [];
  316. const run = vi.fn<ExecutionPort["run"]>(async () => {
  317. throw new Error("Plan must not reach the execution port");
  318. });
  319. const requestPermission = vi.fn(async () => ({
  320. decision: "allow" as const,
  321. resolvedAt: new Date(),
  322. }));
  323. const executor = createToolExecutor({
  324. registry,
  325. permissionService: new PermissionService(),
  326. permissionBroker: { requestPermission },
  327. executionPort: { run },
  328. mode: "plan",
  329. workingDirectory: process.cwd(),
  330. workspaceRoot: process.cwd(),
  331. sessionId: createSessionId("sed-plan-denial"),
  332. emitEvent: async (event) => {
  333. events.push(event);
  334. },
  335. });
  336. const toolCallId = createToolCallId("sed-plan-call");
  337. const result = await executor.execute({
  338. id: toolCallId,
  339. name: "Bash",
  340. input: { command: "sed -n -e 'e printf sed-probe' README.md" },
  341. });
  342. expect(run).not.toHaveBeenCalled();
  343. expect(result).toMatchObject({
  344. success: false,
  345. error: { type: CoreErrorType.PermissionDenied },
  346. });
  347. expect(requestPermission).not.toHaveBeenCalled();
  348. expect(
  349. events.filter((event) => event.type === SessionEventType.PermissionDenied),
  350. ).toMatchObject([{ payload: { toolCallId, toolName: "Bash" } }]);
  351. expect(events.some((event) => event.type === SessionEventType.PermissionRequested)).toBe(false);
  352. });
  353. it("allows common read-only inspection Bash commands in plan mode", () => {
  354. const service = new PermissionService();
  355. const commands = [
  356. "rg -n foo src",
  357. 'grep -R -n "already referenced\\|destination physical cluster" src/metaoscpp || true',
  358. "grep -R -n foo src | head -20",
  359. "grep -R -n foo src 2>/dev/null",
  360. "cat < README.md",
  361. 'find src -name "*.ts" -maxdepth 3',
  362. "find src -type f -name '*.ts'",
  363. "git status --short",
  364. "git status --porcelain --branch --untracked-files=all",
  365. "git diff --name-only --",
  366. "git diff --exit-code -- src/index.ts",
  367. "git log --oneline -n 5",
  368. "git log --oneline -8 -- tests/xxx.ts",
  369. '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',
  370. "git show --stat HEAD",
  371. "git ls-files --others --exclude-standard",
  372. "git rev-parse --show-toplevel",
  373. "git grep -n foo -- src",
  374. "git branch --show-current",
  375. 'cd "/workspace/project" && grep -R -n "foo" src',
  376. 'LC_ALL=C cd "/workspace/project" && grep -R -n "foo" src',
  377. ];
  378. for (const command of commands) {
  379. expect(isBashInputReadOnly({ command })).toBe(true);
  380. expect(isBashInputConcurrencySafe({ command })).toBe(true);
  381. const readOnlyDecision = service.checkPermission(
  382. {
  383. input: { command },
  384. mode: "plan",
  385. riskLevel: bashToolEntry.metadata.riskLevel,
  386. toolName: "Bash",
  387. },
  388. withRuntimeCapability({ command }),
  389. );
  390. expect(readOnlyDecision.decision).toBe("allow");
  391. expect(readOnlyDecision.ruleId).toBe("mode.plan.readOnly");
  392. }
  393. const writeDecision = service.checkPermission(
  394. {
  395. input: { command: "cat README.md > out.txt" },
  396. mode: "plan",
  397. riskLevel: bashToolEntry.metadata.riskLevel,
  398. toolName: "Bash",
  399. },
  400. withRuntimeCapability({ command: "cat README.md > out.txt" }),
  401. );
  402. expect(writeDecision.decision).toBe("deny");
  403. expect(writeDecision.ruleId).toBe("mode.plan.nonReadOnly");
  404. });
  405. it("allows the grep and fd readonly safe flags", () => {
  406. const commands = [
  407. "grep -c foo README.md",
  408. "grep --count foo README.md",
  409. "grep --color=never -n foo README.md",
  410. "grep --colour=never -n foo README.md",
  411. "grep --silent foo README.md",
  412. "grep -b foo README.md",
  413. "grep --byte-offset foo README.md",
  414. "grep --label stdin foo -",
  415. "grep -T foo README.md",
  416. "grep --initial-tab foo README.md",
  417. "grep -u foo README.md",
  418. "grep --unix-byte-offsets foo README.md",
  419. "grep -Z foo README.md",
  420. "grep --null foo README.md",
  421. "grep -z foo README.md",
  422. "grep --null-data foo README.md",
  423. "grep --group-separator='--' -A 1 foo README.md",
  424. "grep --no-group-separator -A 1 foo README.md",
  425. "grep -D read foo README.md",
  426. "grep --devices=read foo README.md",
  427. "grep -d skip foo README.md",
  428. "grep --line-buffered foo README.md",
  429. "grep -U foo README.md",
  430. "grep --binary foo README.md",
  431. "grep --help",
  432. "grep -V",
  433. "grep --version",
  434. "fd --ignore-case foo src",
  435. "fdfind --ignore-case foo src",
  436. ];
  437. for (const command of commands) {
  438. expect(isBashInputReadOnly({ command }), command).toBe(true);
  439. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  440. }
  441. });
  442. it("allows the direct readonly argv branches", () => {
  443. const commands = [
  444. "node -v",
  445. "node --version",
  446. "python --version",
  447. "python3 --version",
  448. "ip addr",
  449. "history",
  450. "history 20",
  451. "arch",
  452. "arch --help",
  453. "ifconfig en0",
  454. "printf '%d\\n' 42",
  455. "printf -- '%s\\n' hello",
  456. "find . -name package.json",
  457. "find . -newer marker -type f",
  458. "cal -3",
  459. "uptime",
  460. "type grep",
  461. "unexpand README.md",
  462. "tsort graph.txt",
  463. "pr README.md",
  464. ];
  465. for (const command of commands) {
  466. expect(isBashInputReadOnly({ command }), command).toBe(true);
  467. expect(isBashInputConcurrencySafe({ command }), command).toBe(true);
  468. }
  469. });
  470. it("rejects direct readonly argv negative branches", () => {
  471. const commands = [
  472. "node -e 'console.log(1)'",
  473. "python -c 'print(1)'",
  474. "history abc",
  475. "arch -x",
  476. "printf -v name value",
  477. "printf '%d\\n' not-a-number",
  478. "printf '%s\\n' $(touch out.txt)",
  479. "find . -exec rm {} \\;",
  480. "find . -files0-from list",
  481. "ifconfig -a",
  482. ];
  483. for (const command of commands) {
  484. expect(isBashInputReadOnly({ command }), command).toBe(false);
  485. expect(isBashInputConcurrencySafe({ command }), command).toBe(false);
  486. }
  487. });
  488. it("requires approval for git runtime guard conditions", async () => {
  489. const service = new PermissionService();
  490. const testRoot = await mkdtemp(join(tmpdir(), "zcode-bash-git-guard-"));
  491. try {
  492. const normalRepo = join(testRoot, "normal-repo");
  493. await writeMinimalGitDir(normalRepo);
  494. expect(withRuntimeCapability({ command: "git status --short" }, normalRepo)?.readOnly).toBe(
  495. true,
  496. );
  497. const bareLike = join(testRoot, "bare-like");
  498. await writeGitIndicators(bareLike);
  499. expect(withRuntimeCapability({ command: "git status --short" }, bareLike).readOnly).toBe(
  500. false,
  501. );
  502. const redirected = join(testRoot, "redirected");
  503. const redirectedTarget = join(testRoot, "external.git");
  504. await mkdir(redirected, { recursive: true });
  505. await writeGitIndicators(redirectedTarget);
  506. await writeFile(join(redirected, ".git"), `gitdir: ${redirectedTarget}\n`);
  507. expect(withRuntimeCapability({ command: "git status --short" }, redirected).readOnly).toBe(
  508. false,
  509. );
  510. const decision = service.checkPermission(
  511. {
  512. input: { command: "git status --short" },
  513. mode: "plan",
  514. riskLevel: bashToolEntry.metadata.riskLevel,
  515. toolName: "Bash",
  516. },
  517. withRuntimeCapability({ command: "git status --short" }, bareLike),
  518. );
  519. expect(decision.decision).toBe("deny");
  520. expect(decision.ruleId).toBe("mode.plan.nonReadOnly");
  521. } finally {
  522. await rm(testRoot, { force: true, recursive: true });
  523. }
  524. });
  525. it("keeps mutating Bash commands denied in plan mode", () => {
  526. const service = new PermissionService();
  527. const commands = [
  528. "grep foo src > out.txt",
  529. "find . -exec rm {} \\;",
  530. "find . -delete",
  531. "find . -fprint out.txt",
  532. "git -c core.pager=cat status",
  533. "git -C . status --short",
  534. "git -C/tmp status --short",
  535. "git --exec-path=/tmp status",
  536. "git checkout main",
  537. 'cd "/workspace/project" && git status --short',
  538. "git status && rm out.txt",
  539. "FOO=bar grep foo src",
  540. ];
  541. for (const command of commands) {
  542. const decision = service.checkPermission(
  543. {
  544. input: { command },
  545. mode: "plan",
  546. riskLevel: bashToolEntry.metadata.riskLevel,
  547. toolName: "Bash",
  548. },
  549. withRuntimeCapability({ command }),
  550. );
  551. expect(decision.decision, command).toBe("deny");
  552. expect(decision.ruleId, command).toBe("mode.plan.nonReadOnly");
  553. }
  554. });
  555. it("allows read-only Bash commands through the real permission policy", () => {
  556. const service = new PermissionService();
  557. const lsDecision = service.checkPermission(
  558. {
  559. input: { command: "ls" },
  560. mode: "build",
  561. riskLevel: bashToolEntry.metadata.riskLevel,
  562. toolName: "Bash",
  563. },
  564. withRuntimeCapability({ command: "ls" }),
  565. );
  566. expect(lsDecision.decision).toBe("allow");
  567. expect(lsDecision.ruleId).toBe("mode.build.readOnly");
  568. const redirectDecision = service.checkPermission(
  569. {
  570. input: { command: "ls > out.txt" },
  571. mode: "build",
  572. riskLevel: bashToolEntry.metadata.riskLevel,
  573. toolName: "Bash",
  574. },
  575. withRuntimeCapability({ command: "ls > out.txt" }),
  576. );
  577. expect(redirectDecision.decision).toBe("ask");
  578. const sedDecision = service.checkPermission(
  579. {
  580. input: { command: "sed -i 's/a/b/' file.txt" },
  581. mode: "build",
  582. riskLevel: bashToolEntry.metadata.riskLevel,
  583. toolName: "Bash",
  584. },
  585. withRuntimeCapability({ command: "sed -i 's/a/b/' file.txt" }),
  586. );
  587. expect(sedDecision.decision).toBe("ask");
  588. const findExecDecision = service.checkPermission(
  589. {
  590. input: { command: "find . -exec rm {} \\;" },
  591. mode: "build",
  592. riskLevel: bashToolEntry.metadata.riskLevel,
  593. toolName: "Bash",
  594. },
  595. withRuntimeCapability({ command: "find . -exec rm {} \\;" }),
  596. );
  597. expect(findExecDecision.decision).toBe("ask");
  598. const treeOutputDecision = service.checkPermission(
  599. {
  600. input: { command: "tree -o out.txt" },
  601. mode: "build",
  602. riskLevel: bashToolEntry.metadata.riskLevel,
  603. toolName: "Bash",
  604. },
  605. withRuntimeCapability({ command: "tree -o out.txt" }),
  606. );
  607. expect(treeOutputDecision.decision).toBe("ask");
  608. const treeSafeFlagDecision = service.checkPermission(
  609. {
  610. input: { command: "tree -L 2" },
  611. mode: "build",
  612. riskLevel: bashToolEntry.metadata.riskLevel,
  613. toolName: "Bash",
  614. },
  615. withRuntimeCapability({ command: "tree -L 2" }),
  616. );
  617. expect(treeSafeFlagDecision.decision).toBe("allow");
  618. expect(treeSafeFlagDecision.ruleId).toBe("mode.build.readOnly");
  619. const multilineDecision = service.checkPermission(
  620. {
  621. input: { command: "ls\nrm file.txt" },
  622. mode: "build",
  623. riskLevel: bashToolEntry.metadata.riskLevel,
  624. toolName: "Bash",
  625. },
  626. withRuntimeCapability({ command: "ls\nrm file.txt" }),
  627. );
  628. expect(multilineDecision.decision).toBe("ask");
  629. const commandSubstitutionDecision = service.checkPermission(
  630. {
  631. input: { command: "ls $(touch out.txt)" },
  632. mode: "build",
  633. riskLevel: bashToolEntry.metadata.riskLevel,
  634. toolName: "Bash",
  635. },
  636. withRuntimeCapability({ command: "ls $(touch out.txt)" }),
  637. );
  638. expect(commandSubstitutionDecision.decision).toBe("ask");
  639. });
  640. it("prepares a conservative matcher when Bash security parsing is unavailable", () => {
  641. const envMatcher = prepareBashPermissionMatcher({
  642. command: "FOO=bar git push origin main",
  643. });
  644. expect(envMatcher?.("git push")).toBe(true);
  645. expect(envMatcher?.("git push:*")).toBe(true);
  646. expect(envMatcher?.("npm *")).toBe(true);
  647. const compoundMatcher = prepareBashPermissionMatcher({
  648. command: "ls && git status",
  649. });
  650. expect(compoundMatcher?.("ls")).toBe(true);
  651. expect(compoundMatcher?.("git status")).toBe(true);
  652. expect(compoundMatcher?.("git:*")).toBe(true);
  653. expect(compoundMatcher?.("rm *")).toBe(true);
  654. const commandSubstitutionMatcher = prepareBashPermissionMatcher({
  655. command: "ls $(touch out.txt)",
  656. });
  657. expect(commandSubstitutionMatcher?.("ls")).toBe(true);
  658. expect(commandSubstitutionMatcher?.("rm *")).toBe(true);
  659. const emptyMatcher = prepareBashPermissionMatcher({ command: "" });
  660. expect(emptyMatcher?.("anything")).toBe(false);
  661. });
  662. });
  663. function withRuntimeCapability(input: unknown, cwd = process.cwd()): PermissionToolCapability {
  664. const runtimeCapability = bashToolEntry.resolvePermissionCapability?.(input, {
  665. workingDirectory: cwd,
  666. workspaceRoot: cwd,
  667. } as never);
  668. return {
  669. ...bashToolEntry.metadata,
  670. ...runtimeCapability,
  671. permission: bashToolEntry.permission,
  672. ...(runtimeCapability?.permission
  673. ? { permission: { ...bashToolEntry.permission, ...runtimeCapability.permission } }
  674. : undefined),
  675. };
  676. }
  677. async function writeMinimalGitDir(repoPath: string): Promise<void> {
  678. await mkdir(join(repoPath, ".git", "objects"), { recursive: true });
  679. await mkdir(join(repoPath, ".git", "refs"), { recursive: true });
  680. await writeFile(join(repoPath, ".git", "HEAD"), "ref: refs/heads/main\n");
  681. }
  682. async function writeGitIndicators(repoPath: string): Promise<void> {
  683. await mkdir(join(repoPath, "objects"), { recursive: true });
  684. await mkdir(join(repoPath, "refs"), { recursive: true });
  685. await writeFile(join(repoPath, "HEAD"), "ref: refs/heads/main\n");
  686. }