Skip to main content

lean_ctx/core/
pathjail.rs

1use std::path::{Path, PathBuf};
2
3const IDE_CONFIG_DIRS: &[&str] = &[
4    ".lean-ctx",
5    ".cursor",
6    ".claude",
7    ".codex",
8    ".codeium",
9    ".gemini",
10    ".qwen",
11    ".trae",
12    ".kiro",
13    ".verdent",
14    ".pi",
15    ".amp",
16    ".aider",
17    ".continue",
18];
19
20pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
21    let mut out = Vec::new();
22
23    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
24        out.push(canonicalize_or_self(&data_dir));
25    }
26
27    if let Some(home) = dirs::home_dir() {
28        for dir in IDE_CONFIG_DIRS {
29            let p = home.join(dir);
30            if p.exists() {
31                out.push(canonicalize_or_self(&p));
32            }
33        }
34    }
35
36    let cfg = crate::core::config::Config::load();
37    for p in &cfg.allow_paths {
38        let pb = PathBuf::from(p);
39        out.push(canonicalize_or_self(&pb));
40    }
41    for p in &cfg.extra_roots {
42        let pb = PathBuf::from(p);
43        out.push(canonicalize_or_self(&pb));
44    }
45
46    let v = std::env::var("LCTX_ALLOW_PATH")
47        .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
48        .unwrap_or_default();
49    if !v.trim().is_empty() {
50        for p in std::env::split_paths(&v) {
51            out.push(canonicalize_or_self(&p));
52        }
53    }
54
55    let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
56    if !extra.trim().is_empty() {
57        for p in std::env::split_paths(&extra) {
58            out.push(canonicalize_or_self(&p));
59        }
60    }
61
62    out
63}
64
65fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
66    path.starts_with(prefix)
67}
68
69pub fn canonicalize_or_self(path: &Path) -> PathBuf {
70    super::pathutil::safe_canonicalize_bounded(path, 2000)
71}
72
73fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
74    let mut cur = path.to_path_buf();
75    let mut remainder: Vec<std::ffi::OsString> = Vec::new();
76    loop {
77        if cur.exists() {
78            return Some((canonicalize_or_self(&cur), remainder));
79        }
80        let name = cur.file_name()?.to_os_string();
81        remainder.push(name);
82        if !cur.pop() {
83            return None;
84        }
85    }
86}
87
88pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, String> {
89    if candidate.to_string_lossy().as_bytes().contains(&0) {
90        return Err("path contains null byte".to_string());
91    }
92
93    #[cfg(feature = "no-jail")]
94    {
95        let _ = jail_root;
96        return Ok(canonicalize_or_self(candidate));
97    }
98
99    #[allow(unreachable_code)]
100    {
101        let cfg = crate::core::config::Config::load();
102        if cfg.path_jail == Some(false) {
103            return Ok(canonicalize_or_self(candidate));
104        }
105
106        let root = canonicalize_or_self(jail_root);
107        let allow = allow_paths_from_env_and_config();
108
109        let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
110            format!(
111                "path does not exist and has no existing ancestor: {}",
112                candidate.display()
113            )
114        })?;
115
116        let allowed =
117            is_under_prefix(&base, &root) || allow.iter().any(|p| is_under_prefix(&base, p));
118
119        #[cfg(windows)]
120        let allowed = allowed || is_under_prefix_windows(&base, &root);
121
122        if !allowed {
123            let base_msg = format!(
124                "path escapes project root: {} (root: {})",
125                candidate.display(),
126                root.display(),
127            );
128            let hint = if crate::core::protocol::meta_visible() {
129                format!(
130                ". Hint: set LEAN_CTX_ALLOW_PATH={} or add it to allow_paths in ~/.lean-ctx/config.toml",
131                candidate.parent().unwrap_or(candidate).display()
132            )
133            } else {
134                String::new()
135            };
136            return Err(format!("{base_msg}{hint}"));
137        }
138
139        #[cfg(windows)]
140        reject_symlink_on_windows(candidate)?;
141
142        let mut out = base;
143        for part in remainder.iter().rev() {
144            out.push(part);
145        }
146
147        // Re-validate after reconstruction: if the final path exists, canonicalize
148        // and re-check to close TOCTOU window (symlink created between check and use).
149        if out.exists() {
150            let final_canon = canonicalize_or_self(&out);
151            let final_ok = is_under_prefix(&final_canon, &root)
152                || allow.iter().any(|p| is_under_prefix(&final_canon, p));
153            #[cfg(windows)]
154            let final_ok = final_ok || is_under_prefix_windows(&final_canon, &root);
155            if !final_ok {
156                return Err(format!(
157                    "post-canonicalize jail escape detected: {} resolves to {}",
158                    candidate.display(),
159                    final_canon.display()
160                ));
161            }
162        }
163
164        Ok(out)
165    }
166}
167
168#[cfg(windows)]
169fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
170    let path_str = normalize_windows_path(&path.to_string_lossy());
171    let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
172    path_str.starts_with(&prefix_str)
173}
174
175#[cfg(windows)]
176fn normalize_windows_path(s: &str) -> String {
177    let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
178    stripped.to_lowercase().replace('/', "\\")
179}
180
181#[cfg(windows)]
182fn reject_symlink_on_windows(path: &Path) -> Result<(), String> {
183    if let Ok(meta) = std::fs::symlink_metadata(path) {
184        if meta.is_symlink() {
185            return Err(format!(
186                "symlink not allowed in jailed path: {}",
187                path.display()
188            ));
189        }
190    }
191    Ok(())
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[cfg(not(feature = "no-jail"))]
199    #[test]
200    fn rejects_path_outside_root() {
201        let tmp = tempfile::tempdir().unwrap();
202        let root = tmp.path().join("root");
203        let other = tmp.path().join("other");
204        std::fs::create_dir_all(&root).unwrap();
205        std::fs::create_dir_all(&other).unwrap();
206        std::fs::write(root.join("a.txt"), "ok").unwrap();
207        std::fs::write(other.join("b.txt"), "no").unwrap();
208
209        let ok = jail_path(&root.join("a.txt"), &root);
210        assert!(ok.is_ok());
211
212        let bad = jail_path(&other.join("b.txt"), &root);
213        assert!(bad.is_err());
214    }
215
216    #[test]
217    fn allows_nonexistent_child_under_root() {
218        let tmp = tempfile::tempdir().unwrap();
219        let root = tmp.path().join("root");
220        std::fs::create_dir_all(&root).unwrap();
221        std::fs::write(root.join("a.txt"), "ok").unwrap();
222
223        let p = root.join("new").join("file.txt");
224        let ok = jail_path(&p, &root).unwrap();
225        assert!(ok.to_string_lossy().contains("file.txt"));
226    }
227
228    #[test]
229    fn ide_config_dirs_list_is_not_empty() {
230        assert!(IDE_CONFIG_DIRS.len() >= 10);
231        assert!(IDE_CONFIG_DIRS.contains(&".codex"));
232        assert!(IDE_CONFIG_DIRS.contains(&".cursor"));
233        assert!(IDE_CONFIG_DIRS.contains(&".claude"));
234        assert!(IDE_CONFIG_DIRS.contains(&".gemini"));
235    }
236
237    #[test]
238    fn canonicalize_or_self_strips_verbatim() {
239        let tmp = tempfile::tempdir().unwrap();
240        let dir = tmp.path().join("project");
241        std::fs::create_dir_all(&dir).unwrap();
242
243        let result = canonicalize_or_self(&dir);
244        let s = result.to_string_lossy();
245        assert!(
246            !s.starts_with(r"\\?\"),
247            "canonicalize_or_self should strip verbatim prefix, got: {s}"
248        );
249    }
250
251    #[test]
252    fn jail_path_accepts_same_dir_different_format() {
253        let tmp = tempfile::tempdir().unwrap();
254        let root = tmp.path().join("project");
255        std::fs::create_dir_all(&root).unwrap();
256        std::fs::write(root.join("file.rs"), "ok").unwrap();
257
258        let result = jail_path(&root.join("file.rs"), &root);
259        assert!(result.is_ok(), "same dir should be accepted: {result:?}");
260    }
261
262    #[cfg(not(feature = "no-jail"))]
263    #[test]
264    fn error_message_contains_escape_info() {
265        let tmp = tempfile::tempdir().unwrap();
266        let root = tmp.path().join("root");
267        let other = tmp.path().join("other");
268        std::fs::create_dir_all(&root).unwrap();
269        std::fs::create_dir_all(&other).unwrap();
270        std::fs::write(other.join("b.txt"), "no").unwrap();
271
272        let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
273        assert!(
274            err.contains("path escapes project root"),
275            "error should mention escape: {err}"
276        );
277    }
278
279    #[test]
280    fn allow_path_env_permits_outside_root() {
281        let tmp = tempfile::tempdir().unwrap();
282        let root = tmp.path().join("root");
283        let other = tmp.path().join("other");
284        std::fs::create_dir_all(&root).unwrap();
285        std::fs::create_dir_all(&other).unwrap();
286        std::fs::write(other.join("b.txt"), "allowed").unwrap();
287
288        let canon = canonicalize_or_self(&other);
289        std::env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
290        let result = jail_path(&other.join("b.txt"), &root);
291        std::env::remove_var("LEAN_CTX_ALLOW_PATH");
292
293        assert!(
294            result.is_ok(),
295            "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
296        );
297    }
298
299    #[cfg(all(unix, not(feature = "no-jail")))]
300    #[test]
301    fn rejects_symlink_escape_on_unix() {
302        use std::os::unix::fs::symlink;
303
304        let tmp = tempfile::tempdir().unwrap();
305        let root = tmp.path().join("root");
306        let other = tmp.path().join("other");
307        std::fs::create_dir_all(&root).unwrap();
308        std::fs::create_dir_all(&other).unwrap();
309        std::fs::write(other.join("secret.txt"), "no").unwrap();
310
311        let link = root.join("link.txt");
312        symlink(other.join("secret.txt"), &link).unwrap();
313
314        let bad = jail_path(&link, &root);
315        assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
316    }
317
318    #[test]
319    fn rejects_null_byte_in_path() {
320        let tmp = tempfile::tempdir().unwrap();
321        let root = tmp.path().join("root");
322        std::fs::create_dir_all(&root).unwrap();
323
324        let bad_path = PathBuf::from("file\0.txt");
325        let result = jail_path(&bad_path, &root);
326        assert!(result.is_err(), "null byte in path must be rejected");
327        assert!(
328            result.unwrap_err().contains("null byte"),
329            "error must mention null byte"
330        );
331    }
332}