返回 CodeWhale
shell_parse_policy.rs
根目录 / crates / execpolicy / tests / shell_parse_policy.rs
1 //! Deny rules hold against commands whose word the shell resolves at run
2 //! time, and allow rules only cover the command as written.
3
4 use codewhale_execpolicy::{
5 AskForApproval, ExecApprovalRequirement, ExecPolicyContext, ExecPolicyEngine, PermissionAction,
6 Ruleset, ToolAskRule,
7 bash_arity::BashArityDict,
8 command_safety::{is_agent_readonly_shell_command, is_parallel_readonly_command},
9 toml_rules::{ExecPolicyConfig, RuleDecision},
10 };
11
12 fn context(command: &str, approval: AskForApproval) -> ExecPolicyContext<'_> {
13 ExecPolicyContext {
14 command,
15 cwd: "/workspace",
16 tool: Some("exec_shell"),
17 path: None,
18 ask_for_approval: approval,
19 sandbox_mode: None,
20 }
21 }
22
23 fn deny_rm_engines() -> [ExecPolicyEngine; 2] {
24 [
25 ExecPolicyEngine::new(vec![], vec!["rm".to_string()]),
26 ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(vec![
27 ToolAskRule {
28 action: PermissionAction::Deny,
29 ..ToolAskRule::exec_shell("rm")
30 },
31 ])]),
32 ]
33 }
34
35 /// Spellings whose command word is only known at run time, or which run a
36 /// command behind a reserved word or a wrapper's operands.
37 const HIDDEN_RM: &[&str] = &[
38 "v=rm; $v -f f",
39 "v=rm; \"$v\" -f f",
40 "v=rm; ${v} -f f",
41 "sudo $v f",
42 "bash -c '$v f'",
43 "eval \"$v f\"",
44 "$(echo rm) -f f",
45 "`echo rm` f",
46 "rm${IFS}x",
47 "x=r; ${x}m f",
48 "IFS=,; c=rm,x; $c",
49 "/bin/r[m] -f f",
50 "{rm,-f,f}",
51 "$'\\x72m' f",
52 "printf rm | sh",
53 "echo rm x | bash",
54 "sh <<< 'rm x'",
55 "source <(echo rm x)",
56 "find . -exec rm {} +",
57 "find . -execdir rm {} \\;",
58 "find . -delete",
59 "if true; then rm x; fi",
60 "while rm x; do :; done",
61 "until rm x; do :; done",
62 "! rm x",
63 "function f { rm x; }",
64 "chroot /newroot rm -rf /",
65 "chroot /newroot sh -c 'rm -rf /'",
66 "sudo --user root bash -c 'rm -rf /'",
67 "sudo --user root rm -rf /",
68 "timeout -s KILL 5 rm x",
69 "env -S'rm x'",
70 // Wrapper options missing from the option tables, read both ways.
71 "env -P /usr/bin rm -rf /",
72 "ls | xargs -J % rm -rf %",
73 "proot -R /x rm -rf /",
74 "chroot -u root / rm -rf /",
75 "doas -a style rm x",
76 "sudo -a type rm x",
77 // Substitution bodies read past quotes, and a `case` inside one.
78 "echo $(case x in x) rm -rf /;; esac)",
79 "echo $(echo \")\"; rm -rf /)",
80 "echo 'unterminated $(rm x)",
81 // `<<` inside arithmetic is a shift, not a heredoc.
82 "((x = 1 << 2))\nrm -rf /",
83 "let x=1<<2\nrm x",
84 // Replacement strings are only known at run time.
85 "echo 'rm -rf /' | xargs -I{} sh -c {}",
86 "echo rm | xargs -I CMD CMD -rf /",
87 "find . -exec sh -c {} \\;",
88 // More wrappers, shells and code-as-string commands.
89 "bash.exe -c 'rm -rf /'",
90 "caffeinate -i rm -rf /",
91 "arch -arm64 rm -rf /",
92 "noglob rm -rf /",
93 "nsenter -t 1 -m rm x",
94 "unshare -r rm x",
95 "sandbox-exec -n no-network rm x",
96 "runuser -u root -- rm x",
97 "trap 'rm -rf /' EXIT",
98 "su -c 'rm -rf /' root",
99 "flock /tmp/lock -c 'rm x'",
100 "script -qc 'rm x' /dev/null",
101 "watch 'ls; rm -rf /'",
102 "cmd /c rm x",
103 "pwsh -NoProfile -Command rm x",
104 "powershell -enc cgBtACAAeAA=",
105 "wsl -e rm x",
106 // Options may follow `-c`; the command string is the first operand.
107 "bash -c -e 'rm -rf /'",
108 "sh -c -- 'rm -rf /'",
109 "bash -c -o pipefail 'rm x'",
110 // A script operand that names stdin reads the pipe or here-string.
111 "echo 'rm x' | bash /dev/stdin",
112 "bash /dev/stdin <<< 'rm x'",
113 ". /dev/stdin <<< 'rm x'",
114 "sh /proc/self/fd/0 <<< 'rm x'",
115 // Launchers that run their operands as a command.
116 "pkexec rm x",
117 "pkexec --user root rm x",
118 "run0 -u root rm x",
119 "fakeroot rm -rf /",
120 "taskset -c 0 rm x",
121 "taskset 0x3 rm x",
122 "strace -f -o /tmp/t rm x",
123 "ltrace rm x",
124 "chrt 1 rm -rf /",
125 "chrt -r 10 rm x",
126 "prlimit --nofile=10 rm -rf /",
127 "systemd-run --user --scope rm x",
128 "numactl -N 0 rm x",
129 "firejail --noprofile rm x",
130 "xvfb-run -a rm x",
131 "dbus-launch --exit-with-session rm x",
132 "proxychains -q rm x",
133 "eatmydata rm x",
134 "cpulimit -l 50 rm x",
135 "sg wheel -c 'rm x'",
136 "sg wheel 'rm x'",
137 "gtimeout 5 rm x",
138 "gnice -n 5 rm x",
139 "v=rm; $=v -f f",
140 "v=rm; $~v -f f",
141 "v=rm; $^v -f f",
142 "$'rm' -f f",
143 "/bin/(r)m -f f",
144 "/bin/r(m) -f f",
145 "/usr/bin/rm(N) -f f",
146 "setopt equals; =rm -f f",
147 "=rm -f f",
148 "rm# x",
149 "hash x=/bin/rm; x -f f",
150 "hash -p /bin/rm x; x -f f",
151 "alias x=rm\nx -f f",
152 "shopt -s expand_aliases\nalias x=rm\nx -f f",
153 "emulate -L sh; rm x",
154 "iex 'rm f'",
155 "Invoke-Expression 'rm f'",
156 "iex ('r'+'m f')",
157 "'rm f' | iex",
158 "genv rm x",
159 "genv -i rm x",
160 "genv -S'rm x'",
161 "echo x | gxargs rm",
162 "echo 'rm -rf /' | gxargs -I{} sh -c {}",
163 "gtime -p rm x",
164 "gsetsid -f rm x",
165 "toybox rm x",
166 "script -q /dev/null rm x",
167 "script -t 0 -q /dev/null rm x",
168 "parallel rm ::: x",
169 "parallel ::: 'rm x'",
170 "bwrap --ro-bind / / rm x",
171 "bwrap --ro-bind / / -- rm x",
172 "setarch x86_64 rm x",
173 "setarch x86_64 -R rm x",
174 "linux64 rm x",
175 "faketime '2020-01-01' rm x",
176 "faketime -f '-1d' rm x",
177 "rlwrap -a rm x",
178 "chronic rm x",
179 "ifne rm x",
180 "runcon system_u:system_r:unconfined_t:s0 rm x",
181 "runcon -t unconfined_t rm x",
182 "chpst -u nobody rm x",
183 "softlimit -m 1024 rm x",
184 "valgrind --tool=none rm x",
185 "perf stat rm x",
186 "perf stat -r 2 -e cycles rm x",
187 "perf record -g rm x",
188 "watchexec -w src rm x",
189 "watchexec -w src 'ls; rm x'",
190 "entr rm x",
191 "entr -s 'ls; rm x' /_",
192 "systemd-inhibit --why=test rm x",
193 "cgexec -g cpu:test rm x",
194 "daemonize /bin/rm x",
195 "start-stop-daemon -S -x /bin/rm -- x",
196 "start-stop-daemon --start --exec=/bin/rm -- -rf /",
197 "nsjail --config /tmp/c -- rm x",
198 "torify rm x",
199 "launchctl asuser 501 rm x",
200 "launchctl bsexec 123 rm x",
201 "/lib64/ld-linux-x86-64.so.2 /bin/rm x",
202 "/lib/ld-linux-aarch64.so.1 --library-path /tmp /bin/rm x",
203 "ld.so /bin/rm x",
204 "npm exec -- rm x",
205 "opam exec -- rm x",
206 "op run -- rm x",
207 "kubectl exec pod -- rm x",
208 "kubectl exec pod -- sh -c 'rm x'",
209 "uv run rm x",
210 "uv run --with pkg rm x",
211 "poetry run rm x",
212 "pipx run rm x",
213 "bundle exec rm x",
214 "nix develop -c rm x",
215 "nix develop .#dev -c bash -c 'rm x'",
216 "nix develop -c$(echo rm) x",
217 "nix develop -c$(echo rm)",
218 "nix develop --command=$(echo rm) x",
219 "nix develop --command$(echo =rm) x",
220 "nix develop --command='rm x'",
221 "nix develop --command='rm -rf /'",
222 "nix develop -crm x",
223 "nix develop -ic rm x",
224 "nix develop -icrm x",
225 "nix shell -c$(echo rm) x",
226 "nix shell --command=$(echo rm) x",
227 "nix shell --command='rm x'",
228 "nix shell -ic rm x",
229 "nix-shell -p busybox --run 'rm x'",
230 "nix-shell --run$(echo =rm) x",
231 "su -c$(echo rm) x",
232 "npx -c$(echo rm) x",
233 "npx -c$(echo rm)",
234 "start-stop-daemon -S -x$(echo /bin/rm) -- x",
235 "start-stop-daemon -S --exec=$(echo /bin/rm) -- x",
236 "launchctl submit -p$(echo /bin/rm) -- x",
237 "cmd /c$(echo rm) x",
238 "pwsh -c$(echo rm) x",
239 "find . -exec$(echo rm) x \\;",
240 "sh -c$(echo rm) x",
241 "nu --commands$(echo =rm) x",
242 "docker run --entrypoint=$(echo /bin/rm) alpine x",
243 "docker run --entrypoint$(echo =/bin/rm) alpine x",
244 "docker run --rm alpine rm x",
245 "docker run --entrypoint /bin/rm alpine -rf /",
246 "docker exec ctr rm x",
247 "npx -c 'rm x'",
248 "ssh host rm x",
249 "ssh -p 2222 user@host 'ls; rm x'",
250 "tmux new-session -d 'rm x'",
251 "tmux new-session -d -s s rm x",
252 "screen -dm rm x",
253 "screen -dmS s rm x",
254 "elvish -c 'rm x'",
255 "nu -c 'rm x'",
256 "nu --commands 'rm x'",
257 "xonsh -c 'rm x'",
258 "oksh -c 'rm x'",
259 "posh -c 'rm x'",
260 "osh -c 'rm x'",
261 "echo 'rm x' | elvish",
262 "nu <<< 'rm x'",
263 "alias qq='rm -rf'; eval qq /",
264 "hash -p /bin/rm r; r x",
265 "hash -p/bin/rm r; r x",
266 "hash -lp /bin/rm r; r x",
267 "hash r=/bin/rm; r x",
268 "=rm x",
269 "parallel 'rm {}' ::: x",
270 "parallel -j 2 -- rm ::: x",
271 "echo 'rm x' | parallel",
272 "parallel -j 2 ::: ls 'rm x'",
273 "parallel :::: cmds.txt ::: 'rm x'",
274 "parallel :::: cmds.txt",
275 "parallel sh -c ::: 'rm x'",
276 "parallel eval ::: 'rm x'",
277 "parallel 'sh -c {}' ::: 'rm x'",
278 "parallel bash -c {} ::: 'rm x'",
279 "at now <<< 'rm x'",
280 "echo 'rm x' | batch",
281 "at now <<EOF\nrm x\nEOF",
282 "echo 'rm x' | at -q b now",
283 "echo 'rm x' | at -qb now",
284 "at -f script.sh now",
285 "at -f script.sh -l",
286 "at -l -f script.sh",
287 "awk 'BEGIN{system(\"rm x\")}'",
288 "awk 'BEGIN{\"rm x\" | getline}'",
289 "awk 'BEGIN{\"rm x\" |& getline}'",
290 "awk 'BEGIN{print \"x\" | \"rm y\"}'",
291 "awk 'BEGIN{print \"x\" |& \"rm y\"}'",
292 "awk 'BEGIN{c=\"rm x\"; system(c)}'",
293 "awk 'BEGIN{system(\"r\" \"m\" \" x\")}'",
294 r#"awk 'BEGIN{system("\162\155 x")}'"#,
295 "awk '{x = a / b; system(\"rm x\"); y = c / d}'",
296 "gawk -e 'BEGIN{system(\"rm x\")}'",
297 "gawk --source='BEGIN{system(\"rm x\")}'",
298 "awk $PROG file",
299 "sed 's/a/rm x/e'",
300 "sed 's#a#rm x#ge'",
301 "sed 's|a|rm x|2ep'",
302 "sed 's/.*/rm x/e'",
303 "sed 's/a/rm x/ew /tmp/out'",
304 "sed 's/^//e'",
305 "sed 'e rm x'",
306 "sed '1e rm x'",
307 "sed '/foo/e rm x'",
308 "sed 'e'",
309 "sed '1{e}'",
310 "sed 's/foo/bar/g; e rm x'",
311 "sed -e 's/a/b/' -e 's/c/rm x/e'",
312 "sed --expression='e rm x'",
313 "sed -i '' 's/a/rm x/e' file.txt",
314 "sed -i .bak 's/a/rm x/e' file.txt",
315 "sed $PROG file",
316 "echo 'rm x' | ssh host",
317 "echo 'rm x' |& ssh host",
318 "echo 'rm x' |\nssh host",
319 "ssh host < script",
320 "ssh host 0< script",
321 "ssh host <<< 'rm x'",
322 "ssh host 0<<< 'rm x'",
323 "ssh host <<EOF\nrm x\nEOF",
324 "ssh host sh <<EOF\nrm x\nEOF",
325 "ssh host 'ssh host2' <<EOF\nrm x\nEOF",
326 "ssh host ls <<EOF\n$(rm x)\nEOF",
327 "echo 'rm x' | find . -exec ssh host \\;",
328 "echo 'rm x' | { a; ssh host; }",
329 "echo 'rm x' | { { a; }; ssh host; }",
330 "echo 'rm x' | (a; ssh host)",
331 "{ a; ssh host; } <<< 'rm x'",
332 "(a; ssh host) < script",
333 "numactl --strict rm",
334 "numactl --strict -N 0 rm",
335 "su $(echo -c) 'rm x'",
336 "su $FLAG 'rm x'",
337 "su --$(echo command) 'rm x'",
338 "nix $(echo develop) -c rm x",
339 "nix develop $(echo -c) rm x",
340 "nix develop --$(echo command) rm x",
341 "docker $(echo run) --entrypoint rm alpine",
342 "docker run $(echo --entrypoint) rm alpine",
343 "docker run $(echo --entrypoint=rm) alpine",
344 "docker run --entrypoint $(echo rm) alpine",
345 "docker run --entrypoint=$(echo rm) alpine",
346 "start-stop-daemon --start $(echo --exec) rm -- x",
347 "start-stop-daemon --start $FLAG rm -- x",
348 "start-stop-daemon --start --$(echo exec) /bin/rm -- x",
349 "start-stop-daemon -K $(echo --start) --exec /bin/rm -- x",
350 "nix-shell $(echo --run) 'rm x'",
351 "npx $(echo -c) 'rm x'",
352 "npm $(echo exec) -c 'rm x'",
353 "npm exec $(echo -c) 'rm x'",
354 "uv $(echo run) rm x",
355 "tmux $(echo new-session) -d 'rm x'",
356 "launchctl $(echo submit) -p /bin/rm",
357 "launchctl submit $(echo -p) /bin/rm",
358 "ssh $(echo -p) 22 host rm x",
359 "screen -r $(echo -m) rm x",
360 "find . $(echo -exec) rm {} +",
361 "cmd $(echo /c) rm x",
362 "bash --$(echo command) 'rm x'",
363 "env -S $(echo 'rm x')",
364 "env --$(echo 'split-string=rm x')",
365 "tmux display-popup 'rm x'",
366 "tmux popup -E 'rm x'",
367 "tmux display-popup -EE -d /tmp -t s -w 80% -h 50% -x C -y C -T title -s fg=red -S fg=blue -b single -e FOO=1 'rm x'",
368 "tmux display-popup -E rm x",
369 "tmux confirm-before 'rm x'",
370 "tmux confirm -b -c y -p 'sure?' -t s 'rm x'",
371 "tmux confirm-before -p 'delete?' \"run-shell 'rm x'\"",
372 "tmux confirm-before \"display-popup -E 'rm x'\"",
373 "tmux confirm-before \"list-sessions ; run-shell 'rm x'\"",
374 "tmux command-prompt -I 'rm x'",
375 "tmux command-prompt -I'rm x'",
376 "tmux command-prompt -bI 'rm x'",
377 "tmux command-prompt -I \"run-shell 'rm x'\"",
378 "tmux command-prompt -I 'echo hi,rm x'",
379 "tmux command-prompt \"run-shell 'rm x'\"",
380 "tmux command-prompt -p 'cmd:' \"run-shell 'rm %%'\"",
381 "tmux command-prompt -I 'rm x' \"run-shell '%%'\"",
382 "tmux command-prompt -I 'foo,rm x' \"run-shell '%2'\"",
383 "tmux command-prompt -p 'cmd:' \"run-shell '%%'\"",
384 "tmux command-prompt -p 'cmd:' '%%'",
385 "tmux bind-key k run-shell 'rm x'",
386 "tmux bind k run 'rm x'",
387 "tmux bind-key -n F1 run-shell 'rm x'",
388 "tmux bind-key -r -T root -N 'note' k display-popup -E 'rm x'",
389 "tmux bind-key k \"run-shell 'rm x'\"",
390 "tmux bind-key k confirm-before \"run-shell 'rm x'\"",
391 "tmux bind-key k display-message hi \\; run-shell 'rm x'",
392 "tmux bind-key k source-file /tmp/evil.conf",
393 "tmux bind-key k $CMD",
394 "tmux bind-key k '$CMD'",
395 "tmux source-file f",
396 "tmux source ~/.tmux.conf",
397 "tmux source-file -q -t %0 f",
398 "tmux source-file -n -F '#(rm x)'",
399 "tmux source-file -t -n f",
400 "tmux source-file -- -n",
401 "tmux run-shell 'rm x'",
402 "tmux run -b -d 1 -c /tmp 'rm x'",
403 "tmux run-shell -C \"display-popup 'rm x'\"",
404 "tmux send-keys -t s 'rm x' Enter",
405 "tmux if-shell 'true' 'rm x'",
406 "tmux if-shell 'true' \"run-shell 'rm x'\"",
407 "tmux pipe-pane -o 'rm x'",
408 "tmux list-sessions \\; display-popup 'rm x'",
409 "oc rsh pod rm x",
410 "oc rsh pod -- rm x",
411 "oc -n prod rsh -c app pod rm x",
412 "oc exec pod -- rm x",
413 "oc exec pod rm x",
414 "oc exec -n prod pod -c app -- sh -c 'rm x'",
415 "oc exec -f pod.yaml rm x",
416 "oc debug node/n -- chroot /host rm x",
417 "oc debug --image=alpine -- rm x",
418 "oc run tmp --image=alpine -- rm x",
419 "oc exec pod -- $v x",
420 "vagrant ssh -c 'rm x'",
421 "vagrant ssh --command 'rm x'",
422 "vagrant ssh --command='rm x'",
423 "vagrant ssh default -c 'rm x'",
424 "vagrant ssh -- rm x",
425 "vagrant ssh default -- -t 'ls; rm x'",
426 "vagrant ssh -c \"$CMD\"",
427 "vagrant winrm -c 'rm x'",
428 "op run --env-file .env -- rm x",
429 "op run --env-file .env rm x",
430 "op run -- $v x",
431 "op plugin run rm x",
432 "opam exec rm x",
433 "opam exec --switch default rm x",
434 "opam exec -- $v x",
435 "helm template . --post-renderer rm",
436 "helm upgrade rel . --post-renderer=/bin/rm",
437 "helm install rel . --post-renderer sh --post-renderer-args -c --post-renderer-args 'rm x'",
438 "helm template . --post-renderer \"$RENDERER\"",
439 "helm template . $(echo --post-renderer) rm",
440 "helm template . --$(echo post-renderer) rm",
441 "helm plugin install ./evil",
442 "helm plugin $(echo install) ./evil",
443 "oc $(echo exec) pod -- rm x",
444 "vagrant ssh $(echo -c) 'rm x'",
445 "op $(echo run) -- rm x",
446 "op plugin $(echo run) rm x",
447 "opam $(echo exec) rm x",
448 // ssh -o ProxyCommand / LocalCommand (including under -N and normalized whitespace).
449 "ssh -o 'ProxyCommand=rm x' host",
450 "ssh -N -o 'ProxyCommand=rm x' host",
451 "ssh -oProxyCommand='rm x' host",
452 "ssh -o 'ProxyCommand = rm x' host",
453 "ssh -o 'ProxyCommand\trm x' host",
454 "ssh -o 'PermitLocalCommand=yes' -o 'LocalCommand=rm x' host",
455 "ssh -N -o 'PermitLocalCommand = yes' -o 'LocalCommand=rm x' host",
456 "ssh -o ' PermitLocalCommand=yes' -o 'LocalCommand=rm x' host",
457 "ssh -o 'PermitLocalCommand\t=\tyes' -o 'LocalCommand=rm x' host",
458 "ssh -o \"PermitLocalCommand=$YES\" -o 'LocalCommand=rm x' host",
459 "ssh -o \"$OPT\" host",
460 "echo 'rm x' | mosh host",
461 "echo 'rm x' | dbclient host",
462 // screen -X / -Q (including combined with -r/-R/-d).
463 "screen -X screen rm x",
464 "screen -X exec rm x",
465 "screen -X eval 'rm x'",
466 "screen -X stuff 'rm x\n'",
467 "screen -X at 0 rm x",
468 "screen -r s -X stuff 'rm x\n'",
469 "screen -r 1 -X exec rm x",
470 "screen -dr -X exec rm x",
471 "screen -R s -X screen rm",
472 "screen -r s -Q stuff 'rm x\n'",
473 "screen -X \"exec 'rm x\"",
474 // kubectl exec / run / debug.
475 "kubectl exec pod rm x",
476 "kubectl exec pod -- rm x",
477 "kubectl exec -c ctr pod rm x",
478 "kubectl exec -n ns pod rm x",
479 "kubectl run tmp --image=alpine -- rm x",
480 // docker/podman container/compose groups, create, buildx --call, --health-cmd.
481 "docker container run alpine rm x",
482 "docker container exec ctr rm x",
483 "podman container run alpine rm x",
484 "podman container exec ctr rm x",
485 "docker create alpine rm x",
486 "docker compose exec svc rm x",
487 "docker compose run svc rm x",
488 "docker compose -f x.yml exec svc rm x",
489 "docker compose -f=x exec svc rm x",
490 "docker compose --ansi never exec svc rm x",
491 "docker compose -p proj exec svc rm x",
492 "docker --context prod compose exec svc rm x",
493 "docker buildx bake --call 'system(\"rm x\")'",
494 "docker run --health-cmd 'rm x' alpine",
495 "docker run --health-cmd='rm x' alpine",
496 // parallel --compress-program / --decompress-program & bwrap --args.
497 "parallel --compress-program 'rm x' ::: y",
498 "parallel --compress-program='rm x' ::: y",
499 "parallel --compress-program=rm echo ::: y",
500 "parallel --compress-program='rm x' echo ::: y",
501 "parallel --decompress-program='rm x' echo ::: y",
502 "bwrap --args 3",
503 "bwrap --dev-bind / / --args=4",
504 // Shell -c aliases, gawk -i/-l, and pwsh - / piped stdin.
505 "oil -c 'rm x'",
506 "ysh -c 'rm x'",
507 "pdksh -c 'rm x'",
508 "loksh -c 'rm x'",
509 "rksh -c 'rm x'",
510 "ion -c 'rm x'",
511 "ngs -c 'rm x'",
512 "gawk -i /dev/stdin '{print}' f",
513 "gawk --include=/dev/stdin '{print}' f",
514 "gawk -l \"$EXT\" '{print}' f",
515 "gawk --load=\"$EXT\" '{print}' f",
516 "pwsh -",
517 "powershell -",
518 "pwsh <<EOF\nrm x\nEOF",
519 "echo 'rm x' | pwsh",
520 "echo 'rm x' | powershell",
521 "pwsh -File -",
522 "pwsh -File /dev/stdin",
523 // Quoted dynamic words, INERT_DASH_DASH_HEADS, and separated nix -c shell-string.
524 "find . \"$X\" rm {} +",
525 "docker run \"$X\" alpine",
526 "npm exec -- \"$X\"",
527 "true -- $v",
528 "sed -- \"$X\"",
529 "awk -- \"$X\"",
530 "nix develop -c 'echo a; rm -rf /'",
531 ];
532
533 /// Literal spellings that were already denied and must stay denied.
534 const LITERAL_RM: &[&str] = &[
535 "rm -f f",
536 "\\rm x",
537 "r''m x",
538 "/bin/rm x",
539 "(rm x)",
540 "{ rm x; }",
541 "case a in a) rm x;; esac",
542 "f(){ rm -f x; }; f",
543 "xargs rm",
544 "command -p rm x",
545 ];
546
547 /// Commands whose parse runs into a budget: past the budget, nothing was
548 /// checked, so the command is unresolved.
549 fn budget_commands() -> Vec<String> {
550 vec![
551 format!("sudo {}rm -rf /", "-H ".repeat(600)),
552 format!("env {}rm -rf /", "-i ".repeat(600)),
553 (1..=256)
554 .map(|index| format!("true {index}"))
555 .chain(["rm -rf /".to_string()])
556 .collect::<Vec<_>>()
557 .join("; "),
558 ]
559 }
560
561 fn denied(engine: &ExecPolicyEngine, command: &str) -> bool {
562 let decision = engine
563 .check(context(command, AskForApproval::Never))
564 .expect("policy check");
565 !decision.allow
566 && matches!(
567 decision.requirement,
568 ExecApprovalRequirement::Forbidden { .. }
569 )
570 }
571
572 #[test]
573 fn deny_rules_hold_against_runtime_resolved_and_reserved_word_spellings() {
574 let budget = budget_commands();
575 let mut missed = Vec::new();
576 for engine in deny_rm_engines() {
577 for command in HIDDEN_RM
578 .iter()
579 .chain(LITERAL_RM)
580 .copied()
581 .chain(budget.iter().map(String::as_str))
582 {
583 if !denied(&engine, command) {
584 missed.push(command.chars().take(80).collect::<String>());
585 }
586 }
587 }
588 assert!(missed.is_empty(), "not denied: {missed:#?}");
589 }
590
591 #[test]
592 fn unresolved_words_prompt_only_where_a_person_always_sees_the_prompt() {
593 let engine = ExecPolicyEngine::new(vec![], vec!["rm".to_string()]);
594 let requirement = |approval| {
595 engine
596 .check(context("v=rm; $v x", approval))
597 .expect("policy check")
598 .requirement
599 };
600 assert!(matches!(
601 requirement(AskForApproval::OnRequest),
602 ExecApprovalRequirement::NeedsApproval { .. }
603 ));
604 assert!(matches!(
605 requirement(AskForApproval::UnlessTrusted),
606 ExecApprovalRequirement::NeedsApproval { .. }
607 ));
608 // `OnFailure` is also the posture of sessions that approve on their own.
609 for approval in [AskForApproval::OnFailure, AskForApproval::Never] {
610 assert!(matches!(
611 requirement(approval),
612 ExecApprovalRequirement::Forbidden { .. }
613 ));
614 }
615 }
616
617 #[test]
618 fn ordinary_commands_stay_allowed_next_to_a_deny_rule() {
619 for engine in deny_rm_engines() {
620 for command in [
621 "ls *.rs",
622 "echo $HOME",
623 "[ -f x ] && ls",
624 "find . -name '*.rs'",
625 "if true; then ls; fi",
626 "rmdir x",
627 "sudo -u root ls",
628 "command -v rm",
629 "command -pV rm",
630 "sudo -E ls $f",
631 "nice -5 ls",
632 "timeout -v 5 ls",
633 "xargs -I{} echo {}",
634 "find . -exec grep -l x {} +",
635 "cat <<EOF\nhello\nEOF\nls",
636 "for ((i = 0; i < 3; i++)); do echo $i; done",
637 "echo $(echo \")\")",
638 "watch -n 5 ls",
639 "arr=(a b)",
640 "arr+=(c)",
641 "f() { ls; }",
642 "f(){ ls; }",
643 "g++ x.cc",
644 "set -euo pipefail",
645 "hash -r",
646 "grep foo$ file",
647 "~/bin/tool --flag=a%b",
648 "./a.out x=1",
649 "FOO=bar ls",
650 "git rm old.txt",
651 "git rm -f old.txt",
652 "grep rm notes.txt",
653 "grep -rn rm src/",
654 "docker rm my-container",
655 "docker run --rm alpine ls",
656 "docker run --rm alpine git rm old.txt",
657 "uv add rm",
658 "uv run git rm old.txt",
659 "poetry add rm",
660 "perf list rm",
661 "ssh host git rm old.txt",
662 "ssh -N host",
663 "runcon -t unconfined_t git rm old.txt",
664 "script -q /dev/null git rm old.txt",
665 "start-stop-daemon -K -x /bin/rm",
666 "start-stop-daemon -S -x /bin/echo -- hi",
667 "docker run --entrypoint /bin/echo alpine hi",
668 "nix develop -c echo hi",
669 "nix develop --command echo hi",
670 "nix develop --command=echo hi",
671 "nix develop -c grep -c rm notes.txt",
672 "nix shell -c echo hi",
673 "screen -r rm",
674 "/lib64/ld-linux-x86-64.so.2 --list /bin/rm",
675 "grep \"--\" rm notes.txt",
676 "grep -- \"$PATTERN\" notes.txt",
677 "cargo test -p codewhale-engine -- --nocapture",
678 "parallel echo ::: a b",
679 "at -l",
680 "at -q a -l",
681 "at -r 3",
682 "at -d 3",
683 "at -c 3",
684 "batch -l",
685 "awk '{print}'",
686 "awk '{print $1}'",
687 "awk -F: '{print $1}' /etc/passwd",
688 "awk '/foo|bar/ {print}' file.txt",
689 "awk '$1 == \"a\" || $2 == \"b\" {print}' file.txt",
690 "awk '{print $1 / 2}' file.txt",
691 "awk '{print \"system(\\\"rm x\\\")\"}'",
692 "sed -n '/x/p'",
693 "sed 's/foo/bar/g'",
694 "sed -e 's/echo/echoed/g'",
695 "sed 's/e/x/g'",
696 "sed 's/a/b/w readme.txt'",
697 "sed 'y/abcde/ABCDE/'",
698 "sed ':end; s/a/b/; t end'",
699 "sed -i 's/foo/bar/' file.txt",
700 "sed -i '' 's/foo/bar/g' file.txt",
701 "x || ssh host",
702 "echo x | y || ssh host",
703 "echo x | y && ssh host",
704 "echo x | y; ssh host",
705 "ssh host 3< f",
706 "ssh host {fd}< f",
707 "ssh host 3<<< 'rm x'",
708 "ssh host 3<&0",
709 "ssh host 3<<EOF\nrm x\nEOF",
710 "ssh host ls <<EOF\nrm x\nEOF",
711 "ssh host <<EOF\nls\nEOF",
712 "ssh -N host < f",
713 "echo x | ssh -N host",
714 "find . -exec ssh host \\;",
715 "echo x | { a; b; }; ssh host",
716 "echo x | (a; b); ssh host",
717 "{ a; ssh host; } 3< f",
718 "numactl --strict ls",
719 "numactl --strict echo hello",
720 "echo $(whoami)",
721 "echo $(date)",
722 "git commit -m $(cat msg)",
723 "ls $DIR",
724 "docker ps",
725 "docker ps --filter \"$F\"",
726 "docker run --rm alpine echo $(whoami)",
727 "docker run --rm -e \"$FOO\" alpine ls",
728 "docker run --rm --env=\"$FOO\" alpine ls",
729 "docker run --entrypoint '' alpine ls",
730 "nix --version",
731 "nix build $FLAKE",
732 "npm test $FILTER",
733 "runuser -u root -- echo $(date)",
734 "flock /tmp/lock echo $(date)",
735 "script -q /dev/null echo $(date)",
736 "bash ./script.sh $ARG",
737 "find $DIR -name \"$PAT\"",
738 "screen -r \"$SESSION\"",
739 "tmux list-sessions",
740 "tmux ls",
741 "tmux display-message \"hi\"",
742 "tmux attach",
743 "tmux attach-session -t work",
744 "tmux -V",
745 "tmux display-popup -C",
746 "tmux display-popup -E ls",
747 "tmux display-popup -T 'rm x' ls",
748 "tmux confirm-before -p 'rm?' kill-pane",
749 "tmux confirm-before -b -c y 'display-message hi'",
750 "tmux command-prompt -p 'Rename:' \"rename-window '%%'\"",
751 "tmux command-prompt -p 'rm?' \"rename-window '%%'\"",
752 "tmux command-prompt -p -I \"rename-window '%%'\"",
753 "tmux command-prompt -I 'mywin' \"rename-window '%%'\"",
754 "tmux bind-key -n k list-sessions",
755 "tmux bind-key -N 'rm shortcut' k display-message hi",
756 "tmux bind-key -r -N 'note' k",
757 "tmux source-file -n ~/.tmux.conf",
758 "tmux source-file -n -t %0 ~/.tmux.conf",
759 "tmux if-shell -F '#{==:#{session_name},work}' 'display-message ok'",
760 "tmux pipe-pane",
761 "tmux send-keys -t s 'ls' Enter",
762 "oc get pods",
763 "oc rsh pod",
764 "oc exec pod -- ls",
765 "oc exec --namespace=\"$NS\" pod -- ls",
766 "vagrant status",
767 "vagrant ssh",
768 "vagrant ssh -c 'ls'",
769 "op item list",
770 "op run --env-file .env -- ls",
771 "op run --env-file=\"$ENV_FILE\" -- ls",
772 "opam list",
773 "opam exec -- ls",
774 "helm list",
775 "helm status my-release",
776 "helm template .",
777 "helm template . --namespace=\"$NS\"",
778 "helm template . --post-renderer kustomize",
779 "helm plugin list",
780 ] {
781 let decision = engine
782 .check(context(command, AskForApproval::Never))
783 .expect("policy check");
784 assert!(decision.allow, "{command:?} was denied: {decision:?}");
785 }
786 }
787 // Without any deny rule, a runtime-resolved word is left to the mode.
788 let open = ExecPolicyEngine::new(vec![], vec![]);
789 for command in ["v=ls; $v", "echo $HOME", "ls *.rs"] {
790 let decision = open
791 .check(context(command, AskForApproval::Never))
792 .expect("policy check");
793 assert!(decision.allow, "{command:?} was denied: {decision:?}");
794 }
795 }
796
797 #[test]
798 fn trusted_prefix_does_not_cover_interposed_options_or_nested_code() {
799 let engine = ExecPolicyEngine::new(vec!["git status".to_string(), "ls".to_string()], vec![]);
800 let trusted = |command: &str| {
801 matches!(
802 engine
803 .check(context(command, AskForApproval::UnlessTrusted))
804 .expect("policy check")
805 .requirement,
806 ExecApprovalRequirement::Skip { .. }
807 )
808 };
809 assert!(trusted("git status"));
810 assert!(trusted("git status -s --porcelain"));
811 assert!(trusted("ls -la"));
812 for command in [
813 "git -ccore.fsmonitor=x status",
814 "git -c core.fsmonitor=x status",
815 "git --exec-path=/x status",
816 "git -C /elsewhere status",
817 "ls $(touch x)",
818 "ls `touch x`",
819 "$L -la",
820 ] {
821 assert!(!trusted(command), "{command:?} was auto-approved");
822 }
823
824 let dict = BashArityDict::new();
825 assert!(!dict.allow_rule_matches("git status", "git --exec-path=/x status"));
826 assert!(dict.allow_rule_matches("python -m pytest", "python -m pytest -x"));
827 assert!(!dict.allow_rule_matches("python -m pytest", "python -m pip install x"));
828 }
829
830 #[test]
831 fn file_rules_fail_closed_on_runtime_resolved_words() {
832 let config = ExecPolicyConfig::parse(
833 r#"
834 [rules.shell]
835 allow = ["git status", "ls"]
836 deny = ["rm", "rm *"]
837 "#,
838 )
839 .expect("parse rules");
840 let budget = budget_commands();
841 let missed: Vec<&str> = HIDDEN_RM
842 .iter()
843 .copied()
844 .chain(budget.iter().map(String::as_str))
845 .filter(|command| !matches!(config.evaluate(command), RuleDecision::Deny(_)))
846 .collect();
847 assert!(missed.is_empty(), "not denied: {missed:#?}");
848 assert_eq!(config.evaluate("git status -s"), RuleDecision::Allow);
849 for command in ["git -ccore.fsmonitor=x status", "ls $(touch x)"] {
850 assert!(
851 matches!(config.evaluate(command), RuleDecision::AskUser(_)),
852 "{command:?} was auto-approved"
853 );
854 }
855 }
856
857 #[test]
858 fn agent_read_only_rejects_a_glob_that_can_expand_to_an_option() {
859 for command in ["rg foo *", "ls *", "git log ''*", "cat *.md"] {
860 assert!(
861 !is_agent_readonly_shell_command(command),
862 "{command:?} was classified read-only"
863 );
864 }
865 for command in [
866 "ls src/*",
867 "rg foo ./*",
868 "find . -name '*.rs'",
869 "cat README.md",
870 ] {
871 assert!(
872 is_agent_readonly_shell_command(command),
873 "{command:?} was rejected"
874 );
875 }
876 }
877
878 #[test]
879 fn parallel_read_only_rejects_parentheses() {
880 assert!(is_parallel_readonly_command("cat README.md"));
881 for command in [
882 "cat .(e:'touch pwned':)",
883 "ls foo(e:'id':)",
884 "rg needle .(+cmd)",
885 "cat (id)",
886 "gh pr view 1(e:'id':)",
887 ] {
888 assert!(
889 !is_parallel_readonly_command(command),
890 "{command:?} was classified read-only"
891 );
892 }
893 }
894
895 #[test]
896 fn typed_deny_rule_skips_global_options_before_the_subcommand() {
897 let engine = ExecPolicyEngine::with_rulesets(vec![
898 Ruleset::user(vec![], vec![]).with_ask_rules(vec![ToolAskRule {
899 action: PermissionAction::Deny,
900 workspace: Some("/workspace".to_string()),
901 ..ToolAskRule::exec_shell("git push")
902 }]),
903 ]);
904 for command in [
905 "git push",
906 "git -C . push",
907 "git -c a=b push origin main",
908 "git --no-pager push",
909 ] {
910 assert!(denied(&engine, command), "{command} must be denied");
911 }
912 assert!(!denied(&engine, "git -C . status"));
913 // The rule stays scoped to its workspace.
914 let elsewhere = ExecPolicyContext {
915 cwd: "/other",
916 ..context("git -C . push", AskForApproval::Never)
917 };
918 assert!(engine.check(elsewhere).expect("policy check").allow);
919 }
920
921 #[test]
922 fn subcommand_deny_rules_hold_against_glob_group_spellings() {
923 let engines = [
924 ExecPolicyEngine::new(vec![], vec!["git push".to_string()]),
925 ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(vec![
926 ToolAskRule {
927 action: PermissionAction::Deny,
928 ..ToolAskRule::exec_shell("git push")
929 },
930 ])]),
931 ];
932 for engine in &engines {
933 for command in [
934 "git push",
935 "/usr/bin/git(N) push",
936 "/usr/bin/(g)it push",
937 "g=git; $=g push",
938 ] {
939 assert!(denied(engine, command), "{command} must be denied");
940 }
941 for command in ["git status", "git log --oneline -3"] {
942 let decision = engine
943 .check(context(command, AskForApproval::Never))
944 .expect("policy check");
945 assert!(decision.allow, "{command:?} was denied: {decision:?}");
946 }
947 }
948 }
949
949 lines RUST