Skip to main content

lean_ctx/core/
command_cwd.rs

1//! Which directory a command's segments actually run in (GH #1661, #1662).
2//!
3//! A tool call carries one `cwd`, but the command it runs may move: `cd repo &&
4//! grep -rn … .` walks a tree the call never named, and `cd "$SCRATCH" && curl
5//! -o shot.png …` writes to a directory that is sanctioned for exactly that.
6//! Judging either against the call's `cwd` alone gets the answer wrong — too
7//! lenient in the first case, too strict in the second.
8//!
9//! Only a plain leading `cd <literal>` is followed. Anything the shell would
10//! have to evaluate — a variable, a substitution, `pushd`, a subshell — leaves
11//! the directory unknown, and an unknown directory is reported as such rather
12//! than guessed at.
13
14use std::path::{Path, PathBuf};
15
16/// One command segment together with the directory it runs in.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SegmentCwd {
19    pub segment: String,
20    /// `None` once a `cd` has moved somewhere this cannot resolve statically.
21    pub cwd: Option<PathBuf>,
22}
23
24/// Split `command` into segments, tracking `cd` as it goes.
25///
26/// Segmentation is delegated to the shell tokenizer so this never disagrees
27/// with the allowlist about where one command ends and the next begins.
28pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
29    let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
30    let mut out = Vec::new();
31
32    for segment in super::shell_allowlist::extract_all_commands_pub(command) {
33        if let Some(target) = cd_target(&segment) {
34            cwd = resolve_cd(cwd.as_deref(), target);
35            // The `cd` itself runs in the directory it is leaving; recording it
36            // with the new one would misattribute a `cd` that fails.
37            out.push(SegmentCwd {
38                segment,
39                cwd: cwd.clone(),
40            });
41            continue;
42        }
43        out.push(SegmentCwd {
44            segment,
45            cwd: cwd.clone(),
46        });
47    }
48    out
49}
50
51/// The directory in effect once every segment has run.
52pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
53    segments_with_cwd(command, base)
54        .last()
55        .and_then(|s| s.cwd.clone())
56}
57
58/// The literal argument of a segment that is exactly `cd <path>`.
59fn cd_target(segment: &str) -> Option<&str> {
60    let mut words = segment.split_whitespace();
61    if words.next()? != "cd" {
62        return None;
63    }
64    let target = words.next()?;
65    if words.next().is_some() {
66        // `cd a b` is not something to reason about.
67        return None;
68    }
69    Some(target)
70}
71
72/// Apply one `cd`, or give up on knowing the directory.
73///
74/// `cd` with no resolvable target is not "stay here": it moves somewhere this
75/// cannot see. Returning `None` keeps callers from judging a later segment
76/// against a directory it does not run in.
77fn resolve_cd(from: Option<&Path>, target: &str) -> Option<PathBuf> {
78    let unquoted = target.trim_matches(['"', '\'']);
79    if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
80        return None;
81    }
82    // `cd ~` and `cd ~/x` are the shell's expansion, not a relative path.
83    if let Some(rest) = unquoted.strip_prefix('~') {
84        let home = std::env::var_os("HOME").map(PathBuf::from)?;
85        return Some(join_in(&home, rest.trim_start_matches('/')));
86    }
87    // This is shell text, so `/tmp` is an absolute POSIX path even on Windows,
88    // where `Path::is_absolute` says otherwise. Agents write Unix paths there
89    // routinely (Git Bash, WSL, generated commands) — the same reason
90    // `is_unix_scratch_prefix` exists (#1467). Treating them as relative made a
91    // `cd /tmp` resolve to nothing on Windows, and the guard then judged the
92    // download target against no directory at all.
93    if unquoted.starts_with('/') {
94        return Some(PathBuf::from(normalize_posix(unquoted)));
95    }
96    let path = Path::new(unquoted);
97    if path.is_absolute() {
98        return Some(normalize(path));
99    }
100    Some(join_in(from?, unquoted))
101}
102
103/// Join `rel` under `base`, keeping a POSIX-rooted base POSIX.
104///
105/// `Path::join` would splice a backslash into `/tmp` on Windows, and the
106/// scratch-prefix checks match on `/tmp/`.
107pub fn join_in(base: &Path, rel: &str) -> PathBuf {
108    let base_str = base.to_string_lossy();
109    if base_str.starts_with('/') {
110        return PathBuf::from(normalize_posix(&format!(
111            "{}/{rel}",
112            base_str.trim_end_matches('/')
113        )));
114    }
115    normalize(&base.join(rel))
116}
117
118/// Resolve `.` and `..` in a POSIX path textually, on any platform.
119fn normalize_posix(path: &str) -> String {
120    let mut out: Vec<&str> = Vec::new();
121    for part in path.split('/') {
122        match part {
123            "" | "." => {}
124            ".." => {
125                out.pop();
126            }
127            other => out.push(other),
128        }
129    }
130    format!("/{}", out.join("/"))
131}
132
133/// Resolve `.` and `..` textually. The directory may not exist yet, so this
134/// deliberately does not touch the filesystem.
135fn normalize(path: &Path) -> PathBuf {
136    use std::path::Component;
137    let mut out = PathBuf::new();
138    for component in path.components() {
139        match component {
140            Component::CurDir => {}
141            Component::ParentDir => {
142                out.pop();
143            }
144            other => out.push(other),
145        }
146    }
147    out
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn a_leading_cd_moves_the_following_segments() {
156        let segs = segments_with_cwd(
157            "cd /tmp/work && curl -o x.png http://e/x",
158            Some(Path::new("/proj")),
159        );
160        assert_eq!(
161            segs.last().unwrap().cwd.as_deref(),
162            Some(Path::new("/tmp/work"))
163        );
164    }
165
166    #[test]
167    fn without_a_cd_every_segment_keeps_the_call_directory() {
168        let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
169        assert!(
170            segs.iter()
171                .all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
172        );
173    }
174
175    #[test]
176    fn a_relative_cd_is_joined_onto_the_call_directory() {
177        assert_eq!(
178            final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
179            Some(PathBuf::from("/proj/sub/dir"))
180        );
181        assert_eq!(
182            final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
183            Some(PathBuf::from("/proj/side"))
184        );
185    }
186
187    /// A directory the shell would have to compute is unknown, not the old one
188    /// — judging a later segment against a stale directory is how a guard ends
189    /// up permitting or blocking the wrong thing.
190    #[test]
191    fn an_unresolvable_cd_makes_the_directory_unknown() {
192        assert_eq!(
193            final_cwd("cd \"$TMPDIR\" && ls", Some(Path::new("/proj"))),
194            None
195        );
196        assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
197    }
198
199    /// A Unix path in shell text stays a Unix path on Windows too (#1467).
200    /// This is the case that broke CI: `cd /tmp` resolved to nothing there, so
201    /// the download guard judged `shot.png` against no directory at all.
202    #[test]
203    fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
204        assert_eq!(
205            final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
206            Some(PathBuf::from("/tmp"))
207        );
208        assert_eq!(
209            final_cwd("cd /private/tmp/session/../session && ls", None),
210            Some(PathBuf::from("/private/tmp/session"))
211        );
212        assert_eq!(
213            join_in(Path::new("/tmp/work"), "sub/shot.png"),
214            PathBuf::from("/tmp/work/sub/shot.png"),
215            "and joins with a forward slash, which the scratch prefixes match on"
216        );
217    }
218
219    #[test]
220    fn no_base_and_no_cd_is_unknown() {
221        assert_eq!(final_cwd("ls -la", None), None);
222    }
223}