Skip to main content

agentmux_bashwrap/
github_text.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The text scan: what an agent's `gh` is refused for when the text it sends holds a credential.
5//!
6//! The push scan (`secret_scan.rs`) looks at the lines a push adds; this looks at the words an
7//! agent puts in a pull request, an issue, a comment, a review, release notes or a `gh api` field,
8//! with the same formats and the same rule: say where and what kind, never the text itself.
9//! Spec: `SPEC_CONNECT_WITH_GITHUB` ยง5.6, phase G3b.
10//!
11//! The `gh` function the wrapper exports calls `github-text-guard -- <gh args>` before it runs
12//! `gh`. The reply is the arguments to run, each followed by a NUL, then `ok`; or `refused` (the
13//! reason is on stderr). A body given on stdin (`--body-file -`, `-F -`, `--input -`) is read here,
14//! scanned, and handed to `gh` as a file, because stdin can't be read twice.
15
16use crate::secret_scan::credential_in;
17use std::io::{Read, Write};
18
19/// The most findings reported; a command with more is refused all the same.
20const MAX_HITS: usize = 20;
21/// The largest text read for the scan (a PR body is at most 65,536 characters; a `gh api --input`
22/// file can be bigger). A larger one is refused: it can't be scanned.
23const MAX_TEXT_BYTES: u64 = 8 * 1024 * 1024;
24/// What `gh` reads (a body file, stdin) goes to it as a copy in this folder of the temp directory,
25/// and copies older than a day are removed.
26const COPIES_DIR: &str = "agentmux-gh-text";
27const COPIES_KEEP: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
28
29/// Where a credential-shaped string is in the command, and what kind.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Hit {
32    pub place: String,
33    pub line: u32,
34    pub category: &'static str,
35}
36
37/// The two command words of `gh <args>` (`pr create`), skipping flags and the value of `-R`/`--repo`.
38fn command_words(args: &[String]) -> (Option<&str>, Option<&str>) {
39    let mut words = Vec::new();
40    let mut i = 0;
41    while i < args.len() && words.len() < 2 {
42        let a = args[i].as_str();
43        if a == "-R" || a == "--repo" {
44            i += 1;
45        } else if !a.starts_with('-') {
46            words.push(a);
47        }
48        i += 1;
49    }
50    (words.first().copied(), words.get(1).copied())
51}
52
53/// Does `gh <args>` send text to GitHub that someone wrote: a PR, issue, comment, review, merge
54/// message, release notes or an API call?
55pub fn sends_text(args: &[String]) -> bool {
56    match command_words(args) {
57        (Some("pr"), Some("create" | "new" | "edit" | "comment" | "review" | "merge" | "close" | "reopen" | "revert")) => true,
58        (Some("issue"), Some("create" | "new" | "edit" | "comment" | "close" | "reopen")) => true,
59        (Some("release"), Some("create" | "new" | "edit")) => true,
60        (Some("api"), _) => true,
61        _ => false,
62    }
63}
64
65fn is_api(args: &[String]) -> bool {
66    command_words(args).0 == Some("api")
67}
68
69/// Flags whose value is a file of text: `--body-file`/`-F` (and `--notes-file`) on the commands
70/// that take a body, `--input` on `gh api`. A file argument of `-` is stdin.
71fn takes_file(flag: &str, api: bool) -> bool {
72    match flag {
73        "--body-file" | "--notes-file" => true,
74        "-F" => !api,
75        "--input" => api,
76        _ => false,
77    }
78}
79
80/// An argument that is a flag, not text: it starts with `-`, is short and has no whitespace. A body
81/// that begins with `- ` (a list) or `---` is text and is scanned.
82fn is_flag(a: &str) -> bool {
83    a.len() > 1 && a.starts_with('-') && a.len() <= 40 && !a.chars().any(char::is_whitespace)
84}
85
86/// `--name` of a `--name=value` argument, if `arg` is one.
87fn long_flag_value(arg: &str) -> Option<(&str, &str)> {
88    let (flag, value) = arg.split_once('=')?;
89    let name = flag.strip_prefix("--")?;
90    (name.starts_with(|c: char| c.is_ascii_alphabetic()) && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then_some((flag, value))
91}
92
93/// `-X<value>`: a short flag with its value attached (`-bTEXT`, `-Fpath`, `-fkey=value`), as `-X` and `<value>`.
94fn short_attached(arg: &str) -> Option<(&str, &str)> {
95    let rest = arg.strip_prefix('-')?;
96    let mut chars = rest.chars();
97    let letter = chars.next().filter(char::is_ascii_alphabetic)?;
98    let value = chars.as_str();
99    (!value.is_empty() && !value.starts_with('-')).then(|| (&arg[..1 + letter.len_utf8()], value))
100}
101
102/// One piece of text the command sends: given on the command line, or in a file (`-` for stdin).
103#[derive(Debug, PartialEq, Eq)]
104enum Source {
105    Inline(String),
106    File(String),
107}
108
109/// Everything in `args` that is text: each argument itself, and the files the file flags name,
110/// each with the place to report (the flag before it, else the argument's position).
111fn sources(args: &[String]) -> Vec<(String, Source)> {
112    let api = is_api(args);
113    let mut out = Vec::new();
114    for (i, arg) in args.iter().enumerate() {
115        let prev = i.checked_sub(1).map(|p| args[p].as_str()).filter(|p| is_flag(p));
116        // `--flag=value`
117        if let Some((flag, value)) = long_flag_value(arg) {
118            if takes_file(flag, api) {
119                out.push((flag.to_string(), Source::File(value.to_string())));
120            } else if api && matches!(flag, "--field") {
121                push_field(&mut out, flag, value);
122            } else {
123                out.push((flag.to_string(), Source::Inline(value.to_string())));
124            }
125            continue;
126        }
127        // A flag-like argument is scanned whole too: a credential can be glued to it (`-bTEXT`), or be
128        // an argument that merely begins with a dash. A short flag's attached value is its own source.
129        if arg.starts_with('-') && arg.len() > 1 {
130            if let Some((flag, value)) = short_attached(arg) {
131                if takes_file(flag, api) {
132                    out.push((flag.to_string(), Source::File(value.to_string())));
133                } else if api && matches!(flag, "-F") {
134                    push_field(&mut out, flag, value);
135                } else if api && matches!(flag, "-f") {
136                    let key = value.split_once('=').map(|(k, _)| k).unwrap_or("");
137                    out.push((format!("{flag} {key}"), Source::Inline(value.to_string())));
138                } else {
139                    out.push((flag.to_string(), Source::Inline(value.to_string())));
140                }
141            }
142            if !is_flag(arg) || short_attached(arg).is_some() {
143                out.push((prev.map(str::to_string).unwrap_or_else(|| format!("argument {}", i + 1)), Source::Inline(arg.clone())));
144            }
145            continue;
146        }
147        let place = prev.map(str::to_string).unwrap_or_else(|| format!("argument {}", i + 1));
148        match prev {
149            Some(flag) if takes_file(flag, api) => out.push((place, Source::File(arg.clone()))),
150            Some("-F" | "--field") if api => push_field(&mut out, prev.unwrap_or("-F"), arg),
151            Some("-f" | "--raw-field") if api => {
152                let key = arg.split_once('=').map(|(k, _)| k).unwrap_or("");
153                out.push((format!("{} {key}", prev.unwrap_or("-f")), Source::Inline(arg.clone())));
154            }
155            _ => out.push((place, Source::Inline(arg.clone()))),
156        }
157    }
158    out
159}
160
161/// A `gh api` field `key=value` (`-F`/`--field`): `value` is text, or `@file` (`@-` for stdin).
162fn push_field(out: &mut Vec<(String, Source)>, flag: &str, field: &str) {
163    let (key, value) = field.split_once('=').unwrap_or(("", field));
164    let place = format!("{flag} {key}");
165    match value.strip_prefix('@') {
166        Some(path) => out.push((place, Source::File(path.to_string()))),
167        None => out.push((place, Source::Inline(value.to_string()))),
168    }
169}
170
171/// The credentials in `text`, a line at a time.
172fn scan_text(place: &str, text: &str, hits: &mut Vec<Hit>) {
173    for (n, line) in text.lines().enumerate() {
174        if hits.len() >= MAX_HITS {
175            return;
176        }
177        if let Some(category) = credential_in(line) {
178            let hit = Hit { place: place.to_string(), line: n as u32 + 1, category };
179            if !hits.contains(&hit) {
180                hits.push(hit);
181            }
182        }
183    }
184}
185
186/// What the scan of a command found.
187#[derive(Debug, Default, PartialEq, Eq)]
188pub struct Scan {
189    pub hits: Vec<Hit>,
190    /// A file too large to scan: the command is refused.
191    pub too_large: Vec<String>,
192    /// Every file the command reads (`-` for stdin) with the text scanned. `gh` is given a copy of
193    /// each, so it reads exactly what was scanned: stdin and pipes can't be read twice, and a
194    /// file could change between the scan and `gh` opening it.
195    pub copies: Vec<(String, Vec<u8>)>,
196}
197
198impl Scan {
199    fn keep_copy(&mut self, original: &str, bytes: Vec<u8>) {
200        if !self.copies.iter().any(|(o, _)| o == original) {
201            self.copies.push((original.to_string(), bytes));
202        }
203    }
204}
205
206/// Scan `gh <args>`. `read_file` gives a file's text, whatever kind of file it is (a pipe, a
207/// device): `Ok(None)` when it isn't there (gh will say so itself), `Err` when it is too large to
208/// scan. `stdin` gives what stdin holds, read at most once. The bytes are kept as they are for the
209/// copy `gh` is given (a binary upload must arrive unchanged); only the scan reads them as text.
210pub fn scan(args: &[String], read_file: impl Fn(&str) -> Result<Option<Vec<u8>>, ()>, mut stdin: impl FnMut() -> Result<Vec<u8>, ()>) -> Scan {
211    let mut result = Scan::default();
212    for (place, source) in sources(args) {
213        match source {
214            Source::Inline(text) => scan_text(&place, &text, &mut result.hits),
215            Source::File(path) if path == "-" => match stdin() {
216                Ok(bytes) => {
217                    scan_text(&place, &String::from_utf8_lossy(&bytes), &mut result.hits);
218                    result.keep_copy(&path, bytes);
219                }
220                Err(()) => result.too_large.push(format!("{place} (stdin)")),
221            },
222            Source::File(path) => match read_file(&path) {
223                Ok(Some(bytes)) => {
224                    scan_text(&format!("{place} {path}"), &String::from_utf8_lossy(&bytes), &mut result.hits);
225                    result.keep_copy(&path, bytes);
226                }
227                Ok(None) => {}
228                Err(()) => result.too_large.push(format!("{place} {path}")),
229            },
230        }
231    }
232    result
233}
234
235/// `args` with every file the command reads replaced by its copy: `files` maps the value the
236/// command gave (`-` for stdin, or a path) to where the copy is.
237pub fn replace_files(args: &[String], files: &std::collections::HashMap<String, String>) -> Vec<String> {
238    let api = is_api(args);
239    // `key=@file` of a `gh api` field.
240    let field = |kv: &str| kv.split_once('=').and_then(|(k, v)| files.get(v.strip_prefix('@')?).map(|p| format!("{k}=@{p}")));
241    let mut out = Vec::with_capacity(args.len());
242    for (i, arg) in args.iter().enumerate() {
243        let prev = i.checked_sub(1).map(|p| args[p].as_str()).filter(|p| is_flag(p));
244        let after_file_flag = prev.is_some_and(|p| takes_file(p, api));
245        let after_field_flag = api && prev.is_some_and(|p| matches!(p, "-F" | "--field"));
246        let attached = short_attached(arg).and_then(|(flag, value)| {
247            if takes_file(flag, api) {
248                files.get(value).map(|p| format!("{flag}{p}"))
249            } else if api && flag == "-F" {
250                field(value).map(|v| format!("{flag}{v}"))
251            } else {
252                None
253            }
254        });
255        let replaced = if attached.is_some() {
256            attached
257        } else if after_file_flag {
258            files.get(arg.as_str()).cloned()
259        } else if after_field_flag {
260            field(arg)
261        } else if let Some((flag, value)) = long_flag_value(arg) {
262            if takes_file(flag, api) {
263                files.get(value).map(|p| format!("{flag}={p}"))
264            } else if api && flag == "--field" {
265                field(value).map(|v| format!("{flag}={v}"))
266            } else {
267                None
268            }
269        } else {
270            None
271        };
272        out.push(replaced.unwrap_or_else(|| arg.clone()));
273    }
274    out
275}
276
277/// The refusal: where, and what kind, never the text.
278pub fn refusal_text(args: &[String], scan: &Scan) -> String {
279    let (a, b) = command_words(args);
280    let mut out = format!(
281        "agentmux: `gh {} {}` is refused: the text it sends {}. Nothing was sent.\n",
282        a.unwrap_or(""),
283        b.unwrap_or(""),
284        if scan.hits.is_empty() { "can't be checked" } else { "has what looks like a credential" }
285    );
286    for h in &scan.hits {
287        out.push_str(&format!("  {}, line {}  {}\n", h.place, h.line, h.category));
288    }
289    for f in &scan.too_large {
290        out.push_str(&format!("  {f}  too large to check (over {} MB)\n", MAX_TEXT_BYTES / (1024 * 1024)));
291    }
292    if scan.hits.is_empty() {
293        out.push_str("Send less text, or put it in the repository instead.\n");
294    } else {
295        out.push_str("The text is not shown here. Take it out (and rotate it if it was real), then run the command again.\n");
296    }
297    out
298}
299
300/// A file's text, whatever it is: a regular file, a named pipe, `/dev/stdin`, a process
301/// substitution. `gh` reads those too, so the scan must. `Ok(None)` for a path that isn't there or
302/// is a directory (gh says so itself); `Err` when there is more than the scan reads.
303fn read_file_limited(path: &str) -> Result<Option<Vec<u8>>, ()> {
304    if std::fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false) {
305        return Ok(None);
306    }
307    let Ok(file) = std::fs::File::open(path) else { return Ok(None) };
308    let mut buf = Vec::new();
309    let _ = file.take(MAX_TEXT_BYTES + 1).read_to_end(&mut buf);
310    if buf.len() as u64 > MAX_TEXT_BYTES {
311        return Err(());
312    }
313    Ok(Some(buf))
314}
315
316fn read_stdin_limited() -> Result<Vec<u8>, ()> {
317    let mut buf = Vec::new();
318    let _ = std::io::stdin().lock().take(MAX_TEXT_BYTES + 1).read_to_end(&mut buf);
319    if buf.len() as u64 > MAX_TEXT_BYTES {
320        return Err(());
321    }
322    Ok(buf)
323}
324
325/// The folder the copies go in: the user's own (mode 0700 on Unix; a folder that is someone
326/// else's, or open to others, is not used), with the files older than a day removed.
327fn copies_dir() -> Option<std::path::PathBuf> {
328    let dir = std::env::temp_dir().join(COPIES_DIR);
329    #[cfg(unix)]
330    {
331        use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
332        std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir).ok()?;
333        let meta = std::fs::symlink_metadata(&dir).ok()?;
334        // SAFETY: geteuid has no preconditions and cannot fail.
335        let me = unsafe { libc::geteuid() };
336        if !meta.is_dir() || meta.uid() != me || meta.permissions().mode() & 0o077 != 0 {
337            return None;
338        }
339    }
340    #[cfg(not(unix))]
341    std::fs::create_dir_all(&dir).ok()?;
342    if let Ok(entries) = std::fs::read_dir(&dir) {
343        for e in entries.flatten() {
344            let old = e.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > COPIES_KEEP);
345            if old {
346                let _ = std::fs::remove_file(e.path());
347            }
348        }
349    }
350    Some(dir)
351}
352
353/// Write `text` where `gh` can read it as a file.
354fn write_copy(dir: &std::path::Path, bytes: &[u8]) -> Option<String> {
355    static COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
356    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
357    let path = dir.join(format!("{}-{}-{n}.txt", std::process::id(), agentmux_common::time::now_ms()));
358    let mut options = std::fs::OpenOptions::new();
359    options.write(true).create_new(true);
360    #[cfg(unix)]
361    {
362        use std::os::unix::fs::OpenOptionsExt;
363        options.mode(0o600);
364    }
365    options.open(&path).ok()?.write_all(bytes).ok()?;
366    Some(path.to_string_lossy().into_owned())
367}
368
369/// `github-text-guard -- <gh args>`: scan what the command sends. Prints the arguments to run
370/// (a stdin body replaced by a file), each followed by a NUL, then `ok`; or `refused` with the
371/// reason on stderr and exit status 1.
372pub fn run_github_text_guard(gh_args: &[String]) -> i32 {
373    let mut stdout = std::io::stdout();
374    let mut finish = |args: &[String], verdict: &str| {
375        for a in args {
376            let _ = stdout.write_all(a.as_bytes());
377            let _ = stdout.write_all(&[0]);
378        }
379        let _ = stdout.write_all(verdict.as_bytes());
380        let _ = stdout.write_all(&[0]);
381        let _ = stdout.flush();
382    };
383    if !sends_text(gh_args) {
384        finish(gh_args, "ok");
385        return 0;
386    }
387    // Stdin is read once, whichever flags name it.
388    let mut stdin_text: Option<Vec<u8>> = None;
389    let result = scan(gh_args, read_file_limited, || {
390        if let Some(text) = &stdin_text {
391            return Ok::<Vec<u8>, ()>(text.clone());
392        }
393        let text = read_stdin_limited()?;
394        stdin_text = Some(text.clone());
395        Ok(text)
396    });
397    if !result.hits.is_empty() || !result.too_large.is_empty() {
398        eprint!("{}", refusal_text(gh_args, &result));
399        finish(&[], "refused");
400        return 1;
401    }
402    let mut files = std::collections::HashMap::new();
403    if !result.copies.is_empty() {
404        let dir = copies_dir();
405        for (original, bytes) in &result.copies {
406            match dir.as_deref().and_then(|d| write_copy(d, bytes)) {
407                Some(path) => {
408                    files.insert(original.clone(), path);
409                }
410                None => {
411                    eprintln!("agentmux: this gh command is refused: the text it reads was checked but couldn't be handed on after the check.");
412                    finish(&[], "refused");
413                    return 1;
414                }
415            }
416        }
417    }
418    let args = replace_files(gh_args, &files);
419    finish(&args, "ok");
420    0
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    fn args(a: &[&str]) -> Vec<String> {
428        a.iter().map(|s| s.to_string()).collect()
429    }
430    // Built from pieces, so this file holds no credential-shaped string of its own.
431    fn token() -> String {
432        format!("{}{}", "ghp_", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8")
433    }
434    fn no_files(_: &str) -> Result<Option<Vec<u8>>, ()> {
435        Ok(None)
436    }
437    fn no_stdin() -> Result<Vec<u8>, ()> {
438        Ok(Vec::new())
439    }
440
441    #[test]
442    fn only_commands_that_send_text_are_scanned() {
443        for yes in [
444            &["pr", "create", "--title", "x"][..],
445            &["pr", "comment", "12", "--body", "x"],
446            &["issue", "create"],
447            &["issue", "comment", "3"],
448            &["pr", "review", "4", "--approve"],
449            &["pr", "merge", "4", "--body", "x"],
450            &["release", "create", "v1"],
451            // gh's `new` aliases send the same text.
452            &["issue", "new"],
453            &["pr", "new", "--body", "x"],
454            &["release", "new", "v1"],
455            &["api", "repos/o/r/issues/1/comments"],
456            &["pr", "-R", "o/r", "edit", "3"],
457        ] {
458            assert!(sends_text(&args(yes)), "{yes:?}");
459        }
460        for no in [&["pr", "list"][..], &["pr", "view", "3"], &["issue", "list"], &["repo", "view"], &["auth", "status"], &["--version"], &[]] {
461            assert!(!sends_text(&args(no)), "{no:?}");
462        }
463    }
464
465    #[test]
466    fn a_credential_in_any_text_argument_is_found_with_its_flag_and_line() {
467        let body = format!("first line\nthe key is {}\nlast", token());
468        let s = scan(&args(&["pr", "create", "--title", "fine", "--body", &body]), no_files, no_stdin);
469        assert_eq!(s.hits, vec![Hit { place: "--body".into(), line: 2, category: "GitHub token" }]);
470        // The same in the `--flag=value` and short spellings.
471        let s = scan(&args(&["issue", "comment", "3", &format!("--body={}", token())]), no_files, no_stdin);
472        assert_eq!(s.hits, vec![Hit { place: "--body".into(), line: 1, category: "GitHub token" }]);
473        let s = scan(&args(&["pr", "create", "-t", &token()]), no_files, no_stdin);
474        assert_eq!(s.hits[0].place, "-t");
475        // A body that begins with a dash is text, not a flag.
476        let bullet = format!("- item
477- key {}", token());
478        assert_eq!(scan(&args(&["pr", "comment", "1", "--body", &bullet]), no_files, no_stdin).hits.len(), 1);
479        let dashes = format!("--- notes
480{}", token());
481        assert_eq!(scan(&args(&["pr", "comment", "1", "-b", &dashes]), no_files, no_stdin).hits.len(), 1);
482        // Clean text finds nothing.
483        assert!(scan(&args(&["pr", "create", "--title", "Fix the thing", "--body", "It works."]), no_files, no_stdin).hits.is_empty());
484    }
485
486    #[test]
487    fn a_body_file_is_read_and_a_missing_one_is_left_to_gh() {
488        let read = |p: &str| -> Result<Option<Vec<u8>>, ()> { Ok((p == "body.md").then(|| format!("# Notes\n{}\n", token()).into_bytes())) };
489        let s = scan(&args(&["pr", "create", "--body-file", "body.md"]), read, no_stdin);
490        assert_eq!(s.hits, vec![Hit { place: "--body-file body.md".into(), line: 2, category: "GitHub token" }]);
491        let s = scan(&args(&["pr", "comment", "1", "-F", "body.md"]), read, no_stdin);
492        assert_eq!(s.hits.len(), 1);
493        let s = scan(&args(&["pr", "create", "--body-file=body.md"]), read, no_stdin);
494        assert_eq!(s.hits.len(), 1);
495        let s = scan(&args(&["pr", "create", "--body-file", "nope.md"]), read, no_stdin);
496        assert!(s.hits.is_empty() && s.too_large.is_empty());
497        // Too large to scan is refused, not waved through.
498        let big = |_: &str| -> Result<Option<Vec<u8>>, ()> { Err(()) };
499        assert_eq!(scan(&args(&["pr", "create", "--body-file", "huge.md"]), big, no_stdin).too_large.len(), 1);
500    }
501
502    fn files(pairs: &[(&str, &str)]) -> std::collections::HashMap<String, String> {
503        pairs.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()
504    }
505
506    #[test]
507    fn what_gh_reads_is_handed_on_as_a_copy_of_what_was_scanned() {
508        // stdin
509        let a = args(&["pr", "create", "--title", "t", "--body-file", "-"]);
510        let s = scan(&a, no_files, || Ok(format!("x\n{}\n", token()).into_bytes()));
511        assert_eq!(s.hits[0].place, "--body-file");
512        assert_eq!(s.copies.len(), 1);
513        assert_eq!(s.copies[0].0, "-");
514        assert_eq!(replace_files(&a, &files(&[("-", "/tmp/b.txt")])), args(&["pr", "create", "--title", "t", "--body-file", "/tmp/b.txt"]));
515        assert_eq!(replace_files(&args(&["issue", "comment", "1", "-F", "-"]), &files(&[("-", "P")])), args(&["issue", "comment", "1", "-F", "P"]));
516        assert_eq!(replace_files(&args(&["pr", "create", "--body-file=-"]), &files(&[("-", "P")])), args(&["pr", "create", "--body-file=P"]));
517        // A lone `-` that is not a file flag's value is left alone.
518        assert_eq!(replace_files(&args(&["pr", "create", "--title", "-"]), &files(&[("-", "P")])), args(&["pr", "create", "--title", "-"]));
519        // A regular file, a pipe or `/dev/stdin` the same: gh reads the copy, not the original, which
520        // can't be read twice (a pipe) or could change after the scan (a file).
521        let read = |p: &str| -> Result<Option<Vec<u8>>, ()> { Ok((p == "/dev/stdin" || p == "body.md").then(|| b"clean".to_vec())) };
522        let s = scan(&args(&["pr", "create", "--body-file", "/dev/stdin", "-F", "body.md", "-F", "body.md"]), read, no_stdin);
523        assert_eq!(s.copies.iter().map(|(o, _)| o.as_str()).collect::<Vec<_>>(), vec!["/dev/stdin", "body.md"]);
524        assert_eq!(
525            replace_files(&args(&["pr", "create", "--body-file", "/dev/stdin", "-F", "body.md"]), &files(&[("/dev/stdin", "C1"), ("body.md", "C2")])),
526            args(&["pr", "create", "--body-file", "C1", "-F", "C2"])
527        );
528        // A path that isn't there is left alone: gh says so itself.
529        assert!(scan(&args(&["pr", "create", "--body-file", "nope"]), no_files, no_stdin).copies.is_empty());
530    }
531
532    #[test]
533    fn a_binary_file_reaches_gh_byte_for_byte() {
534        // Not valid UTF-8 (a binary upload, or a legacy encoding): the scan reads it as text, the copy is the bytes.
535        let bytes: Vec<u8> = vec![0x00, 0xff, 0xfe, b'a', 0x80, 0xc3, 0x28];
536        let expected = bytes.clone();
537        let read = move |p: &str| -> Result<Option<Vec<u8>>, ()> { Ok((p == "asset.bin").then(|| bytes.clone())) };
538        let s = scan(&args(&["api", "x", "--input", "asset.bin"]), read, no_stdin);
539        assert!(s.hits.is_empty());
540        assert_eq!(s.copies, vec![("asset.bin".to_string(), expected)]);
541        // `gh pr revert` sends a title and a body too.
542        assert!(sends_text(&args(&["pr", "revert", "3"])));
543    }
544
545    #[test]
546    fn a_repository_flag_with_its_value_glued_on_does_not_hide_the_command() {
547        for lead in [&["-Ro/r"][..], &["-R=o/r"], &["--repo=o/r"], &["-R", "o/r"]] {
548            let mut a: Vec<&str> = lead.to_vec();
549            a.extend(["pr", "create", "--title", "x"]);
550            let a: Vec<String> = a.iter().map(|s| s.to_string()).collect();
551            assert!(sends_text(&a), "{lead:?}");
552        }
553    }
554
555    #[test]
556    fn a_short_flag_with_its_value_glued_on_is_scanned_too() {
557        let aws = format!("{}{}", "AKIA", "ABCDEFGHIJKLMNOP");
558        for a in [
559            args(&["pr", "create", &format!("-t{aws}")]),
560            args(&["pr", "create", &format!("-b{aws}")]),
561            args(&["pr", "create", &format!("-b{}", token())]),
562            args(&["issue", "comment", "1", &format!("-sk-ant-{}", "api03-abcdefghijklmnopqrstuvwxyz0123456789")]),
563            args(&["api", "x", &format!("-fbody={aws}")]),
564            args(&["api", "x", &format!("--raw-field=body={aws}")]),
565        ] {
566            assert!(!scan(&a, no_files, no_stdin).hits.is_empty(), "{a:?}");
567        }
568        // The file flags with the path glued on name a file to read and copy.
569        let read = |p: &str| -> Result<Option<Vec<u8>>, ()> { Ok((p == "b.md").then(|| aws.clone().into_bytes())) };
570        let a = args(&["pr", "create", "-Fb.md"]);
571        let s = scan(&a, read, no_stdin);
572        assert_eq!((s.hits.len(), s.copies.len()), (1, 1));
573        assert_eq!(replace_files(&a, &files(&[("b.md", "C")])), args(&["pr", "create", "-FC"]));
574        let a = args(&["api", "x", "-Fbody=@b.md"]);
575        assert_eq!(scan(&a, read, no_stdin).hits.len(), 1);
576        assert_eq!(replace_files(&a, &files(&[("b.md", "C")])), args(&["api", "x", "-Fbody=@C"]));
577        // Plain flags are not text.
578        assert!(scan(&args(&["pr", "create", "--draft", "--fill", "-d", "-R", "o/r"]), no_files, no_stdin).hits.is_empty());
579    }
580
581    #[test]
582    fn a_file_of_any_kind_is_read_for_the_scan() {
583        let dir = std::env::temp_dir().join(format!("amx-gh-text-{}", std::process::id()));
584        std::fs::create_dir_all(&dir).unwrap();
585        let file = dir.join("b.md");
586        std::fs::write(&file, format!("{}
587", token())).unwrap();
588        let bytes = read_file_limited(file.to_str().unwrap()).unwrap().unwrap();
589        assert!(credential_in(&String::from_utf8_lossy(&bytes)).is_some());
590        // A directory and a missing path are gh's to report.
591        assert_eq!(read_file_limited(dir.to_str().unwrap()), Ok(None));
592        assert_eq!(read_file_limited(dir.join("nope").to_str().unwrap()), Ok(None));
593        #[cfg(unix)]
594        {
595            // A device, which is not a regular file, is read too (and `/dev/null` is empty).
596            assert_eq!(read_file_limited("/dev/null"), Ok(Some(Vec::new())));
597        }
598        let _ = std::fs::remove_dir_all(&dir);
599    }
600
601    #[test]
602    fn gh_api_fields_and_input_are_text_too() {
603        let read = |p: &str| -> Result<Option<Vec<u8>>, ()> { Ok((p == "c.txt").then(|| token().into_bytes())) };
604        let s = scan(&args(&["api", "repos/o/r/issues/1/comments", "-f", &format!("body={}", token())]), read, no_stdin);
605        assert_eq!(s.hits, vec![Hit { place: "-f body".into(), line: 1, category: "GitHub token" }]);
606        let s = scan(&args(&["api", "x", "-F", "body=@c.txt"]), read, no_stdin);
607        assert_eq!(s.hits[0].place, "-F body c.txt");
608        let s = scan(&args(&["api", "x", "--input", "c.txt"]), read, no_stdin);
609        assert_eq!(s.hits.len(), 1);
610        // On `gh api`, `-F` is a field, not a body file.
611        assert!(!takes_file("-F", true) && takes_file("-F", false));
612        // `-F key=@-` reads stdin.
613        let a = args(&["api", "x", "-F", "body=@-"]);
614        assert_eq!(scan(&a, no_files, no_stdin).copies.len(), 1);
615        assert_eq!(replace_files(&a, &files(&[("-", "P")])), args(&["api", "x", "-F", "body=@P"]));
616        assert_eq!(replace_files(&args(&["api", "x", "--field", "b=@c.txt"]), &files(&[("c.txt", "P")])), args(&["api", "x", "--field", "b=@P"]));
617        assert_eq!(replace_files(&args(&["api", "x", "--field=b=@c.txt"]), &files(&[("c.txt", "P")])), args(&["api", "x", "--field=b=@P"]));
618        assert_eq!(replace_files(&args(&["api", "x", "--input", "-"]), &files(&[("-", "P")])), args(&["api", "x", "--input", "P"]));
619    }
620
621    #[test]
622    fn the_refusal_names_where_and_what_kind_and_never_the_text() {
623        let a = args(&["pr", "create", "--body", &token()]);
624        let s = scan(&a, no_files, no_stdin);
625        let text = refusal_text(&a, &s);
626        assert!(text.contains("`gh pr create` is refused") && text.contains("--body, line 1  GitHub token"), "{text}");
627        assert!(!text.contains("ghp_"), "{text}");
628        let big = Scan { too_large: vec!["--body-file huge.md".into()], ..Scan::default() };
629        let text = refusal_text(&a, &big);
630        assert!(text.contains("can't be checked") && text.contains("too large"), "{text}");
631    }
632}