guarded-command.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { describe, expect, it } from "vitest";
  2. import { execFile } from "node:child_process";
  3. import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { analyzeBashCommand } from "../src/tool/handlers/bash-command-parser.js";
  8. import { matchDangerousCommand } from "../src/tool/handlers/guarded/command.js";
  9. import { optionTable, parseOptions } from "../src/tool/handlers/guarded/options.js";
  10. const matches = [
  11. [
  12. "remove-critical-path",
  13. "rm -rf build",
  14. "rm -f -R build",
  15. "rm --recursive --force build",
  16. 'rm -rf "$target"',
  17. "rm -rf -- -i",
  18. "rm -rfi build",
  19. ],
  20. [
  21. "system-storage",
  22. "dd if=in of=out",
  23. "mount /dev/disk /mnt",
  24. "umount /mnt",
  25. "mkfs /dev/disk",
  26. "mkfs.ext4 /dev/disk",
  27. ],
  28. [
  29. "git-reset-hard",
  30. "git reset --hard",
  31. "git -C repo reset --hard HEAD",
  32. "git --git-dir=repo reset --hard",
  33. ],
  34. [
  35. "git-clean-force",
  36. "git clean -fd",
  37. "git clean -dfx",
  38. "git clean -f file",
  39. "git clean -f -- --dry-run",
  40. ],
  41. [
  42. "git-push-force",
  43. "git push -f origin main",
  44. "git push --force-with-lease",
  45. "git push --mirror",
  46. "git push origin +HEAD:main",
  47. "git push --force origin 'refs/heads/*:refs/heads/*'",
  48. "git push --force --no-dry-run",
  49. "git push --force-with-lease --no-force",
  50. ],
  51. [
  52. "git-discard-tree",
  53. "git checkout -f main",
  54. "git checkout HEAD -- .",
  55. "git restore .",
  56. "git restore --staged --worktree ./",
  57. "git restore --source=HEAD :/",
  58. ],
  59. ["git-stash-clear", "git stash clear"],
  60. ["git-worktree-force-remove", "git worktree remove -ff path", "git worktree remove --force path"],
  61. [
  62. "rsync-delete",
  63. "rsync -a --delete src/ dest/",
  64. "rsync --del src/ dest/",
  65. "rsync --delete-before src/ dest/",
  66. "rsync --delete-during src/ dest/",
  67. "rsync --delete-delay src/ dest/",
  68. "rsync --delete-after src/ dest/",
  69. "rsync --delete-excluded src/ dest/",
  70. ],
  71. ] as const;
  72. describe("Guarded finite command contract", () => {
  73. for (const dialect of ["posix", "git-bash", "cmd"] as const) {
  74. it.each([
  75. "git push origin +refs/heads/*:refs/heads/*",
  76. 'git push origin "+refs/heads/*:refs/heads/*"',
  77. 'git push origin "+main"',
  78. 'git push --force origin "refs/heads/*:refs/heads/*"',
  79. "git push --repo origin +refs/heads/*:refs/heads/*",
  80. ])(`recognizes force refspecs in ${dialect}: %s`, (command) => {
  81. expect(matchDangerousCommand(command, dialect)).toMatchObject({
  82. status: "matched",
  83. ruleId: "safety.bash.git-push-force",
  84. });
  85. });
  86. it.each([
  87. "git push --dry-run origin +refs/heads/*:refs/heads/*",
  88. "git push -n origin +refs/heads/*:refs/heads/*",
  89. "git push origin refs/heads/*:refs/heads/*",
  90. 'git push --push-option "+refs/heads/*:refs/heads/*" origin main',
  91. 'git push --repo "+refs/heads/*:refs/heads/*" main',
  92. 'git push "+refs/heads/*:refs/heads/*" main',
  93. ])(`preserves force refspec boundaries in ${dialect}: %s`, (command) => {
  94. expect(matchDangerousCommand(command, dialect).status).not.toBe("matched");
  95. });
  96. }
  97. for (const [id, ...commands] of matches) {
  98. it.each(commands)(`${id}: %s`, (command) => {
  99. expect(matchDangerousCommand(command, "posix")).toMatchObject({
  100. status: "matched",
  101. ruleId: `safety.bash.${id}`,
  102. });
  103. });
  104. }
  105. it.each([
  106. "env A=b rm -rf build",
  107. "env -u A rm -rf build",
  108. "time -o file rm -rf build",
  109. "/usr/bin/time --output=file rm -rf build",
  110. "sudo -u root rm -rf build",
  111. "env -C repo time -f '%e' sudo --user=root rm -rf build",
  112. "echo hello; rm -rf build",
  113. "false || rm -rf build",
  114. "true && rm -rf build",
  115. "echo hi | rm -rf build",
  116. '"/bin/rm" -rf build',
  117. "r\\m -rf build",
  118. "for x in a; do echo hi; done; rm -rf build",
  119. ])("recognizes reliable command nodes: %s", (command) => {
  120. expect(matchDangerousCommand(command, "posix").status).toBe("matched");
  121. });
  122. it.each([
  123. "rm -f file",
  124. "rm -- -rf",
  125. "rm --help",
  126. "rm --version",
  127. "mount",
  128. "dd --help",
  129. "mount --version",
  130. "mkfs --help",
  131. "git reset --soft HEAD",
  132. "git reset -- --hard",
  133. "git clean -nfd",
  134. "git clean -fd --dry-run",
  135. "git clean -fd -e --dry-run --dry-run",
  136. "git push -nf",
  137. "git push --force --no-force",
  138. "git push --force-if-includes",
  139. "git push --force-with-lease --no-force-with-lease",
  140. "git push --mirror --no-mirror",
  141. "git push --repo +not-a-refspec",
  142. "git push --push-option=--force",
  143. "git restore --staged .",
  144. "git restore file",
  145. "git checkout -b branch",
  146. "git checkout -b .",
  147. "git stash drop",
  148. "git worktree remove path",
  149. "rsync --delete -n src/ dest/",
  150. "rsync --exclude --delete src/ dest/",
  151. "rsync --filter=--delete src/ dest/",
  152. "echo 'rm -rf build'",
  153. "echo hi # rm -rf build",
  154. "echo hi > 'rm -rf build'",
  155. "time -o 'rm -rf build' echo ok",
  156. "sudo -u rm echo -rf build",
  157. "env A='rm -rf build' echo ok",
  158. ])("does not invent a destructive effect: %s", (command) => {
  159. expect(matchDangerousCommand(command, "posix").status).toBe("notMatched");
  160. });
  161. it.each([
  162. ["git clean -fd -e --dry-run", "git clean -fd --dry-run", "git-clean-force"],
  163. ["git clean -nfd --no-dry-run", "git clean -fd --no-dry-run -n", "git-clean-force"],
  164. ["git push -f --push-option --dry-run", "git push -f --dry-run", "git-push-force"],
  165. ["git push -nf --no-dry-run", "git push -f --no-dry-run -n", "git-push-force"],
  166. ["git push --mirror --no-force", "git push --mirror --no-mirror", "git-push-force"],
  167. ["rsync --delete --exclude --help src/ dest/", "rsync --delete --help", "rsync-delete"],
  168. [
  169. "rsync --delete --filter --dry-run src/ dest/",
  170. "rsync --delete -n src/ dest/",
  171. "rsync-delete",
  172. ],
  173. ])("keeps exemption words distinct from values/cancellation: %s", (dangerous, exempt, rule) => {
  174. expect(matchDangerousCommand(dangerous, "posix")).toMatchObject({
  175. status: "matched",
  176. ruleId: `safety.bash.${rule}`,
  177. });
  178. expect(matchDangerousCommand(exempt, "posix")).toEqual({ status: "notMatched" });
  179. });
  180. it.each([
  181. "bash -c 'rm -rf build'",
  182. "powershell -Command 'rm -rf build'",
  183. "eval 'rm -rf build'",
  184. "$exe -rf build",
  185. "git -c alias.wipe='reset --hard' wipe",
  186. "env -S 'rm -rf build'",
  187. "time --unknown rm -rf build",
  188. "for x in a; do rm -rf build; done",
  189. "rm 'unterminated",
  190. "x".repeat(10_001),
  191. ])("labels unsupported boundaries: %s", (command) => {
  192. expect(matchDangerousCommand(command, "posix").status).toBe("unsupported");
  193. });
  194. // 2026-09-17 review:已识别的危险选项不因同一命令内出现未知选项而失效(存在性规则)。
  195. it.each([
  196. ["rm -rfx build", "remove-critical-path"],
  197. ["rm -rfP build", "remove-critical-path"],
  198. ["rm -rf -W build", "remove-critical-path"],
  199. ["rm -rf --preserve-root=all build", "remove-critical-path"],
  200. ["rm -rf --totally-unknown build", "remove-critical-path"],
  201. ["rsync -a --delete --info=progress2 src/ dest/", "rsync-delete"],
  202. ["rsync -a --delete --stats src/ dest/", "rsync-delete"],
  203. ["rsync -ai --delete src/ dest/", "rsync-delete"],
  204. ["rsync -a --delete --partial-dir=.rsync-partial src/ dest/", "rsync-delete"],
  205. ["rsync --unknown-flag --delete src/ dest/", "rsync-delete"],
  206. ["git push --force --no-verify origin main", "git-push-force"],
  207. ["git push --force --no-recurse-submodules origin main", "git-push-force"],
  208. ["git push --force --totally-unknown origin main", "git-push-force"],
  209. ["git -c core.pager=cat reset --hard HEAD~1", "git-reset-hard"],
  210. ["git -p reset --hard", "git-reset-hard"],
  211. ["git --exec-path=/opt/git reset --hard", "git-reset-hard"],
  212. ["git reset --hard --totally-unknown", "git-reset-hard"],
  213. ["git checkout -f -t origin/main", "git-discard-tree"],
  214. ["git checkout -f --guess main", "git-discard-tree"],
  215. ["git stash clear --totally-unknown", "git-stash-clear"],
  216. ["git worktree remove --force --totally-unknown path", "git-worktree-force-remove"],
  217. ])("keeps recognized dangerous options when an unknown option appears: %s", (command, rule) => {
  218. expect(matchDangerousCommand(command, "posix")).toMatchObject({
  219. status: "matched",
  220. ruleId: `safety.bash.${rule}`,
  221. });
  222. });
  223. it.each([
  224. "rm --totally-unknown build",
  225. "rsync --unknown-flag src/ dest/",
  226. "git push --totally-unknown origin main",
  227. "git reset --totally-unknown",
  228. ])("still reports unsupported when unknown options leave no reliable hit: %s", (command) => {
  229. expect(matchDangerousCommand(command, "posix").status).toBe("unsupported");
  230. });
  231. it("unknown options in interspersed scans do not consume the next word or enter flags", () => {
  232. const words = analyzeBashCommand("rm --unknown -rf target").commands[0]!.words.slice(1);
  233. const parsed = parseOptions(words, optionTable("-r -f"), {
  234. ordering: "interspersed",
  235. unknown: "continue",
  236. });
  237. expect(parsed.unsupported).toBe(true);
  238. expect(parsed.flags).toEqual(["-r", "-f"]);
  239. expect(parsed.operands.map((word) => word.value)).toEqual(["target"]);
  240. });
  241. it.each([
  242. "git reset --hard 2>nul",
  243. "git reset --hard > out.txt",
  244. "git reset --hard >> out.txt",
  245. "git push --force origin main 2>nul",
  246. "rm -rf build 2>nul",
  247. "rm -rf build 2> nul",
  248. ])("CMD trailing redirection target keeps the command matched: %s", (command) => {
  249. expect(matchDangerousCommand(command, "cmd").status).toBe("matched");
  250. });
  251. it.each(["git reset --hard >", "git reset --hard 2>", "git reset --hard > "])(
  252. "CMD redirection without a target stays unsupported: %s",
  253. (command) => {
  254. expect(matchDangerousCommand(command, "cmd").status).toBe("unsupported");
  255. },
  256. );
  257. it.each([
  258. "rm -rf build",
  259. '"C:\\tools\\git.exe" reset --hard',
  260. "echo ok & git stash clear",
  261. "git clean -fd && echo ok",
  262. ])("CMD: %s", (command) => {
  263. expect(matchDangerousCommand(command, "cmd").status).toBe("matched");
  264. });
  265. it.each([">rem", "> rem", "2>rem", ">>rem", "<rem", '>"rem"'])(
  266. "CMD redirection target is not a REM comment: %s",
  267. (redirection) => {
  268. expect(matchDangerousCommand(`${redirection} git reset --hard`, "cmd")).toMatchObject({
  269. status: "matched",
  270. ruleId: "safety.bash.git-reset-hard",
  271. });
  272. },
  273. );
  274. it.each([
  275. "rem git reset --hard",
  276. ">rem rem git reset --hard",
  277. ">rem rem ignored & git reset --hard",
  278. ])("CMD preserves actual REM comments: %s", (command) => {
  279. expect(matchDangerousCommand(command, "cmd")).toEqual({ status: "notMatched" });
  280. });
  281. it.each([
  282. "rem rm -rf build",
  283. ":: rm -rf build",
  284. 'echo "rm -rf build"',
  285. "'rm' -rf build",
  286. "git reset '--hard'",
  287. "(echo hi & (rm -rf build))",
  288. ])("CMD quotes/comments: %s", (command) => {
  289. expect(matchDangerousCommand(command, "cmd").status).not.toBe("matched");
  290. });
  291. it("does not apply Bash grammar to legacy or unsupported shells", () => {
  292. expect(matchDangerousCommand("rm -rf build", "legacy-shell").status).toBe("unsupported");
  293. });
  294. it.each(["posix", "git-bash", "cmd"] as const)(
  295. "%s keeps rm recursive + force independent of help position and wrappers",
  296. (dialect) => {
  297. for (const flags of ["-rf", "-f -R", "--recursive --force"]) {
  298. for (const query of ["--help", "--version"]) {
  299. for (const args of [
  300. `${flags} target ${query}`,
  301. `${query} ${flags} target`,
  302. `${flags} ${query}`,
  303. `${flags} -- ${query}`,
  304. ]) {
  305. for (const wrapper of ["", "env A=b ", "time -o timing.txt ", "sudo -u root "]) {
  306. const command = `${wrapper}rm ${args}`;
  307. expect(matchDangerousCommand(command, dialect), command).toMatchObject({
  308. status: "matched",
  309. ruleId: "safety.bash.remove-critical-path",
  310. });
  311. }
  312. }
  313. }
  314. }
  315. for (const command of ["rm --help", "rm -- -rf"]) {
  316. expect(matchDangerousCommand(command, dialect), command).toEqual({ status: "notMatched" });
  317. }
  318. },
  319. );
  320. it("makes operand scanning a caller-owned policy instead of a shared default", () => {
  321. const words = analyzeBashCommand("rm -rf target --help").commands[0]!.words.slice(1);
  322. const table = optionTable("-r -f --help");
  323. const stopped = parseOptions(words, table, {
  324. ordering: "stop-at-operand",
  325. unknown: "abort",
  326. });
  327. expect(stopped.flags).toEqual(["-r", "-f"]);
  328. expect(stopped.operands.map((word) => word.value)).toEqual(["target", "--help"]);
  329. const interspersed = parseOptions(words, table, {
  330. ordering: "interspersed",
  331. unknown: "continue",
  332. });
  333. expect(interspersed.flags).toEqual(["-r", "-f", "--help"]);
  334. expect(interspersed.operands.map((word) => word.value)).toEqual(["target"]);
  335. });
  336. it("abort policy stops at the first unknown option so wrappers cannot locate the real command", () => {
  337. const words = analyzeBashCommand("time --unknown rm -rf target").commands[0]!.words.slice(1);
  338. const parsed = parseOptions(words, optionTable("-p"), {
  339. ordering: "stop-at-operand",
  340. unknown: "abort",
  341. });
  342. expect(parsed.unsupported).toBe(true);
  343. expect(parsed.flags).toEqual([]);
  344. });
  345. it.skipIf(process.platform !== "darwin")(
  346. "native macOS rm treats trailing help/version as deletion operands in an isolated directory",
  347. async () => {
  348. // 独立 oracle:不调用 matcher 来决定真实程序应如何解析;所有删除目标都由本测试创建。
  349. const directory = await mkdtemp(join(tmpdir(), "zcode-guarded-rm-oracle-"));
  350. try {
  351. await mkdir(join(directory, "target"));
  352. await writeFile(join(directory, "target", "keep.txt"), "case-owned");
  353. await writeFile(join(directory, "--help"), "case-owned");
  354. await writeFile(join(directory, "--version"), "case-owned");
  355. await promisify(execFile)("/bin/rm", ["-rf", "target", "--help", "--version"], {
  356. cwd: directory,
  357. timeout: 5000,
  358. });
  359. for (const operand of ["target", "--help", "--version"]) {
  360. await expect(access(join(directory, operand))).rejects.toMatchObject({ code: "ENOENT" });
  361. }
  362. expect(matchDangerousCommand("rm -rf target --help --version", "posix").status).toBe(
  363. "matched",
  364. );
  365. } finally {
  366. await rm(directory, { recursive: true, force: true });
  367. }
  368. },
  369. );
  370. });