Skip to main content

lean_ctx_ext/core/
command_cwd.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Which directory a command's segments actually run in (GH #1661, #1662).
3//!
4//! A tool call carries one `cwd`, but the command it runs may move: `cd repo &&
5//! grep -rn … .` walks a tree the call never named, and `cd "$SCRATCH" && curl
6//! -o shot.png …` writes to a directory that is sanctioned for exactly that.
7//! Judging either against the call's `cwd` alone gets the answer wrong — too
8//! lenient in the first case, too strict in the second.
9//!
10//! Only a plain `cd <literal>` segment is followed, and only where it is
11//! certain to have run before the next command (#1850). A target spelled
12//! through a variable is followed when that variable is known — `$TMPDIR`, or
13//! one this same command set to a literal (#2079, `command_vars`). Everything
14//! else that can move the shell — any other variable, a substitution,
15//! `pushd`/`popd`, a `cd`
16//! inside a subshell, a brace group, a loop or a function, a `cd` that may be
17//! skipped (`a || cd x`) or may fail (`cd missing; …`) — leaves the directory
18//! unknown, and an unknown directory is reported as such rather than guessed
19//! at. The write guard relies on that: judging a later command against a
20//! directory it does not run in is how a redirect lands in the project.
21//!
22//! Quoted text is data: `printf '… cd /tmp …' > f` does not move anything
23//! (#2081). The exception is `eval`, which runs text in this shell, so any
24//! `eval` leaves the directory unknown.
25
26use std::path::{Path, PathBuf};
27
28use super::command_vars::{KnownVars, expand_leading_variable, literal_assignments_before_each};
29use super::shell_allowlist::Separator;
30
31/// One command segment together with the directory it runs in.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct SegmentCwd {
34    pub segment: String,
35    /// `None` once a `cd` has moved somewhere this cannot resolve statically,
36    /// or when more than one directory is possible.
37    pub cwd: Option<PathBuf>,
38}
39
40/// Split `command` into segments, tracking `cd` as it goes.
41///
42/// Segmentation is delegated to the shell tokenizer so this never disagrees
43/// with the allowlist about where one command ends and the next begins.
44pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
45    track(command, base).0
46}
47
48/// The directory in effect once every segment has run.
49pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
50    track(command, base).1
51}
52
53/// A `cd` that may not be in effect: it can fail (its target does not exist
54/// yet) or be skipped (`a && cd x`, `a || cd x`). Commands reached from it only
55/// through `&&` — and the pipelines among them — run in `moved`; anything that
56/// can also be reached when the `cd` did not happen runs in either directory.
57struct Pending {
58    moved: Option<PathBuf>,
59    /// Where the shell is if this `cd` did not take effect.
60    old: Option<PathBuf>,
61    /// Behind `||`: a successful left side skips the `cd` entirely.
62    skippable: bool,
63    /// `cd x || …`: the next segment is the fallback, which runs only if the
64    /// `cd` did not take effect.
65    fallback: bool,
66}
67
68impl Pending {
69    fn either(self) -> Option<PathBuf> {
70        merge(self.moved, self.old.as_deref())
71    }
72}
73
74fn track(command: &str, base: Option<&Path>) -> (Vec<SegmentCwd>, Option<PathBuf>) {
75    let segments = super::shell_allowlist::segments_with_separators(command);
76    let vars = literal_assignments_before_each(&segments);
77    // `CDPATH` reroutes a relative `cd sub` to wherever it finds `sub` first.
78    let cdpath = std::env::var_os("CDPATH").is_some_and(|v| !v.is_empty())
79        || segments.iter().any(|(s, _)| s.contains("CDPATH"));
80
81    // The directory the next segment starts in.
82    let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
83    // Where the current and-or list started: `a && cd x &` runs the whole list
84    // in a background subshell, so nothing in it moves what comes after.
85    let mut list_base = cwd.clone();
86    let mut pending: Option<Pending> = None;
87    let mut prev: Option<Separator> = None;
88    let mut out = Vec::with_capacity(segments.len());
89
90    for ((segment, sep), vars) in segments.into_iter().zip(vars) {
91        // Every segment runs where it starts — a `cd` included: its own
92        // redirect is opened before it moves, and a failed `cd` stays put.
93        let here = cwd.clone();
94        let mut own = here.clone();
95
96        if let Some(p) = pending.take_if(|p| p.fallback) {
97            // `cd x || exit 1; …` — past the fallback, only a working `cd` is
98            // left. A skippable `cd` is not: `a || cd x || exit` exits on neither
99            // path when `a` succeeds.
100            cwd = if exits(&segment) && !p.skippable {
101                p.moved
102            } else if cd_target(&segment).is_some() || moves_opaquely(&segment) {
103                None
104            } else {
105                p.either()
106            };
107        } else if let Some(target) = cd_target(&segment) {
108            let moved = if cdpath && is_cdpath_candidate(target) {
109                None
110            } else {
111                resolve_cd(here.as_deref(), target, &vars)
112            };
113            // With an uncertain `cd` still open (`cd a && cd b`), not taking
114            // this one leaves the shell in `a` *or* where `a` started.
115            let old = match pending.take() {
116                Some(p) => merge(here.clone(), p.old.as_deref()),
117                None => here.clone(),
118            };
119            let runs_unconditionally = matches!(
120                prev,
121                None | Some(Separator::Sequence | Separator::Background)
122            );
123            if prev == Some(Separator::Pipe) || sep == Some(Separator::Pipe) {
124                // A pipeline element runs in a subshell — in bash. zsh runs the
125                // last one in the current shell, so neither reading is safe.
126                cwd = merge(moved, old.as_deref());
127            } else if runs_unconditionally && moved.as_deref().is_some_and(Path::is_dir) {
128                // Runs, and into a directory that exists: it takes effect.
129                cwd = moved;
130            } else {
131                let skippable = prev == Some(Separator::Or);
132                let p = Pending {
133                    moved,
134                    old,
135                    skippable,
136                    fallback: sep == Some(Separator::Or),
137                };
138                cwd = match sep {
139                    Some(Separator::Or) => p.old.clone(),
140                    Some(Separator::Sequence) => merge(p.moved.clone(), p.old.as_deref()),
141                    _ if skippable => merge(p.moved.clone(), p.old.as_deref()),
142                    _ => p.moved.clone(),
143                };
144                if matches!(sep, Some(Separator::Or | Separator::And) | None) {
145                    pending = Some(p);
146                }
147            }
148        } else {
149            if moves_opaquely(&segment) {
150                own = None;
151                // A subshell `( … )` cannot move what follows it; anything else
152                // (a brace group, a loop body, a function, `pushd`) can.
153                if !segment.starts_with('(') {
154                    cwd = None;
155                    pending = None;
156                }
157            }
158            // Leaving the `&&` chain of an uncertain `cd`: what comes next can
159            // also be reached when that `cd` did not happen.
160            if let Some(p) = pending.take() {
161                match sep {
162                    Some(Separator::And | Separator::Pipe) | None => pending = Some(p),
163                    Some(Separator::Or | Separator::Sequence | Separator::Background) => {
164                        cwd = p.either();
165                    }
166                }
167            }
168        }
169
170        out.push(SegmentCwd { segment, cwd: own });
171        match sep {
172            Some(Separator::Background) => {
173                cwd.clone_from(&list_base);
174                pending = None;
175            }
176            Some(Separator::Sequence) => list_base.clone_from(&cwd),
177            _ => {}
178        }
179        prev = sep;
180    }
181    (out, cwd)
182}
183
184/// One directory when both possibilities agree, otherwise unknown.
185fn merge(a: Option<PathBuf>, b: Option<&Path>) -> Option<PathBuf> {
186    if a.as_deref() == b { a } else { None }
187}
188
189/// A `cd x || exit` fallback: nothing after it runs unless the `cd` worked.
190fn exits(segment: &str) -> bool {
191    matches!(segment.split_whitespace().next(), Some("exit" | "return"))
192}
193
194/// A relative name `CDPATH` would look up (`./x` and `../x` bypass it).
195fn is_cdpath_candidate(target: &str) -> bool {
196    let t = target.trim_matches(['"', '\'']);
197    !(t.starts_with('/')
198        || t.starts_with('~')
199        || t.starts_with("./")
200        || t.starts_with("../")
201        || t == "."
202        || t == ".."
203        || Path::new(t).is_absolute())
204}
205
206/// Whether a segment that is not a plain `cd <literal>` may still change the
207/// directory: `pushd`, `popd`, `cd` after `do`/`then`/`builtin`/`command`, or
208/// any of them inside a subshell, brace group, substitution or function body.
209/// Deliberately broad — a false positive only makes the directory unknown.
210///
211/// Only words the shell runs count (#2081): `printf 'cd /tmp' > f` prints the
212/// words, it does not run them. Two scans together cover that:
213///
214/// - the segment with its quoted text blanked, split at whitespace and
215///   operators — this sees `{ cd x; }`, `${ cd x; }`, `do cd x`;
216/// - the shell's own words, quotes removed, split only at operators — this sees
217///   a quoted command name (`"cd" x`, `c'd' x`), which still runs.
218///
219/// A substitution inside double quotes (`"$(cd x)"`) runs in a subshell and
220/// cannot move this one. `eval` runs arbitrary text in this shell, so any
221/// `eval` makes the directory unknown.
222fn moves_opaquely(segment: &str) -> bool {
223    const MOVERS: [&str; 4] = ["cd", "pushd", "popd", "chdir"];
224    let split_words = |text: &str| -> Vec<String> {
225        text.split(|c: char| c.is_whitespace() || OPERATORS.contains(c))
226            .map(str::to_string)
227            .collect()
228    };
229    let mut words = split_words(&blank_quoted(segment));
230    words.extend(
231        super::shell_allowlist::shell_tokenize(segment)
232            .iter()
233            .flat_map(|token| token.split(|c: char| OPERATORS.contains(c)))
234            .map(str::to_string),
235    );
236    words
237        .iter()
238        .any(|w| w == "eval" || MOVERS.contains(&w.as_str()))
239}
240
241/// Characters that end a shell word besides whitespace.
242const OPERATORS: &str = "(){};&|`";
243
244/// `segment` with every quoted character — quotes included — replaced by a
245/// space, so a word scan sees only what is not quoted. A backslash escapes the
246/// next character outside single quotes, as in the shell.
247fn blank_quoted(segment: &str) -> String {
248    let mut out = String::with_capacity(segment.len());
249    let mut chars = segment.chars();
250    let mut single = false;
251    let mut double = false;
252    while let Some(c) = chars.next() {
253        match c {
254            '\\' if !single => {
255                // Consumed here, the escaped character never toggles a quote.
256                let next = chars.next();
257                if double {
258                    out.push(' ');
259                    if next.is_some() {
260                        out.push(' ');
261                    }
262                } else {
263                    out.push(c);
264                    out.extend(next);
265                }
266            }
267            '\'' if !double => {
268                single = !single;
269                out.push(' ');
270            }
271            '"' if !single => {
272                double = !double;
273                out.push(' ');
274            }
275            _ if single || double => out.push(' '),
276            _ => out.push(c),
277        }
278    }
279    out
280}
281
282/// The literal argument of a segment that is exactly `cd <path>`.
283fn cd_target(segment: &str) -> Option<&str> {
284    let mut words = segment.split_whitespace();
285    if words.next()? != "cd" {
286        return None;
287    }
288    let target = words.next()?;
289    if words.next().is_some() {
290        // `cd a b` is not something to reason about.
291        return None;
292    }
293    Some(target)
294}
295
296/// Apply one `cd`, or give up on knowing the directory.
297///
298/// `cd` with no resolvable target is not "stay here": it moves somewhere this
299/// cannot see. Returning `None` keeps callers from judging a later segment
300/// against a directory it does not run in.
301///
302/// A target that starts with a known variable (`cd $TMPDIR/x`, `D=/tmp/x; cd
303/// "$D"`) is followed like its literal value (#2079). Inside single quotes `$`
304/// is a literal character, and any other variable is unknown.
305fn resolve_cd(from: Option<&Path>, target: &str, vars: &KnownVars) -> Option<PathBuf> {
306    let unquoted = target.trim_matches(['"', '\'']);
307    let expanded;
308    let unquoted = if unquoted.starts_with('$') && !target.starts_with('\'') {
309        expanded = expand_leading_variable(unquoted, vars)?;
310        expanded.as_str()
311    } else {
312        unquoted
313    };
314    if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
315        return None;
316    }
317    // `cd ~` and `cd ~/x` are the shell's expansion, not a relative path.
318    if let Some(rest) = unquoted.strip_prefix('~') {
319        let home = std::env::var_os("HOME").map(PathBuf::from)?;
320        return Some(join_in(&home, rest.trim_start_matches('/')));
321    }
322    // This is shell text, so `/tmp` is an absolute POSIX path even on Windows,
323    // where `Path::is_absolute` says otherwise. Agents write Unix paths there
324    // routinely (Git Bash, WSL, generated commands) — the same reason
325    // `is_unix_scratch_prefix` exists (#1467). Treating them as relative made a
326    // `cd /tmp` resolve to nothing on Windows, and the guard then judged the
327    // download target against no directory at all.
328    if unquoted.starts_with('/') {
329        return Some(PathBuf::from(normalize_posix(unquoted)));
330    }
331    let path = Path::new(unquoted);
332    if path.is_absolute() {
333        return Some(normalize(path));
334    }
335    Some(join_in(from?, unquoted))
336}
337
338/// Join `rel` under `base`, keeping a POSIX-rooted base POSIX.
339///
340/// `Path::join` would splice a backslash into `/tmp` on Windows, and the
341/// scratch-prefix checks match on `/tmp/`.
342pub fn join_in(base: &Path, rel: &str) -> PathBuf {
343    let base_str = base.to_string_lossy();
344    if base_str.starts_with('/') {
345        return PathBuf::from(normalize_posix(&format!(
346            "{}/{rel}",
347            base_str.trim_end_matches('/')
348        )));
349    }
350    normalize(&base.join(rel))
351}
352
353/// Resolve `.` and `..` in a POSIX path textually, on any platform.
354fn normalize_posix(path: &str) -> String {
355    let mut out: Vec<&str> = Vec::new();
356    for part in path.split('/') {
357        match part {
358            "" | "." => {}
359            ".." => {
360                out.pop();
361            }
362            other => out.push(other),
363        }
364    }
365    format!("/{}", out.join("/"))
366}
367
368/// Resolve `.` and `..` textually. The directory may not exist yet, so this
369/// deliberately does not touch the filesystem.
370fn normalize(path: &Path) -> PathBuf {
371    use std::path::Component;
372    let mut out = PathBuf::new();
373    for component in path.components() {
374        match component {
375            Component::CurDir => {}
376            Component::ParentDir => {
377                out.pop();
378            }
379            other => out.push(other),
380        }
381    }
382    out
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn a_leading_cd_moves_the_following_segments() {
391        let segs = segments_with_cwd(
392            "cd /tmp/work && curl -o x.png http://e/x",
393            Some(Path::new("/proj")),
394        );
395        assert_eq!(
396            segs.last().unwrap().cwd.as_deref(),
397            Some(Path::new("/tmp/work"))
398        );
399    }
400
401    #[test]
402    fn without_a_cd_every_segment_keeps_the_call_directory() {
403        let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
404        assert!(
405            segs.iter()
406                .all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
407        );
408    }
409
410    #[test]
411    fn a_relative_cd_is_joined_onto_the_call_directory() {
412        assert_eq!(
413            final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
414            Some(PathBuf::from("/proj/sub/dir"))
415        );
416        assert_eq!(
417            final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
418            Some(PathBuf::from("/proj/side"))
419        );
420    }
421
422    /// A directory the shell would have to compute is unknown, not the old one
423    /// — judging a later segment against a stale directory is how a guard ends
424    /// up permitting or blocking the wrong thing.
425    #[test]
426    fn an_unresolvable_cd_makes_the_directory_unknown() {
427        assert_eq!(
428            final_cwd(
429                "cd \"$LEAN_CTX_2079_NEVER_SET\" && ls",
430                Some(Path::new("/proj"))
431            ),
432            None
433        );
434        assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
435    }
436
437    /// A Unix path in shell text stays a Unix path on Windows too (#1467).
438    /// This is the case that broke CI: `cd /tmp` resolved to nothing there, so
439    /// the download guard judged `shot.png` against no directory at all.
440    #[test]
441    fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
442        assert_eq!(
443            final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
444            Some(PathBuf::from("/tmp"))
445        );
446        assert_eq!(
447            final_cwd("cd /private/tmp/session/../session && ls", None),
448            Some(PathBuf::from("/private/tmp/session"))
449        );
450        assert_eq!(
451            join_in(Path::new("/tmp/work"), "sub/shot.png"),
452            PathBuf::from("/tmp/work/sub/shot.png"),
453            "and joins with a forward slash, which the scratch prefixes match on"
454        );
455    }
456
457    #[test]
458    fn no_base_and_no_cd_is_unknown() {
459        assert_eq!(final_cwd("ls -la", None), None);
460    }
461
462    fn cwds(command: &str) -> Vec<Option<PathBuf>> {
463        segments_with_cwd(command, Some(Path::new("/proj")))
464            .into_iter()
465            .map(|s| s.cwd)
466            .collect()
467    }
468
469    const MISSING: &str = "/lean-ctx-1850-does-not-exist";
470
471    /// A `cd` runs where it starts: its own redirect is opened before it moves.
472    #[test]
473    fn a_cd_segment_runs_in_the_directory_before_it() {
474        assert_eq!(cwds("cd /tmp && ls")[0], Some(PathBuf::from("/proj")));
475    }
476
477    /// #1850: `cd x && a; b` — if the `cd` fails, `a` is skipped but `b` still
478    /// runs, in the old directory. Past the `;` both are possible.
479    #[test]
480    fn a_cd_that_may_fail_does_not_carry_past_a_sequence() {
481        let got = cwds(&format!("cd {MISSING} && true; echo x"));
482        assert_eq!(got[1], Some(PathBuf::from(MISSING)), "reached only via &&");
483        assert_eq!(got[2], None);
484    }
485
486    #[test]
487    fn a_cd_that_may_be_skipped_leaves_the_directory_unknown() {
488        assert_eq!(cwds("false && cd /tmp; echo x")[2], None);
489        assert_eq!(cwds("true || cd /tmp && echo x")[2], None);
490        assert_eq!(cwds("cd /tmp | cat; echo x")[2], None, "a pipeline element");
491    }
492
493    /// `cd a && cd .` must not merge the two possibilities into one directory
494    /// just because both `cd`s name the same place.
495    #[test]
496    fn a_second_cd_does_not_make_a_failed_first_one_certain() {
497        assert_eq!(cwds(&format!("cd {MISSING} && cd . ; echo x"))[2], None);
498    }
499
500    #[test]
501    fn cd_or_exit_leaves_only_the_moved_directory() {
502        let got = cwds(&format!("cd {MISSING} || exit 1; echo x"));
503        assert_eq!(got[1], Some(PathBuf::from("/proj")), "the fallback");
504        assert_eq!(got[2], Some(PathBuf::from(MISSING)));
505    }
506
507    /// `&` runs the whole and-or list in a background subshell.
508    #[test]
509    fn a_backgrounded_list_does_not_move_what_follows() {
510        assert_eq!(
511            cwds("cd /tmp && echo a & echo b")[2],
512            Some(PathBuf::from("/proj"))
513        );
514    }
515
516    #[test]
517    fn opaque_movers_make_the_directory_unknown() {
518        for command in [
519            "pushd /tmp && echo x",
520            "builtin cd /tmp && echo x",
521            "{ cd /tmp; } && echo x",
522        ] {
523            assert_eq!(cwds(command).last(), Some(&None), "{command}");
524        }
525        let subshell = cwds("(cd /tmp) && echo x");
526        assert_eq!(subshell[0], None, "its own directory is not followed");
527        assert_eq!(
528            subshell[1],
529            Some(PathBuf::from("/proj")),
530            "but it cannot move the parent shell"
531        );
532    }
533
534    #[test]
535    fn cdpath_makes_a_relative_cd_unknown() {
536        assert_eq!(cwds("CDPATH=/elsewhere; cd sub && ls")[2], None);
537        assert_eq!(
538            cwds("CDPATH=/elsewhere; cd ./sub && ls")[2],
539            Some(PathBuf::from("/proj/sub")),
540            "`./` bypasses CDPATH"
541        );
542    }
543
544    /// #2081: quoted text is data. The reporter's form: a log line that
545    /// mentions `cd $TMPDIR`, written with a relative redirect.
546    #[test]
547    fn a_cd_inside_a_quoted_argument_does_not_move_anything() {
548        for command in [
549            "printf '%s\\n' 'note: cd /tmp mention' > f.txt",
550            "cd /proj && printf '| %s | (cd $TMPDIR not followed) |\\n' x >> f.txt",
551            "echo \"pushd here, popd there, then cd back\" > f.txt",
552            "echo \"$(cd /tmp; pwd)\" > f.txt",
553            "echo 'it'\\''s cd' > f.txt",
554        ] {
555            assert_eq!(
556                cwds(command).last(),
557                Some(&Some(PathBuf::from("/proj"))),
558                "{command}"
559            );
560        }
561    }
562
563    /// Quoting the command name does not stop the shell running it, and `eval`
564    /// runs text in this shell: those still leave the directory unknown.
565    #[test]
566    fn a_quoted_command_name_or_eval_still_moves_the_shell() {
567        for command in [
568            "\"cd\" /tmp && echo x",
569            "c'd' /tmp && echo x",
570            "\\cd /tmp && echo x",
571            "builtin 'cd' /tmp && echo x",
572            "eval 'cd /tmp' && echo x",
573            "'eval' \"c\"\"d /tmp\" && echo x",
574            "echo ${ cd /tmp; } && echo x",
575        ] {
576            assert_eq!(cwds(command).last(), Some(&None), "{command}");
577        }
578    }
579
580    /// #2079: a `cd` through a variable this command set to a literal, or
581    /// through `$TMPDIR`, is followed like the literal.
582    #[test]
583    fn a_cd_through_a_known_variable_is_followed() {
584        assert_eq!(
585            cwds("D=/tmp && cd $D && echo x").last(),
586            Some(&Some(PathBuf::from("/tmp")))
587        );
588        assert_eq!(
589            cwds("D=/tmp; cd \"${D}/sub\" && echo x").last(),
590            Some(&Some(PathBuf::from("/tmp/sub")))
591        );
592        assert_eq!(
593            cwds("D=sub; cd $D && echo x").last(),
594            Some(&Some(PathBuf::from("/proj/sub"))),
595            "a relative value is joined like a relative literal"
596        );
597        let expected = std::env::var("TMPDIR")
598            .ok()
599            .filter(|t| !t.is_empty() && !t.contains(['$', '`']))
600            .map(|t| resolve_cd(None, &t, &KnownVars::default()));
601        assert_eq!(
602            final_cwd("cd $TMPDIR && ls", Some(Path::new("/proj"))),
603            expected.flatten(),
604            "$TMPDIR resolves exactly as its value spelled out"
605        );
606    }
607
608    /// Anything the variable resolution cannot vouch for stays unknown.
609    #[test]
610    fn a_cd_through_an_unknown_variable_stays_unknown() {
611        for command in [
612            "cd $D && echo x",
613            "true && D=/tmp; cd $D && echo x",
614            "D=/tmp; read D; cd $D && echo x",
615            "TMPDIR=$PWD; cd $TMPDIR && echo x",
616            "unset TMPDIR; cd $TMPDIR && echo x",
617            // Inside single quotes `$D` is the literal name of a directory.
618            "D=/tmp; cd '$D' && echo x",
619            "D=/tmp; cd $Dx && echo x",
620        ] {
621            assert_eq!(cwds(command).last(), Some(&None), "{command}");
622        }
623    }
624}