1#![expect(
2 clippy::indexing_slicing,
3 reason = "Dangerous-command matching uses validated token lengths and fixed ASCII option prefixes."
4)]
5
6pub fn command_might_be_dangerous(command: &[String]) -> bool {
20 let Some(command) = unwrap_command_prefix(command) else {
21 return !command.is_empty();
22 };
23 let Some(executable) = command.first() else {
24 return false;
25 };
26 if executable_is_dynamic(executable) {
27 return true;
28 }
29
30 if is_encoded_powershell_invocation(command) {
34 return true;
35 }
36
37 #[cfg(windows)]
38 {
39 if crate::command_safety::windows::is_dangerous_command_windows(command) {
40 return true;
41 }
42 }
43
44 if is_dangerous_to_call_with_exec(command) {
45 return true;
46 }
47
48 if command.len() >= 3
51 && matches!(extract_command_name(&command[0]), "bash" | "sh" | "zsh")
52 && (command[1] == "-c" || command[1] == "-lc" || command[1] == "-ilc")
53 {
54 let script = &command[2];
55 if let Ok(sub_commands) = crate::command_safety::shell_parser::parse_shell_commands(script) {
56 for sub_cmd in sub_commands {
57 if command_might_be_dangerous(&sub_cmd) {
58 return true;
59 }
60 }
61 } else {
62 return true;
63 }
64 }
65
66 false
67}
68
69pub fn command_requires_approval(command: &[String]) -> bool {
77 let Some(command) = unwrap_command_prefix(command) else {
78 return false;
79 };
80 if is_inline_code_execution(command) {
81 return true;
82 }
83
84 if command.len() >= 3
85 && matches!(extract_command_name(&command[0]), "bash" | "sh" | "zsh")
86 && matches!(command[1].as_str(), "-c" | "-lc" | "-ilc")
87 && let Ok(commands) = crate::command_safety::shell_parser::parse_shell_commands(&command[2])
88 {
89 return commands.iter().any(|nested| command_requires_approval(nested));
90 }
91
92 false
93}
94
95fn executable_is_dynamic(executable: &str) -> bool {
96 executable
97 .chars()
98 .any(|character| matches!(character, '$' | '`' | '*' | '?' | '[' | ']' | '{' | '}'))
99}
100
101fn is_environment_assignment(argument: &str) -> bool {
102 let Some((name, _value)) = argument.split_once('=') else {
103 return false;
104 };
105 let mut characters = name.chars();
106 characters
107 .next()
108 .is_some_and(|character| character == '_' || character.is_ascii_alphabetic())
109 && characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
110}
111
112pub(super) struct UnwrappedCommand<'a> {
113 pub(super) command: &'a [String],
114 pub(super) changes_directory: bool,
115}
116
117const PROGRAM_RUNNERS: &[&str] = &["builtin", "command", "exec", "nohup", "setsid", "time"];
123
124const LOOKUP_ONLY_OPTIONS: &[&str] = &["-p", "-v", "-V"];
126
127pub(super) fn unwrap_command_prefix(command: &[String]) -> Option<&[String]> {
128 unwrap_command_prefix_with_context(command).map(|unwrapped| unwrapped.command)
129}
130
131pub(super) fn unwrap_command_prefix_with_context(mut command: &[String]) -> Option<UnwrappedCommand<'_>> {
132 let mut changes_directory = false;
133 loop {
134 while command.first().is_some_and(|argument| is_environment_assignment(argument)) {
135 command = &command[1..];
136 }
137 let executable = command.first()?;
138 match extract_command_name(executable) {
139 "env" => {
140 command = &command[1..];
141 while let Some(argument) = command.first().map(String::as_str) {
142 if is_environment_assignment(argument) || matches!(argument, "-i" | "--ignore-environment") {
143 command = &command[1..];
144 } else if matches!(argument, "-u" | "--unset") {
145 command = command.get(2..)?;
146 } else if argument.starts_with("--unset=") {
147 command = &command[1..];
148 } else if argument == "--" {
149 command = &command[1..];
150 break;
151 } else if argument.starts_with('-') {
152 return None;
153 } else {
154 break;
155 }
156 }
157 }
158 "sudo" => {
159 command = &command[1..];
160 while let Some(argument) = command.first().map(String::as_str) {
161 if argument == "--" {
162 command = &command[1..];
163 break;
164 }
165 if matches!(argument, "-u" | "--user" | "-g" | "--group" | "-h" | "--host" | "-C" | "--chdir") {
166 changes_directory |= argument == "--chdir";
167 command = command.get(2..)?;
168 } else if matches!(argument, "-E" | "-H" | "-n" | "-S" | "-k" | "-K" | "-b")
169 || argument.starts_with("--user=")
170 || argument.starts_with("--group=")
171 || argument.starts_with("--host=")
172 || argument.starts_with("--chdir=")
173 {
174 changes_directory |= argument.starts_with("--chdir=");
175 command = &command[1..];
176 } else if argument.starts_with('-') {
177 return None;
178 } else {
179 break;
180 }
181 }
182 }
183 name if PROGRAM_RUNNERS.contains(&name) => {
184 let (options, program) = split_runner_options(command.get(1..)?);
185 if matches!(name, "builtin" | "command")
186 && options.iter().any(|option| LOOKUP_ONLY_OPTIONS.contains(&option.as_str()))
187 {
188 return Some(UnwrappedCommand { command, changes_directory });
190 }
191 command = program;
192 }
193 _ => return Some(UnwrappedCommand { command, changes_directory }),
194 }
195 }
196}
197
198fn split_runner_options(arguments: &[String]) -> (&[String], &[String]) {
200 let mut index = 0;
201 while index < arguments.len() && arguments[index].starts_with('-') {
202 index += 1;
203 }
204 arguments.split_at(index)
205}
206
207fn is_inline_code_execution(command: &[String]) -> bool {
208 let Some(executable) = command.first().map(|value| extract_command_name(value).to_ascii_lowercase()) else {
209 return false;
210 };
211 let arguments = &command[1..];
212 match executable.as_str() {
213 "python" | "python3" | "python.exe" | "python3.exe" => arguments.iter().any(|argument| argument == "-c"),
214 "node" | "node.exe" | "ruby" | "ruby.exe" | "perl" | "perl.exe" | "osascript" => {
215 arguments.iter().any(|argument| argument == "-e")
216 }
217 "php" | "php.exe" => arguments.iter().any(|argument| argument == "-r"),
218 "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => arguments.iter().any(|argument| {
219 ["-command", "-c", "-encodedcommand", "-encoded", "-enc", "-e"]
220 .iter()
221 .any(|option| argument.eq_ignore_ascii_case(option))
222 }),
223 _ => false,
224 }
225}
226
227fn is_encoded_powershell_invocation(command: &[String]) -> bool {
228 let Some(executable) = command.first() else {
229 return false;
230 };
231 let executable = extract_command_name(executable).to_ascii_lowercase();
232 if !matches!(executable.as_str(), "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe") {
233 return false;
234 }
235
236 command.iter().skip(1).any(|argument| {
237 ["-encodedcommand", "-encoded", "-enc", "-e"]
238 .iter()
239 .any(|option| argument.eq_ignore_ascii_case(option))
240 })
241}
242
243fn is_git_global_option_with_value(arg: &str) -> bool {
245 matches!(
246 arg,
247 "-C" | "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" | "--super-prefix" | "--work-tree"
248 )
249}
250
251fn is_git_global_option_with_inline_value(arg: &str) -> bool {
253 matches!(
254 arg,
255 s if s.starts_with("--config-env=")
256 || s.starts_with("--exec-path=")
257 || s.starts_with("--git-dir=")
258 || s.starts_with("--namespace=")
259 || s.starts_with("--super-prefix=")
260 || s.starts_with("--work-tree=")
261 ) || ((arg.starts_with("-C") || arg.starts_with("-c")) && arg.len() > 2)
262}
263
264pub fn git_global_option_requires_prompt(arg: &str) -> bool {
267 matches!(
268 arg,
269 "-C" | "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" | "--super-prefix" | "--work-tree"
270 ) || matches!(
271 arg,
272 s if (s.starts_with("-C") && s.len() > 2)
273 || (s.starts_with("-c") && s.len() > 2)
274 || s.starts_with("--config-env=")
275 || s.starts_with("--exec-path=")
276 || s.starts_with("--git-dir=")
277 || s.starts_with("--namespace=")
278 || s.starts_with("--super-prefix=")
279 || s.starts_with("--work-tree=")
280 )
281}
282
283pub(crate) fn find_git_subcommand<'a>(command: &'a [String], subcommands: &[&str]) -> Option<(usize, &'a str)> {
288 let cmd0 = command.first().map(String::as_str)?;
289 if !cmd0.ends_with("git") {
290 return None;
291 }
292
293 let mut skip_next = false;
294 for (idx, arg) in command.iter().enumerate().skip(1) {
295 if skip_next {
296 skip_next = false;
297 continue;
298 }
299
300 let arg = arg.as_str();
301
302 if is_git_global_option_with_inline_value(arg) {
303 continue;
304 }
305
306 if is_git_global_option_with_value(arg) {
307 skip_next = true;
308 continue;
309 }
310
311 if arg == "--" || arg.starts_with('-') {
312 continue;
313 }
314
315 if subcommands.contains(&arg) {
316 return Some((idx, arg));
317 }
318
319 return None;
323 }
324
325 None
326}
327
328fn short_flag_group_contains(arg: &str, target: char) -> bool {
330 arg.starts_with('-') && !arg.starts_with("--") && arg.chars().skip(1).any(|c| c == target)
331}
332
333fn git_push_is_dangerous(push_args: &[String]) -> bool {
335 push_args.iter().map(String::as_str).any(|arg| {
336 matches!(arg, "--force" | "--force-with-lease" | "--force-if-includes" | "--delete" | "-f" | "-d")
337 || arg.starts_with("--force-with-lease=")
338 || arg.starts_with("--force-if-includes=")
339 || arg.starts_with("--delete=")
340 || short_flag_group_contains(arg, 'f')
341 || short_flag_group_contains(arg, 'd')
342 || git_push_refspec_is_dangerous(arg)
343 })
344}
345
346fn git_push_refspec_is_dangerous(arg: &str) -> bool {
348 (arg.starts_with('+') || arg.starts_with(':')) && arg.len() > 1
350}
351
352fn git_clean_is_force(clean_args: &[String]) -> bool {
354 clean_args.iter().map(String::as_str).any(|arg| {
355 matches!(arg, "--force" | "-f") || arg.starts_with("--force=") || short_flag_group_contains(arg, 'f')
356 })
357}
358
359const GIT_GUARDED_SUBCOMMANDS: &[&str] = &["reset", "rm", "branch", "push", "clean"];
364
365fn git_reset_is_destructive(reset_args: &[String]) -> bool {
368 reset_args
369 .iter()
370 .any(|arg| matches!(arg.as_str(), "--hard" | "--merge" | "--keep"))
371}
372
373fn git_rm_is_destructive(rm_args: &[String]) -> bool {
376 !rm_args.iter().any(|arg| arg == "--cached")
377}
378
379fn git_branch_is_force_delete(branch_args: &[String]) -> bool {
384 let mut deletes = false;
385 let mut forces = false;
386 for arg in branch_args {
387 match arg.as_str() {
388 "-D" => {
389 deletes = true;
390 forces = true;
391 }
392 "-d" | "--delete" => deletes = true,
393 "-f" | "--force" => forces = true,
394 _ => {
395 if arg.starts_with("--delete=") {
396 deletes = true;
397 }
398 if arg.starts_with("--force=") {
399 forces = true;
400 }
401 if short_flag_group_contains(arg, 'd') {
402 deletes = true;
403 }
404 if short_flag_group_contains(arg, 'D') {
405 deletes = true;
406 forces = true;
407 }
408 if short_flag_group_contains(arg, 'f') {
409 forces = true;
410 }
411 }
412 }
413 }
414 deletes && forces
415}
416
417fn classify_git_subcommand(subcommand: &str, args: &[String]) -> Option<&'static str> {
422 let scan_args = if subcommand == "push" {
431 args
432 } else {
433 match args.iter().position(|arg| arg == "--") {
434 Some(end) => &args[..end],
435 None => args,
436 }
437 };
438 match subcommand {
439 "reset" if git_reset_is_destructive(scan_args) => {
440 Some("git reset --hard/--merge/--keep discards uncommitted changes; use `git stash` or `git reset --soft`")
441 }
442 "rm" if git_rm_is_destructive(scan_args) => {
443 Some("git rm deletes working-tree files; unstage with `git rm --cached` instead")
444 }
445 "branch" if git_branch_is_force_delete(scan_args) => {
446 Some("git branch -D/--delete --force skips the unmerged-branch guard; use `-d` for merged branches")
447 }
448 "push" if git_push_is_dangerous(scan_args) => Some("git push force-updates or deletes remote refs"),
449 "clean" if git_clean_is_force(scan_args) => Some("git clean --force deletes untracked files"),
450 _ => None,
451 }
452}
453
454pub fn dangerous_command_reason(command: &[String]) -> Option<&'static str> {
459 let command = unwrap_command_prefix(command)?;
460 let cmd0 = command.first().map(String::as_str);
461 let (idx, subcommand) = if extract_command_name(cmd0.unwrap_or("")) == "git" {
462 find_git_subcommand(command, GIT_GUARDED_SUBCOMMANDS)?
463 } else {
464 let (idx, subcommand) = find_git_subcommand_from_args(command, GIT_GUARDED_SUBCOMMANDS)?;
468 if subcommand == "rm" {
469 return None;
470 }
471 (idx, subcommand)
472 };
473 classify_git_subcommand(subcommand, &command[idx + 1..])
474}
475
476fn is_dangerous_git_subcommand(command: &[String]) -> bool {
479 find_git_subcommand_from_args(command, GIT_GUARDED_SUBCOMMANDS)
480 .and_then(|(idx, subcommand)| classify_git_subcommand(subcommand, &command[idx + 1..]))
481 .is_some()
482}
483
484fn find_git_subcommand_from_args<'a>(args: &'a [String], subcommands: &[&str]) -> Option<(usize, &'a str)> {
486 let mut skip_next = false;
487 for (idx, arg) in args.iter().enumerate() {
488 if skip_next {
489 skip_next = false;
490 continue;
491 }
492
493 let arg = arg.as_str();
494
495 if is_git_global_option_with_inline_value(arg) {
496 continue;
497 }
498
499 if is_git_global_option_with_value(arg) {
500 skip_next = true;
501 continue;
502 }
503
504 if arg == "--" || arg.starts_with('-') {
505 continue;
506 }
507
508 if subcommands.contains(&arg) {
509 return Some((idx, arg));
510 }
511
512 return None;
514 }
515
516 None
517}
518
519fn is_dangerous_to_call_with_exec(command: &[String]) -> bool {
521 if command.is_empty() {
522 return false;
523 }
524
525 let cmd0 = command.first().map(String::as_str);
526 let base_cmd = extract_command_name(cmd0.unwrap_or(""));
527
528 match base_cmd {
529 "git" => {
531 let Some((subcommand_idx, subcommand)) = find_git_subcommand(command, GIT_GUARDED_SUBCOMMANDS) else {
532 return false;
533 };
534
535 classify_git_subcommand(subcommand, &command[subcommand_idx + 1..]).is_some()
536 }
537
538 "rm" => matches!(command.get(1).map(String::as_str), Some("-f" | "-rf" | "-fr" | "-r")),
540
541 _ if base_cmd == "mkfs" || base_cmd.starts_with("mkfs.") => true,
543 "dd" | "shutdown" | "reboot" | "init" => true,
544
545 _ if base_cmd.ends_with(':') && command.len() >= 2 => command[1] == "(){:|:&};:",
547
548 "sudo" => {
550 if command.len() > 1 {
551 is_dangerous_to_call_with_exec(&command[1..])
552 } else {
553 false
554 }
555 }
556
557 _ => is_dangerous_git_subcommand(command),
559 }
560}
561
562fn extract_command_name(cmd: &str) -> &str {
564 std::path::Path::new(cmd)
565 .file_name()
566 .and_then(|osstr| osstr.to_str())
567 .unwrap_or(cmd)
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573
574 fn vec_str(args: &[&str]) -> Vec<String> {
575 args.iter().map(|s| s.to_string()).collect()
576 }
577
578 #[test]
579 fn powershell_encoded_options_remain_hard_denials_in_any_ascii_case() {
580 for executable in ["powershell", "PowerShell.exe", "pwsh", "PWSH.EXE", "/usr/bin/pwsh"] {
581 for option in ["-encodedcommand", "-encoded", "-enc", "-e"] {
582 for variant in [option.to_string(), option.to_ascii_uppercase()] {
583 let command = vec_str(&[executable, "-NoProfile", &variant, "ZQ=="]);
584 assert!(command_might_be_dangerous(&command), "hard denial: {command:?}");
585 assert!(command_requires_approval(&command), "approval classification: {command:?}");
586 }
587 }
588 }
589 let wrapped = vec_str(&["env", "MODE=test", "pwsh", "-EnCoDeDcOmMaNd", "ZQ=="]);
590 assert!(command_might_be_dangerous(&wrapped));
591 assert!(command_requires_approval(&wrapped));
592 }
593
594 #[test]
595 fn powershell_inline_options_require_approval_without_hard_denial() {
596 for executable in ["powershell", "powershell.exe", "pwsh", "pwsh.exe"] {
597 for option in ["-command", "-c", "-Command", "-COMMAND", "-C"] {
598 let command = vec_str(&[executable, "-NoProfile", option, "Write-Output ok"]);
599 assert!(!command_might_be_dangerous(&command), "inline code: {command:?}");
600 assert!(command_requires_approval(&command), "approval: {command:?}");
601 }
602 }
603 }
604
605 #[test]
606 fn powershell_option_near_misses_and_non_powershell_programs_stay_distinct() {
607 for option in [
608 "-commands",
609 "-encodedcommandx",
610 "--enc",
611 "enc",
612 "-en",
613 "-e=ZQ==",
614 "-command ",
615 " -command",
616 "-commánd",
617 "-enç",
618 ] {
619 let command = vec_str(&["pwsh", option, "example.ps1"]);
620 assert!(!command_might_be_dangerous(&command), "near miss: {command:?}");
621 assert!(!command_requires_approval(&command), "near miss: {command:?}");
622 }
623 for command in [
624 vec_str(&["pwsh", "-File", "example.ps1"]),
625 vec_str(&["echo", "-ENCODEDCOMMAND", "ZQ=="]),
626 ] {
627 assert!(!command_might_be_dangerous(&command), "ordinary arguments: {command:?}");
628 assert!(!command_requires_approval(&command), "ordinary arguments: {command:?}");
629 }
630 }
631
632 #[test]
633 fn git_reset_recoverable_modes_pass_preflight() {
634 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "reset"])));
637 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--soft", "HEAD~1"])));
638 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--mixed", "HEAD~1"])));
639 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "HEAD~1", "--", "file.txt"])));
640 }
641
642 #[test]
643 fn git_reset_destructive_modes_still_preflight_blocked() {
644 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--hard"])));
645 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--merge"])));
646 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--keep"])));
647 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "-C", "sub", "reset", "--hard"])));
649 assert!(command_might_be_dangerous(&vec_str(&["sudo", "git", "reset", "--hard"])));
650 assert!(
651 command_might_be_dangerous(&vec_str(&["FOO=bar", "env", "git", "reset", "--hard"])),
652 "env-prefixed destructive reset must stay blocked"
653 );
654 }
655
656 #[test]
657 fn git_rm_index_only_passes_preflight_and_working_tree_delete_stays_blocked() {
658 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "file.txt"])));
659 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "-rf", "dir"])));
660 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "--cached", "file.txt"])));
661 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "-r", "--cached", "dir"])));
662 assert!(
663 is_dangerous_to_call_with_exec(&vec_str(&["sudo", "git", "rm", "file.txt"])),
664 "sudo-wrapped working-tree delete must stay blocked"
665 );
666 }
667
668 #[test]
669 fn git_branch_force_delete_is_blocked_but_merged_delete_passes() {
670 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "-d", "feature"])));
672 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "--delete", "feature"])));
673 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "-D", "feature"])));
674 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "--delete", "--force", "feature"])));
675 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "-d", "-f", "feature"])));
676 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "-df", "feature"])));
677 }
678
679 #[test]
680 fn end_of_options_separator_cannot_hide_working_tree_git_rm() {
681 assert!(
685 is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "--", "--cached", "file.txt"])),
686 "`--cached` after `--` is a path; the invocation deletes working-tree files"
687 );
688 assert!(
689 is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "--ignore-unmatch", "--", "--cached", "file.txt"])),
690 "--ignore-unmatch must not let a missing `--cached` path mask the deletion"
691 );
692 assert!(is_dangerous_to_call_with_exec(&vec_str(&["sudo", "git", "rm", "--", "--cached", "file.txt"])));
693 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "rm", "--cached", "--", "file.txt"])));
695 let reason = dangerous_command_reason(&vec_str(&["git", "rm", "--", "--cached", "file.txt"]))
697 .expect("end-of-options git rm carries a reason");
698 assert!(reason.contains("git rm"), "reason should name the pattern: {reason}");
699 }
700
701 #[test]
702 fn end_of_options_separator_stops_flag_classification_for_other_guarded_subcommands() {
703 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--", "--hard"])));
706 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "--", "-D", "feature"])));
707 assert!(!is_dangerous_to_call_with_exec(&vec_str(&["git", "clean", "--", "-fd"])));
708 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "reset", "--hard", "--", "file.txt"])));
710 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "branch", "-D", "--", "feature"])));
711 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "clean", "-fd", "--", "dir"])));
712 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "push", "origin", "--", "--force"])));
715 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "push", "origin", "--", ":refs/heads/main"])));
716 assert!(is_dangerous_to_call_with_exec(&vec_str(&["git", "push", "--force", "--", "origin", "main"])));
717 }
718
719 #[test]
720 fn dangerous_command_reason_names_git_pattern_and_skips_safe_commands() {
721 let destructive = vec_str(&["git", "reset", "--hard"]);
722 let reason = dangerous_command_reason(&destructive).expect("git reset --hard carries a reason");
723 assert!(reason.contains("git reset"), "reason should name the pattern: {reason}");
724
725 let recoverable = vec_str(&["git", "reset", "--soft", "HEAD~1"]);
726 assert!(dangerous_command_reason(&recoverable).is_none());
727
728 let safe = vec_str(&["git", "status"]);
729 assert!(dangerous_command_reason(&safe).is_none());
730
731 let pushed = vec_str(&["sudo", "git", "rm", "file.txt"]);
732 let sudo_reason = dangerous_command_reason(&pushed).expect("sudo-wrapped git rm carries a reason");
733 assert!(sudo_reason.contains("git rm"), "sudo prefix must be unwrapped: {sudo_reason}");
734 }
735
736 #[test]
737 fn dangerous_command_reason_does_not_label_plain_rm_as_git_rm() {
738 for cmd in [
742 vec_str(&["rm", "-f", "build.log"]),
743 vec_str(&["rm", "-rf", "dir"]),
744 vec_str(&["sudo", "rm", "-rf", "/tmp/x"]),
745 ] {
746 assert!(command_might_be_dangerous(&cmd), "plain rm must stay classified dangerous: {cmd:?}");
747 assert_eq!(dangerous_command_reason(&cmd), None, "plain rm must not receive the git rm remedy: {cmd:?}");
748 }
749 }
750
751 #[test]
752 fn git_status_is_safe() {
753 let cmd = vec!["git".to_string(), "status".to_string()];
754 assert!(!is_dangerous_to_call_with_exec(&cmd));
755 }
756
757 #[test]
758 fn git_log_is_safe() {
759 let cmd = vec!["git".to_string(), "log".to_string()];
760 assert!(!is_dangerous_to_call_with_exec(&cmd));
761 }
762
763 #[test]
764 fn rm_f_is_dangerous() {
765 let cmd = vec!["rm".to_string(), "-f".to_string(), "file.txt".to_string()];
766 assert!(is_dangerous_to_call_with_exec(&cmd));
767 }
768
769 #[test]
770 fn rm_rf_is_dangerous() {
771 let cmd = vec!["rm".to_string(), "-rf".to_string(), "/".to_string()];
772 assert!(is_dangerous_to_call_with_exec(&cmd));
773 }
774
775 #[test]
776 fn rm_without_flags_is_safe() {
777 let cmd = vec!["rm".to_string()];
778 assert!(!is_dangerous_to_call_with_exec(&cmd));
779 }
780
781 #[test]
784 fn launcher_prefixes_cannot_hide_a_destructive_command() {
785 for runner in ["nohup", "setsid", "time", "exec", "command", "builtin"] {
786 for destructive in [
787 vec!["rm", "-rf", "/"],
788 vec!["rm", "-f", "file.txt"],
789 vec!["git", "reset", "--hard", "HEAD~1"],
790 vec!["dd", "if=/dev/zero", "of=/dev/sda"],
791 ] {
792 let mut command = vec![runner.to_string()];
793 command.extend(destructive.iter().map(|word| (*word).to_string()));
794 assert!(
795 command_might_be_dangerous(&command),
796 "{runner} must not hide a destructive command: {command:?}"
797 );
798 }
799 }
800 }
801
802 #[test]
805 fn command_lookup_options_do_not_run_the_program() {
806 for command in [
807 vec!["command", "-v", "rm"],
808 vec!["command", "-V", "rm"],
809 vec!["builtin", "-p", "rm"],
810 ] {
811 let command: Vec<String> = command.into_iter().map(str::to_owned).collect();
812 assert!(
813 !command_might_be_dangerous(&command),
814 "a path lookup must not be classified as the program: {command:?}"
815 );
816 }
817 }
818
819 #[test]
821 fn runner_options_are_skipped_before_the_program() {
822 for command in [
823 vec!["nohup", "--", "rm", "-rf", "/"],
824 vec!["time", "-p", "rm", "-rf", "/"],
825 ] {
826 let command: Vec<String> = command.into_iter().map(str::to_owned).collect();
827 assert!(command_might_be_dangerous(&command), "runner options must not hide the program: {command:?}");
828 }
829 }
830
831 #[test]
832 fn mkfs_is_dangerous() {
833 let cmd = vec!["mkfs".to_string()];
834 assert!(is_dangerous_to_call_with_exec(&cmd));
835 }
836
837 #[test]
838 fn mkfs_variants_are_dangerous() {
839 let cmd = vec!["mkfs.ext4".to_string(), "/dev/sda1".to_string()];
840 assert!(is_dangerous_to_call_with_exec(&cmd));
841 }
842
843 #[test]
844 fn dd_is_dangerous() {
845 let cmd = vec!["dd".to_string(), "if=/dev/zero".to_string()];
846 assert!(is_dangerous_to_call_with_exec(&cmd));
847 }
848
849 #[test]
850 fn shutdown_is_dangerous() {
851 let cmd = vec!["shutdown".to_string()];
852 assert!(is_dangerous_to_call_with_exec(&cmd));
853 }
854
855 #[test]
856 fn sudo_git_reset_is_dangerous() {
857 let cmd = vec![
858 "sudo".to_string(),
859 "git".to_string(),
860 "reset".to_string(),
861 "--hard".to_string(),
862 ];
863 assert!(is_dangerous_to_call_with_exec(&cmd));
864 }
865
866 #[test]
867 fn sudo_git_status_is_safe() {
868 let cmd = vec!["sudo".to_string(), "git".to_string(), "status".to_string()];
869 assert!(!is_dangerous_to_call_with_exec(&cmd));
870 }
871
872 #[test]
873 fn absolute_path_git_reset_hard_is_dangerous() {
874 let cmd = vec!["/usr/bin/git".to_string(), "reset".to_string(), "--hard".to_string()];
875 assert!(is_dangerous_to_call_with_exec(&cmd));
876 let bare = vec!["/usr/bin/git".to_string(), "reset".to_string()];
878 assert!(!is_dangerous_to_call_with_exec(&bare));
879 }
880
881 #[test]
882 fn empty_command_is_safe() {
883 let cmd: Vec<String> = vec![];
884 assert!(!is_dangerous_to_call_with_exec(&cmd));
885 }
886
887 #[test]
888 fn command_might_be_dangerous_detects_git_reset_hard() {
889 let cmd = vec!["git".to_string(), "reset".to_string(), "--hard".to_string()];
890 assert!(command_might_be_dangerous(&cmd));
891 let bare = vec!["git".to_string(), "reset".to_string()];
893 assert!(!command_might_be_dangerous(&bare));
894 }
895
896 #[test]
897 fn command_might_be_dangerous_allows_git_status() {
898 let cmd = vec!["git".to_string(), "status".to_string()];
899 assert!(!command_might_be_dangerous(&cmd));
900 }
901
902 #[test]
903 fn wrappers_and_absolute_executables_do_not_hide_dangerous_commands() {
904 assert!(command_might_be_dangerous(&vec_str(&[
905 "env",
906 "MODE=test",
907 "sudo",
908 "-u",
909 "root",
910 "/usr/bin/git",
911 "reset",
912 "--hard",
913 ])));
914 assert!(command_might_be_dangerous(&vec_str(&["MODE=test", "/bin/sh", "-c", "rm -rf /",])));
915 }
916
917 #[test]
918 fn inline_interpreter_programs_are_code_execution_boundaries() {
919 for command in [
920 vec_str(&["/usr/bin/python3", "-c", "print('ok')"]),
921 vec_str(&["node", "-e", "console.log('ok')"]),
922 vec_str(&["ruby", "-e", "puts 'ok'"]),
923 vec_str(&["perl", "-e", "print 'ok'"]),
924 vec_str(&["php", "-r", "echo 'ok';"]),
925 vec_str(&["osascript", "-e", "return 1"]),
926 vec_str(&["pwsh", "-Command", "Write-Output ok"]),
927 ] {
928 assert!(!command_might_be_dangerous(&command), "inline code is not forbidden outright: {command:?}");
929 assert!(command_requires_approval(&command), "inline code should require policy admission: {command:?}");
930 }
931
932 let nested = vec_str(&["bash", "-lc", "python3 -c 'print(1)'"]);
933 assert!(command_requires_approval(&nested));
934 assert!(!command_might_be_dangerous(&nested));
935 }
936
937 #[test]
938 fn dynamic_or_unknown_wrapped_executables_fail_closed() {
939 assert!(command_might_be_dangerous(&vec_str(&["$TOOL", "status"])));
940 assert!(command_might_be_dangerous(&vec_str(&["env", "--unknown", "git", "status"])));
941 assert!(command_might_be_dangerous(&vec_str(&["sudo", "--unknown", "git", "status"])));
942 }
943
944 #[test]
947 fn git_branch_delete_is_dangerous_only_when_forced() {
948 assert!(!command_might_be_dangerous(&vec_str(&["git", "branch", "-d", "feature",])));
950 assert!(command_might_be_dangerous(&vec_str(&["git", "branch", "-D", "feature",])));
951 let script = "git branch --delete --force feature";
953 if let Ok(sub_commands) = crate::command_safety::shell_parser::parse_shell_commands(script) {
954 for sub_cmd in sub_commands {
955 assert!(command_might_be_dangerous(&sub_cmd), "sub-command should be dangerous: {sub_cmd:?}");
956 }
957 }
958 }
959
960 #[test]
961 fn git_branch_delete_with_stacked_short_flags_is_dangerous_only_when_forced() {
962 assert!(!command_might_be_dangerous(&vec_str(&["git", "branch", "-dv", "feature",])));
965 assert!(!command_might_be_dangerous(&vec_str(&["git", "branch", "-vd", "feature",])));
966 assert!(command_might_be_dangerous(&vec_str(&["git", "branch", "-vD", "feature",])));
967 assert!(command_might_be_dangerous(&vec_str(&["git", "branch", "-Dvv", "feature",])));
968 assert!(command_might_be_dangerous(&vec_str(&["git", "branch", "-df", "feature",])));
969 }
970
971 #[test]
972 fn git_branch_delete_with_global_options_is_dangerous_only_when_forced() {
973 assert!(!command_might_be_dangerous(&vec_str(&["git", "-C", ".", "branch", "-d", "feature",])));
974 assert!(command_might_be_dangerous(&vec_str(&["git", "-c", "color.ui=false", "branch", "-D", "feature",])));
975 let script = "git -C . branch -D feature";
977 if let Ok(sub_commands) = crate::command_safety::shell_parser::parse_shell_commands(script) {
978 for sub_cmd in sub_commands {
979 assert!(command_might_be_dangerous(&sub_cmd), "sub-command should be dangerous: {sub_cmd:?}");
980 }
981 }
982 }
983
984 #[test]
985 fn git_checkout_reset_is_not_dangerous() {
986 assert!(!command_might_be_dangerous(&vec_str(&["git", "checkout", "reset",])));
989 }
990
991 #[test]
994 fn git_push_force_is_dangerous() {
995 assert!(command_might_be_dangerous(&vec_str(&["git", "push", "--force", "origin", "main",])));
996 assert!(command_might_be_dangerous(&vec_str(&["git", "push", "-f", "origin", "main",])));
997 assert!(command_might_be_dangerous(&vec_str(&[
998 "git",
999 "-C",
1000 ".",
1001 "push",
1002 "--force-with-lease",
1003 "origin",
1004 "main",
1005 ])));
1006 }
1007
1008 #[test]
1009 fn git_push_plus_refspec_is_dangerous() {
1010 assert!(command_might_be_dangerous(&vec_str(&["git", "push", "origin", "+main",])));
1011 assert!(command_might_be_dangerous(&vec_str(
1012 &["git", "push", "origin", "+refs/heads/main:refs/heads/main",]
1013 )));
1014 }
1015
1016 #[test]
1017 fn git_push_delete_flag_is_dangerous() {
1018 assert!(command_might_be_dangerous(&vec_str(&["git", "push", "--delete", "origin", "feature",])));
1019 assert!(command_might_be_dangerous(&vec_str(&["git", "push", "-d", "origin", "feature",])));
1020 }
1021
1022 #[test]
1023 fn git_push_delete_refspec_is_dangerous() {
1024 assert!(command_might_be_dangerous(&vec_str(&["git", "push", "origin", ":feature",])));
1025 let script = "git push origin :feature";
1027 if let Ok(sub_commands) = crate::command_safety::shell_parser::parse_shell_commands(script) {
1028 for sub_cmd in sub_commands {
1029 assert!(command_might_be_dangerous(&sub_cmd), "sub-command should be dangerous: {sub_cmd:?}");
1030 }
1031 }
1032 }
1033
1034 #[test]
1035 fn git_push_without_force_is_not_dangerous() {
1036 assert!(!command_might_be_dangerous(&vec_str(&["git", "push", "origin", "main",])));
1037 }
1038
1039 #[test]
1042 fn git_clean_force_is_dangerous_even_when_f_is_not_first_flag() {
1043 assert!(command_might_be_dangerous(&vec_str(&["git", "clean", "-fdx",])));
1044 assert!(command_might_be_dangerous(&vec_str(&["git", "clean", "-xdf",])));
1045 assert!(command_might_be_dangerous(&vec_str(&["git", "clean", "--force",])));
1046 }
1047}