Skip to main content

lean_ctx/cli/
allow_cmd.rs

1//! `lean-ctx allow` — manage the shell allowlist additively.
2//!
3//! Setting `shell_allowlist` directly replaces the entire built-in default list
4//! (a footgun reported in #341). This command instead writes to the additive
5//! `shell_allowlist_extra` field, so a user can permit one extra binary (e.g.
6//! `acli`) without losing `git`, `cargo`, … and without restarting anything —
7//! the MCP server re-reads `config.toml` (mtime-invalidated) on the next command.
8
9use crate::core::config;
10use crate::core::shell_allowlist;
11
12pub fn cmd_allow(args: &[String]) {
13    // `--help` anywhere shows usage instead of treating it as a command to
14    // allow (`lean-ctx allow git --help` must not allowlist "--help", GH #393).
15    if args.iter().any(|a| a == "--help" || a == "-h") {
16        print_usage();
17        return;
18    }
19    match args.first().map(std::string::String::as_str) {
20        None => print_usage(),
21        Some("--list" | "list" | "ls") => print_effective(),
22        Some("--remove" | "-r" | "remove" | "rm") => remove(&args[1..]),
23        _ => add(args),
24    }
25}
26
27/// Adds one or more commands to the additive `shell_allowlist_extra`.
28fn add(cmds: &[String]) {
29    let requested: Vec<String> = cmds
30        .iter()
31        .map(|c| c.trim().to_string())
32        .filter(|c| !c.is_empty())
33        .collect();
34
35    if requested.is_empty() {
36        print_usage();
37        return;
38    }
39
40    let mut extra = current_extra_from_global();
41    let mut added = Vec::new();
42    for cmd in requested {
43        if extra.iter().any(|e| e == &cmd) {
44            println!("  already allowed: {cmd}");
45        } else {
46            extra.push(cmd.clone());
47            added.push(cmd);
48        }
49    }
50
51    if added.is_empty() {
52        println!("\nNothing to add — all commands were already in the allowlist.");
53        print_effective();
54        return;
55    }
56
57    if let Err(e) = write_extra(&extra) {
58        eprintln!("Error: {e}");
59        std::process::exit(1);
60    }
61
62    println!("Allowed (additive): {}", added.join(", "));
63    println!("These are merged on top of the defaults — nothing else was removed.");
64    println!("Takes effect immediately; no MCP/daemon restart needed.");
65
66    // GH #1419 follow-up: warn (don't refuse) when the new entry is shadowed
67    // by a broader one already in effect — e.g. the default "git" makes
68    // `lean-ctx allow "git status"` scope nothing. The entry is still
69    // written; the warning only informs.
70    let effective = shell_allowlist::effective_allowlist_pub();
71    for cmd in &added {
72        if let Some(covering) = shell_allowlist::shadowing_entry(&effective, cmd) {
73            println!(
74                "  \x1b[33m⚠ '{cmd}' has no effect — it's already covered by '{covering}'.\x1b[0m"
75            );
76            println!(
77                "    To scope a default binary like '{covering}', replace `shell_allowlist` \
78                 directly — `shell_allowlist_extra` can only add, never narrow."
79            );
80        }
81    }
82    print_effective();
83}
84
85/// Removes one or more commands from `shell_allowlist_extra`.
86fn remove(cmds: &[String]) {
87    let to_remove: Vec<String> = cmds
88        .iter()
89        .map(|c| c.trim().to_string())
90        .filter(|c| !c.is_empty())
91        .collect();
92
93    if to_remove.is_empty() {
94        eprintln!("Usage: lean-ctx allow --remove <cmd> [<cmd>...]");
95        std::process::exit(1);
96    }
97
98    let before = current_extra_from_global();
99    let after: Vec<String> = before
100        .iter()
101        .filter(|e| !to_remove.iter().any(|r| r == *e))
102        .cloned()
103        .collect();
104
105    let removed: Vec<&String> = before.iter().filter(|e| !after.contains(e)).collect();
106    if removed.is_empty() {
107        println!("None of those were in shell_allowlist_extra (nothing changed).");
108        println!(
109            "Note: built-in defaults can't be removed here — set `shell_allowlist` explicitly to override the whole list."
110        );
111        return;
112    }
113
114    if let Err(e) = write_extra(&after) {
115        eprintln!("Error: {e}");
116        std::process::exit(1);
117    }
118
119    let names: Vec<&str> = removed.iter().map(|s| s.as_str()).collect();
120    println!("Removed from extra allowlist: {}", names.join(", "));
121    print_effective();
122}
123
124/// Prints the fully-resolved allowlist the MCP server actually enforces, the real
125/// config path, and — critically — whether `config.toml` failed to parse (in which
126/// case lean-ctx is silently on defaults, the usual cause of "my edit did nothing").
127fn print_effective() {
128    let effective = shell_allowlist::effective_allowlist_pub();
129    let parse_err = config::last_config_parse_error();
130    let path = config::Config::path().map_or_else(
131        || "~/.lean-ctx/config.toml".to_string(),
132        |p| p.display().to_string(),
133    );
134
135    println!("\nShell allowlist (enforced by the MCP tools):");
136    println!("  Config: {path}");
137
138    if let Some(err) = parse_err {
139        println!("  \x1b[31m⚠ config.toml FAILED to parse — running on DEFAULTS.\x1b[0m");
140        println!("    {err}");
141        println!("    Fix the TOML above, then re-run `lean-ctx allow --list`.");
142    }
143
144    if effective.is_empty() {
145        println!("  Mode: disabled (every command is allowed)");
146        return;
147    }
148
149    println!(
150        "  Mode: restricted — {} command(s) permitted",
151        effective.len()
152    );
153
154    let extra = current_extra_from_global();
155    if extra.is_empty() {
156        println!("  Extra (additive, via `lean-ctx allow`): none");
157    } else {
158        println!(
159            "  Extra (additive, via `lean-ctx allow`): {}",
160            extra.join(", ")
161        );
162    }
163}
164
165/// Reads `shell_allowlist_extra` from the raw GLOBAL config table (not the merged
166/// runtime view) so we never accidentally persist project-local or default values.
167fn current_extra_from_global() -> Vec<String> {
168    global_list("shell_allowlist_extra")
169}
170
171/// The string array `key` of the raw GLOBAL config table.
172fn global_list(key: &str) -> Vec<String> {
173    let Some(path) = config::Config::path() else {
174        return Vec::new();
175    };
176    let Ok(raw) = std::fs::read_to_string(&path) else {
177        return Vec::new();
178    };
179    let Ok(table) = raw.parse::<toml::Table>() else {
180        return Vec::new();
181    };
182    table
183        .get(key)
184        .and_then(toml::Value::as_array)
185        .map(|arr| {
186            arr.iter()
187                .filter_map(|v| v.as_str().map(str::to_string))
188                .collect()
189        })
190        .unwrap_or_default()
191}
192
193/// Adds `programs` to the global `shell_allowlist_extra`, as `lean-ctx allow`
194/// does, without printing. Returns the entries that were new. Used when the
195/// user answers an approval prompt with "always allow".
196pub(crate) fn allow_programs(programs: &[String]) -> Result<Vec<String>, String> {
197    add_to_global_list("shell_allowlist_extra", programs)
198}
199
200/// Adds `languages` to the global `execute_allowed_languages`: the "always
201/// allow" answer to a `ctx_execute` approval prompt.
202pub(crate) fn allow_execute_languages(languages: &[String]) -> Result<Vec<String>, String> {
203    add_to_global_list("execute_allowed_languages", languages)
204}
205
206fn add_to_global_list(key: &str, entries: &[String]) -> Result<Vec<String>, String> {
207    let mut list = global_list(key);
208    let added: Vec<String> = entries
209        .iter()
210        .filter(|p| !p.is_empty() && !list.contains(p))
211        .cloned()
212        .collect();
213    if added.is_empty() {
214        return Ok(added);
215    }
216    list.extend(added.iter().cloned());
217    config::setter::set_by_key(key, &list.join(","))
218        .map(|_| ())
219        .map_err(|e| e.to_string())?;
220    Ok(added)
221}
222
223/// Persists the extra list via the schema-validated setter (minimal-config round-trip).
224fn write_extra(extra: &[String]) -> Result<(), String> {
225    config::setter::set_by_key("shell_allowlist_extra", &extra.join(","))
226        .map(|_| ())
227        .map_err(|e| e.to_string())
228}
229
230fn print_usage() {
231    println!(
232        "Usage: lean-ctx allow <cmd> [<cmd>...]   Add command(s) to the shell allowlist (additive)\n\
233         \x20      lean-ctx allow --list             Show the effective allowlist + config path\n\
234         \x20      lean-ctx allow --remove <cmd>     Remove command(s) you previously added\n\
235         \n\
236         Why this exists: editing `shell_allowlist` replaces the whole built-in list.\n\
237         `lean-ctx allow` appends to `shell_allowlist_extra`, keeping git/cargo/npm/… intact.\n\
238         \n\
239         Entry grammar: one or more words, optionally ending in a lone `*`.\n\
240         A single word (\"cargo\") always allows any subcommand/args. A multi-word\n\
241         entry with no `*` (\"git status\") matches that exact command only. A\n\
242         trailing `*` (\"terraform plan *\") matches that subcommand plus any\n\
243         (or no) further arguments.\n\
244         Example: lean-ctx allow acli"
245    );
246    print_effective();
247}