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    let Some(path) = config::Config::path() else {
169        return Vec::new();
170    };
171    let Ok(raw) = std::fs::read_to_string(&path) else {
172        return Vec::new();
173    };
174    let Ok(table) = raw.parse::<toml::Table>() else {
175        return Vec::new();
176    };
177    table
178        .get("shell_allowlist_extra")
179        .and_then(toml::Value::as_array)
180        .map(|arr| {
181            arr.iter()
182                .filter_map(|v| v.as_str().map(str::to_string))
183                .collect()
184        })
185        .unwrap_or_default()
186}
187
188/// Persists the extra list via the schema-validated setter (minimal-config round-trip).
189fn write_extra(extra: &[String]) -> Result<(), String> {
190    config::setter::set_by_key("shell_allowlist_extra", &extra.join(","))
191        .map(|_| ())
192        .map_err(|e| e.to_string())
193}
194
195fn print_usage() {
196    println!(
197        "Usage: lean-ctx allow <cmd> [<cmd>...]   Add command(s) to the shell allowlist (additive)\n\
198         \x20      lean-ctx allow --list             Show the effective allowlist + config path\n\
199         \x20      lean-ctx allow --remove <cmd>     Remove command(s) you previously added\n\
200         \n\
201         Why this exists: editing `shell_allowlist` replaces the whole built-in list.\n\
202         `lean-ctx allow` appends to `shell_allowlist_extra`, keeping git/cargo/npm/… intact.\n\
203         \n\
204         Entry grammar: one or more words, optionally ending in a lone `*`.\n\
205         A single word (\"cargo\") always allows any subcommand/args. A multi-word\n\
206         entry with no `*` (\"git status\") matches that exact command only. A\n\
207         trailing `*` (\"terraform plan *\") matches that subcommand plus any\n\
208         (or no) further arguments.\n\
209         Example: lean-ctx allow acli"
210    );
211    print_effective();
212}