Skip to main content

agentmux_bashwrap/
publish_scan.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container agent's push, judged by the host's publish guard.
5//!
6//! The `pre-push` hook (`git_hooks.rs`) collects what the push publishes with the container's own git: per ref update
7//! the commits' messages, the added paths and the added lines, as the text git prints. `ask` posts it to srv
8//! (`POST /api/v1/github/push-scan`), which gives it as data to the host's `gh-agent scan-push`. The host never opens
9//! the container's clone; the material is all it sees.
10//!
11//! - A machine with no publish guard, and a native agent's shell, never reach srv: srv says
12//!   `AGENTMUX_PUBLISH_GUARD=1` in a container's commands on a machine whose guard can judge a container's push,
13//!   `=0` on one that has no guard, and `=older-gh-agent` on one whose gh-agent is too old to judge it. The hook
14//!   does nothing and says nothing for `0`. Where srv says nothing (an AgentMux older than the check), the hook says
15//!   once per push that it was checked for credentials only, and lets it go on: nothing on that host can judge it.
16//! - With `older-gh-agent`, a push to a GitHub repository is refused, saying to update gh-agent on the host and to
17//!   have it rewrite its hooks (the version is read from the hooks' header).
18//! - With `1`, an AgentMux that has no route to ask (404 or 405) refuses the push, and says to update AgentMux.
19//! - A push to a repository the guard finds private is not collected at all.
20//! - On a machine that has the guard, a public repository's push whose check cannot run (srv unreachable, too slow,
21//!   too large, refused) is refused, with what to do.
22//!
23//! The git commands are the ones gh-agent's own pre-push hook runs; the two judge the same text.
24
25use std::process::{Command, Stdio};
26use std::time::Duration;
27
28use agentmux_common::win32::NoWindow;
29use serde::Serialize;
30use serde_json::Value;
31
32use crate::mps_client::WpsClient;
33
34/// srv runs the guard for up to a minute (a first read of the pattern list, a visibility lookup, the scan).
35const ASK_TIMEOUT: Duration = Duration::from_secs(75);
36/// Past this many commits a push is refused by the guard without being read.
37const MAX_PUSH_COMMITS: u64 = 500;
38/// The most material one push may send; the same figure srv enforces.
39const MAX_MATERIAL_BYTES: usize = 16 * 1024 * 1024;
40const MAX_CHANGESETS: usize = 100;
41const ZERO: &str = "0000000000000000000000000000000000000000";
42
43/// One ref update of the push.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct RefUpdate {
46    pub local_ref: String,
47    pub local_sha: String,
48    /// The ref on the remote that the push updates (the hook's third field).
49    pub remote_ref: String,
50    pub remote_sha: String,
51}
52
53/// The material of one ref update, as srv takes it.
54#[derive(Debug, Default, Serialize, PartialEq, Eq)]
55pub struct Part {
56    pub r#ref: String,
57    /// The ref the push updates on the remote, and whether the remote has none yet: a new branch or tag becomes public with
58    /// the push, so its name is judged too.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub remote_ref: Option<String>,
61    pub new_ref: bool,
62    pub count: u64,
63    pub remote_named: bool,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub tag_message: Option<String>,
66    pub messages: String,
67    pub name_status: String,
68    pub patch: String,
69    pub changesets: Vec<Changeset>,
70}
71
72#[derive(Debug, Serialize, PartialEq, Eq)]
73pub struct Changeset {
74    pub path: String,
75    pub text: String,
76}
77
78/// `owner/repo`, lowercase, of a github.com remote URL (https, ssh or scp form); `None` for anything else.
79pub fn repo_of_remote_url(url: &str) -> Option<String> {
80    let url = url.trim();
81    // Host names are case-insensitive; the lowercase copy has the same byte offsets as the original.
82    let at = url.to_ascii_lowercase().find("github.com")?;
83    let (before, after) = (&url[..at], &url[at + "github.com".len()..]);
84    // Whatever precedes the host must end the scheme or the user: `https://`, `git@`, `ssh://git@`, or `ssh.` is ssh.github.com.
85    let before_lower = before.to_ascii_lowercase();
86    if !(before.is_empty() || before.ends_with('/') || before.ends_with('@') || before_lower.ends_with("ssh.")) {
87        return None;
88    }
89    // A port belongs to a URL (`ssh://git@ssh.github.com:443/o/r`). In scp form (`git@github.com:o/r`) the colon only
90    // separates the host from the path, and an owner may start with digits (`1password`).
91    let rest = if url.contains("://") {
92        let no_port = after.strip_prefix(':').and_then(|p| {
93            let path = p.trim_start_matches(|c: char| c.is_ascii_digit());
94            (path.len() < p.len() && path.starts_with('/')).then_some(path)
95        });
96        no_port.unwrap_or(after).trim_start_matches('/')
97    } else {
98        after.strip_prefix(':').unwrap_or(after).trim_start_matches('/')
99    };
100    let rest = rest.trim_end_matches('/');
101    let rest = rest.strip_suffix(".git").unwrap_or(rest);
102    let (owner, name) = rest.split_once('/')?;
103    let ok = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
104    (ok(owner) && ok(name)).then(|| format!("{owner}/{name}").to_ascii_lowercase())
105}
106
107/// The ref updates on the hook's stdin (`<local ref> <local sha> <remote ref> <remote sha>`), deletions left out.
108pub fn parse_updates(input: &str) -> Vec<RefUpdate> {
109    input
110        .lines()
111        .filter_map(|line| {
112            let f: Vec<&str> = line.split_whitespace().collect();
113            match f.as_slice() {
114                [local_ref, local_sha, remote_ref, remote_sha] if !local_sha.chars().all(|c| c == '0') => Some(RefUpdate {
115                    local_ref: local_ref.to_string(),
116                    local_sha: local_sha.to_string(),
117                    remote_ref: remote_ref.to_string(),
118                    remote_sha: remote_sha.to_string(),
119                }),
120                _ => None,
121            }
122        })
123        .collect()
124}
125
126/// The `.changesets/*.md` files named in `git log -z --name-status` output: only the guard decides which of them the
127/// push added, so every path of that shape is sent (at most [`MAX_CHANGESETS`]).
128pub fn changeset_paths(name_status: &str) -> Vec<String> {
129    let mut out: Vec<String> = Vec::new();
130    for token in name_status.split('\0') {
131        let t = token.trim_start_matches('\n');
132        if let Some(name) = t.strip_prefix(".changesets/") {
133            if name.ends_with(".md") && !name.contains('/') && !name.is_empty() && !out.iter().any(|p| p == t) && out.len() < MAX_CHANGESETS {
134                out.push(t.to_string());
135            }
136        }
137    }
138    out
139}
140
141/// The body of an annotated tag's message from `git cat-file tag`: everything after the first blank line.
142pub fn tag_body(tag: &str) -> String {
143    let normalized = tag.replace("\r\n", "\n");
144    normalized.splitn(2, "\n\n").nth(1).unwrap_or("").to_string()
145}
146
147/// Runs git with these arguments in the current directory: its stdout, or what failed.
148pub type Git<'a> = &'a dyn Fn(&[&str]) -> Result<String, String>;
149
150/// Most annotated tags one pushed object may be wrapped in (a tag of a tag of ...); more fails the check.
151const MAX_TAG_DEPTH: usize = 8;
152
153/// The object a tag points at: the `object` line of `git cat-file tag` output.
154fn tag_target(tag: &str) -> Option<String> {
155    tag.lines().take_while(|l| !l.is_empty()).find_map(|l| l.strip_prefix("object ")).map(|s| s.trim().to_string())
156}
157
158/// What `sha` is once the annotated tags around it are peeled: the message of those tags, joined in order (`None`
159/// when `sha` is no tag object), and the type of what is left (`commit`, `blob`, `tree`, or `tag` for a tag git
160/// could not follow).
161fn peel_tags(sha: &str, git: Git) -> Result<(Option<String>, String), String> {
162    let mut at = sha.to_string();
163    let mut bodies: Vec<String> = Vec::new();
164    loop {
165        let kind = git(&["cat-file", "-t", &at])?.trim().to_string();
166        if kind != "tag" {
167            return Ok(((!bodies.is_empty()).then(|| bodies.join("\n")), kind));
168        }
169        if bodies.len() >= MAX_TAG_DEPTH {
170            return Err(format!("this push is a tag wrapped in more than {MAX_TAG_DEPTH} tags"));
171        }
172        let raw = git(&["cat-file", "tag", &at])?;
173        bodies.push(tag_body(&raw));
174        match tag_target(&raw) {
175            Some(next) => at = next,
176            None => return Ok((Some(bodies.join("\n")), kind)),
177        }
178    }
179}
180
181/// The material of each ref update. The commands are the ones gh-agent's own pre-push hook runs, so both judge the same text.
182pub fn collect(updates: &[RefUpdate], remote: &str, git: Git) -> Result<Vec<Part>, String> {
183    let named = git(&["remote"])?.lines().any(|l| l.trim() == remote);
184    let mut parts = Vec::new();
185    for u in updates {
186        // A remote tip this clone never fetched can't be excluded; leave it out.
187        let known_tip = u.remote_sha != ZERO && !u.remote_sha.is_empty() && git(&["cat-file", "-e", &format!("{}^{{commit}}", u.remote_sha)]).is_ok();
188        let mut range: Vec<String> = vec![u.local_sha.clone(), "--not".to_string()];
189        if named {
190            range.push(format!("--remotes={remote}"));
191        }
192        if known_tip {
193            range.push(u.remote_sha.clone());
194        }
195        let with = |head: &[&str]| -> Vec<String> { head.iter().map(|s| s.to_string()).chain(range.iter().cloned()).collect() };
196        let run = |args: Vec<String>| -> Result<String, String> {
197            let refs: Vec<&str> = args.iter().map(String::as_str).collect();
198            git(&refs)
199        };
200        let count: u64 = run(with(&["rev-list", "--count"]))?.trim().parse().map_err(|_| "couldn't count the commits in this push".to_string())?;
201        let mut part = Part {
202            r#ref: u.local_ref.clone(),
203            remote_ref: Some(u.remote_ref.clone()).filter(|r| !r.is_empty()),
204            new_ref: u.remote_sha.is_empty() || u.remote_sha == ZERO,
205            count,
206            remote_named: named,
207            ..Part::default()
208        };
209        if count <= MAX_PUSH_COMMITS {
210            // By what the pushed object is, not by what its source ref is called: `git push origin <tag-sha>:refs/heads/x`
211            // and `refs/heads/y:refs/tags/v1` publish a tag's message as much as `refs/tags/v1` does.
212            let (message, kind) = peel_tags(&u.local_sha, git)?;
213            // The range lists commits, so only a commit can be read: any other object fails the check.
214            if kind != "commit" {
215                return Err(format!("{} points at a {kind}, not a commit, so its content cannot be checked", u.local_ref));
216            }
217            part.tag_message = message;
218            if count > 0 {
219                part.messages = run(with(&["log", "--format=%H%x00%B%x1e"]))?;
220                part.name_status = run(with(&["-c", "core.quotePath=false", "log", "--reverse", "-z", "--name-status", "--find-renames", "--format=%x01%H"]))?;
221                for path in changeset_paths(&part.name_status) {
222                    // A changeset a later commit removed names nothing.
223                    if let Ok(text) = git(&["show", &format!("{}:{path}", u.local_sha)]) {
224                        part.changesets.push(Changeset { path, text });
225                    }
226                }
227                let diff = ["--format=commit %H", "-p", "--text", "--unified=0", "--no-color", "--no-ext-diff", "--no-textconv", "--find-renames"];
228                let log = |kind: &[&str]| -> Vec<String> { kind.iter().chain(diff.iter()).map(|s| s.to_string()).chain(range.iter().cloned()).collect() };
229                part.patch = run(log(&["log", "--no-merges"]))? + &run(log(&["log", "--merges", "--cc"]))?;
230            }
231        }
232        parts.push(part);
233        if count > MAX_PUSH_COMMITS {
234            break;
235        }
236    }
237    Ok(parts)
238}
239
240/// git in the current directory.
241fn real_git(args: &[&str]) -> Result<String, String> {
242    let mut cmd = Command::new("git");
243    cmd.args(args).stdin(Stdio::null()).stderr(Stdio::piped());
244    // Windows: git is a console program, and this process has no console of its own.
245    cmd.no_window();
246    let out = cmd.output().map_err(|e| format!("couldn't run git: {e}"))?;
247    if !out.status.success() {
248        return Err(format!("git {} failed: {}", args.first().copied().unwrap_or(""), String::from_utf8_lossy(&out.stderr).trim()));
249    }
250    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
251}
252
253/// What srv said.
254#[derive(Debug, PartialEq, Eq)]
255pub enum Answer {
256    /// This machine has no publish guard, or the repository is not one it guards: nothing to do, nothing to say.
257    NotNeeded,
258    /// A guard that judges. `public` is whether the repository is one it guards.
259    Judged { public: bool, code: i64, lines: Vec<String> },
260    /// The check could not run: what to tell the agent.
261    Unavailable(String),
262    /// The machine said it has the guard, but its AgentMux has no route to ask: waiting does not help.
263    NoRoute,
264}
265
266/// Read srv's answer: its status and body.
267pub fn read_answer(status: u16, body: &Value) -> Answer {
268    let error = || body.get("error").and_then(Value::as_str).map(str::to_string);
269    match status {
270        200..=299 => {
271            if body.get("guard").and_then(Value::as_str) == Some("none") {
272                return Answer::NotNeeded;
273            }
274            let Some(code) = body.get("code").and_then(Value::as_i64) else {
275                return Answer::Unavailable("AgentMux gave no verdict on this push".to_string());
276            };
277            let lines = body.get("lines").and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
278            // An answer that doesn't say is taken as public: the guard is not switched off by silence.
279            let public = body.get("public").and_then(Value::as_bool).unwrap_or(true);
280            Answer::Judged { public, code, lines }
281        }
282        // A machine that said it has the guard, and an AgentMux that does not know the route: the push is not sent.
283        404 | 405 => Answer::NoRoute,
284        413 => Answer::Unavailable(error().unwrap_or_else(|| "this push is too large to check: split it into smaller pushes".to_string())),
285        429 => Answer::Unavailable(error().unwrap_or_else(|| "too many pushes are being checked: wait a minute and push again".to_string())),
286        _ => Answer::Unavailable(error().unwrap_or_else(|| format!("AgentMux refused to check this push ({status}): try again in a minute"))),
287    }
288}
289
290#[derive(Serialize)]
291struct Request<'a> {
292    repo: &'a str,
293    allow_new_docs: bool,
294    parts: &'a [Part],
295}
296
297/// Ask srv to judge `parts` (empty: only whether this machine guards `repo`).
298fn ask(repo: &str, allow_new_docs: bool, parts: &[Part]) -> Answer {
299    let Some(client) = WpsClient::from_env() else {
300        return Answer::Unavailable("AGENTMUX_LOCAL_URL / AGENTMUX_AUTH_KEY aren't set: run this from an agent's own shell".to_string());
301    };
302    let agent_token = std::env::var("AGENTMUX_AGENT_TOKEN").ok();
303    let rt = match tokio::runtime::Runtime::new() {
304        Ok(rt) => rt,
305        Err(e) => return Answer::Unavailable(format!("couldn't start: {e}")),
306    };
307    let body = Request { repo, allow_new_docs, parts };
308    match rt.block_on(client.post_json_status("/api/v1/github/push-scan", agent_token.as_deref(), &body, ASK_TIMEOUT)) {
309        Ok((status, answer)) => read_answer(status, &answer),
310        Err(e) => Answer::Unavailable(format!("couldn't reach AgentMux to check this push: {e}")),
311    }
312}
313
314/// What to do after a check that could not run.
315fn refuse_unavailable(why: &str) -> i32 {
316    eprintln!("agentmux: this push to a public repository was not checked, so it is not sent: {why}");
317    eprintln!("agentmux: try the push again; if it keeps failing, ask your leader.");
318    1
319}
320
321/// What to do when the machine has the guard but its AgentMux cannot be asked: not a thing to try again.
322fn refuse_no_route() -> i32 {
323    eprintln!("agentmux: this push to a public repository was not checked, so it is not sent: the AgentMux on this host has no publish check to ask.");
324    eprintln!("agentmux: ask your leader to update AgentMux on this host.");
325    1
326}
327
328fn show(lines: &[String]) {
329    for line in lines {
330        eprintln!("{line}");
331    }
332}
333
334/// What this machine has for a push in this shell.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum Guard {
337    /// A container's command on a machine srv says has a publish guard (`AGENTMUX_PUBLISH_GUARD=1`): ask it.
338    Scan,
339    /// A native agent (its own gh-agent hook guards its push), or a machine srv says has no guard (`=0`): the hook
340    /// makes no request and says nothing, so it can never refuse a push for want of an answer.
341    Nothing,
342    /// A container's command where srv said nothing: an AgentMux older than the check. Said out loud.
343    OlderAgentMux,
344    /// A container's command on a machine whose gh-agent cannot judge a container's push (`AGENTMUX_PUBLISH_GUARD=older-gh-agent`).
345    /// The push to a GitHub repository is refused, saying how to fix the host: it is one of ours and the fix takes a minute.
346    OlderGhAgent,
347}
348
349fn guard_here() -> Guard {
350    if std::env::var("AGENTMUX_IN_CONTAINER").map_or(true, |v| v != "1") {
351        return Guard::Nothing;
352    }
353    match std::env::var("AGENTMUX_PUBLISH_GUARD").as_deref() {
354        Ok("1") => Guard::Scan,
355        Ok("0") => Guard::Nothing,
356        Ok("older-gh-agent") => Guard::OlderGhAgent,
357        _ => Guard::OlderAgentMux,
358    }
359}
360
361/// The publish guard's part of `pre-push <remote> <url>`: 0 to go on, anything else refuses the push.
362pub fn check_push(remote: &str, url: &str, input: &str) -> i32 {
363    let allow = std::env::var("GH_AGENT_ALLOW_NEW_DOCS").is_ok_and(|v| v == "1");
364    check_with(remote, url, input, guard_here(), allow, &ask, &real_git)
365}
366
367/// [`check_push`] with its surroundings given: what the machine has, the override, srv, and git.
368fn check_with(remote: &str, url: &str, input: &str, guard: Guard, allow: bool, ask: &dyn Fn(&str, bool, &[Part]) -> Answer, git: Git) -> i32 {
369    if guard == Guard::Nothing {
370        return 0;
371    }
372    let Some(repo) = repo_of_remote_url(url) else { return 0 };
373    let updates = parse_updates(input);
374    if updates.is_empty() {
375        return 0;
376    }
377    if guard == Guard::OlderAgentMux {
378        eprintln!("agentmux: this push to a GitHub repository was checked for credentials only: the AgentMux on this host is older than the publish check, so the push itself was not scanned.");
379        return 0;
380    }
381    if guard == Guard::OlderGhAgent {
382        eprintln!("agentmux: this push to a GitHub repository was not checked, so it is not sent: the gh-agent on this host is too old to judge a container's push (it needs 0.13 or later).");
383        eprintln!("agentmux: ask your leader to update gh-agent on the host and then run `gh-agent hooks-path` there: the check reads the version from the hooks' header, and hooks an older gh-agent wrote keep refusing after the update.");
384        return 1;
385    }
386    // First only whether this machine guards this repository, so a private one's push is not read.
387    match ask(&repo, allow, &[]) {
388        Answer::NotNeeded => return 0,
389        Answer::Unavailable(why) => return refuse_unavailable(&why),
390        Answer::NoRoute => return refuse_no_route(),
391        Answer::Judged { public: false, .. } => return 0,
392        Answer::Judged { public: true, .. } => {}
393    }
394    let parts = match collect(&updates, remote, git) {
395        Ok(p) => p,
396        Err(why) => return refuse_unavailable(&why),
397    };
398    let size: usize = parts.iter().map(|p| p.tag_message.as_deref().map_or(0, str::len) + p.messages.len() + p.name_status.len() + p.patch.len() + p.changesets.iter().map(|c| c.path.len() + c.text.len()).sum::<usize>()).sum();
399    if size > MAX_MATERIAL_BYTES {
400        return refuse_unavailable("it is too large to check: split it into smaller pushes");
401    }
402    match ask(&repo, allow, &parts) {
403        Answer::NotNeeded => 0,
404        Answer::Unavailable(why) => refuse_unavailable(&why),
405        Answer::NoRoute => refuse_no_route(),
406        Answer::Judged { code, lines, .. } => {
407            show(&lines);
408            i32::from(code != 0)
409        }
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use serde_json::json;
417    use std::cell::RefCell;
418    use std::collections::HashMap;
419
420    #[test]
421    fn a_github_remote_is_owner_slash_repo_in_lowercase_and_nothing_else_is() {
422        for (url, want) in [
423            ("https://github.com/AgentMuxAI/agentmux.git", Some("agentmuxai/agentmux")),
424            ("https://github.com/agentmuxai/agentmux", Some("agentmuxai/agentmux")),
425            ("https://github.com/agentmuxai/agentmux/", Some("agentmuxai/agentmux")),
426            ("git@github.com:agentmuxai/agentmux.git", Some("agentmuxai/agentmux")),
427            ("ssh://git@github.com/agentmuxai/agentmux.git", Some("agentmuxai/agentmux")),
428            ("ssh://git@ssh.github.com:443/agentmuxai/agentmux.git", Some("agentmuxai/agentmux")),
429            ("https://x-access-token:t@github.com/o/r.git", Some("o/r")),
430            ("https://GitHub.com/O/R.git", Some("o/r")),
431            ("HTTPS://GITHUB.COM/o/r", Some("o/r")),
432            ("git@GitHub.com:o/r.git", Some("o/r")),
433            ("git@github.com:1password/r.git", Some("1password/r")),
434            ("git@github.com:123/r.git", Some("123/r")),
435            ("https://github.com/123/r", Some("123/r")),
436            ("ssh://git@github.com:22/1password/r.git", Some("1password/r")),
437            ("ssh://git@ssh.github.com:443/1password/r.git", Some("1password/r")),
438            ("https://github.com:443/o/r", Some("o/r")),
439            ("https://notgithub.com/o/r.git", None),
440            ("https://github.com.evil.example/o/r.git", None),
441            ("https://gitlab.com/o/r.git", None),
442            ("/some/local/path", None),
443            ("https://github.com/onlyowner", None),
444            ("", None),
445        ] {
446            assert_eq!(repo_of_remote_url(url).as_deref(), want, "{url}");
447        }
448    }
449
450    #[test]
451    fn the_updates_are_read_and_deletions_are_left_out() {
452        let sha = "a".repeat(40);
453        let input = format!("refs/heads/x {sha} refs/heads/x {ZERO}\n(delete) {ZERO} refs/heads/y {sha}\n\nbroken line\n");
454        let got = parse_updates(&input);
455        assert_eq!(got, vec![RefUpdate { local_ref: "refs/heads/x".into(), local_sha: sha, remote_ref: "refs/heads/x".into(), remote_sha: ZERO.into() }]);
456    }
457
458    #[test]
459    fn changesets_are_found_among_the_paths_git_lists() {
460        let out = "\x01abc\0\nA\0.changesets/one.md\0\nA\0src/a.rs\0\x01def\0\nR100\0.changesets/two.md\0.changesets/three.md\0\nA\0.changesets/dir/x.md\0\nA\0.changesets/README.txt\0";
461        assert_eq!(changeset_paths(out), vec![".changesets/one.md", ".changesets/two.md", ".changesets/three.md"]);
462        assert!(changeset_paths("").is_empty());
463    }
464
465    #[test]
466    fn a_tags_message_is_what_follows_its_header() {
467        assert_eq!(tag_body("object abc\ntype commit\ntag v1\n\nthe notes\nmore"), "the notes\nmore");
468        assert_eq!(tag_body("object abc\r\n\r\nnotes"), "notes");
469        assert_eq!(tag_body("object abc"), "");
470    }
471
472    /// A fake git that answers by the first words of the command, and remembers what was run.
473    struct FakeGit {
474        answers: HashMap<&'static str, String>,
475        ran: RefCell<Vec<String>>,
476    }
477
478    impl FakeGit {
479        fn run(&self, args: &[&str]) -> Result<String, String> {
480            let line = args.join(" ");
481            self.ran.borrow_mut().push(line.clone());
482            let key = ["remote", "rev-list", "cat-file -e", "cat-file -t", "cat-file tag", "show", "log --format=%H", "-c core.quotePath=false log", "log --no-merges", "log --merges"]
483                .into_iter()
484                .find(|k| line.starts_with(k))
485                .ok_or_else(|| format!("unexpected: {line}"))?;
486            self.answers.get(key).cloned().ok_or_else(|| format!("fails: {line}"))
487        }
488    }
489
490    fn fake(count: &str) -> FakeGit {
491        let answers = HashMap::from([
492            ("remote", "origin\nupstream\n".to_string()),
493            ("rev-list", format!("{count}\n")),
494            ("cat-file -e", String::new()),
495            ("cat-file -t", "commit\n".to_string()),
496            ("log --format=%H", "abc\0unrelated\n\x1e".to_string()),
497            ("-c core.quotePath=false log", "\x01abc\0\nA\0.changesets/c.md\0\nA\0plans/PLAN_X.md\0".to_string()),
498            ("show", "the changeset".to_string()),
499            ("log --no-merges", "commit abc\n+line\n".to_string()),
500            ("log --merges", String::new()),
501        ]);
502        FakeGit { answers, ran: RefCell::new(Vec::new()) }
503    }
504
505    fn update(local_ref: &str, remote_sha: &str) -> RefUpdate {
506        RefUpdate { local_ref: local_ref.into(), local_sha: "b".repeat(40), remote_ref: local_ref.into(), remote_sha: remote_sha.into() }
507    }
508
509    #[test]
510    fn the_material_is_what_gh_agents_own_hook_would_read_and_nothing_more() {
511        let git = fake("2");
512        let parts = collect(&[update("refs/heads/x", &"c".repeat(40))], "origin", &|a| git.run(a)).unwrap();
513        assert_eq!(parts.len(), 1);
514        let p = &parts[0];
515        assert_eq!((p.r#ref.as_str(), p.count, p.remote_named), ("refs/heads/x", 2, true));
516        assert_eq!(p.messages, "abc\0unrelated\n\x1e");
517        assert!(p.name_status.contains("plans/PLAN_X.md"));
518        assert_eq!(p.patch, "commit abc\n+line\n");
519        assert_eq!(p.changesets, vec![Changeset { path: ".changesets/c.md".into(), text: "the changeset".into() }]);
520        assert!(p.tag_message.is_none());
521        let ran = git.ran.borrow().join("\n");
522        // The range: the tip, then what the named remote's refs and the remote's tip already have.
523        assert!(ran.contains(&format!("rev-list --count {} --not --remotes=origin {}", "b".repeat(40), "c".repeat(40))), "{ran}");
524        assert!(ran.contains("-c core.quotePath=false log --reverse -z --name-status --find-renames --format=%x01%H"), "{ran}");
525        assert!(ran.contains("log --no-merges --format=commit %H -p --text --unified=0 --no-color --no-ext-diff --no-textconv --find-renames"), "{ran}");
526        assert!(ran.contains("log --merges --cc --format=commit %H -p"), "{ran}");
527    }
528
529    /// `fake`, except that the object `b`*40 (what `update` pushes) is an annotated tag whose message is `notes` and which
530    /// points at the commit `a`*40.
531    fn with_tag<'a>(git: &'a FakeGit, notes: &str) -> impl Fn(&[&str]) -> Result<String, String> + 'a {
532        let (tag, commit) = ("b".repeat(40), "a".repeat(40));
533        let notes = notes.to_string();
534        move |a: &[&str]| match a {
535            ["cat-file", "-t", s] if *s == tag => Ok("tag\n".into()),
536            ["cat-file", "tag", s] if *s == tag => Ok(format!("object {commit}\ntype commit\ntag v1\ntagger t <t@t> 1 +0000\n\n{notes}")),
537            _ => git.run(a),
538        }
539    }
540
541    #[test]
542    fn a_tags_message_is_collected_by_what_is_pushed_whatever_its_ref_is_called() {
543        let git = fake("1");
544        let run = with_tag(&git, "the notes");
545        for local_ref in ["refs/tags/v1", "refs/heads/x", "HEAD", &"b".repeat(40)] {
546            let parts = collect(&[update(local_ref, ZERO)], "origin", &run).unwrap();
547            assert_eq!(parts[0].tag_message.as_deref(), Some("the notes"), "{local_ref}");
548        }
549        // A commit is not a tag, even under a tag's name.
550        let parts = collect(&[update("refs/tags/v1", ZERO)], "origin", &|a| git.run(a)).unwrap();
551        assert!(parts[0].tag_message.is_none());
552    }
553
554    #[test]
555    fn a_tag_wrapped_in_tags_gives_every_message_and_a_loop_fails_the_check() {
556        let git = fake("1");
557        let (outer, inner, commit) = ("b".repeat(40), "c".repeat(40), "a".repeat(40));
558        let nested = |a: &[&str]| match a {
559            ["cat-file", "-t", s] if *s == outer || *s == inner => Ok("tag\n".to_string()),
560            ["cat-file", "tag", s] if *s == outer => Ok(format!("object {inner}\ntype tag\n\nouter notes")),
561            ["cat-file", "tag", s] if *s == inner => Ok(format!("object {commit}\ntype commit\n\ninner notes")),
562            _ => git.run(a),
563        };
564        let parts = collect(&[update("refs/tags/v1", ZERO)], "origin", &nested).unwrap();
565        assert_eq!(parts[0].tag_message.as_deref(), Some("outer notes\ninner notes"));
566        // A tag that points at itself cannot be read to its end.
567        let looped = |a: &[&str]| match a {
568            ["cat-file", "-t", _] => Ok("tag\n".to_string()),
569            ["cat-file", "tag", s] => Ok(format!("object {s}\ntype tag\n\nagain")),
570            _ => git.run(a),
571        };
572        assert!(collect(&[update("refs/tags/v1", ZERO)], "origin", &looped).is_err());
573    }
574
575    #[test]
576    fn a_push_whose_object_is_not_a_commit_fails_the_check_under_any_ref_name() {
577        let git = fake("0");
578        let (pushed, target) = ("b".repeat(40), "a".repeat(40));
579        // The pushed object is `kind`, or a tag whose target is `kind`.
580        let object_is = |kind: &'static str, via_tag: bool| {
581            let (pushed, target, git) = (pushed.clone(), target.clone(), &git);
582            move |a: &[&str]| match a {
583                ["cat-file", "-t", s] if via_tag && *s == pushed => Ok("tag\n".to_string()),
584                ["cat-file", "tag", s] if *s == pushed => Ok(format!("object {target}\ntype {kind}\n\nnotes")),
585                ["cat-file", "-t", _] => Ok(format!("{kind}\n")),
586                _ => git.run(a),
587            }
588        };
589        for kind in ["blob", "tree"] {
590            for via_tag in [false, true] {
591                for local_ref in ["refs/tags/v1", "refs/heads/x", "HEAD"] {
592                    let err = collect(&[update(local_ref, ZERO)], "origin", &object_is(kind, via_tag)).unwrap_err();
593                    assert!(err.contains(&format!("points at a {kind}, not a commit")), "{kind} {via_tag} {local_ref}: {err}");
594                }
595            }
596        }
597        // A tag of a commit is read as before.
598        let parts = collect(&[update("refs/tags/v1", ZERO)], "origin", &object_is("commit", true)).unwrap();
599        assert_eq!(parts[0].tag_message.as_deref(), Some("notes"));
600        // A tag git cannot follow (no object line) is no commit either.
601        let broken = |a: &[&str]| match a {
602            ["cat-file", "-t", _] => Ok("tag\n".to_string()),
603            ["cat-file", "tag", _] => Ok("tag v1\n\nnotes".to_string()),
604            _ => git.run(a),
605        };
606        assert!(collect(&[update("refs/tags/v1", ZERO)], "origin", &broken).unwrap_err().contains("not a commit"));
607    }
608
609    #[test]
610    fn a_bare_url_excludes_no_remote_and_a_new_branch_has_no_tip_to_exclude() {
611        let git = fake("1");
612        let parts = collect(&[update("refs/heads/new", ZERO)], "https://github.com/o/r.git", &|a| git.run(a)).unwrap();
613        assert!(!parts[0].remote_named);
614        let ran = git.ran.borrow().join("\n");
615        assert!(ran.contains(&format!("rev-list --count {} --not\n", "b".repeat(40))) || ran.contains(&format!("rev-list --count {} --not", "b".repeat(40))), "{ran}");
616        assert!(!ran.contains("--remotes="), "{ran}");
617    }
618
619    #[test]
620    fn far_more_commits_than_a_normal_push_are_counted_and_not_read() {
621        let git = fake("501");
622        let parts = collect(&[update("refs/heads/x", ZERO)], "origin", &|a| git.run(a)).unwrap();
623        assert_eq!(parts[0].count, 501);
624        assert!(parts[0].messages.is_empty() && parts[0].patch.is_empty());
625        assert!(!git.ran.borrow().iter().any(|l| l.starts_with("log")), "no log was run");
626    }
627
628    #[test]
629    fn a_git_failure_is_a_failure_not_an_empty_push() {
630        let mut git = fake("1");
631        git.answers.remove("log --no-merges");
632        assert!(collect(&[update("refs/heads/x", ZERO)], "origin", &|a| git.run(a)).is_err());
633        let mut git = fake("x");
634        git.answers.insert("rev-list", "not a number".to_string());
635        assert!(collect(&[update("refs/heads/x", ZERO)], "origin", &|a| git.run(a)).is_err());
636    }
637
638    #[test]
639    fn what_srv_says_is_read_and_a_silence_does_not_switch_the_guard_off() {
640        assert_eq!(read_answer(200, &json!({ "guard": "none", "code": 0, "lines": [] })), Answer::NotNeeded);
641        assert_eq!(
642            read_answer(200, &json!({ "guard": "gh-agent", "code": 1, "lines": ["no", "way"], "public": true })),
643            Answer::Judged { public: true, code: 1, lines: vec!["no".into(), "way".into()] }
644        );
645        assert_eq!(read_answer(200, &json!({ "guard": "gh-agent", "code": 0, "lines": [], "public": false })), Answer::Judged { public: false, code: 0, lines: vec![] });
646        // no `public` field: taken as public
647        assert_eq!(read_answer(200, &json!({ "guard": "gh-agent", "code": 0, "lines": [] })), Answer::Judged { public: true, code: 0, lines: vec![] });
648        // no verdict at all
649        assert!(matches!(read_answer(200, &json!({ "guard": "gh-agent" })), Answer::Unavailable(_)));
650        for status in [400, 401, 403, 429, 500, 503] {
651            assert!(matches!(read_answer(status, &json!({ "error": "why" })), Answer::Unavailable(w) if w == "why"), "{status}");
652        }
653        assert!(matches!(read_answer(413, &Value::Null), Answer::Unavailable(w) if w.contains("split it")));
654    }
655
656    #[test]
657    fn a_part_names_the_remote_ref_and_whether_the_push_creates_it() {
658        let git = fake("1");
659        let created = collect(&[update("refs/heads/new-branch", ZERO)], "origin", &|a| git.run(a)).unwrap();
660        assert_eq!((created[0].remote_ref.as_deref(), created[0].new_ref), (Some("refs/heads/new-branch"), true));
661        let moved = collect(&[update("refs/heads/old-branch", &"c".repeat(40))], "origin", &|a| git.run(a)).unwrap();
662        assert_eq!((moved[0].remote_ref.as_deref(), moved[0].new_ref), (Some("refs/heads/old-branch"), false));
663        // A push to a differently named remote ref sends the remote's name, not the local one.
664        let renamed = RefUpdate { local_ref: "refs/heads/local".into(), local_sha: "b".repeat(40), remote_ref: "refs/tags/v1".into(), remote_sha: ZERO.into() };
665        let parts = collect(&[renamed], "origin", &|a| git.run(a)).unwrap();
666        assert_eq!((parts[0].r#ref.as_str(), parts[0].remote_ref.as_deref(), parts[0].new_ref), ("refs/heads/local", Some("refs/tags/v1"), true));
667        let body = serde_json::to_value(&parts[0]).unwrap();
668        assert_eq!((body["remote_ref"].as_str(), body["new_ref"].as_bool()), (Some("refs/tags/v1"), Some(true)));
669    }
670
671    #[test]
672    fn the_request_is_the_shape_srv_takes() {
673        let parts = vec![Part { r#ref: "refs/heads/x".into(), count: 1, remote_named: true, messages: "m".into(), ..Part::default() }];
674        let body = serde_json::to_value(Request { repo: "o/r", allow_new_docs: true, parts: &parts }).unwrap();
675        assert_eq!(body["repo"], "o/r");
676        assert_eq!(body["allow_new_docs"], true);
677        assert_eq!(body["parts"][0]["ref"], "refs/heads/x");
678        assert!(body["parts"][0].get("tag_message").is_none());
679        assert_eq!(body["parts"][0]["changesets"], json!([]));
680    }
681
682    const PUSH: &str = "refs/heads/x bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb refs/heads/x 0000000000000000000000000000000000000000\n";
683
684    /// Runs the hook's check with srv's answers, counting the requests it made.
685    fn check(guarded: bool, url: &str, answers: Vec<Answer>) -> (i32, usize) {
686        check_guard(if guarded { Guard::Scan } else { Guard::Nothing }, url, answers)
687    }
688
689    fn check_guard(guard: Guard, url: &str, answers: Vec<Answer>) -> (i32, usize) {
690        let git = fake("1");
691        let asked = RefCell::new(0usize);
692        let answers = RefCell::new(answers.into_iter());
693        let ask = |_: &str, _: bool, _: &[Part]| -> Answer {
694            *asked.borrow_mut() += 1;
695            answers.borrow_mut().next().expect("asked more than the test expected")
696        };
697        let code = check_with("origin", url, PUSH, guard, false, &ask, &|a| git.run(a));
698        (code, asked.into_inner())
699    }
700
701    #[test]
702    fn a_machine_with_no_guard_and_a_native_agent_are_never_asked_and_never_refused() {
703        // Every way the question would fail, were it asked: unreachable, no environment, 401, 400, 429, 500, too large.
704        for why in ["couldn't reach AgentMux", "AGENTMUX_LOCAL_URL isn't set", "401", "400", "too many pushes", "500", "too large"] {
705            let (code, asked) = check(false, "https://github.com/o/r.git", vec![Answer::Unavailable(why.into())]);
706            assert_eq!((code, asked), (0, 0), "{why}");
707        }
708    }
709
710    #[test]
711    fn on_a_guarded_machine_a_check_that_cannot_run_refuses_and_a_private_repository_is_not_read() {
712        let url = "https://github.com/o/r.git";
713        assert_eq!(check(true, url, vec![Answer::Unavailable("down".into())]), (1, 1));
714        assert_eq!(check(true, url, vec![Answer::NotNeeded]), (0, 1));
715        assert_eq!(check(true, url, vec![Answer::Judged { public: false, code: 0, lines: vec![] }]), (0, 1));
716        let public = || Answer::Judged { public: true, code: 0, lines: vec![] };
717        assert_eq!(check(true, url, vec![public(), Answer::Judged { public: true, code: 0, lines: vec![] }]), (0, 2));
718        assert_eq!(check(true, url, vec![public(), Answer::Judged { public: true, code: 1, lines: vec!["no".into()] }]), (1, 2));
719        assert_eq!(check(true, url, vec![public(), Answer::Unavailable("timed out".into())]), (1, 2));
720        // not a github.com remote: nothing to ask
721        assert_eq!(check(true, "https://gitlab.com/o/r.git", vec![]), (0, 0));
722    }
723
724    #[test]
725    fn an_agentmux_older_than_the_check_lets_the_push_go_and_says_so_without_asking() {
726        assert_eq!(check_guard(Guard::OlderAgentMux, "https://github.com/o/r.git", vec![]), (0, 0));
727    }
728
729    #[test]
730    fn a_gh_agent_too_old_to_judge_a_container_push_refuses_a_github_push_without_asking() {
731        assert_eq!(check_guard(Guard::OlderGhAgent, "https://github.com/o/r.git", vec![]), (1, 0));
732        // Nothing to refuse for a remote that is not GitHub's.
733        assert_eq!(check_guard(Guard::OlderGhAgent, "https://gitlab.com/o/r.git", vec![]), (0, 0));
734    }
735
736    #[test]
737    fn a_route_the_host_lacks_while_it_says_it_has_the_guard_refuses_the_push() {
738        for status in [404, 405] {
739            assert_eq!(read_answer(status, &Value::Null), Answer::NoRoute, "{status}");
740        }
741        let url = "https://github.com/o/r.git";
742        assert_eq!(check(true, url, vec![Answer::NoRoute]), (1, 1), "the first question");
743        let public = || Answer::Judged { public: true, code: 0, lines: vec![] };
744        assert_eq!(check(true, url, vec![public(), Answer::NoRoute]), (1, 2), "the scan itself");
745    }
746
747    #[test]
748    fn the_marker_values_are_read_as_srv_says_them() {
749        let read = |value: Option<&str>| {
750            let was = std::env::var("AGENTMUX_PUBLISH_GUARD").ok();
751            let was_in = std::env::var("AGENTMUX_IN_CONTAINER").ok();
752            std::env::set_var("AGENTMUX_IN_CONTAINER", "1");
753            match value {
754                Some(v) => std::env::set_var("AGENTMUX_PUBLISH_GUARD", v),
755                None => std::env::remove_var("AGENTMUX_PUBLISH_GUARD"),
756            }
757            let guard = guard_here();
758            for (name, old) in [("AGENTMUX_PUBLISH_GUARD", was), ("AGENTMUX_IN_CONTAINER", was_in)] {
759                match old {
760                    Some(v) => std::env::set_var(name, v),
761                    None => std::env::remove_var(name),
762                }
763            }
764            guard
765        };
766        assert_eq!(read(Some("1")), Guard::Scan);
767        assert_eq!(read(Some("0")), Guard::Nothing);
768        assert_eq!(read(Some("older-gh-agent")), Guard::OlderGhAgent);
769        assert_eq!(read(None), Guard::OlderAgentMux);
770        assert_eq!(read(Some("anything else")), Guard::OlderAgentMux);
771    }
772}