1use std::path::PathBuf;
14use std::time::Duration;
15
16use agentmux_common::win32::NoWindow;
17use serde::Deserialize;
18use zeroize::Zeroizing;
19
20const TIMEOUT: Duration = Duration::from_secs(50);
24const FINISH_TIMEOUT: Duration = Duration::from_secs(150);
27
28pub struct HostToken {
30 pub token: Zeroizing<String>,
31 pub expires_at: i64,
33 pub bot_slug: Option<String>,
35}
36
37#[derive(Deserialize)]
38struct Output {
39 token: String,
40 expires_at: Option<i64>,
41 acting_as: Option<String>,
42 scope: Option<String>,
45 repositories: Option<Vec<String>>,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Scope {
53 Api,
54 Push,
55}
56
57impl Scope {
58 fn name(self) -> &'static str {
59 match self {
60 Scope::Api => "api",
61 Scope::Push => "push",
62 }
63 }
64}
65
66pub const GH_AGENT_TOO_OLD: &str = "this machine's gh-agent cannot give a container a narrowed GitHub token: update gh-agent (npm i -g @a5af/gh-agent)";
69
70pub fn is_too_old(error: &str) -> bool {
72 error == GH_AGENT_TOO_OLD
73}
74
75pub const PUBLISH_GUARD_ENV: &str = "AGENTMUX_PUBLISH_GUARD";
78
79pub fn installed() -> Option<PathBuf> {
81 which::which("gh-agent").ok()
82}
83
84pub fn took_too_long() -> String {
86 format!(
87 "GitHub token took too long: this machine's gh-agent didn't answer in {} s (it keeps going, so the next try is quick). Try again in a minute",
88 TIMEOUT.as_secs()
89 )
90}
91
92pub fn is_took_too_long(error: &str) -> bool {
94 error.starts_with("GitHub token took too long")
95}
96
97pub(crate) fn is_name(s: &str) -> bool {
100 !s.is_empty() && s.len() <= 100 && !s.starts_with(['-', '.']) && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
101}
102
103fn parse(stdout: &[u8], scope: Scope, repo: &str) -> Result<HostToken, String> {
107 let out: Output = serde_json::from_slice(stdout).map_err(|_| "gh-agent gave no token".to_string())?;
108 if out.token.is_empty() {
109 return Err("gh-agent gave no token".to_string());
110 }
111 let one_repo = out.repositories.as_deref().is_some_and(|r| r.len() == 1 && r[0].eq_ignore_ascii_case(repo));
112 if out.scope.as_deref() != Some(scope.name()) || !one_repo {
113 return Err(GH_AGENT_TOO_OLD.to_string());
114 }
115 let bot_slug = out.acting_as.map(|a| a.trim_end_matches("[bot]").to_string()).filter(|a| !a.is_empty());
116 Ok(HostToken { token: Zeroizing::new(out.token), expires_at: out.expires_at.unwrap_or(0), bot_slug })
117}
118
119fn parse_user_id(body: &[u8]) -> Option<u64> {
121 #[derive(Deserialize)]
122 struct User {
123 id: u64,
124 }
125 serde_json::from_slice::<User>(body).ok().map(|u| u.id)
126}
127
128const LOOKUP_RETRY: Duration = Duration::from_secs(60);
131
132#[derive(Clone, Copy)]
134enum Lookup {
135 Found(u64),
136 Failed(std::time::Instant),
137}
138
139fn remembered(entry: Option<Lookup>, now: std::time::Instant) -> Option<Option<u64>> {
141 match entry? {
142 Lookup::Found(id) => Some(Some(id)),
143 Lookup::Failed(at) if now.saturating_duration_since(at) < LOOKUP_RETRY => Some(None),
144 Lookup::Failed(_) => None,
145 }
146}
147
148async fn fetch_bot_user_id(slug: &str) -> Option<u64> {
149 let client = crate::http_client::builder().timeout(Duration::from_secs(5)).user_agent("agentmux-srv").build().ok()?;
150 let resp = client
151 .get(format!("https://api.github.com/users/{slug}%5Bbot%5D"))
152 .header("Accept", "application/vnd.github+json")
153 .send()
154 .await
155 .ok()?
156 .error_for_status()
157 .ok()?;
158 parse_user_id(&resp.bytes().await.ok()?)
159}
160
161pub async fn bot_user_id(slug: &str) -> Option<u64> {
165 static KNOWN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, Lookup>>> = std::sync::OnceLock::new();
166 let known = KNOWN.get_or_init(Default::default);
167 let entry = known.lock().unwrap_or_else(|e| e.into_inner()).get(slug).copied();
168 if let Some(answer) = remembered(entry, std::time::Instant::now()) {
169 return answer;
170 }
171 if !is_name(slug) {
172 return None;
173 }
174 let id = fetch_bot_user_id(slug).await;
175 let outcome = id.map_or_else(|| Lookup::Failed(std::time::Instant::now()), Lookup::Found);
176 known.lock().unwrap_or_else(|e| e.into_inner()).insert(slug.to_string(), outcome);
177 id
178}
179
180fn token_args(owner: &str, repo: &str, scope: Scope, workflows: bool) -> Vec<String> {
183 let mut args = vec!["token".to_string(), "--repo".to_string(), format!("{owner}/{repo}"), "--scope".to_string(), scope.name().to_string()];
184 if workflows && scope == Scope::Push {
185 args.push("--workflows".to_string());
186 }
187 args.push("--json".to_string());
188 args
189}
190
191async fn finish(child: tokio::process::Child) -> Result<std::process::Output, String> {
193 match tokio::time::timeout(FINISH_TIMEOUT, child.wait_with_output()).await {
194 Ok(Ok(out)) => Ok(out),
195 Ok(Err(e)) => Err(format!("couldn't run gh-agent: {e}")),
196 Err(_) => Err(took_too_long()),
197 }
198}
199
200async fn wait_for<T>(run: &mut tokio::task::JoinHandle<Result<T, String>>, limit: Duration) -> Result<T, String> {
203 match tokio::time::timeout(limit, run).await {
204 Ok(Ok(done)) => done,
205 Ok(Err(_)) => Err("couldn't run gh-agent: it stopped unexpectedly".to_string()),
206 Err(_) => Err(took_too_long()),
207 }
208}
209
210pub async fn token_for(slug: &str, owner: &str, repo: &str, scope: Scope, workflows: bool) -> Result<HostToken, String> {
212 if !is_name(owner) || !is_name(repo) {
213 return Err("not a GitHub repository".to_string());
214 }
215 let exe = installed().ok_or_else(|| "gh-agent isn't installed on this machine".to_string())?;
216 let mut cmd = tokio::process::Command::new(&exe);
217 crate::backend::pane_env::sanitize_external_command(&mut cmd);
219 cmd.args(token_args(owner, repo, scope, workflows))
220 .env("AGENTMUX_AGENT_ID", slug)
221 .stdin(std::process::Stdio::null())
222 .stdout(std::process::Stdio::piped())
223 .stderr(std::process::Stdio::null())
224 .kill_on_drop(true);
226 cmd.no_window();
227 let child = cmd.spawn().map_err(|e| format!("couldn't run gh-agent: {e}"))?;
228 let mut run = tokio::spawn(finish(child));
229 let out = wait_for(&mut run, TIMEOUT).await?;
230 if !out.status.success() {
231 return Err("gh-agent gave no token for that repository".to_string());
232 }
233 parse(&out.stdout, scope, repo)
234}
235
236const MERGE_TIMEOUT: Duration = Duration::from_secs(90);
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
241#[serde(rename_all = "lowercase")]
242pub enum MergeMethod {
243 Squash,
244 Merge,
245 Rebase,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct MergeRequest {
251 pub owner: String,
252 pub repo: String,
253 pub number: u64,
254 pub method: Option<MergeMethod>,
255 pub auto: bool,
256 pub delete_branch: bool,
257}
258
259pub fn merge_args(r: &MergeRequest) -> Vec<String> {
262 let mut args = vec!["pr".to_string(), "merge".to_string(), r.number.to_string(), "--repo".to_string(), format!("{}/{}", r.owner, r.repo)];
263 match r.method {
264 Some(MergeMethod::Squash) => args.push("--squash".to_string()),
265 Some(MergeMethod::Merge) => args.push("--merge".to_string()),
266 Some(MergeMethod::Rebase) => args.push("--rebase".to_string()),
267 None => {}
268 }
269 if r.auto {
270 args.push("--auto".to_string());
271 }
272 if r.delete_branch {
273 args.push("--delete-branch".to_string());
274 }
275 args
276}
277
278pub fn merge_request_ok(r: &MergeRequest) -> Result<(), String> {
280 if !is_name(&r.owner) || !is_name(&r.repo) {
281 return Err("not a GitHub repository".to_string());
282 }
283 if r.number == 0 || r.number > 100_000_000 {
284 return Err("not a pull request number".to_string());
285 }
286 Ok(())
287}
288
289pub async fn merge_pr(slug: &str, r: &MergeRequest) -> Result<String, String> {
292 merge_request_ok(r)?;
293 let exe = installed().ok_or_else(|| "gh-agent isn't installed on this machine".to_string())?;
294 let mut cmd = tokio::process::Command::new(&exe);
295 crate::backend::pane_env::sanitize_external_command(&mut cmd);
296 cmd.args(merge_args(r))
297 .env("AGENTMUX_AGENT_ID", slug)
298 .current_dir(std::env::temp_dir())
299 .stdin(std::process::Stdio::null())
300 .stdout(std::process::Stdio::piped())
301 .stderr(std::process::Stdio::piped())
302 .kill_on_drop(true);
303 cmd.no_window();
304 let out = match tokio::time::timeout(MERGE_TIMEOUT, cmd.output()).await {
305 Ok(Ok(out)) => out,
306 Ok(Err(e)) => return Err(format!("couldn't run gh-agent: {e}")),
307 Err(_) => return Err(format!("the merge took too long: gh-agent didn't answer in {} s. Look at the pull request before trying again", MERGE_TIMEOUT.as_secs())),
308 };
309 let said = bounded_lines(&[out.stderr.as_slice(), out.stdout.as_slice()].concat());
310 if out.status.success() {
311 Ok(said)
312 } else if said.is_empty() {
313 Err("gh-agent could not merge the pull request and said nothing".to_string())
314 } else {
315 Err(said)
316 }
317}
318
319fn bounded_lines(bytes: &[u8]) -> String {
321 let text = String::from_utf8_lossy(bytes);
322 let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with("gh-agent:")).take(12).collect();
323 lines.join("\n").chars().take(2000).collect()
324}
325
326const SCAN_TIMEOUT: Duration = Duration::from_secs(60);
329
330#[derive(Debug, PartialEq, Eq)]
332pub enum ScanOutcome {
333 Judged { code: i64, lines: Vec<String>, public: bool },
335 Failed(String),
337}
338
339#[derive(Deserialize)]
340struct Verdict {
341 code: i64,
342 lines: Vec<String>,
343 #[serde(default = "yes")]
345 public: bool,
346}
347
348fn yes() -> bool {
349 true
350}
351
352fn parse_verdict(stdout: &[u8]) -> Result<(i64, Vec<String>, bool), String> {
354 let v: Verdict = serde_json::from_slice(stdout).map_err(|_| "gh-agent gave no verdict".to_string())?;
355 let lines = v.lines.into_iter().take(50).map(|l| l.chars().take(1000).collect()).collect();
357 Ok((v.code, lines, v.public))
358}
359
360pub async fn scan_push(slug: &str, repo: &str, material: &[u8]) -> ScanOutcome {
364 use tokio::io::AsyncWriteExt;
365 let Some((owner, name)) = repo.split_once('/') else { return ScanOutcome::Failed("not a GitHub repository".to_string()) };
366 if !is_name(owner) || !is_name(name) {
367 return ScanOutcome::Failed("not a GitHub repository".to_string());
368 }
369 let Some(exe) = installed() else { return ScanOutcome::Failed("gh-agent isn't installed on this machine".to_string()) };
370 let mut cmd = tokio::process::Command::new(&exe);
371 crate::backend::pane_env::sanitize_external_command(&mut cmd);
372 cmd.args(["scan-push", "--repo", repo])
373 .env("AGENTMUX_AGENT_ID", slug)
374 .current_dir(std::env::temp_dir())
375 .stdin(std::process::Stdio::piped())
376 .stdout(std::process::Stdio::piped())
377 .stderr(std::process::Stdio::piped())
378 .kill_on_drop(true);
379 cmd.no_window();
380 let mut child = match cmd.spawn() {
381 Ok(c) => c,
382 Err(e) => return ScanOutcome::Failed(format!("couldn't run gh-agent: {e}")),
383 };
384 if let Some(mut stdin) = child.stdin.take() {
385 let material = material.to_vec();
386 tokio::spawn(async move {
388 let _ = stdin.write_all(&material).await;
389 let _ = stdin.shutdown().await;
390 });
391 }
392 let out = match tokio::time::timeout(SCAN_TIMEOUT, child.wait_with_output()).await {
393 Ok(Ok(out)) => out,
394 Ok(Err(e)) => return ScanOutcome::Failed(format!("gh-agent failed: {e}")),
395 Err(_) => {
396 return ScanOutcome::Failed(format!("the publish guard didn't answer in {} s: try the push again in a minute", SCAN_TIMEOUT.as_secs()));
397 }
398 };
399 if !out.status.success() {
400 let said = String::from_utf8_lossy(&out.stderr);
402 let first = said.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("it gave no reason");
403 if said.contains("unknown command \"scan-push\"") {
405 return ScanOutcome::Failed("this machine's gh-agent is too old to check a container's push: update it (npm i -g @a5af/gh-agent)".to_string());
406 }
407 return ScanOutcome::Failed(format!("the publish guard could not check this push: {}", first.chars().take(300).collect::<String>()));
408 }
409 match parse_verdict(&out.stdout) {
410 Ok((code, lines, public)) => ScanOutcome::Judged { code, lines, public },
411 Err(why) => ScanOutcome::Failed(why),
412 }
413}
414
415#[cfg(any(test, feature = "test-support"))]
417pub mod fake {
418 use std::path::{Path, PathBuf};
419
420 pub static PATH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
422
423 pub fn install(dir: &Path, stdout: &str, code: i32) -> std::ffi::OsString {
426 let log = dir.join("calls.log");
427 #[cfg(windows)]
428 {
429 let script = format!("@echo off\r\necho %*>>\"{}\"\r\necho {}\r\nexit /b {}\r\n", log.display(), stdout, code);
430 std::fs::write(dir.join("gh-agent.cmd"), script).unwrap();
431 }
432 #[cfg(not(windows))]
433 {
434 use std::os::unix::fs::PermissionsExt;
435 let script = format!("#!/bin/sh\necho \"$@\" >> '{}'\nprintf '%s\\n' '{}'\nexit {}\n", log.display(), stdout, code);
436 let path = dir.join("gh-agent");
437 std::fs::write(&path, script).unwrap();
438 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
439 }
440 let old = std::env::var_os("PATH").unwrap_or_default();
441 let mut paths = vec![dir.to_path_buf()];
442 paths.extend(std::env::split_paths(&old));
443 std::env::set_var("PATH", std::env::join_paths(paths).unwrap());
444 old
445 }
446
447 pub fn calls(dir: &Path) -> Vec<String> {
449 let log: PathBuf = dir.join("calls.log");
450 std::fs::read_to_string(log).unwrap_or_default().lines().map(|l| l.trim().to_string()).collect()
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 #[test]
459 fn only_account_and_repository_names_are_passed_on() {
460 for ok in ["agentmuxai", "agentmux-landing", "my_repo.js", "a"] {
461 assert!(is_name(ok), "{ok}");
462 }
463 for bad in ["", "-x", ".hidden", "a b", "a/b", "a;b", "--repo", "a\nb", &"x".repeat(101)] {
464 assert!(!is_name(bad), "{bad:?}");
465 }
466 }
467
468 #[test]
469 fn the_bots_user_id_is_read_from_githubs_answer() {
470 assert_eq!(parse_user_id(br#"{"login":"muxagent[bot]","id":331051269,"type":"Bot"}"#), Some(331051269));
471 assert_eq!(parse_user_id(br#"{"message":"Not Found"}"#), None);
472 assert_eq!(parse_user_id(b"x"), None);
473 }
474
475 #[test]
476 fn a_failed_lookup_is_not_repeated_for_a_minute() {
477 let now = std::time::Instant::now();
478 assert_eq!(remembered(None, now), None);
479 assert_eq!(remembered(Some(Lookup::Found(7)), now), Some(Some(7)));
480 assert_eq!(remembered(Some(Lookup::Failed(now)), now), Some(None));
481 if let Some(later) = now.checked_add(LOOKUP_RETRY + Duration::from_secs(1)) {
482 assert_eq!(remembered(Some(Lookup::Failed(now)), later), None);
483 assert_eq!(remembered(Some(Lookup::Found(7)), later), Some(Some(7)));
484 }
485 }
486
487 #[test]
488 fn the_token_and_its_expiry_are_read_from_the_json() {
489 let narrowed = |extra: &str| format!(r#"{{"token":"ghs_x","scope":"api","repositories":["hello"]{extra}}}"#);
490 let got = parse(narrowed(r#","expires_at":1793224607,"acting_as":"muxagent[bot]","tier":"shared","owner":"o""#).as_bytes(), Scope::Api, "hello").unwrap();
491 assert_eq!((got.token.as_str(), got.expires_at, got.bot_slug.as_deref()), ("ghs_x", 1793224607, Some("muxagent")));
492 assert!(parse(b"not json", Scope::Api, "hello").is_err());
493 assert!(parse(br#"{"token":""}"#, Scope::Api, "hello").is_err());
494 assert_eq!(parse(narrowed("").as_bytes(), Scope::Api, "HELLO").unwrap().expires_at, 0, "a repository name is not case sensitive");
495 }
496
497 #[test]
498 fn a_token_that_is_not_the_narrowed_one_asked_for_is_never_passed_on() {
499 let wide = br#"{"token":"ghs_WIDE","expires_at":1793224607,"acting_as":"muxagent[bot]","tier":"shared","owner":"o"}"#;
501 assert_eq!(parse(wide, Scope::Api, "hello").err().as_deref(), Some(GH_AGENT_TOO_OLD));
502 assert!(is_too_old(GH_AGENT_TOO_OLD));
503 let api = br#"{"token":"t","scope":"api","repositories":["hello"]}"#;
505 assert!(parse(api, Scope::Push, "hello").is_err(), "an api token is not a push token");
506 assert!(parse(api, Scope::Api, "other").is_err());
507 assert!(parse(br#"{"token":"t","scope":"api","repositories":["hello","other"]}"#, Scope::Api, "hello").is_err());
508 assert!(parse(br#"{"token":"t","scope":"api"}"#, Scope::Api, "hello").is_err());
509 assert!(parse(api, Scope::Api, "hello").is_ok());
510 }
511
512 fn merge(method: Option<MergeMethod>, auto: bool, delete_branch: bool) -> MergeRequest {
513 MergeRequest { owner: "agentmuxai".into(), repo: "agentmux".into(), number: 42, method, auto, delete_branch }
514 }
515
516 #[test]
517 fn a_merge_is_run_with_fixed_arguments_and_never_admin() {
518 assert_eq!(merge_args(&merge(None, false, false)), ["pr", "merge", "42", "--repo", "agentmuxai/agentmux"]);
519 assert_eq!(
520 merge_args(&merge(Some(MergeMethod::Squash), true, true)),
521 ["pr", "merge", "42", "--repo", "agentmuxai/agentmux", "--squash", "--auto", "--delete-branch"]
522 );
523 for m in [None, Some(MergeMethod::Merge), Some(MergeMethod::Rebase)] {
524 let args = merge_args(&merge(m, true, true));
525 assert!(!args.iter().any(|a| a == "--admin"), "{args:?}");
526 }
527 }
528
529 #[test]
530 fn only_a_real_repository_and_number_are_merged() {
531 assert!(merge_request_ok(&merge(None, false, false)).is_ok());
532 let mut bad = merge(None, false, false);
533 bad.number = 0;
534 assert!(merge_request_ok(&bad).is_err());
535 for owner in ["", "-x", "a b", "a/b", "--admin"] {
536 let mut r = merge(None, false, false);
537 r.owner = owner.into();
538 assert!(merge_request_ok(&r).is_err(), "{owner:?}");
539 }
540 let mut r = merge(None, false, false);
541 r.repo = "..".into();
542 assert!(merge_request_ok(&r).is_err());
543 }
544
545 #[test]
546 fn what_a_merge_says_is_short_and_without_the_identity_line() {
547 let said = bounded_lines(b"gh-agent: agenta as muxagent[bot] (shared App) -> o [cached]\n\n! Pull request #42 will be added to the merge queue\n");
548 assert_eq!(said, "! Pull request #42 will be added to the merge queue");
549 assert!(bounded_lines(&vec![b'x'; 5000]).chars().count() <= 2000);
550 assert_eq!(bounded_lines(b""), "");
551 }
552
553 #[tokio::test]
554 async fn a_token_call_names_its_scope_and_an_older_gh_agent_is_refused() {
555 let _guard = fake::PATH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
556 let dir = tempfile::tempdir().unwrap();
557 let old = fake::install(dir.path(), r#"{"token":"ghs_NARROW","expires_at":1793224607,"acting_as":"muxagent[bot]","scope":"api","repositories":["hello"]}"#, 0);
558 let got = token_for("aria", "octo", "hello", Scope::Api, false).await;
559 assert_eq!(got.as_ref().map(|t| t.token.as_str()).ok(), Some("ghs_NARROW"), "{:?}", got.as_ref().err());
560 assert_eq!(fake::calls(dir.path()), ["token --repo octo/hello --scope api --json"]);
561 let dir2 = tempfile::tempdir().unwrap();
563 fake::install(dir2.path(), r#"{"token":"ghs_WIDE","expires_at":1793224607,"acting_as":"muxagent[bot]","tier":"shared"}"#, 0);
564 let refused = token_for("aria", "octo", "hello", Scope::Push, false).await;
565 std::env::set_var("PATH", old);
566 assert_eq!(refused.err().as_deref(), Some(GH_AGENT_TOO_OLD));
567 }
568
569 #[tokio::test]
570 async fn a_caller_that_stops_waiting_leaves_the_work_running() {
571 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
572 let flag = done.clone();
573 let mut run = tokio::spawn(async move {
574 tokio::time::sleep(Duration::from_millis(120)).await;
575 flag.store(true, std::sync::atomic::Ordering::SeqCst);
576 Ok::<_, String>(7)
577 });
578 assert_eq!(wait_for(&mut run, Duration::from_millis(20)).await, Err(took_too_long()));
580 assert!(!done.load(std::sync::atomic::Ordering::SeqCst));
581 drop(run);
582 tokio::time::sleep(Duration::from_millis(300)).await;
584 assert!(done.load(std::sync::atomic::Ordering::SeqCst));
585 }
586
587 #[tokio::test]
588 async fn a_caller_that_waits_long_enough_gets_the_answer_or_the_reason() {
589 let mut ok = tokio::spawn(async { Ok::<_, String>(7) });
590 assert_eq!(wait_for(&mut ok, Duration::from_secs(5)).await, Ok(7));
591 let mut failed = tokio::spawn(async { Err::<u8, _>("couldn't run gh-agent: x".to_string()) });
592 assert_eq!(wait_for(&mut failed, Duration::from_secs(5)).await, Err("couldn't run gh-agent: x".to_string()));
593 let mut crashed = tokio::spawn(async { if true { panic!("boom") } else { Ok::<u8, String>(1) } });
594 assert!(wait_for(&mut crashed, Duration::from_secs(5)).await.unwrap_err().contains("stopped unexpectedly"));
595 }
596
597 #[test]
598 fn a_container_asks_longer_than_srv_waits_and_srv_lets_a_mint_finish() {
599 assert!(TIMEOUT >= Duration::from_secs(40), "a loaded machine's mint has taken 26 s");
600 assert!(FINISH_TIMEOUT > TIMEOUT);
601 }
602
603 #[test]
604 fn every_call_names_its_scope_so_none_can_come_back_installation_wide() {
605 assert_eq!(token_args("o", "r", Scope::Api, false), ["token", "--repo", "o/r", "--scope", "api", "--json"]);
606 assert_eq!(token_args("o", "r", Scope::Push, false), ["token", "--repo", "o/r", "--scope", "push", "--json"]);
607 assert_eq!(token_args("o", "r", Scope::Push, true), ["token", "--repo", "o/r", "--scope", "push", "--workflows", "--json"]);
608 assert!(!token_args("o", "r", Scope::Api, true).contains(&"--workflows".to_string()), "workflows goes only with push");
609 }
610
611 #[test]
612 fn the_verdict_is_read_from_the_json_and_kept_short() {
613 let (code, lines, public) = parse_verdict(br#"{"code":1,"lines":["a","b"]}"#).unwrap();
614 assert_eq!((code, lines, public), (1, vec!["a".to_string(), "b".to_string()], true));
615 assert!(!parse_verdict(br#"{"code":0,"lines":[],"public":false}"#).unwrap().2);
616 let many = format!(r#"{{"code":0,"lines":[{}]}}"#, (0..80).map(|i| format!("\"{i}\"")).collect::<Vec<_>>().join(","));
617 assert_eq!(parse_verdict(many.as_bytes()).unwrap().1.len(), 50);
618 let long = format!(r#"{{"code":0,"lines":["{}"]}}"#, "x".repeat(5000));
619 assert_eq!(parse_verdict(long.as_bytes()).unwrap().1[0].chars().count(), 1000);
620 assert!(parse_verdict(b"not json").is_err());
621 assert!(parse_verdict(br#"{"lines":[]}"#).is_err());
622 }
623
624 #[tokio::test]
625 async fn only_an_owner_and_a_repository_name_reach_the_command() {
626 for bad in ["", "a", "a/b/c", "-x/y", "a/b;c", "../x/y", "a/--flag"] {
627 assert!(matches!(scan_push("aria", bad, b"{}").await, ScanOutcome::Failed(_)), "{bad:?}");
628 }
629 }
630}