Skip to main content

lean_ctx/core/shell_allowlist/
config.rs

1pub(super) fn effective_allowlist() -> Vec<String> {
2    filter_valid_entries(raw_allowlist_entries())
3}
4
5/// The same union `effective_allowlist()` builds, before `*`-placement
6/// filtering — shared with the invalid-entry and upgrade-advisory doctor
7/// checks, which need to see entries `effective_allowlist()` would drop.
8fn raw_allowlist_entries() -> Vec<String> {
9    // LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE completely replaces the config (for testing)
10    if let Ok(ov) = std::env::var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE") {
11        return ov
12            .split(',')
13            .map(|s| s.trim().to_string())
14            .filter(|s| !s.is_empty())
15            .collect();
16    }
17    let cfg = crate::core::config::Config::load();
18    let mut list = cfg.shell_allowlist;
19    // `shell_allowlist_extra` is purely additive (written by `lean-ctx allow <cmd>`),
20    // so users can permit a command without nuking the built-in defaults. It only
21    // matters in restricted mode — when the base list is empty all commands pass anyway.
22    if !list.is_empty() {
23        for entry in cfg.shell_allowlist_extra {
24            if !entry.is_empty() && !list.contains(&entry) {
25                list.push(entry);
26            }
27        }
28    }
29    if let Ok(env_val) = std::env::var("LEAN_CTX_SHELL_ALLOWLIST") {
30        for entry in env_val
31            .split(',')
32            .map(|s| s.trim().to_string())
33            .filter(|s| !s.is_empty())
34        {
35            if !list.contains(&entry) {
36                list.push(entry);
37            }
38        }
39    }
40    list
41}
42
43/// Public accessor: entries the effective allowlist silently dropped for
44/// invalid `*` placement (§4 of the design doc). Used by `lean-ctx doctor`
45/// to surface a count, and by `--fix` to know which raw config lines to
46/// comment out.
47#[must_use]
48pub fn invalid_allowlist_entries_pub() -> Vec<String> {
49    raw_allowlist_entries()
50        .into_iter()
51        .filter(|e| !is_valid_allowlist_entry(e))
52        .collect()
53}
54
55/// Public accessor: multi-word entries with no trailing `*` — their meaning
56/// changed under subcommand scoping (now exact-match only, previously
57/// "whole binary"). Used by the `lean-ctx doctor` upgrade advisory (§2 of
58/// the design doc). Always empty when `shell_allowlist_subcommand_scoping =
59/// false`, since those entries' meaning didn't change under the compat path.
60#[must_use]
61pub fn narrowed_allowlist_entries_pub() -> Vec<String> {
62    if !crate::core::config::Config::load().shell_allowlist_subcommand_scoping {
63        return Vec::new();
64    }
65    raw_allowlist_entries()
66        .into_iter()
67        .filter(|e| is_valid_allowlist_entry(e))
68        .filter(|e| {
69            let words: Vec<&str> = e.split_whitespace().collect();
70            words.len() > 1 && words.last() != Some(&"*")
71        })
72        .collect()
73}
74
75/// §2 "Shadowing warnings": is `a` made useless by a different entry already
76/// in `entries`? Entry A is shadowed by B when B matches every command A
77/// matches: B is a single word equal to A's first word, or B ends in `*` and
78/// B's words before the `*` are a leading run of A's words (ignoring A's own
79/// trailing `*`). Returns the first covering entry, in list order. Shared by
80/// `lean-ctx allow` (write-time warning) and `lean-ctx doctor` (read-only
81/// advisory) so the rule can't drift between the two.
82#[must_use]
83pub fn shadowing_entry(entries: &[String], a: &str) -> Option<String> {
84    let a_words: Vec<&str> = a.split_whitespace().collect();
85    let a_prefix: &[&str] = if a_words.last() == Some(&"*") {
86        &a_words[..a_words.len() - 1]
87    } else {
88        &a_words
89    };
90    entries
91        .iter()
92        .find(|b| {
93            if b.as_str() == a {
94                return false;
95            }
96            let b_words: Vec<&str> = b.split_whitespace().collect();
97            if b_words.len() == 1 {
98                b_words.first() == a_words.first()
99            } else if b_words.last() == Some(&"*") {
100                let b_prefix = &b_words[..b_words.len() - 1];
101                b_prefix.len() <= a_prefix.len() && a_prefix.starts_with(b_prefix)
102            } else {
103                false
104            }
105        })
106        .cloned()
107}
108
109/// All shadowed entries in `entries`, paired with the entry that covers each
110/// one — used by the `lean-ctx doctor` advisory (§2).
111#[must_use]
112pub fn shadowed_allowlist_entries_pub(entries: &[String]) -> Vec<(String, String)> {
113    entries
114        .iter()
115        .filter_map(|a| shadowing_entry(entries, a).map(|b| (a.clone(), b)))
116        .collect()
117}
118
119/// §4 of the design doc: an entry's only valid `*` placement is a single
120/// trailing token. Bare `*`, an embedded `*`, or more than one `*` are
121/// invalid.
122pub(crate) fn is_valid_allowlist_entry(entry: &str) -> bool {
123    let words: Vec<&str> = entry.split_whitespace().collect();
124    match words.iter().filter(|w| **w == "*").count() {
125        0 => true,
126        1 => words.len() > 1 && words.last() == Some(&"*"),
127        _ => false,
128    }
129}
130
131/// Drops invalid entries rather than failing closed on the whole allowlist
132/// (§4): removing one allow-entry can only make matching *more*
133/// restrictive, never less, so this is safe by construction — mirrors the
134/// `ShellSecurity::resolve()` precedent (an unknown value falls back to
135/// enforce, never to open).
136fn filter_valid_entries(entries: Vec<String>) -> Vec<String> {
137    entries
138        .into_iter()
139        .filter(|entry| {
140            let valid = is_valid_allowlist_entry(entry);
141            if !valid {
142                tracing::warn!(
143                    "[shell_allowlist] dropping invalid allowlist entry '{entry}': `*` must be \
144                     the single trailing token, not embedded, bare, or repeated"
145                );
146            }
147            valid
148        })
149        .collect()
150}
151
152/// Could this token plausibly be an executable name?
153///
154/// Deliberately permissive — the point is to catch obvious scanner debris
155/// (unbalanced parens, quotes, `$`, `&`, embedded spaces), not to validate
156/// against the filesystem. A name that would need quoting to type is not a name
157/// the user should be told to allowlist.
158pub(super) fn is_plausible_command_name(base: &str) -> bool {
159    if base.is_empty() {
160        return false;
161    }
162    !base.chars().any(|c| {
163        c.is_whitespace() || matches!(c, '(' | ')' | '"' | '\'' | '$' | '&' | '|' | ';' | '`')
164    })
165}
166
167/// Builds the actionable, self-diagnosing message shown when a command's base binary
168/// is not in the allowlist. Unlike a bare "not allowed" string, it tells the user
169/// (1) the exact additive fix, (2) the real config path the MCP server reads, and
170/// (3) — crucially — whether their `config.toml` silently failed to parse (in which
171/// case lean-ctx is on defaults, which is the usual reason an allowlist edit "did
172/// nothing"). That last signal is otherwise invisible over an MCP/stdio transport.
173pub(super) fn allowlist_block_message(base: &str, tokens: &[String], entries: &[String]) -> String {
174    let cfg_path = crate::core::config::Config::path().map_or_else(
175        || "~/.lean-ctx/config.toml".to_string(),
176        |p| p.display().to_string(),
177    );
178
179    // #1814: a `$var` command word is a *correct* split, not a mis-split — the
180    // variable genuinely is the command, and the allowlist cannot see what it
181    // expands to at run time. Sending that caller to file a mis-split bug wastes
182    // their time and ours, and "quote the fragment differently" cannot help:
183    // no quoting makes a variable command allowable. Say what actually works.
184    if let Some(name) = base.strip_prefix('$') {
185        let hint = name.trim_start_matches('{').trim_end_matches('}');
186        return format!(
187            "[BLOCKED — DO NOT RETRY] '{base}' expands to the command name at run time, so \
188             the allowlist cannot see which command would run.\n\
189             Write the command literally instead (e.g. `echo hi`, `.venv/bin/python -c ...`) — \
190             that is the form the allowlist can gate.\n\
191             Do NOT run `lean-ctx allow {hint}`; it would allowlist the variable's name, not \
192             the command.\n\
193             Config in effect: {cfg_path}"
194        );
195    }
196
197    // A base that cannot be a command name means the scanner mis-split the line,
198    // not that the user needs to allow something. Printing
199    // `lean-ctx allow print(urllib.parse.quote(sys.argv[1],safe=))` — a real
200    // example from GH #1646 — invites the reader to copy a command that cannot
201    // work and hides the actual fault. Say which it is.
202    if !is_plausible_command_name(base) {
203        return format!(
204            "[BLOCKED] '{base}' is not in the shell allowlist — but it does not look like a \
205             command name, which means lean-ctx split your command line wrongly rather than \
206             finding a command to gate.\n\
207             Do NOT run `lean-ctx allow` on it; that would allowlist a fragment.\n\
208             Quote the fragment differently if you can, and please report the original command \
209             at https://github.com/yvgude/lean-ctx/issues — a mis-split is a bug in lean-ctx.\n\
210             Config in effect: {cfg_path}"
211        );
212    }
213
214    let mut msg = format!(
215        "[BLOCKED — DO NOT RETRY] '{base}' is not in the shell allowlist. \
216         This is a permanent restriction, not a transient error.\n\
217         Fix (additive, keeps the defaults): run  lean-ctx allow {base}\n\
218         Config in effect: {cfg_path}\n\
219         Or disable the allowlist entirely: set  shell_allowlist = []\n\
220         Or turn off all shell gating (you own the risk): set  shell_security = \"off\"  \
221         (or env LEAN_CTX_SHELL_SECURITY=off) — compression still applies.\n\
222         Do NOT reroute through ctx_execute(language=\"shell\"): both tools enforce the same \
223         policy. Allow the command explicitly or change shell_security deliberately."
224    );
225
226    if let Some(detail) = closest_entry_detail(tokens, entries) {
227        msg.push_str(&detail);
228    }
229
230    if crate::core::config::cloud_infra_commands().contains(&base) {
231        msg.push_str(
232            "\nNote: cloud/infra CLIs (terraform, kubectl, aws, …) are deliberately \
233             excluded from the defaults — they mutate remote infrastructure with \
234             ambient credentials. Opting in is a deliberate user decision.",
235        );
236    }
237
238    if let Some(parse_err) = crate::core::config::last_config_parse_error() {
239        msg.push_str(&format!(
240            "\n\n⚠ Your config.toml currently FAILS to parse, so lean-ctx is running on the \
241             built-in defaults — this is almost certainly why editing the allowlist had no \
242             effect. Fix the TOML error below, then retry:\n  {parse_err}\n  File: {cfg_path}"
243        ));
244    } else if let Some(missing) = crate::core::config::Config::missing_config_path() {
245        // The resolved config doesn't exist → lean-ctx is on defaults. An edit
246        // made to a config.toml in a different dir (XDG vs legacy ~/.lean-ctx) or
247        // under a sandboxed/container HOME is never read — say so over MCP (#540).
248        msg.push_str(&format!(
249            "\n\n⚠ No config file exists at {} — lean-ctx is running on built-in defaults. \
250             If you added the command to a config.toml in a DIFFERENT location (XDG \
251             ~/.config/lean-ctx vs legacy ~/.lean-ctx, or your MCP client launches lean-ctx \
252             in a sandbox/container with a different HOME), the runtime never reads it. \
253             `lean-ctx doctor` prints the path actually in effect; pin it with \
254             LEAN_CTX_CONFIG_DIR.",
255            missing.display()
256        ));
257    }
258
259    // A project-local `shell_allowlist`/`shell_allowlist_extra` is silently
260    // withheld for an untrusted workspace; surface that here so the edit's
261    // no-op reason isn't buried in an MCP-invisible stderr warning (#540).
262    if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
263        msg.push_str("\n\n⚠ ");
264        msg.push_str(&notice);
265    }
266
267    msg
268}
269
270/// §6 of the design doc: names the closest matching allowlist entry and
271/// where the command's tokens diverge from it, so an LLM agent can
272/// self-correct without a human round-trip. Only fires when at least one
273/// entry shares the base binary — otherwise "not in the shell allowlist"
274/// already says enough. Longest common token prefix; ties resolve to the
275/// first entry in list order (same convention as `levenshtein::closest()`).
276fn closest_entry_detail(tokens: &[String], entries: &[String]) -> Option<String> {
277    let base = tokens.first()?.as_str();
278    let mut best: Option<(&str, usize)> = None;
279    for entry in entries {
280        let words: Vec<&str> = entry.split_whitespace().collect();
281        if words.first() != Some(&base) {
282            continue;
283        }
284        let shared = tokens
285            .iter()
286            .zip(words.iter())
287            .take_while(|(t, w)| t.as_str() == **w)
288            .count();
289        if best.is_none_or(|(_, len)| shared > len) {
290            best = Some((entry.as_str(), shared));
291        }
292    }
293    let (entry, shared) = best?;
294    let entry_words: Vec<&str> = entry.split_whitespace().collect();
295    let diverges_at = entry_words.get(shared).copied();
296    let got = tokens.get(shared).map(String::as_str);
297    let mut detail = match (diverges_at, got) {
298        (Some(expected), Some(got)) => {
299            format!("\n(closest entry '{entry}' requires subcommand '{expected}', got '{got}')")
300        }
301        _ => format!("\n(closest entry '{entry}')"),
302    };
303    if got.is_some_and(|g| g.starts_with('-')) {
304        detail.push_str(
305            "\nGlobal options before the subcommand are not matched. Run \
306             `cd <dir> && <cmd>` instead, or add an explicit allowlist entry.",
307        );
308    }
309    Some(detail)
310}
311/// Public accessor: the fully-resolved allowlist actually enforced by the MCP tools
312/// (base `shell_allowlist` + additive `shell_allowlist_extra` + env), deduplicated.
313/// Empty means blocklist-only mode (all commands pass). Used by `lean-ctx allow`
314/// and `lean-ctx doctor` to show users exactly what the runtime sees.
315#[must_use]
316pub fn effective_allowlist_pub() -> Vec<String> {
317    effective_allowlist()
318}
319
320/// GH #1466: Check whether the user has explicitly allowed an interpreter for
321/// inline/heredoc use in Claude Code's own permission system.
322///
323/// Reads `permissions.allow` from both global (`~/.claude/settings.json`) and
324/// project-local (`.claude/settings.local.json`) settings. Entries like
325/// `Bash(python3:*)` or `Bash(python3:)` grant the interpreter `python3`
326/// inline-execution rights, bypassing the heredoc/eval-flag block.
327///
328/// Cached per-process to avoid re-reading settings on every shell invocation.
329pub(super) fn claude_allows_interpreter_inline(interpreter: &str) -> bool {
330    use std::sync::OnceLock;
331
332    static CACHE: OnceLock<Vec<String>> = OnceLock::new();
333
334    let allowed = CACHE.get_or_init(|| {
335        let mut interpreters = Vec::new();
336        collect_claude_bash_permissions(&mut interpreters);
337        interpreters
338    });
339
340    allowed.iter().any(|a| a == interpreter)
341}
342
343/// Parse `Bash(<cmd>:...)` entries from Claude's `permissions.allow` arrays.
344fn collect_claude_bash_permissions(out: &mut Vec<String>) {
345    let paths = claude_settings_paths();
346    for path in &paths {
347        if let Ok(content) = std::fs::read_to_string(path) {
348            if let Ok(json) = crate::core::jsonc::parse_jsonc(&content) {
349                extract_bash_interpreters(&json, out);
350            }
351        }
352    }
353}
354
355/// Returns candidate Claude settings paths (global + project-local).
356fn claude_settings_paths() -> Vec<std::path::PathBuf> {
357    let mut paths = Vec::with_capacity(2);
358
359    if let Some(home) = crate::core::home::resolve_home_dir() {
360        paths.push(home.join(".claude").join("settings.json"));
361    }
362
363    if let Ok(cwd) = std::env::current_dir() {
364        paths.push(cwd.join(".claude").join("settings.local.json"));
365    }
366
367    paths
368}
369
370/// Extract interpreter names from `Bash(<interpreter>:...)` permission entries.
371pub(super) fn extract_bash_interpreters(json: &serde_json::Value, out: &mut Vec<String>) {
372    let allow = json
373        .pointer("/permissions/allow")
374        .and_then(|v| v.as_array());
375
376    let Some(arr) = allow else { return };
377
378    for entry in arr {
379        let Some(s) = entry.as_str() else { continue };
380        if let Some(inner) = parse_bash_permission(s) {
381            if !inner.is_empty() && !out.contains(&inner) {
382                out.push(inner);
383            }
384        }
385    }
386}
387
388/// Parse a Claude permission entry like `Bash(python3:*)` → `Some("python3")`.
389/// Accepted formats: `Bash(cmd:)`, `Bash(cmd:*)`, `Bash(cmd:<anything>)`.
390pub(super) fn parse_bash_permission(entry: &str) -> Option<String> {
391    let rest = entry.strip_prefix("Bash(")?;
392    let rest = rest.strip_suffix(')')?;
393    let colon_pos = rest.find(':')?;
394    let cmd = &rest[..colon_pos];
395    if cmd.is_empty() {
396        return None;
397    }
398    let base = cmd.rsplit('/').next().unwrap_or(cmd);
399    Some(base.to_string())
400}
401
402#[cfg(test)]
403mod tests {
404    use super::{allowlist_block_message, shadowing_entry};
405
406    /// §2 of the design doc: pure-helper shadowing rule, all five agreed cases.
407    #[test]
408    fn shadowing_rule_matches_design_doc_cases() {
409        let entries = |a: &str, b: &str| vec![a.to_string(), b.to_string()];
410
411        assert_eq!(
412            shadowing_entry(&entries("git status", "git"), "git status"),
413            Some("git".to_string()),
414            "a single-word entry shadows any multi-word entry sharing its first word"
415        );
416        assert_eq!(
417            shadowing_entry(&entries("git status -s", "git status *"), "git status -s"),
418            Some("git status *".to_string()),
419            "a trailing-* entry shadows a longer exact entry sharing its prefix"
420        );
421        assert_eq!(
422            shadowing_entry(&entries("git status", "git status *"), "git status"),
423            Some("git status *".to_string()),
424            "a trailing-* entry shadows the identical exact entry"
425        );
426        assert_eq!(
427            shadowing_entry(&entries("git log", "git status *"), "git log"),
428            None,
429            "different subcommands must not shadow each other"
430        );
431        assert_eq!(
432            shadowing_entry(&entries("git status *", "git status"), "git status *"),
433            None,
434            "an exact entry must not shadow a broader trailing-* entry"
435        );
436    }
437
438    /// #1814: a `$var` command word is a *correct* split, not a mis-split. The
439    /// old text asked the caller to file a bug for intended behaviour and
440    /// suggested re-quoting, which cannot help — no quoting makes a variable
441    /// command gateable.
442    #[test]
443    fn variable_command_word_explains_expansion_not_a_parser_bug() {
444        for base in ["$X", "$PY", "${CMD}"] {
445            let msg = allowlist_block_message(base, &[], &[]);
446            assert!(
447                msg.contains("expands to the command name at run time"),
448                "{base}: must explain expansion, got: {msg}"
449            );
450            assert!(
451                !msg.contains("mis-split"),
452                "{base}: must not blame the parser, got: {msg}"
453            );
454            assert!(
455                !msg.contains("github.com/yvgude/lean-ctx/issues"),
456                "{base}: must not request a bug report for intended behaviour"
457            );
458        }
459    }
460
461    /// The genuine mis-split guidance must survive for tokens that really are
462    /// not command names — that is what #1646 added it for.
463    #[test]
464    fn genuine_mis_splits_still_ask_for_a_report() {
465        let msg = allowlist_block_message("print(urllib.parse.quote(sys.argv[1],safe=))", &[], &[]);
466        assert!(msg.contains("mis-split"), "got: {msg}");
467        assert!(msg.contains("github.com/yvgude/lean-ctx/issues"));
468    }
469
470    /// An ordinary unknown command keeps the actionable `lean-ctx allow` path.
471    #[test]
472    fn ordinary_command_still_offers_allow() {
473        let msg = allowlist_block_message("ncat", &[], &[]);
474        assert!(msg.contains("lean-ctx allow ncat"), "got: {msg}");
475        assert!(!msg.contains("expands to the command name"));
476    }
477}