1use crate::secret_scan::credential_in;
17use std::io::{Read, Write};
18
19const MAX_HITS: usize = 20;
21const MAX_TEXT_BYTES: u64 = 8 * 1024 * 1024;
24const COPIES_DIR: &str = "agentmux-gh-text";
27const COPIES_KEEP: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Hit {
32 pub place: String,
33 pub line: u32,
34 pub category: &'static str,
35}
36
37fn 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
53pub 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
69fn 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
80fn is_flag(a: &str) -> bool {
83 a.len() > 1 && a.starts_with('-') && a.len() <= 40 && !a.chars().any(char::is_whitespace)
84}
85
86fn 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
93fn 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#[derive(Debug, PartialEq, Eq)]
104enum Source {
105 Inline(String),
106 File(String),
107}
108
109fn 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 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 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
161fn 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
171fn 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#[derive(Debug, Default, PartialEq, Eq)]
188pub struct Scan {
189 pub hits: Vec<Hit>,
190 pub too_large: Vec<String>,
192 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
206pub 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
235pub fn replace_files(args: &[String], files: &std::collections::HashMap<String, String>) -> Vec<String> {
238 let api = is_api(args);
239 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
277pub 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
300fn 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
325fn 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 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
353fn 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
369pub 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 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 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 &["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 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 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 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 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 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 assert_eq!(replace_files(&args(&["pr", "create", "--title", "-"]), &files(&[("-", "P")])), args(&["pr", "create", "--title", "-"]));
519 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 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 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 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 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 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 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 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 assert!(!takes_file("-F", true) && takes_file("-F", false));
612 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}