Skip to main content

agentmux_srv/server/app_api/
push_scan.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/github/push-scan`: a container agent's push, judged by the host's publish guard.
5//!
6//! A container's `pre-push` hook (`agentmux-bashwrap git-hook pre-push`) collects what the push publishes with the
7//! container's own git (per ref: the commits' messages, the added paths and the added lines) and posts it here as
8//! data. srv gives it, on stdin, to the host's `gh-agent scan-push --repo OWNER/REPO` and answers with its verdict.
9//!
10//! The material is data: nothing here opens the container's clone or runs git in it, and the request carries no path.
11//! Whether the repository is public is decided by `gh-agent` asking GitHub about the `owner/repo`, never by a flag in
12//! the request.
13//!
14//! Callable with a container agent's own token only. Every field is checked and capped before anything runs; the
15//! checks are the pure functions below.
16
17use std::collections::{HashMap, VecDeque};
18use std::sync::{Mutex, OnceLock};
19use std::time::{Duration, Instant};
20
21use axum::extract::{Extension, State};
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Response};
24use axum::Json;
25use serde::{Deserialize, Serialize};
26use serde_json::json;
27
28use super::AppState;
29use crate::identity::gh_agent_token::{self, ScanOutcome};
30use crate::server::caller::Caller;
31
32/// The most a request may carry, in bytes. The route's body limit is this.
33pub(crate) const MAX_BODY_BYTES: usize = 17 * 1024 * 1024;
34/// The most the pushed material may weigh once read; a bigger push is refused with what to do about it.
35const MAX_MATERIAL_BYTES: usize = 16 * 1024 * 1024;
36const MAX_PARTS: usize = 64;
37const MAX_FIELD_BYTES: usize = 8 * 1024 * 1024;
38const MAX_CHANGESETS: usize = 100;
39const MAX_CHANGESET_BYTES: usize = 64 * 1024;
40const MAX_REF_BYTES: usize = 512;
41/// Pushes one agent may ask to have judged in a window, and the window.
42const RATE_LIMIT: usize = 12;
43const RATE_WINDOW: Duration = Duration::from_secs(60);
44/// Judgements running at once on this machine.
45const MAX_RUNNING: usize = 2;
46
47/// What the container sends: one push, the same for every ref it updates.
48#[derive(Debug, Deserialize, Serialize)]
49#[serde(deny_unknown_fields)]
50pub(crate) struct PushScanRequest {
51    /// `owner/repo`.
52    repo: String,
53    /// The agent set `GH_AGENT_ALLOW_NEW_DOCS=1`; the guard records the use like any other.
54    allow_new_docs: bool,
55    /// Empty asks only whether this machine has a publish guard to run.
56    parts: Vec<Part>,
57}
58
59#[derive(Debug, Deserialize, Serialize)]
60#[serde(deny_unknown_fields)]
61struct Part {
62    r#ref: String,
63    /// The ref the push updates on the remote and whether the remote has none yet, for gh-agent's check of a name that
64    /// becomes public with the push. Both are optional: material that omits them is judged as before.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    remote_ref: Option<String>,
67    #[serde(default)]
68    new_ref: bool,
69    count: u64,
70    remote_named: bool,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    tag_message: Option<String>,
73    #[serde(default)]
74    messages: String,
75    #[serde(default)]
76    name_status: String,
77    #[serde(default)]
78    patch: String,
79    #[serde(default)]
80    changesets: Vec<Changeset>,
81}
82
83#[derive(Debug, Deserialize, Serialize)]
84#[serde(deny_unknown_fields)]
85struct Changeset {
86    path: String,
87    text: String,
88}
89
90/// A GitHub account or repository name: nothing that could be read as an option or a path.
91fn is_name(s: &str) -> bool {
92    !s.is_empty() && s.len() <= 100 && !s.starts_with(['-', '.']) && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
93}
94
95/// `owner/repo` in lowercase, or why the request names no repository.
96fn repo_slug(repo: &str) -> Result<String, String> {
97    match repo.split_once('/') {
98        Some((owner, name)) if is_name(owner) && is_name(name) => Ok(format!("{owner}/{name}").to_ascii_lowercase()),
99        _ => Err("repo is not owner/repo".to_string()),
100    }
101}
102
103/// A ref name as git writes one: printable, no control characters, a bounded length.
104fn is_ref(s: &str) -> bool {
105    !s.is_empty() && s.len() <= MAX_REF_BYTES && s.bytes().all(|b| (0x20..0x7f).contains(&b) || b >= 0x80)
106}
107
108/// Every field of the request checked and capped, or the first thing wrong with it.
109pub(crate) fn validate(req: &PushScanRequest) -> Result<String, String> {
110    let slug = repo_slug(&req.repo)?;
111    if req.parts.len() > MAX_PARTS {
112        return Err(format!("more than {MAX_PARTS} refs in one push"));
113    }
114    let mut total = 0usize;
115    for (i, p) in req.parts.iter().enumerate() {
116        if !is_ref(&p.r#ref) {
117            return Err(format!("part {i}: the ref is not a ref name"));
118        }
119        if p.remote_ref.as_deref().is_some_and(|r| !is_ref(r)) {
120            return Err(format!("part {i}: the remote ref is not a ref name"));
121        }
122        if p.count > 10_000_000 {
123            return Err(format!("part {i}: count is out of range"));
124        }
125        let fields = [p.tag_message.as_deref().unwrap_or(""), &p.messages, &p.name_status, &p.patch];
126        for f in fields {
127            if f.len() > MAX_FIELD_BYTES {
128                return Err(format!("part {i}: a field is over {MAX_FIELD_BYTES} bytes"));
129            }
130            total += f.len();
131        }
132        if p.changesets.len() > MAX_CHANGESETS {
133            return Err(format!("part {i}: more than {MAX_CHANGESETS} changesets"));
134        }
135        for c in &p.changesets {
136            if c.path.len() > 1024 || c.text.len() > MAX_CHANGESET_BYTES {
137                return Err(format!("part {i}: a changeset is too large"));
138            }
139            total += c.path.len() + c.text.len();
140        }
141    }
142    if total > MAX_MATERIAL_BYTES {
143        return Err(format!("the push is over {MAX_MATERIAL_BYTES} bytes to check: split it into smaller pushes"));
144    }
145    Ok(slug)
146}
147
148/// A sliding window per agent.
149struct Limiter {
150    seen: Mutex<HashMap<String, VecDeque<Instant>>>,
151}
152
153impl Limiter {
154    fn new() -> Self {
155        Self { seen: Mutex::new(HashMap::new()) }
156    }
157
158    /// Whether `who` may ask now (and counts it if so).
159    fn allow(&self, who: &str, now: Instant) -> bool {
160        let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
161        let q = seen.entry(who.to_string()).or_default();
162        while q.front().is_some_and(|t| now.duration_since(*t) >= RATE_WINDOW) {
163            q.pop_front();
164        }
165        if q.len() >= RATE_LIMIT {
166            return false;
167        }
168        q.push_back(now);
169        true
170    }
171}
172
173fn limiter() -> &'static Limiter {
174    static LIMITER: OnceLock<Limiter> = OnceLock::new();
175    LIMITER.get_or_init(Limiter::new)
176}
177
178fn running() -> &'static tokio::sync::Semaphore {
179    static RUNNING: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
180    RUNNING.get_or_init(|| tokio::sync::Semaphore::new(MAX_RUNNING))
181}
182
183/// The answer when there is no guard to run here: the hook does nothing and says nothing.
184fn no_guard() -> Response {
185    Json(json!({ "guard": "none", "code": 0, "lines": [] })).into_response()
186}
187
188/// `POST /api/v1/github/push-scan`
189pub(crate) async fn handle_push_scan(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<PushScanRequest>) -> Response {
190    let refuse = |status: StatusCode, message: String| (status, Json(json!({ "error": message }))).into_response();
191    // A machine with no gh-agent has no publish guard to run: first of all, before the rate limit, the request's
192    // validity or the agent lookup can refuse anything, the answer is that there is nothing to do.
193    if gh_agent_token::installed().is_none() {
194        return no_guard();
195    }
196    let Some(uid) = caller.as_ref().and_then(|Extension(c)| c.uid()).map(str::to_string) else {
197        return refuse(StatusCode::UNAUTHORIZED, "no agent token: a push is judged for an agent's own commands".to_string());
198    };
199    let mstore = state.mstore.clone();
200    let (slug_of_agent, in_container) = match tokio::task::spawn_blocking(move || mstore.agent_def_get(&uid)).await {
201        Ok(Ok(Some(def))) => {
202            let in_container = def.runtime().is_container();
203            (def.slug, in_container)
204        }
205        Ok(Ok(None)) => return refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine".to_string()),
206        _ => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "couldn't read the agent".to_string()),
207    };
208    // A native agent's own pre-push hook runs the guard in its clone; this route is for what runs in a container.
209    if !in_container {
210        return no_guard();
211    }
212    let repo = match validate(&req) {
213        Ok(repo) => repo,
214        Err(why) => return refuse(StatusCode::BAD_REQUEST, why),
215    };
216    if !limiter().allow(&slug_of_agent, Instant::now()) {
217        return refuse(StatusCode::TOO_MANY_REQUESTS, format!("too many pushes to check in a minute (at most {RATE_LIMIT}): wait a minute and push again"));
218    }
219    let Ok(_slot) = running().try_acquire() else {
220        return refuse(StatusCode::TOO_MANY_REQUESTS, "other pushes are being checked on this machine: try again in a moment".to_string());
221    };
222    let material = match serde_json::to_vec(&req) {
223        Ok(m) => m,
224        Err(e) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't prepare the push: {e}")),
225    };
226    match gh_agent_token::scan_push(&slug_of_agent, &repo, &material).await {
227        ScanOutcome::Judged { code, lines, public } => Json(json!({ "guard": "gh-agent", "code": code, "lines": lines, "public": public })).into_response(),
228        ScanOutcome::Failed(why) => {
229            tracing::warn!(target: "identity", agent = %slug_of_agent, repo = %repo, error = %why, "identity.github: the publish guard couldn't judge a container agent's push");
230            refuse(StatusCode::SERVICE_UNAVAILABLE, why)
231        }
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn part() -> Part {
240        Part { r#ref: "refs/heads/x".into(), remote_ref: None, new_ref: false, count: 1, remote_named: true, tag_message: None, messages: String::new(), name_status: String::new(), patch: String::new(), changesets: vec![] }
241    }
242
243    fn request(repo: &str, parts: Vec<Part>) -> PushScanRequest {
244        PushScanRequest { repo: repo.into(), allow_new_docs: false, parts }
245    }
246
247    #[test]
248    fn a_repository_is_owner_slash_name_in_a_safe_charset_and_comes_back_lowercase() {
249        assert_eq!(validate(&request("AgentMuxAI/Agentmux", vec![part()])).unwrap(), "agentmuxai/agentmux");
250        for bad in ["", "agentmuxai", "a/b/c", "a b/c", "a/b;rm -rf", "../x/y", "-x/y", "a/.hidden", "a/b\n", "a/b c", &format!("{}/y", "o".repeat(101))] {
251            assert!(validate(&request(bad, vec![])).is_err(), "{bad:?}");
252        }
253    }
254
255    #[test]
256    fn a_ref_is_printable_and_bounded() {
257        for bad in ["", "refs/heads/a\nb", "refs/heads/a\0b", &"r".repeat(MAX_REF_BYTES + 1)] {
258            let mut p = part();
259            p.r#ref = bad.to_string();
260            assert!(validate(&request("a/b", vec![p])).is_err(), "{bad:?}");
261        }
262        let mut p = part();
263        p.r#ref = "refs/heads/feature/é-ü".into();
264        assert!(validate(&request("a/b", vec![p])).is_ok());
265    }
266
267    #[test]
268    fn counts_sizes_and_numbers_of_things_are_capped() {
269        let mut p = part();
270        p.count = 10_000_001;
271        assert!(validate(&request("a/b", vec![p])).is_err());
272        assert!(validate(&request("a/b", (0..=MAX_PARTS).map(|_| part()).collect())).is_err());
273        let mut p = part();
274        p.patch = "x".repeat(MAX_FIELD_BYTES + 1);
275        assert!(validate(&request("a/b", vec![p])).is_err());
276        let mut p = part();
277        p.changesets = (0..=MAX_CHANGESETS).map(|_| Changeset { path: "p".into(), text: "t".into() }).collect();
278        assert!(validate(&request("a/b", vec![p])).is_err());
279        let mut p = part();
280        p.changesets = vec![Changeset { path: "p".into(), text: "t".repeat(MAX_CHANGESET_BYTES + 1) }];
281        assert!(validate(&request("a/b", vec![p])).is_err());
282    }
283
284    #[test]
285    fn a_push_over_the_total_is_refused_with_what_to_do() {
286        let big = |n: usize| {
287            let mut p = part();
288            p.patch = "x".repeat(n);
289            p
290        };
291        let parts = vec![big(MAX_FIELD_BYTES), big(MAX_FIELD_BYTES), big(10)];
292        let why = validate(&request("a/b", parts)).unwrap_err();
293        assert!(why.contains("split it into smaller pushes"), "{why}");
294    }
295
296    #[test]
297    fn the_remote_ref_and_whether_it_is_new_are_checked_and_passed_on() {
298        let json = r#"{"repo":"a/b","allow_new_docs":false,"parts":[{"ref":"refs/heads/x","remote_ref":"refs/heads/new","new_ref":true,"count":1,"remote_named":true}]}"#;
299        let req: PushScanRequest = serde_json::from_str(json).unwrap();
300        assert!(validate(&req).is_ok());
301        let again: serde_json::Value = serde_json::from_slice(&serde_json::to_vec(&req).unwrap()).unwrap();
302        assert_eq!(again["parts"][0]["remote_ref"], "refs/heads/new");
303        assert_eq!(again["parts"][0]["new_ref"], true);
304        // Material without them is read as before, and a remote ref that is not a ref name is refused.
305        let old = r#"{"repo":"a/b","allow_new_docs":false,"parts":[{"ref":"refs/heads/x","count":1,"remote_named":true}]}"#;
306        let old: PushScanRequest = serde_json::from_str(old).unwrap();
307        assert!(validate(&old).is_ok());
308        let mut bad = req;
309        bad.parts[0].remote_ref = Some("refs/heads/\u{1}x".into());
310        assert!(validate(&bad).is_err());
311        bad.parts[0].remote_ref = Some(String::new());
312        assert!(validate(&bad).is_err());
313    }
314
315    #[test]
316    fn a_field_the_request_does_not_know_is_refused_rather_than_passed_on() {
317        let with_extra = r#"{"repo":"a/b","allow_new_docs":false,"parts":[],"cwd":"/workspace/x"}"#;
318        assert!(serde_json::from_str::<PushScanRequest>(with_extra).is_err());
319        let part_extra = r#"{"repo":"a/b","allow_new_docs":false,"parts":[{"ref":"r","count":1,"remote_named":true,"is_public":false}]}"#;
320        assert!(serde_json::from_str::<PushScanRequest>(part_extra).is_err());
321        let ok = r#"{"repo":"a/b","allow_new_docs":true,"parts":[{"ref":"refs/heads/x","count":1,"remote_named":true}]}"#;
322        assert!(serde_json::from_str::<PushScanRequest>(ok).is_ok());
323    }
324
325    #[test]
326    fn what_is_forwarded_is_what_was_read_and_nothing_else() {
327        let ok = r#"{"repo":"a/b","allow_new_docs":true,"parts":[{"ref":"refs/heads/x","count":2,"remote_named":false,"patch":"p","changesets":[{"path":".changesets/a.md","text":"t"}]}]}"#;
328        let req: PushScanRequest = serde_json::from_str(ok).unwrap();
329        let again: serde_json::Value = serde_json::from_slice(&serde_json::to_vec(&req).unwrap()).unwrap();
330        assert_eq!(again["parts"][0]["changesets"][0]["path"], ".changesets/a.md");
331        assert_eq!(again["parts"][0]["count"], 2);
332        assert!(again["parts"][0].get("tag_message").is_none());
333        assert_eq!(again.as_object().unwrap().len(), 3);
334    }
335
336    #[test]
337    fn an_agent_may_ask_a_dozen_times_a_minute_and_each_agent_has_its_own_count() {
338        let l = Limiter::new();
339        let t0 = Instant::now();
340        for _ in 0..RATE_LIMIT {
341            assert!(l.allow("aria", t0));
342        }
343        assert!(!l.allow("aria", t0));
344        assert!(l.allow("other", t0), "another agent is not held back");
345        assert!(l.allow("aria", t0 + RATE_WINDOW), "the window moves on");
346    }
347}