lean_ctx_cli/cli/
allow_path_cmd.rs1use 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
29fn 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
43fn 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 assert!(refusal(Path::new("/")).is_some());
221 if let Some(home) = dirs::home_dir() {
222 let home = std::fs::canonicalize(&home).unwrap_or(home);
223 assert!(refusal(&home).is_some());
224 assert!(refusal(home.parent().unwrap()).is_some(), "ancestor of ~");
225 assert!(refusal(&home.join(".config/app")).is_none());
226 }
227 assert!(refusal(Path::new("/opt/src")).is_none());
228 }
229
230 #[test]
231 fn normalize_makes_relative_paths_absolute() {
232 let p = normalize("some/rel/dir").unwrap();
233 assert!(p.is_absolute(), "{}", p.display());
234 let home = dirs::home_dir().unwrap();
236 assert_eq!(
237 normalize("~/lean-ctx-allow-path-missing").unwrap(),
238 home.join("lean-ctx-allow-path-missing")
239 );
240 }
241}