1use std::io::{Read, Write};
17use std::path::{Path, PathBuf};
18use std::process::{Command, Stdio};
19
20use agentmux_common::win32::NoWindow;
21
22use crate::github::Granted;
23use crate::secret_scan::{refusal_text, scan_diff, Finding};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum Plan {
28 Plain,
30 Push,
32 Commit { cwd: Option<String> },
34}
35
36const COMMIT_COMMANDS: &[&str] = &["commit", "merge", "rebase", "cherry-pick", "am", "revert", "pull", "stash"];
38
39pub fn plan_for(args: &[String]) -> Result<Plan, String> {
41 let mut cwd = None;
42 let mut own_hooks_path = false;
43 let mut i = 0;
44 while i < args.len() {
45 let a = args[i].as_str();
46 let hooks_key = |kv: &str| kv.to_ascii_lowercase().contains("core.hookspath");
47 match a {
48 "-c" | "--config-env" => {
49 own_hooks_path |= args.get(i + 1).is_some_and(|kv| hooks_key(kv));
50 i += 2;
51 }
52 "-C" => {
53 cwd = args.get(i + 1).cloned();
54 i += 2;
55 }
56 "--git-dir" | "--work-tree" | "--namespace" | "--super-prefix" => i += 2,
57 _ if a.starts_with("--config-env=") => {
58 own_hooks_path |= hooks_key(a);
59 i += 1;
60 }
61 _ if a.starts_with('-') => i += 1,
62 _ => break,
63 }
64 }
65 let Some(sub) = args.get(i).map(String::as_str) else { return Ok(Plan::Plain) };
66 let rest = &args[i + 1..];
67 if sub == "push" || COMMIT_COMMANDS.contains(&sub) {
68 if own_hooks_path {
69 return Err("agentmux: git -c core.hooksPath is not allowed for agents: AgentMux's hooks have to run".to_string());
70 }
71 }
72 if sub == "push" {
73 if rest.iter().any(|a| is_no_verify(a)) {
74 return Err("agentmux: git push --no-verify is not allowed for agents: the push scan has to run".to_string());
75 }
76 return Ok(Plan::Push);
77 }
78 if COMMIT_COMMANDS.contains(&sub) {
79 return Ok(Plan::Commit { cwd });
80 }
81 Ok(Plan::Plain)
82}
83
84fn is_no_verify(arg: &str) -> bool {
87 let name = arg.split('=').next().unwrap_or(arg);
88 name.len() >= "--no-v".len() && "--no-verify".starts_with(name)
89}
90
91pub fn commit_env(granted: &Granted) -> Vec<(String, String)> {
95 let mut env = Vec::new();
96 if let (Some(slug), Some(bot_id)) = (granted.bot_slug.as_deref(), granted.bot_user_id) {
97 let name = format!("{slug}[bot]");
98 let email = format!("{bot_id}+{slug}[bot]@users.noreply.github.com");
99 env.extend([
100 ("GIT_AUTHOR_NAME".to_string(), name.clone()),
101 ("GIT_AUTHOR_EMAIL".to_string(), email.clone()),
102 ("GIT_COMMITTER_NAME".to_string(), name),
103 ("GIT_COMMITTER_EMAIL".to_string(), email),
104 ]);
105 }
106 if let (Some(id), Some(login)) = (granted.owner_github_id, granted.owner_login.as_deref()) {
107 env.push((OWNER_ID_ENV.to_string(), id.to_string()));
108 env.push((OWNER_LOGIN_ENV.to_string(), login.to_string()));
109 }
110 env
111}
112
113const OWNER_ID_ENV: &str = "AGENTMUX_OWNER_GITHUB_ID";
115const OWNER_LOGIN_ENV: &str = "AGENTMUX_OWNER_GITHUB_LOGIN";
116pub const GIT_HOST_ENV: &str = "AGENTMUX_GIT_HOST";
118
119pub fn run_git_env(args: &[String]) -> i32 {
121 match plan_for(args) {
122 Err(message) => {
123 eprintln!("{message}");
124 1
125 }
126 Ok(Plan::Commit { cwd }) => {
127 let source = crate::github::default_repo_source(cwd.as_deref());
128 if let Some((owner, repo)) = source.as_deref().and_then(crate::github::repo_of_default) {
129 if let crate::github::Answer::Token(granted) = crate::github::ask(&owner, &repo) {
130 for (k, v) in commit_env(&granted) {
131 println!("{k}={v}");
132 }
133 }
134 }
135 0
136 }
137 Ok(_) => 0,
138 }
139}
140
141fn git_output(args: &[&str]) -> Option<String> {
142 let mut cmd = Command::new("git");
143 cmd.args(args).stdin(Stdio::null()).stderr(Stdio::null());
144 cmd.no_window();
146 let out = cmd.output().ok()?;
147 out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
148}
149
150fn configured_hooks_dir() -> Option<PathBuf> {
155 hooks_dir_from(&git_output(&["config", "--type=path", "--show-scope", "--get-regexp", r"^core\.hookspath$"])?)
156}
157
158fn hooks_dir_from(listing: &str) -> Option<PathBuf> {
161 listing
162 .lines()
163 .filter_map(|line| {
164 let (scope, rest) = line.split_once('\t')?;
165 let (_, value) = rest.split_once(' ')?;
166 (scope != "command" && !value.is_empty() && !value.ends_with(AGENTMUX_HOOKS_DIR)).then(|| PathBuf::from(value))
167 })
168 .last()
169}
170
171pub const AGENTMUX_HOOKS_DIR: &str = "github-hooks";
173
174fn repo_own_hook(name: &str) -> Option<PathBuf> {
177 let dir = configured_hooks_dir().or_else(|| git_output(&["rev-parse", "--git-common-dir"]).map(|d| Path::new(&d).join("hooks")))?;
178 let hook = dir.join(name);
179 (hook.is_file() && is_executable(&hook)).then_some(hook)
180}
181
182fn is_executable(path: &Path) -> bool {
184 #[cfg(unix)]
185 {
186 use std::os::unix::fs::PermissionsExt;
187 std::fs::metadata(path).map(|m| m.permissions().mode() & 0o111 != 0).unwrap_or(false)
188 }
189 #[cfg(not(unix))]
190 {
191 let _ = path;
192 true
193 }
194}
195
196fn run_script(path: &Path, args: &[String], stdin: &[u8]) -> i32 {
197 let mut cmd = if cfg!(windows) {
198 let mut c = Command::new("sh");
200 c.arg(path.to_string_lossy().replace('\\', "/"));
201 c
202 } else {
203 Command::new(path)
204 };
205 cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::inherit()).stderr(Stdio::inherit());
206 cmd.no_window();
207 let Ok(mut child) = cmd.spawn() else {
208 eprintln!("agentmux: couldn't run the repository's {} hook", path.display());
209 return 1;
210 };
211 if let Some(mut input) = child.stdin.take() {
212 let _ = input.write_all(stdin);
213 }
214 child.wait().ok().and_then(|s| s.code()).unwrap_or(1)
215}
216
217fn push_diff(dir: Option<&Path>, remote: &str, local: &str, remote_sha: &str) -> Option<String> {
219 let log = |range: Vec<String>| {
220 let mut cmd = Command::new("git");
221 if let Some(dir) = dir {
222 cmd.current_dir(dir);
223 }
224 cmd.args(["log", "--format=", "-p", "--cc", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", "--text"]).args(range).stdin(Stdio::null()).stderr(Stdio::null());
228 cmd.no_window();
229 cmd.output().ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
230 };
231 let is_name = !remote.is_empty() && !remote.contains([':', '/', '\\']);
232 let whole_branch = || {
233 if is_name {
236 log(vec![local.to_string(), "--not".to_string(), format!("--remotes={remote}")])
237 } else {
238 log(vec![local.to_string()])
239 }
240 };
241 if remote_sha.chars().all(|c| c == '0') {
242 return whole_branch();
243 }
244 log(vec![format!("{remote_sha}..{local}")]).or_else(whole_branch)
246}
247
248fn pre_push(args: &[String]) -> i32 {
250 let mut input = Vec::new();
251 let _ = std::io::stdin().read_to_end(&mut input);
252 if let Some(own) = repo_own_hook("pre-push") {
253 let code = run_script(&own, args, &input);
254 if code != 0 {
255 return code;
256 }
257 }
258 let remote = args.first().map(String::as_str).unwrap_or("");
259 let mut findings: Vec<Finding> = Vec::new();
260 for line in String::from_utf8_lossy(&input).lines() {
261 let mut f = line.split_whitespace();
262 let (Some(_), Some(local), Some(_), Some(remote_sha)) = (f.next(), f.next(), f.next(), f.next()) else { continue };
263 if local.chars().all(|c| c == '0') {
265 continue;
266 }
267 let Some(diff) = push_diff(None, remote, local, remote_sha) else {
269 eprintln!("agentmux: this push is refused: git couldn't list what it adds, so it can't be scanned.");
270 return 1;
271 };
272 for found in scan_diff(&diff) {
273 if !findings.contains(&found) {
274 findings.push(found);
275 }
276 }
277 }
278 if findings.is_empty() {
279 return crate::publish_scan::check_push(remote, args.get(1).map(String::as_str).unwrap_or(""), &String::from_utf8_lossy(&input));
281 }
282 eprint!("{}", refusal_text(&findings));
283 1
284}
285
286pub fn trailers(agent: Option<&str>, host: Option<&str>, owner_id: Option<&str>, owner_login: Option<&str>) -> Vec<String> {
288 let mut out = Vec::new();
289 if let Some(agent) = agent.filter(|a| !a.is_empty()) {
290 match host.filter(|h| !h.is_empty()) {
292 Some(host) => out.push(format!("Agent: {}@{}", agent.to_ascii_lowercase(), host.to_ascii_lowercase())),
293 None => out.push(format!("Agent: {}", agent.to_ascii_lowercase())),
294 }
295 }
296 if let (Some(id), Some(login)) = (owner_id.filter(|v| !v.is_empty()), owner_login.filter(|v| !v.is_empty())) {
297 out.push(format!("Co-authored-by: {login} <{id}+{login}@users.noreply.github.com>"));
298 }
299 out
300}
301
302fn prepare_commit_msg(args: &[String]) -> i32 {
304 if let Some(own) = repo_own_hook("prepare-commit-msg") {
305 let code = run_script(&own, args, &[]);
306 if code != 0 {
307 return code;
308 }
309 }
310 let Some(file) = args.first() else { return 0 };
311 let env = |k: &str| std::env::var(k).ok();
312 let lines = trailers(
313 env("AGENTMUX_AGENT_ID").as_deref(),
314 env(GIT_HOST_ENV).as_deref(),
315 env(OWNER_ID_ENV).as_deref(),
316 env(OWNER_LOGIN_ENV).as_deref(),
317 );
318 if lines.is_empty() {
319 return 0;
320 }
321 let mut cmd = Command::new("git");
322 cmd.args(["interpret-trailers", "--in-place", "--if-exists", "addIfDifferent"]);
323 for line in &lines {
324 cmd.arg("--trailer").arg(line);
325 }
326 cmd.arg(file).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
327 cmd.no_window();
328 let _ = cmd.status();
330 0
331}
332
333fn forward_to_repo_hook(name: &str, args: &[String]) -> i32 {
336 let Some(own) = repo_own_hook(name) else { return 0 };
337 let mut cmd = if cfg!(windows) {
338 let mut c = Command::new("sh");
339 c.arg(own.to_string_lossy().replace('\\', "/"));
340 c
341 } else {
342 Command::new(&own)
343 };
344 cmd.args(args).stdin(Stdio::inherit()).stdout(Stdio::inherit()).stderr(Stdio::inherit());
345 cmd.no_window();
346 match cmd.status() {
347 Ok(status) => status.code().unwrap_or(1),
348 Err(_) => {
349 eprintln!("agentmux: couldn't run the repository's {name} hook");
350 1
351 }
352 }
353}
354
355pub fn run_git_hook(name: &str, args: &[String]) -> i32 {
357 match name {
358 "pre-push" => pre_push(args),
359 "prepare-commit-msg" => prepare_commit_msg(args),
360 other => forward_to_repo_hook(other, args),
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 fn args(a: &[&str]) -> Vec<String> {
369 a.iter().map(|s| s.to_string()).collect()
370 }
371
372 #[test]
373 fn a_push_may_not_skip_the_hooks_and_a_commit_may_not_replace_them() {
374 assert_eq!(plan_for(&args(&["push", "origin", "main"])), Ok(Plan::Push));
375 assert!(plan_for(&args(&["push", "--no-verify"])).unwrap_err().contains("--no-verify"));
376 assert!(plan_for(&args(&["-C", "repo", "push", "origin", "--no-verify=1"])).is_err());
377 for a in ["--no-verif", "--no-ver", "--no-v"] {
379 assert!(plan_for(&args(&["push", a])).is_err(), "{a}");
380 }
381 for a in ["--no-thin", "--no-force-with-lease", "--no-", "--verify"] {
383 assert_eq!(plan_for(&args(&["push", a])), Ok(Plan::Push), "{a}");
384 }
385 assert!(plan_for(&args(&["-c", "core.hooksPath=/dev/null", "push"])).unwrap_err().contains("core.hooksPath"));
386 assert!(plan_for(&args(&["-c", "Core.HooksPath=x", "commit", "-m", "x"])).is_err());
387 assert!(plan_for(&args(&["--git-dir", "x", "push", "--no-verify"])).is_err());
389 assert_eq!(plan_for(&args(&["commit", "-m", "push --no-verify is refused"])), Ok(Plan::Commit { cwd: None }));
391 }
392
393 #[test]
394 fn what_makes_commits_is_told_where_it_runs_and_the_rest_is_left_alone() {
395 assert_eq!(plan_for(&args(&["-C", "work", "commit", "-am", "x"])), Ok(Plan::Commit { cwd: Some("work".into()) }));
396 for sub in ["merge", "rebase", "cherry-pick", "am", "revert", "pull", "stash"] {
397 assert!(matches!(plan_for(&args(&[sub])), Ok(Plan::Commit { .. })), "{sub}");
398 }
399 assert_eq!(plan_for(&args(&["status"])), Ok(Plan::Plain));
400 assert_eq!(plan_for(&args(&["-c", "user.name=x", "log"])), Ok(Plan::Plain));
401 assert_eq!(plan_for(&args(&[])), Ok(Plan::Plain));
402 }
403
404 #[test]
405 fn the_bot_is_author_and_committer_and_the_owner_rides_along_for_the_trailer() {
406 let granted = Granted {
407 token: "t".into(),
408 owner_github_id: Some(42),
409 owner_login: Some("octo".into()),
410 bot_slug: Some("muxagent".into()),
411 bot_user_id: Some(77),
412 };
413 let env: std::collections::HashMap<_, _> = commit_env(&granted).into_iter().collect();
414 assert_eq!(env["GIT_AUTHOR_NAME"], "muxagent[bot]");
415 assert_eq!(env["GIT_COMMITTER_EMAIL"], "77+muxagent[bot]@users.noreply.github.com");
416 assert_eq!((env[OWNER_ID_ENV].as_str(), env[OWNER_LOGIN_ENV].as_str()), ("42", "octo"));
417 let no_bot: std::collections::HashMap<_, _> = commit_env(&Granted { bot_user_id: None, ..granted.clone() }).into_iter().collect();
419 assert!(!no_bot.contains_key("GIT_AUTHOR_NAME"));
420 assert_eq!((no_bot[OWNER_ID_ENV].as_str(), no_bot[OWNER_LOGIN_ENV].as_str()), ("42", "octo"));
421 assert!(commit_env(&Granted { bot_slug: None, owner_github_id: None, ..granted }).is_empty());
423 }
424
425 fn git(dir: &Path, args: &[&str]) -> String {
426 let mut cmd = Command::new("git");
427 cmd.current_dir(dir).args(["-c", "user.name=t", "-c", "user.email=t@example.com"]).args(args);
428 cmd.no_window();
429 let out = cmd.output().unwrap();
430 assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
431 String::from_utf8_lossy(&out.stdout).trim().to_string()
432 }
433
434 #[test]
436 fn a_push_is_scanned_for_what_it_adds_and_not_for_what_the_remote_has() {
437 let dir = std::env::temp_dir().join(format!("amx-push-scan-{}", std::process::id()));
438 let _ = std::fs::remove_dir_all(&dir);
439 std::fs::create_dir_all(&dir).unwrap();
440 let repo = dir.as_path();
441 git(repo, &["init", "-q", "-b", "main"]);
442 std::fs::write(repo.join("a.txt"), "hello
443").unwrap();
444 git(repo, &["add", "."]);
445 git(repo, &["commit", "-q", "-m", "one"]);
446 let first = git(repo, &["rev-parse", "HEAD"]);
447 let token = format!("{}{}", "ghp_", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8");
448 std::fs::write(repo.join("a.txt"), format!("hello
449key = {token}
450")).unwrap();
451 git(repo, &["commit", "-q", "-am", "two"]);
452 let second = git(repo, &["rev-parse", "HEAD"]);
453 let zeros = "0".repeat(40);
454 let found = scan_diff(&push_diff(Some(repo), "origin", &second, &zeros).unwrap());
456 assert_eq!(found.len(), 1);
457 assert_eq!((found[0].file.as_str(), found[0].line, found[0].category), ("a.txt", 2, "GitHub token"));
458 let found = scan_diff(&push_diff(Some(repo), "origin", &second, &first).unwrap());
460 assert_eq!((found[0].file.as_str(), found[0].line), ("a.txt", 2));
461 assert!(scan_diff(&push_diff(Some(repo), "origin", &second, &second).unwrap()).is_empty());
463 git(repo, &["update-ref", "refs/remotes/origin/main", &second]);
466 assert!(scan_diff(&push_diff(Some(repo), "origin", &second, &zeros).unwrap()).is_empty());
467 let by_url = push_diff(Some(repo), "https://example.com/x/y.git", &second, &zeros).unwrap();
468 assert_eq!(scan_diff(&by_url).len(), 1, "a push by URL is not excused by other remotes' history");
469 assert!(push_diff(Some(&dir.join("nowhere")), "origin", &second, &first).is_none());
471 let _ = std::fs::remove_dir_all(&dir);
472 }
473
474 #[test]
476 fn a_credential_added_only_by_a_merge_commit_is_found() {
477 let dir = std::env::temp_dir().join(format!("amx-merge-scan-{}", std::process::id()));
478 let _ = std::fs::remove_dir_all(&dir);
479 std::fs::create_dir_all(&dir).unwrap();
480 let repo = dir.as_path();
481 let write = |text: &str| std::fs::write(repo.join("a.txt"), format!("{text}\n")).unwrap();
482 git(repo, &["init", "-q", "-b", "main"]);
483 write("base");
484 git(repo, &["add", "."]);
485 git(repo, &["commit", "-q", "-m", "base"]);
486 let base = git(repo, &["rev-parse", "HEAD"]);
487 git(repo, &["checkout", "-q", "-b", "side"]);
488 std::fs::write(repo.join("side.txt"), "side\n").unwrap();
489 git(repo, &["add", "."]);
490 git(repo, &["commit", "-q", "-m", "side"]);
491 git(repo, &["checkout", "-q", "main"]);
492 write("main");
493 git(repo, &["commit", "-q", "-am", "main"]);
494 git(repo, &["merge", "-q", "--no-commit", "--no-ff", "side"]);
496 write(&format!("key = {}{}", "ghp_", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8"));
497 git(repo, &["add", "."]);
498 git(repo, &["commit", "-q", "--no-edit"]);
499 let head = git(repo, &["rev-parse", "HEAD"]);
500 let found = scan_diff(&push_diff(Some(repo), "origin", &head, &base).unwrap());
501 assert!(found.iter().any(|f| f.file == "a.txt" && f.category == "GitHub token"), "{found:?}");
502 let _ = std::fs::remove_dir_all(&dir);
503 }
504
505 #[test]
506 fn the_hooks_directory_is_the_most_specific_one_that_is_not_agentmuxs() {
507 let listing = "system\tcore.hookspath /etc/hooks\nglobal\tcore.hookspath /home/a/.githooks\nlocal\tcore.hookspath .husky/_\ncommand\tcore.hookspath /x/github-hooks\n";
508 assert_eq!(hooks_dir_from(listing), Some(PathBuf::from(".husky/_")));
509 let spaced = "global\tcore.hookspath /home/a b/hooks\nlocal\tcore.hookspath /r/github-hooks\n";
511 assert_eq!(hooks_dir_from(spaced), Some(PathBuf::from("/home/a b/hooks")));
512 assert_eq!(hooks_dir_from("command\tcore.hookspath /x/github-hooks\n"), None);
513 assert_eq!(hooks_dir_from(""), None);
514 }
515
516 #[test]
517 fn the_trailers_name_the_agent_and_credit_the_owner() {
518 assert_eq!(
519 trailers(Some("Korp"), None, Some("42"), Some("octo")),
520 vec!["Agent: korp".to_string(), "Co-authored-by: octo <42+octo@users.noreply.github.com>".to_string()]
521 );
522 assert_eq!(trailers(Some("korp"), None, None, None), vec!["Agent: korp".to_string()]);
523 assert_eq!(trailers(Some("KCont"), Some("Narko"), None, None), vec!["Agent: kcont@narko".to_string()]);
525 assert_eq!(trailers(Some("kcont"), Some(""), None, None), vec!["Agent: kcont".to_string()]);
526 assert!(trailers(None, Some("narko"), Some("42"), None).is_empty());
527 }
528}