1use 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
32pub(crate) const MAX_BODY_BYTES: usize = 17 * 1024 * 1024;
34const 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;
41const RATE_LIMIT: usize = 12;
43const RATE_WINDOW: Duration = Duration::from_secs(60);
44const MAX_RUNNING: usize = 2;
46
47#[derive(Debug, Deserialize, Serialize)]
49#[serde(deny_unknown_fields)]
50pub(crate) struct PushScanRequest {
51 repo: String,
53 allow_new_docs: bool,
55 parts: Vec<Part>,
57}
58
59#[derive(Debug, Deserialize, Serialize)]
60#[serde(deny_unknown_fields)]
61struct Part {
62 r#ref: String,
63 #[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
90fn 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
95fn 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
103fn 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
108pub(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
148struct 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 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
183fn no_guard() -> Response {
185 Json(json!({ "guard": "none", "code": 0, "lines": [] })).into_response()
186}
187
188pub(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 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 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 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}