lean_ctx/core/shell_allowlist/
config.rs1pub(super) fn effective_allowlist() -> Vec<String> {
2 filter_valid_entries(raw_allowlist_entries())
3}
4
5fn raw_allowlist_entries() -> Vec<String> {
9 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 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#[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#[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#[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#[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
119pub(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
131fn 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
152pub(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
167pub(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 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 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 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 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
263 msg.push_str("\n\n⚠ ");
264 msg.push_str(¬ice);
265 }
266
267 msg
268}
269
270fn 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#[must_use]
316pub fn effective_allowlist_pub() -> Vec<String> {
317 effective_allowlist()
318}
319
320pub(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
343fn 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
355fn 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
370pub(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
388pub(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 #[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 #[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 #[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 #[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}