Skip to main content

lean_ctx_cli/cli/
allow_path_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx allow-path` — let the path jail admit one more directory.
3//!
4//! The sibling of `lean-ctx allow` (shell commands): appends to the additive
5//! global `allow_paths` list, which the MCP server re-reads on the next tool
6//! call — no restart. It is the single fix the jail's rejection message names,
7//! for a directory outside the home directory or inside a protected zone
8//! (`~/.config/…`). Paths are expanded (`~`, `$VAR`) and made absolute against
9//! the caller's working directory, so the stored entry means the same thing to
10//! a server started elsewhere.
11
12use std::path::{Path, PathBuf};
13
14use lean_ctx::core::config;
15
16pub fn cmd_allow_path(args: &[String]) {
17    if args.iter().any(|a| a == "--help" || a == "-h") {
18        print_usage();
19        return;
20    }
21    match args.first().map(String::as_str) {
22        None => print_usage(),
23        Some("--list" | "list" | "ls") => print_effective(),
24        Some("--remove" | "-r" | "remove" | "rm") => remove(&args[1..]),
25        _ => add(args),
26    }
27}
28
29/// Absolute, expanded form of a user-typed path. Canonical when it exists, so
30/// the entry matches the canonical candidates the jail compares against.
31fn normalize(raw: &str) -> Result<PathBuf, String> {
32    let expanded = lean_ctx::core::pathjail::expand_user_path(raw.trim());
33    let absolute = if expanded.is_absolute() {
34        expanded
35    } else {
36        std::env::current_dir()
37            .map_err(|e| format!("cannot resolve relative path '{raw}': {e}"))?
38            .join(expanded)
39    };
40    Ok(std::fs::canonicalize(&absolute).unwrap_or(absolute))
41}
42
43/// Entries that would grant everything are refused with the explicit switch
44/// instead: `/` silently disables the jail (GH #392); the home directory or
45/// any ancestor of it (`/Users`, `~/..`) would contain every protected zone.
46fn refusal(path: &Path) -> Option<String> {
47    if path.parent().is_none() {
48        return Some(
49            "refusing '/': that allows every path. To disable the jail on purpose: \
50             lean-ctx config set path_jail false"
51                .to_string(),
52        );
53    }
54    let home = dirs::home_dir().map(|h| std::fs::canonicalize(&h).unwrap_or(h));
55    if home.as_deref().is_some_and(|h| h.starts_with(path)) {
56        return Some(
57            "refusing your home directory or a directory containing it: that would also open \
58             ~/.ssh, ~/.aws and every other protected zone. Everything else below ~ is already allowed (path_jail_scope = home); \
59             allow the one protected directory you need instead."
60                .to_string(),
61        );
62    }
63    None
64}
65
66fn add(raw: &[String]) {
67    let mut entries = current_from_global();
68    let mut added = Vec::new();
69    for r in raw.iter().filter(|r| !r.trim().is_empty()) {
70        let path = match normalize(r) {
71            Ok(p) => p,
72            Err(e) => {
73                eprintln!("Error: {e}");
74                std::process::exit(1);
75            }
76        };
77        if let Some(why) = refusal(&path) {
78            eprintln!("Error: {why}");
79            std::process::exit(1);
80        }
81        if !path.exists() {
82            println!(
83                "  note: {} does not exist yet — allowed anyway",
84                path.display()
85            );
86        }
87        let entry = path.to_string_lossy().to_string();
88        if entries.contains(&entry) {
89            println!("  already allowed: {entry}");
90        } else {
91            entries.push(entry.clone());
92            added.push(entry);
93        }
94    }
95    if added.is_empty() {
96        print_effective();
97        return;
98    }
99    if let Err(e) = write(&entries) {
100        eprintln!("Error: {e}");
101        std::process::exit(1);
102    }
103    println!("Allowed: {}", added.join(", "));
104    println!("Takes effect immediately for every agent; no MCP/daemon restart needed.");
105    print_effective();
106}
107
108fn remove(raw: &[String]) {
109    let targets: Vec<String> = raw
110        .iter()
111        .filter(|r| !r.trim().is_empty())
112        .map(|r| normalize(r).map_or_else(|_| r.clone(), |p| p.to_string_lossy().to_string()))
113        .collect();
114    if targets.is_empty() {
115        eprintln!("Usage: lean-ctx allow-path --remove <dir> [<dir>...]");
116        std::process::exit(1);
117    }
118    let before = current_from_global();
119    let after: Vec<String> = before
120        .iter()
121        .filter(|e| !targets.iter().any(|t| t == *e || raw.contains(e)))
122        .cloned()
123        .collect();
124    if after.len() == before.len() {
125        println!("None of those were in allow_paths (nothing changed).");
126        print_effective();
127        return;
128    }
129    if let Err(e) = write(&after) {
130        eprintln!("Error: {e}");
131        std::process::exit(1);
132    }
133    println!(
134        "Removed {} entr(y/ies) from allow_paths.",
135        before.len() - after.len()
136    );
137    print_effective();
138}
139
140fn print_effective() {
141    let path = config::Config::path().map_or_else(
142        || "~/.lean-ctx/config.toml".to_string(),
143        |p| p.display().to_string(),
144    );
145    println!("\nPath jail (enforced by the MCP tools):");
146    println!("  Config: {path}");
147    if let Some(err) = config::last_config_parse_error() {
148        println!("  \x1b[31m⚠ config.toml FAILED to parse — running on DEFAULTS.\x1b[0m");
149        println!("    {err}");
150    }
151    let cfg = config::Config::load();
152    if cfg.path_jail == Some(false) {
153        println!("  Jail: disabled (path_jail = false) — every path is allowed");
154        return;
155    }
156    let scope = lean_ctx::core::pathjail_scope::PathJailScope::resolve();
157    println!(
158        "  Scope: {} {}",
159        scope.as_str(),
160        match scope {
161            lean_ctx::core::pathjail_scope::PathJailScope::Home =>
162                "(read and write everything below ~; dot dirs and ~/Library closed)",
163            lean_ctx::core::pathjail_scope::PathJailScope::Projects =>
164                "(read every project below ~, write the session's own — `lean-ctx config set path_jail_scope home` for all of ~)",
165            lean_ctx::core::pathjail_scope::PathJailScope::Project =>
166                "(only the active project — `lean-ctx config set path_jail_scope home` for all of ~)",
167        }
168    );
169    let entries = current_from_global();
170    if entries.is_empty() {
171        println!("  Extra (via `lean-ctx allow-path`): none");
172    } else {
173        println!("  Extra (via `lean-ctx allow-path`):");
174        for e in entries {
175            println!("    {e}");
176        }
177    }
178}
179
180fn current_from_global() -> Vec<String> {
181    config::global_string_list("allow_paths")
182}
183
184fn write(entries: &[String]) -> Result<(), String> {
185    if entries.iter().any(|e| e.contains(',')) {
186        return Err(
187            "a path containing ',' cannot be stored via the CLI — add it to allow_paths in \
188             config.toml directly"
189                .to_string(),
190        );
191    }
192    config::setter::set_by_key("allow_paths", &entries.join(","))
193        .map(|_| ())
194        .map_err(|e| e.to_string())
195}
196
197fn print_usage() {
198    println!(
199        "Usage: lean-ctx allow-path <dir> [<dir>...]   Let lean-ctx tools read/write this directory\n\
200         \x20      lean-ctx allow-path --list             Show the jail scope + extra directories\n\
201         \x20      lean-ctx allow-path --remove <dir>     Remove a directory you added\n\
202         \n\
203         With the default `path_jail_scope = projects`, every project below your home\n\
204         directory is readable and only the active project is writable; protected\n\
205         locations (~/.ssh, ~/.config and other dot dirs, ~/Library) stay closed. Use\n\
206         this to write in another project, for directories outside ~ (/opt/src,\n\
207         /srv/repo) or for one protected\n\
208         location (~/.config/myapp). Read + write; takes effect immediately, no restart.\n\
209         Example: lean-ctx allow-path /opt/src/vendor-sdk"
210    );
211    print_effective();
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn refuses_entries_that_grant_everything() {
220        let _home = lean_ctx::core::data_dir::test_env_lock();
221        assert!(refusal(Path::new("/")).is_some());
222        if let Some(home) = dirs::home_dir() {
223            let home = std::fs::canonicalize(&home).unwrap_or(home);
224            assert!(refusal(&home).is_some());
225            assert!(refusal(home.parent().unwrap()).is_some(), "ancestor of ~");
226            assert!(refusal(&home.join(".config/app")).is_none());
227        }
228        assert!(refusal(Path::new("/opt/src")).is_none());
229    }
230
231    #[test]
232    fn normalize_makes_relative_paths_absolute() {
233        let _home = lean_ctx::core::data_dir::test_env_lock();
234        let p = normalize("some/rel/dir").unwrap();
235        assert!(p.is_absolute(), "{}", p.display());
236        // A not-yet-existing path keeps its expanded form.
237        let home = dirs::home_dir().unwrap();
238        assert_eq!(
239            normalize("~/lean-ctx-allow-path-missing").unwrap(),
240            home.join("lean-ctx-allow-path-missing")
241        );
242    }
243}