Skip to main content

agentmux_srv_core/identity/
gh_agent_token.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A GitHub token from the host's `gh-agent`, for a container agent.
5//!
6//! A container agent has no GitHub setup of its own, and AgentMux's own token source (the App
7//! broker, `identity::github_tokens`) is not live everywhere yet. Where `gh-agent` is installed on
8//! the host, it already holds the App identity the fleet works under, so `gh-agent token --repo
9//! owner/repo` gives a short-lived installation token narrowed to the repository. srv runs it for
10//! the agent that asked (an agent id and a repository, never a command) and hands the token over
11//! the container route; nothing is written into the container.
12
13use std::path::PathBuf;
14use std::time::Duration;
15
16use agentmux_common::win32::NoWindow;
17use serde::Deserialize;
18use zeroize::Zeroizing;
19
20/// How long a caller waits for `gh-agent token`: a cached token is instant, a fresh one is a round trip, and on a
21/// loaded machine that round trip has taken 20 to 26 s. The container's own ask waits longer than this
22/// (`agentmux-bashwrap`'s `ASK_TIMEOUT`), so the answer here reaches it.
23const TIMEOUT: Duration = Duration::from_secs(50);
24/// How long a `gh-agent token` that the caller stopped waiting for is left to finish. gh-agent keeps what it minted, so
25/// the next ask is instant; a mint stopped half-way is kept by nobody, and every retry would start it over.
26const FINISH_TIMEOUT: Duration = Duration::from_secs(150);
27
28/// A token `gh-agent` minted.
29pub struct HostToken {
30    pub token: Zeroizing<String>,
31    /// Epoch seconds.
32    pub expires_at: i64,
33    /// The bot the token acts as, without the `[bot]` suffix (`muxagent`).
34    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    /// Which narrowed token this is, as a `gh-agent` that can give one says it; a token without it is the
43    /// installation-wide one.
44    scope: Option<String>,
45    repositories: Option<Vec<String>>,
46}
47
48/// What a container's token may do. `Api` reads contents and writes pull requests, issues and the rest; it cannot
49/// write contents. `Push` writes contents and nothing else (`gh-agent token --scope`). There is no third kind: a
50/// container is never handed the installation-wide token.
51#[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
66/// What a container is told when this machine's `gh-agent` cannot give a narrowed token (it predates `--scope`, or it
67/// gave a wider one than asked): the refusal never falls back to the installation-wide token.
68pub 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
70/// Whether `error` (a [`token_for`] error) is [`GH_AGENT_TOO_OLD`].
71pub fn is_too_old(error: &str) -> bool {
72    error == GH_AGENT_TOO_OLD
73}
74
75/// Set to `1` in a container's commands only while this machine has a publish guard (gh-agent installed); the
76/// container's pre-push hook reads it (`agentmux-bashwrap`'s `publish_scan`) and asks nothing when it is absent.
77pub const PUBLISH_GUARD_ENV: &str = "AGENTMUX_PUBLISH_GUARD";
78
79/// `gh-agent` on the host's PATH, if it is installed.
80pub fn installed() -> Option<PathBuf> {
81    which::which("gh-agent").ok()
82}
83
84/// What an agent is told when `gh-agent` is installed but did not answer in [`TIMEOUT`]: not a missing connection.
85pub 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
92/// Whether `error` (a [`token_for`] error) is [`took_too_long`].
93pub fn is_took_too_long(error: &str) -> bool {
94    error.starts_with("GitHub token took too long")
95}
96
97/// A GitHub account or repository name: what the request may name, and nothing that could be read as
98/// an option or a path.
99pub(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
103/// The token in `gh-agent token --json`'s output, if it is exactly the narrowed one asked for: the scope named, and
104/// the one repository. Anything else (no scope field: an older gh-agent that took `--scope` as an unknown flag and
105/// gave the installation-wide token) is refused and dropped, never passed on.
106fn 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
119/// The numeric id in GitHub's answer for a user (`GET /users/<login>`).
120fn 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
128/// How long a failed lookup is not repeated: offline, or GitHub's unauthenticated rate limit, would
129/// otherwise cost every token request the whole timeout.
130const LOOKUP_RETRY: Duration = Duration::from_secs(60);
131
132/// What is known of a bot's id: found for good, or failed at `Instant`.
133#[derive(Clone, Copy)]
134enum Lookup {
135    Found(u64),
136    Failed(std::time::Instant),
137}
138
139/// The answer to give without asking again, if there is one.
140fn 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
161/// The user id of the bot `<slug>[bot]`, which `gh-agent` doesn't say: a commit's author email is
162/// `<id>+<slug>[bot]@users.noreply.github.com`. A public lookup, asked once per bot and kept; `None`
163/// when GitHub can't be reached (not asked again for a minute), and then the commit keeps its own author.
164pub 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
180/// The arguments of `gh-agent token` for a narrowed token: always with `--scope`, so no call can come back as the
181/// installation-wide token. `workflows` (push only) asks for workflows write as well.
182fn 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
191/// The command's end: its output, or why it has none. Past [`FINISH_TIMEOUT`] the child is killed.
192async 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
200/// Wait up to `limit` for `run`. Past it the caller is told [`took_too_long`] and `run` goes on by itself (a dropped
201/// join handle detaches the task, it does not cancel it), so what it was minting is kept for the next ask.
202async 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
210/// A narrowed token for `owner/repo`, minted for the agent `slug`: one repository, and `scope`'s permissions only.
211pub 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    // No instance identity or key reaches it; the agent id below is the one thing it is told.
218    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        // Only a mint that runs past FINISH_TIMEOUT is killed (the future that holds the child is dropped then).
225        .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
236/// How long `gh-agent pr merge` may take: a round trip or two to GitHub, and a merge queue's answer.
237const MERGE_TIMEOUT: Duration = Duration::from_secs(90);
238
239/// How a pull request is merged; none lets the repository's own rule (a merge queue) choose.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
241#[serde(rename_all = "lowercase")]
242pub enum MergeMethod {
243    Squash,
244    Merge,
245    Rebase,
246}
247
248/// What a container asked srv to merge: one pull request, by number, with the few options a merge takes.
249#[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
259/// The arguments of the host's `gh-agent pr merge`: fixed, built here from validated parts, never from the container's
260/// text. There is no `--admin` and no other flag, so GitHub's own rules (a review, a merge queue, the checks) decide.
261pub 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
278/// Whether `r` can be run: names that cannot be read as an option or a path, and a real pull request number.
279pub 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
289/// Merge `r` as the agent `slug` with the host's `gh-agent pr merge`. The token it uses stays on the host; the answer
290/// is what the command said, first lines, bounded. `Ok` when the merge was done or queued, `Err` with what GitHub said.
291pub 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
319/// The first lines of a command's output, bounded, with the lines that only name the acting identity dropped.
320fn 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
326/// How long `gh-agent scan-push` may take: the pattern list is cached for a day, but a first read, a visibility lookup and
327/// the scan itself are round trips.
328const SCAN_TIMEOUT: Duration = Duration::from_secs(60);
329
330/// What the host's publish guard made of a container agent's push.
331#[derive(Debug, PartialEq, Eq)]
332pub enum ScanOutcome {
333    /// Its verdict: 0 passes, anything else refuses, with the lines to show.
334    Judged { code: i64, lines: Vec<String>, public: bool },
335    /// It could not judge (not run, too slow, no answer): what to tell the agent.
336    Failed(String),
337}
338
339#[derive(Deserialize)]
340struct Verdict {
341    code: i64,
342    lines: Vec<String>,
343    /// Whether the repository is one the guard guards. An answer that doesn't say is taken as public.
344    #[serde(default = "yes")]
345    public: bool,
346}
347
348fn yes() -> bool {
349    true
350}
351
352/// The verdict in `gh-agent scan-push`'s output.
353fn 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    // A bounded answer: a few lines of a few hundred characters.
356    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
360/// Judge a container agent's push with the host's `gh-agent scan-push --repo owner/repo`. The `material` (JSON) goes in
361/// on stdin; the arguments are fixed, there is no shell, and the working directory is the temp folder, never anything
362/// of the container's. gh-agent reads no repository and runs no git for this.
363pub 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        // Written while the child works, so a large push can't fill the pipe and wait for a reader that isn't reading.
387        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        // What gh-agent said it could not do, first line, bounded.
401        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        // An older gh-agent doesn't know the command and hands it to gh.
404        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/// A stand-in `gh-agent` on PATH for tests: it appends its arguments to a log, prints one line and exits with a code.
416#[cfg(any(test, feature = "test-support"))]
417pub mod fake {
418    use std::path::{Path, PathBuf};
419
420    /// Tests that change PATH take this first.
421    pub static PATH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
422
423    /// Puts a `gh-agent` in `dir` that logs its arguments, prints `stdout` and exits `code`, and puts `dir` first on PATH.
424    /// Returns the PATH to put back.
425    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    /// The argument lines the stand-in was called with, in order.
448    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        // An older gh-agent takes --scope for an unknown flag and prints the installation-wide token: no scope field.
500        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        // The other scope, another repository, more than one repository, or none named.
504        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        // An older gh-agent takes --scope for an unknown flag and prints the installation-wide token.
562        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        // The caller gives up after 20 ms and is told it took too long...
579        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        // ...and the work still finishes, which is what lets the next ask be quick.
583        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}