use std::path::{Path, PathBuf};
const IDE_CONFIG_DIRS: &[&str] = &[
".lean-ctx",
".cursor",
".claude",
".codex",
".codeium",
".gemini",
".qwen",
".trae",
".kiro",
".verdent",
".pi",
".amp",
".aider",
".continue",
".codebuddy",
];
pub fn expand_user_path(raw: &str) -> PathBuf {
let mut s = raw.to_string();
if (s == "~" || s.starts_with("~/"))
&& let Some(home) = dirs::home_dir()
{
s = format!("{}{}", home.to_string_lossy(), &s[1..]);
}
while let Some(start) = s.find('$') {
let rest = &s[start + 1..];
let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
match stripped.find('}') {
Some(end) => (stripped[..end].to_string(), end + 3),
None => break,
}
} else {
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
(rest[..end].to_string(), end + 1)
};
if name.is_empty() {
break;
}
if let Ok(val) = std::env::var(&name) {
s.replace_range(start..start + token_len, &val);
} else {
tracing::warn!(
"allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
);
break;
}
}
PathBuf::from(s)
}
pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
let mut out = Vec::new();
let cfg = crate::core::config::Config::load();
if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
out.push(canonicalize_secure(&data_dir));
}
if let Some(home) = dirs::home_dir() {
let ide_dirs_allowed = cfg.allow_ide_config_dirs
|| std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
out.extend(home_allow_dirs(&home, ide_dirs_allowed));
}
for p in &cfg.allow_paths {
out.push(canonicalize_secure(&expand_user_path(p)));
}
for p in &cfg.extra_roots {
out.push(canonicalize_secure(&expand_user_path(p)));
}
let v = std::env::var("LCTX_ALLOW_PATH")
.or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
.unwrap_or_default();
if !v.trim().is_empty() {
for p in std::env::split_paths(&v) {
out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
}
}
let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
if !extra.trim().is_empty() {
for p in std::env::split_paths(&extra) {
out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
}
}
out
}
fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
let mut out = Vec::new();
for dir in IDE_CONFIG_DIRS {
if *dir != ".lean-ctx" && !ide_dirs_allowed {
continue;
}
let p = home.join(dir);
if p.exists() {
out.push(canonicalize_secure(&p));
}
}
out
}
fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
path.starts_with(prefix)
}
pub fn canonicalize_or_self(path: &Path) -> PathBuf {
super::pathutil::safe_canonicalize_bounded(path, 2000)
}
fn canonicalize_secure(path: &Path) -> PathBuf {
super::pathutil::canonicalize_secure_bounded(path, 2000)
}
fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
let mut cur = path.to_path_buf();
let mut remainder: Vec<std::ffi::OsString> = Vec::new();
loop {
if cur.exists() {
return Some((canonicalize_secure(&cur), remainder));
}
let name = cur.file_name()?.to_os_string();
remainder.push(name);
if !cur.pop() {
return None;
}
}
}
pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, String> {
jail_path_with_roots(candidate, jail_root, &[])
}
pub fn jail_path_with_roots(
candidate: &Path,
jail_root: &Path,
extra_roots: &[String],
) -> Result<PathBuf, String> {
if candidate.to_string_lossy().as_bytes().contains(&0) {
return Err("path contains null byte".to_string());
}
#[cfg(feature = "no-jail")]
{
let _ = (jail_root, extra_roots);
return Ok(canonicalize_or_self(candidate));
}
#[allow(unreachable_code)]
{
let cfg = crate::core::config::Config::load();
if cfg.path_jail == Some(false) {
return Ok(canonicalize_or_self(candidate));
}
let root = canonicalize_secure(jail_root);
let resolved: PathBuf;
let candidate: &Path = if candidate.is_absolute() {
candidate
} else {
resolved = root.join(candidate);
resolved.as_path()
};
let mut allow = allow_paths_from_env_and_config();
allow.extend(
extra_roots
.iter()
.filter(|r| !r.is_empty())
.map(|r| canonicalize_secure(Path::new(r))),
);
let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
format!(
"path does not exist and has no existing ancestor: {}",
candidate.display()
)
})?;
let allowed =
is_under_prefix(&base, &root) || allow.iter().any(|p| is_under_prefix(&base, p));
#[cfg(windows)]
let allowed = allowed || is_under_prefix_windows(&base, &root);
if !allowed {
let base_msg = format!(
"path escapes project root: {} (root: {})",
candidate.display(),
root.display(),
);
let hint = if crate::core::protocol::meta_visible() {
format!(
". Hint: set LEAN_CTX_ALLOW_PATH={} or add it to allow_paths in ~/.lean-ctx/config.toml",
candidate.parent().unwrap_or(candidate).display()
)
} else {
String::new()
};
return Err(format!("{base_msg}{hint}"));
}
#[cfg(windows)]
reject_symlink_on_windows(candidate)?;
let mut out = base;
for part in remainder.iter().rev() {
out.push(part);
}
if out.exists() {
let final_canon = canonicalize_secure(&out);
let final_ok = is_under_prefix(&final_canon, &root)
|| allow.iter().any(|p| is_under_prefix(&final_canon, p));
#[cfg(windows)]
let final_ok = final_ok || is_under_prefix_windows(&final_canon, &root);
if !final_ok {
return Err(format!(
"post-canonicalize jail escape detected: {} resolves to {}",
candidate.display(),
final_canon.display()
));
}
}
Ok(out)
}
}
#[cfg(windows)]
fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
let path_str = normalize_windows_path(&path.to_string_lossy());
let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
path_str.starts_with(&prefix_str)
}
#[cfg(windows)]
fn normalize_windows_path(s: &str) -> String {
let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
stripped.to_lowercase().replace('/', "\\")
}
#[cfg(windows)]
fn reject_symlink_on_windows(path: &Path) -> Result<(), String> {
if let Ok(meta) = std::fs::symlink_metadata(path) {
if super::pathutil::is_symlink_or_reparse(&meta) {
return Err(format!(
"symlink not allowed in jailed path: {}",
path.display()
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "no-jail"))]
#[test]
fn rejects_path_outside_root() {
let _iso = crate::core::data_dir::isolated_data_dir();
let _alp = ALLOW_PATH_ENV_LOCK.lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(root.join("a.txt"), "ok").unwrap();
std::fs::write(other.join("b.txt"), "no").unwrap();
let ok = jail_path(&root.join("a.txt"), &root);
assert!(ok.is_ok());
let bad = jail_path(&other.join("b.txt"), &root);
assert!(bad.is_err());
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn honors_path_jail_false_after_mtime_preserving_edit() {
let _iso = crate::core::data_dir::isolated_data_dir();
let cfg_path = crate::core::config::Config::path().unwrap();
if let Some(parent) = cfg_path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let secret = outside.join("secret.txt");
std::fs::write(&secret, "x").unwrap();
std::fs::write(&cfg_path, "# jail on\n").unwrap();
let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
assert_eq!(crate::core::config::Config::load().path_jail, None);
std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
assert!(
jail_path(&secret, &root).is_ok(),
"path_jail=false must take effect without a fresh process (#406)"
);
}
#[test]
fn allows_nonexistent_child_under_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("a.txt"), "ok").unwrap();
let p = root.join("new").join("file.txt");
let ok = jail_path(&p, &root).unwrap();
assert!(ok.to_string_lossy().contains("file.txt"));
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn relative_candidate_resolves_against_root_not_cwd() {
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
let jailed = jail_path(Path::new("sub/file.rs"), &root)
.expect("relative candidate should resolve under the jail root");
assert!(jailed.ends_with("sub/file.rs"));
assert!(
is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
"resolved path must live under the jail root: {jailed:?}"
);
}
#[test]
fn ide_config_dirs_list_is_not_empty() {
assert!(IDE_CONFIG_DIRS.len() >= 10);
assert!(IDE_CONFIG_DIRS.contains(&".codex"));
assert!(IDE_CONFIG_DIRS.contains(&".cursor"));
assert!(IDE_CONFIG_DIRS.contains(&".claude"));
assert!(IDE_CONFIG_DIRS.contains(&".gemini"));
}
#[test]
fn ide_config_dirs_are_excluded_by_default() {
let home = tempfile::tempdir().unwrap();
for d in [".lean-ctx", ".cursor", ".claude", ".codex"] {
std::fs::create_dir_all(home.path().join(d)).unwrap();
}
let denied = home_allow_dirs(home.path(), false);
assert_eq!(
denied.len(),
1,
"only ~/.lean-ctx may be allowed: {denied:?}"
);
assert!(denied[0].ends_with(".lean-ctx"));
let allowed = home_allow_dirs(home.path(), true);
assert_eq!(allowed.len(), 4, "opt-in must allow all existing IDE dirs");
}
#[test]
fn canonicalize_or_self_strips_verbatim() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("project");
std::fs::create_dir_all(&dir).unwrap();
let result = canonicalize_or_self(&dir);
let s = result.to_string_lossy();
assert!(
!s.starts_with(r"\\?\"),
"canonicalize_or_self should strip verbatim prefix, got: {s}"
);
}
#[test]
fn jail_path_accepts_same_dir_different_format() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("file.rs"), "ok").unwrap();
let result = jail_path(&root.join("file.rs"), &root);
assert!(result.is_ok(), "same dir should be accepted: {result:?}");
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn error_message_contains_escape_info() {
let _iso = crate::core::data_dir::isolated_data_dir();
let _alp = ALLOW_PATH_ENV_LOCK.lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "no").unwrap();
let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
assert!(
err.contains("path escapes project root"),
"error should mention escape: {err}"
);
}
#[test]
fn expand_user_path_expands_tilde_and_vars() {
let home = dirs::home_dir().expect("home dir");
let home_s = home.to_string_lossy().to_string();
assert_eq!(expand_user_path("~"), home);
assert_eq!(expand_user_path("~/code"), home.join("code"));
assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
assert_eq!(
expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
PathBuf::from(format!("{home_s}/sub/x"))
);
crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
}
#[test]
fn expand_user_path_leaves_unset_vars_verbatim() {
crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
}
static ALLOW_PATH_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(unix)]
#[test]
fn allow_path_root_slash_permits_everything() {
let _guard = ALLOW_PATH_ENV_LOCK.lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "allowed").unwrap();
crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
let result = jail_path(&other.join("b.txt"), &root);
crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
}
#[test]
fn allow_path_env_permits_outside_root() {
let _guard = ALLOW_PATH_ENV_LOCK.lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "allowed").unwrap();
let canon = canonicalize_or_self(&other);
crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
let result = jail_path(&other.join("b.txt"), &root);
crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
assert!(
result.is_ok(),
"LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
);
}
#[cfg(all(unix, not(feature = "no-jail")))]
#[test]
fn rejects_symlink_escape_on_unix() {
use std::os::unix::fs::symlink;
let _iso = crate::core::data_dir::isolated_data_dir();
let _alp = ALLOW_PATH_ENV_LOCK.lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("secret.txt"), "no").unwrap();
let link = root.join("link.txt");
symlink(other.join("secret.txt"), &link).unwrap();
let bad = jail_path(&link, &root);
assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
}
#[test]
fn rejects_null_byte_in_path() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
let bad_path = PathBuf::from("file\0.txt");
let result = jail_path(&bad_path, &root);
assert!(result.is_err(), "null byte in path must be rejected");
assert!(
result.unwrap_err().contains("null byte"),
"error must mention null byte"
);
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn extra_roots_permit_paths_outside_jail() {
let _iso = crate::core::data_dir::isolated_data_dir();
let _alp = ALLOW_PATH_ENV_LOCK.lock().unwrap();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let worktree = tmp.path().join("worktree");
let elsewhere = tmp.path().join("elsewhere");
for d in [&root, &worktree, &elsewhere] {
std::fs::create_dir_all(d).unwrap();
}
let in_worktree = worktree.join("a.txt");
std::fs::write(&in_worktree, "x").unwrap();
let outside = elsewhere.join("b.txt");
std::fs::write(&outside, "y").unwrap();
assert!(jail_path(&in_worktree, &root).is_err());
assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
let extra = vec![worktree.to_string_lossy().to_string()];
assert!(
jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
"path under a session extra_root must resolve (#403)"
);
assert!(
jail_path_with_roots(&outside, &root, &extra).is_err(),
"paths outside ALL roots must still be rejected"
);
assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
}
}