Skip to main content

lean_ctx/core/
path_resolve.rs

1//! Shared path-resolution for tool handlers.
2//!
3//! Previously two near-identical `resolve_path_sync` implementations lived in
4//! `tools/registered/mod.rs` (SessionState-based) and `server/tool_trait.rs`
5//! (ToolContext-based), plus several copies of the project-marker test. This
6//! module is the single source of truth: [`resolve_tool_path`] for jailed path
7//! resolution and a re-export of [`has_project_marker`] for marker detection.
8
9use std::path::{Path, PathBuf};
10
11/// Single canonical project-marker test (`.git`, `Cargo.toml`, …).
12///
13/// Re-exported from [`crate::core::pathutil`] so callers that think in terms of
14/// path resolution have a local, discoverable handle.
15pub use crate::core::pathutil::has_project_marker;
16
17/// Resolve a (possibly relative) tool path to a normalized, jail-checked,
18/// secret-screened absolute path.
19///
20/// Resolution of the input:
21/// 1. absolute path → used as-is
22/// 2. relative path with a project root → `<project_root>/<path>`, whether or
23///    not it exists (a write target), exactly as the tool schemas promise
24/// 3. relative path without a project root → `<shell_cwd>/<path>` (the
25///    directory the client started the session in), else `<jail_root>/<path>`
26///
27/// The base of a relative path never depends on earlier tool calls (#2262):
28/// `ctx_shell` does not move `shell_cwd`, and with a project root it is not
29/// consulted at all. A worktree or other checkout is addressed by absolute
30/// path.
31///
32/// Relative inputs are NEVER resolved against the process CWD: the daemon's
33/// CWD is not the project, so a CWD `exists()` probe made resolution
34/// nondeterministic across MCP/daemon/CLI contexts (and could pick a
35/// same-named file outside the project).
36///
37/// `jail_root` is `project_root`, else `shell_cwd`, else `"."`. The result is
38/// confined to the jail root via [`crate::core::pathjail::jail_path`] and
39/// screened by the secret-path I/O boundary.
40///
41/// Performs blocking filesystem `exists()` checks; callers on async runtimes
42/// must wrap this in `tokio::task::block_in_place`.
43pub fn resolve_tool_path(
44    project_root: Option<&str>,
45    shell_cwd: Option<&str>,
46    raw: &str,
47) -> Result<String, String> {
48    resolve_tool_path_with_roots(project_root, shell_cwd, raw, &[])
49}
50
51/// Like [`resolve_tool_path`], but also permits paths under any of
52/// `extra_roots` (session-scoped trusted roots from `session.extra_roots`).
53///
54/// An empty `extra_roots` is identical to [`resolve_tool_path`]; this is how
55/// sync tool handlers honor MCP `roots/list` / config `extra_roots` for an
56/// explicit path without widening the global jail (#403).
57pub fn resolve_tool_path_with_roots(
58    project_root: Option<&str>,
59    shell_cwd: Option<&str>,
60    raw: &str,
61    extra_roots: &[String],
62) -> Result<String, String> {
63    resolve_tool_path_refusing(project_root, shell_cwd, raw, extra_roots)
64        .map_err(|refusal| refusal.message)
65}
66
67/// A path that did not resolve: the message the caller returns, and the
68/// boundary class when the I/O boundary refused it (`None` for a path that is
69/// merely missing or malformed). The class is what the audit trail records.
70#[derive(Debug)]
71pub struct PathRefusal {
72    pub message: String,
73    pub class: Option<crate::core::security_events::RefusalClass>,
74}
75
76impl From<String> for PathRefusal {
77    fn from(message: String) -> Self {
78        Self {
79            message,
80            class: None,
81        }
82    }
83}
84
85impl PathRefusal {
86    /// The refusal of the secret-path I/O boundary (enforce mode).
87    pub fn secret_path(message: String) -> Self {
88        Self {
89            message,
90            class: Some(crate::core::security_events::RefusalClass::SecretPath),
91        }
92    }
93
94    /// The refusal of the path jail, classified by
95    /// [`crate::core::security_events::RefusalClass::of_jail_error`].
96    pub fn jail(error: &crate::core::error::PathJailError) -> Self {
97        Self {
98            message: error.to_string(),
99            class: crate::core::security_events::RefusalClass::of_jail_error(error),
100        }
101    }
102}
103
104/// [`resolve_tool_path_with_roots`], saying which boundary refused the path.
105pub fn resolve_tool_path_refusing(
106    project_root: Option<&str>,
107    shell_cwd: Option<&str>,
108    raw: &str,
109    extra_roots: &[String],
110) -> Result<String, PathRefusal> {
111    let normalized = crate::core::pathutil::normalize_tool_path(raw);
112    if normalized.is_empty() || normalized == "." {
113        return Ok(crate::core::workspace_authority::project_dot(
114            &normalized,
115            project_root,
116        )?);
117    }
118
119    let p = Path::new(&normalized);
120    let jail_root = project_root.or(shell_cwd).unwrap_or(".").to_string();
121
122    let resolved: PathBuf = if p.is_absolute() {
123        PathBuf::from(&normalized)
124    } else if let Some(root) = project_root {
125        Path::new(root).join(&normalized)
126    } else if let Some(cwd) = shell_cwd {
127        Path::new(cwd).join(&normalized)
128    } else {
129        Path::new(&jail_root).join(&normalized)
130    };
131
132    if project_root.is_none()
133        && let Some(error) = unbound_relative_path(raw, &resolved, shell_cwd.unwrap_or(&jail_root))
134    {
135        return Err(error.into());
136    }
137
138    let jail_root_path = Path::new(&jail_root);
139    let jailed =
140        crate::core::pathjail::jail_path_auto_admitting(&resolved, jail_root_path, extra_roots)
141            .map_err(|e| PathRefusal::jail(&e))?;
142    crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)
143        .map_err(PathRefusal::secret_path)?;
144
145    Ok(crate::core::pathutil::normalize_tool_path(
146        &jailed.to_string_lossy().replace('\\', "/"),
147    ))
148}
149
150/// Refusal for a relative path that cannot mean anything yet: the session has
151/// no project, the host started lean-ctx in a broad directory (OpenCode
152/// launched from `~`), and nothing exists at `resolved`. Without it agents got
153/// "file not found: ~/src/main.rs" and searched the wrong tree. `None` when the
154/// path is absolute, exists, or `base` is an ordinary working directory.
155pub fn unbound_relative_path(raw: &str, resolved: &Path, base: &str) -> Option<String> {
156    let normalized = crate::core::pathutil::normalize_tool_path(raw);
157    if Path::new(&normalized).is_absolute() || resolved.exists() {
158        return None;
159    }
160    let base = std::path::absolute(base).unwrap_or_else(|_| PathBuf::from(base));
161    if !crate::core::pathutil::is_broad_or_unsafe_root(&base) {
162        return None;
163    }
164    Some(format!(
165        "relative path '{raw}' has no project to resolve against: lean-ctx has no project for \
166         this session yet (the host started it in {}, outside a project). Pass the absolute \
167         path instead, e.g. /home/me/code/my-app/{normalized}; that project then stays the \
168         session project.",
169        base.display()
170    ))
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use std::fs;
177
178    #[test]
179    fn empty_and_dot_pass_through() {
180        assert_eq!(resolve_tool_path(None, None, "").unwrap(), "");
181        assert_eq!(resolve_tool_path(None, None, ".").unwrap(), ".");
182    }
183
184    #[test]
185    fn missing_relative_path_without_a_project_says_what_is_missing() {
186        let _home = crate::core::data_dir::test_env_lock();
187        // A host started outside a project: the home directory, as OpenCode
188        // does when launched from `~` (broad on every platform; `/` is not
189        // broad on Windows, where it means the current drive's root).
190        let home = dirs::home_dir()
191            .expect("home dir")
192            .to_string_lossy()
193            .to_string();
194        let error =
195            resolve_tool_path(None, Some(&home), "src/no_such_file_lc_7f3a.rs").unwrap_err();
196        assert!(
197            error.contains("has no project to resolve against"),
198            "{error}"
199        );
200        assert!(error.contains("absolute path"), "{error}");
201
202        // A relative path in an ordinary working directory keeps resolving there.
203        let dir = tempfile::tempdir().unwrap();
204        let cwd = dir.path().to_string_lossy().to_string();
205        let outcome = resolve_tool_path(None, Some(&cwd), "src/no_such_file_lc.rs");
206        assert!(
207            outcome
208                .as_ref()
209                .err()
210                .is_none_or(|e| !e.contains("no project to resolve against")),
211            "{outcome:?}"
212        );
213    }
214
215    #[test]
216    fn relative_resolves_against_project_root() {
217        let _environment = crate::core::data_dir::test_env_lock();
218        let tmp = std::env::temp_dir().join(format!("lc_pr_{}", std::process::id()));
219        let _ = fs::create_dir_all(&tmp);
220        let file = tmp.join("a.txt");
221        fs::write(&file, "x").unwrap();
222        let root = tmp.to_string_lossy().to_string();
223
224        let out = resolve_tool_path(Some(&root), None, "a.txt").unwrap();
225        assert!(out.ends_with("a.txt"), "got {out}");
226        assert!(out.contains(&root) || Path::new(&out).is_absolute());
227
228        let _ = fs::remove_dir_all(&tmp);
229    }
230
231    /// #2262: with a project root, a relative path names the file under that
232    /// root — a session cwd elsewhere is never a second base, not even for a
233    /// file that exists only there.
234    #[test]
235    fn shell_cwd_is_no_second_base_when_a_project_root_is_set() {
236        let _environment = crate::core::data_dir::test_env_lock();
237        let base = tempfile::tempdir().unwrap();
238        let root = base.path().join("root");
239        let cwd = root.join("sub");
240        fs::create_dir_all(&cwd).unwrap();
241        fs::write(cwd.join("only_in_cwd.txt"), "x").unwrap();
242
243        let out = resolve_tool_path(
244            Some(&root.to_string_lossy()),
245            Some(&cwd.to_string_lossy()),
246            "only_in_cwd.txt",
247        )
248        .unwrap();
249        let parent = crate::core::pathjail::canonicalize_or_self(Path::new(&out).parent().unwrap());
250        assert_eq!(
251            parent,
252            crate::core::pathjail::canonicalize_or_self(&root),
253            "{out}"
254        );
255    }
256
257    // P0-3 (#415): a relative path that happens to exist in the *process CWD*
258    // must NOT short-circuit resolution. `Cargo.toml` exists in the package
259    // root (cargo test's CWD) but not in this empty project root — before the
260    // fix the CWD probe returned it as-is, now it must resolve into the root.
261    #[test]
262    fn relative_path_never_resolves_against_process_cwd() {
263        let _environment = crate::core::data_dir::test_env_lock();
264        let cwd = std::env::current_dir().unwrap();
265        assert!(
266            cwd.join("Cargo.toml").exists(),
267            "test premise: CWD contains Cargo.toml"
268        );
269
270        let tmp = std::env::temp_dir().join(format!("lc_pr_nocwd_{}", std::process::id()));
271        fs::create_dir_all(&tmp).unwrap();
272        let root = tmp.to_string_lossy().to_string();
273
274        let out = resolve_tool_path(Some(&root), None, "Cargo.toml").unwrap();
275        // Canonicalize BOTH sides before comparing: on macOS temp_dir() is a
276        // symlink (/var → /private/var) and on Windows it may carry 8.3 short
277        // names (RUNNER~1), so comparing raw strings is platform-flaky. The
278        // resolved file itself does not exist, but its parent does — compare
279        // the canonicalized parents.
280        let canonical_root = crate::core::pathjail::canonicalize_or_self(&tmp);
281        let out_parent = crate::core::pathjail::canonicalize_or_self(
282            Path::new(&out)
283                .parent()
284                .expect("resolved path has a parent"),
285        );
286        assert_eq!(
287            out_parent, canonical_root,
288            "resolved {out} must live under the project root, not the process CWD"
289        );
290        let canonical_cwd = crate::core::pathjail::canonicalize_or_self(&cwd);
291        assert_ne!(
292            out_parent, canonical_cwd,
293            "resolved {out} must not resolve against the process CWD"
294        );
295
296        let _ = fs::remove_dir_all(&tmp);
297    }
298
299    // #403: session-scoped extra_roots must thread through to the jail so an
300    // explicit path under a worktree resolves where the bare resolver rejects
301    // it. Asserts only the Ok case (robust against parallel env mutation): with
302    // the jail on, success here is only possible because extra_roots were honored.
303    #[cfg(not(feature = "no-jail"))]
304    #[test]
305    fn extra_roots_thread_through_resolve_tool_path() {
306        let _environment = crate::core::data_dir::test_env_lock();
307        let base = std::env::temp_dir().join(format!("lc_pr_extra_{}", std::process::id()));
308        let root = base.join("root");
309        let worktree = base.join("worktree");
310        fs::create_dir_all(&root).unwrap();
311        fs::create_dir_all(&worktree).unwrap();
312        let file = worktree.join("a.txt");
313        fs::write(&file, "x").unwrap();
314
315        let root_s = root.to_string_lossy().to_string();
316        let file_abs = file.to_string_lossy().to_string();
317        let extra = vec![worktree.to_string_lossy().to_string()];
318
319        let out = resolve_tool_path_with_roots(Some(&root_s), None, &file_abs, &extra);
320        assert!(
321            out.is_ok(),
322            "extra_roots must thread through the resolver: {out:?}"
323        );
324
325        let _ = fs::remove_dir_all(&base);
326    }
327
328    /// #2262: the Claude Code `EnterWorktree` topology — a full checkout with
329    /// its own `.git` FILE nested under `<repo>/.claude/worktrees/<n>/`, and a
330    /// session cwd inside it. A project-relative path still names the project
331    /// root's file (existing or a write target); the worktree is reached by
332    /// absolute path, or by the path relative to the root.
333    #[test]
334    fn worktree_shell_cwd_does_not_move_the_relative_base() {
335        // Path authorization reads the process-wide protected-runtime profile.
336        // Serialize with tests that temporarily change that profile.
337        let _environment = crate::core::data_dir::test_env_lock();
338        let base = tempfile::tempdir().unwrap();
339        let repo = base.path().join("repo");
340        let wt = repo.join(".claude").join("worktrees").join("fix-x");
341        fs::create_dir_all(repo.join("src")).unwrap();
342        fs::create_dir_all(repo.join(".git")).unwrap(); // main checkout: .git dir
343        fs::create_dir_all(wt.join("src")).unwrap();
344        fs::write(wt.join(".git"), "gitdir: ../../.git/worktrees/fix-x\n").unwrap(); // worktree: .git FILE
345        fs::write(repo.join("src/scoring.rs"), "root").unwrap();
346        fs::write(wt.join("src/scoring.rs"), "worktree").unwrap();
347        let (repo_s, wt_s) = (repo.to_string_lossy(), wt.to_string_lossy());
348
349        let out = resolve_tool_path(Some(&repo_s), Some(&wt_s), "src/scoring.rs").unwrap();
350        assert_eq!(fs::read_to_string(&out).unwrap(), "root", "{out}");
351
352        let new = resolve_tool_path(Some(&repo_s), Some(&wt_s), "src/new_file.rs").unwrap();
353        assert!(
354            !new.contains("worktrees"),
355            "write target stays in the root: {new}"
356        );
357
358        // The #2262 repro path: relative to the root, never doubled.
359        let rel = resolve_tool_path(
360            Some(&repo_s),
361            Some(&wt_s),
362            ".claude/worktrees/fix-x/src/scoring.rs",
363        )
364        .unwrap();
365        assert_eq!(fs::read_to_string(&rel).unwrap(), "worktree", "{rel}");
366        assert_eq!(rel.matches("worktrees").count(), 1, "{rel}");
367
368        let abs = resolve_tool_path(
369            Some(&repo_s),
370            Some(&wt_s),
371            &wt.join("src/scoring.rs").to_string_lossy(),
372        )
373        .unwrap();
374        assert_eq!(fs::read_to_string(&abs).unwrap(), "worktree", "{abs}");
375    }
376
377    #[test]
378    fn tool_context_shape_project_root_only() {
379        let _environment = crate::core::data_dir::test_env_lock();
380        // Mirrors ToolContext::resolve_path_sync (shell_cwd = None).
381        let tmp = std::env::temp_dir().join(format!("lc_pr_ctx_{}", std::process::id()));
382        fs::create_dir_all(&tmp).unwrap();
383        let root = tmp.to_string_lossy().to_string();
384        let out = resolve_tool_path(Some(&root), None, "missing.rs").unwrap();
385        assert!(out.ends_with("missing.rs"), "got {out}");
386        let _ = fs::remove_dir_all(&tmp);
387    }
388
389    // GH #397: on Unix an absolute path under a single-letter root (`/c/…`)
390    // was rewritten to `C:/…`, which `Path::is_absolute()` rejects on Unix —
391    // the path was then re-joined under the (also-translated) project root,
392    // producing the doubled `C:/root/C:/root/file` form from the report.
393    // `/c` cannot be created in this test environment, so the jail may still
394    // reject the path as nonexistent — the regression assertion is that no
395    // `C:/` drive form appears anywhere in the outcome (Ok or Err).
396    #[cfg(not(windows))]
397    #[test]
398    fn single_letter_root_is_never_drive_translated_on_unix() {
399        let _environment = crate::core::data_dir::test_env_lock();
400        for raw in ["/c/Users/me/proj/src/app.ts", "src/app.ts"] {
401            let rendered = match resolve_tool_path(Some("/c/Users/me/proj"), None, raw) {
402                Ok(p) => p,
403                Err(e) => e,
404            };
405            assert!(
406                !rendered.contains("C:/"),
407                "drive translation must not run on unix hosts (raw={raw}): {rendered}"
408            );
409        }
410    }
411
412    // What the audit trail records for a refused path: the boundary's class,
413    // and none for a path that merely does not resolve.
414    #[test]
415    fn a_refusal_names_the_boundary_that_refused() {
416        use crate::core::security_events::RefusalClass;
417        let _environment = crate::core::data_dir::test_env_lock();
418        let tmp = tempfile::tempdir().unwrap();
419        let root = tmp.path().canonicalize().unwrap();
420        fs::write(root.join(".env"), "TOKEN=x").unwrap();
421        let root = root.to_string_lossy().into_owned();
422        let prev = std::env::var("LEAN_CTX_IO_BOUNDARY_MODE").ok();
423        crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", "enforce");
424        let secret = resolve_tool_path_refusing(Some(&root), None, ".env", &[]);
425        let outside =
426            resolve_tool_path_refusing(Some(&root), None, &format!("{root}/../outside.txt"), &[]);
427        match prev {
428            Some(v) => crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", v),
429            None => crate::test_env::remove_var("LEAN_CTX_IO_BOUNDARY_MODE"),
430        }
431        let secret = secret.expect_err("enforce mode refuses a secret path");
432        assert_eq!(secret.class, Some(RefusalClass::SecretPath));
433        assert!(
434            secret.message.contains("Secret-like path"),
435            "{}",
436            secret.message
437        );
438        if !cfg!(feature = "no-jail") {
439            let outside = outside.expect_err("the jail refuses a path outside the root");
440            assert_eq!(outside.class, Some(RefusalClass::OutsideRoot));
441        }
442        let unbound = resolve_tool_path_refusing(None, None, "src/no_such_file_lc_9c1.rs", &[]);
443        if let Err(refusal) = unbound {
444            assert_eq!(refusal.class, None, "{}", refusal.message);
445        }
446    }
447}