Skip to main content

lean_ctx/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 crate::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 = crate::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. Projects below ~ are 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 = crate::core::pathjail_scope::PathJailScope::resolve();
157    println!(
158        "  Scope: {} {}",
159        scope.as_str(),
160        match scope {
161            crate::core::pathjail_scope::PathJailScope::Home =>
162                "(read every project below ~, write the session's own; dot dirs and ~/Library closed)",
163            crate::core::pathjail_scope::PathJailScope::Project =>
164                "(only the active project — `lean-ctx config set path_jail_scope home` for all)",
165        }
166    );
167    let entries = current_from_global();
168    if entries.is_empty() {
169        println!("  Extra (via `lean-ctx allow-path`): none");
170    } else {
171        println!("  Extra (via `lean-ctx allow-path`):");
172        for e in entries {
173            println!("    {e}");
174        }
175    }
176}
177
178fn current_from_global() -> Vec<String> {
179    global_string_list("allow_paths")
180}
181
182/// A string-array key from the raw GLOBAL config table — never the merged
183/// runtime view, so project-local or default values are never persisted
184/// globally.
185pub(crate) fn global_string_list(key: &str) -> Vec<String> {
186    let Some(path) = config::Config::path() else {
187        return Vec::new();
188    };
189    let Ok(raw) = std::fs::read_to_string(&path) else {
190        return Vec::new();
191    };
192    let Ok(table) = raw.parse::<toml::Table>() else {
193        return Vec::new();
194    };
195    table
196        .get(key)
197        .and_then(toml::Value::as_array)
198        .map(|arr| {
199            arr.iter()
200                .filter_map(|v| v.as_str().map(str::to_string))
201                .collect()
202        })
203        .unwrap_or_default()
204}
205
206fn write(entries: &[String]) -> Result<(), String> {
207    if entries.iter().any(|e| e.contains(',')) {
208        return Err(
209            "a path containing ',' cannot be stored via the CLI — add it to allow_paths in \
210             config.toml directly"
211                .to_string(),
212        );
213    }
214    config::setter::set_by_key("allow_paths", &entries.join(","))
215        .map(|_| ())
216        .map_err(|e| e.to_string())
217}
218
219fn print_usage() {
220    println!(
221        "Usage: lean-ctx allow-path <dir> [<dir>...]   Let lean-ctx tools read/write this directory\n\
222         \x20      lean-ctx allow-path --list             Show the jail scope + extra directories\n\
223         \x20      lean-ctx allow-path --remove <dir>     Remove a directory you added\n\
224         \n\
225         With the default `path_jail_scope = home`, every project (a folder with .git,\n\
226         Cargo.toml, package.json, …) below your home directory\n\
227         is readable and the session's own project is writable. Use this to edit another\n\
228         project, for directories outside ~ (/opt/src, /srv/repo) or for one protected\n\
229         location (~/.config/myapp). Read + write; takes effect immediately, no restart.\n\
230         Example: lean-ctx allow-path /opt/src/vendor-sdk"
231    );
232    print_effective();
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    #[test]
240    fn refuses_entries_that_grant_everything() {
241        assert!(refusal(Path::new("/")).is_some());
242        if let Some(home) = dirs::home_dir() {
243            let home = std::fs::canonicalize(&home).unwrap_or(home);
244            assert!(refusal(&home).is_some());
245            assert!(refusal(home.parent().unwrap()).is_some(), "ancestor of ~");
246            assert!(refusal(&home.join(".config/app")).is_none());
247        }
248        assert!(refusal(Path::new("/opt/src")).is_none());
249    }
250
251    #[test]
252    fn normalize_makes_relative_paths_absolute() {
253        let p = normalize("some/rel/dir").unwrap();
254        assert!(p.is_absolute(), "{}", p.display());
255        // A not-yet-existing path keeps its expanded form.
256        let home = dirs::home_dir().unwrap();
257        assert_eq!(
258            normalize("~/lean-ctx-allow-path-missing").unwrap(),
259            home.join("lean-ctx-allow-path-missing")
260        );
261    }
262}