Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / git.rs

git.rs255 lines · 8.2 KiBRaw
1//! Git operations owned by agentd.
2//!
3//! Invariants:
4//! * agentd only ever runs git in the shared bare **mirror** (`git -C
5//! <mirror> ...`). It never runs git inside a sandbox-controlled repo.
6//! * All invocations use argv (no shell) with timeouts.
7//! * The push token travels via `GIT_CONFIG_COUNT/KEY_0/VALUE_0`
8//! (`http.extraHeader = Authorization: Bearer <token>`), never in the URL,
9//! argv, or logs.
10//! * On startup the mirror is created if missing (`clone --bare`), then
11//! pinned with `gc.auto 0` + `gc.pruneExpire never` (slots reference it
12//! via alternates — pruning would corrupt them) and made group/world
13//! readable so the builder uid can fetch from it.
14
15use std::path::Path;
16use std::process::Stdio;
17use std::time::Duration;
18
19const GIT_TIMEOUT: Duration = Duration::from_secs(120);
20const FETCH_TIMEOUT: Duration = Duration::from_secs(300);
21const PUSH_TIMEOUT: Duration = Duration::from_secs(300);
22
23/// Error type that keeps command output but guarantees no secret is
24/// embedded: callers must pass redacted output (the token is never placed in
25/// argv, so `stderr` cannot contain it; still, [`redact`] is applied).
26#[derive(Debug)]
27pub struct GitError(pub String);
28
29impl std::fmt::Display for GitError {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 write!(f, "{}", self.0)
32 }
33}
34
35async fn run_git(
36 dir: Option<&Path>,
37 args: &[&str],
38 extra_env: &[(&str, &str)],
39 timeout: Duration,
40) -> Result<String, GitError> {
41 let mut cmd = tokio::process::Command::new("git");
42 if let Some(d) = dir {
43 cmd.arg("-C").arg(d);
44 }
45 // No pager, no interactive prompts, no sandbox repo config leakage.
46 cmd.env("GIT_PAGER", "cat")
47 .env("GIT_TERMINAL_PROMPT", "0")
48 .env("GIT_CONFIG_NOSYSTEM", "1")
49 .env("GIT_CONFIG_GLOBAL", "/dev/null")
50 .stdin(Stdio::null())
51 .stdout(Stdio::piped())
52 .stderr(Stdio::piped())
53 .args(args);
54 for (k, v) in extra_env {
55 cmd.env(k, v);
56 }
57 // Kill the whole process group on timeout: `kill_on_drop` only kills the
58 // direct child, so spawn detached via `pre_exec`-less approach — use
59 // `Command::kill_on_drop` plus rely on git's own children exiting when
60 // the parent dies. (No shell is ever involved.)
61 let child = cmd
62 .kill_on_drop(true)
63 .spawn()
64 .map_err(|e| GitError(format!("spawn git {}: {e}", args.join(" "))))?;
65 let out = tokio::time::timeout(timeout, child.wait_with_output())
66 .await
67 .map_err(|_| GitError(format!("git {} timed out after {timeout:?}", args.join(" "))))?
68 .map_err(|e| GitError(format!("git {}: {e}", args.join(" "))))?;
69 if !out.status.success() {
70 let stderr = String::from_utf8_lossy(&out.stderr);
71 return Err(GitError(format!(
72 "git {} failed: {}",
73 args.join(" "),
74 stderr.trim()
75 )));
76 }
77 String::from_utf8(out.stdout).map_err(|e| GitError(format!("git output not UTF-8: {e}")))
78}
79
80/// Ensure the bare mirror exists and is fetch-ready. `repo_url` is the
81/// upstream (e.g. `https://git.maproj.org/Modern-Apps.git`). The umask is
82/// relaxed while creating so the builder uid can read the new files.
83pub async fn ensure_mirror(mirror: &Path, repo_url: &str) -> Result<(), GitError> {
84 if mirror.join("HEAD").exists() || mirror.join("config").exists() {
85 return Ok(());
86 }
87 if let Some(parent) = mirror.parent() {
88 std::fs::create_dir_all(parent)
89 .map_err(|e| GitError(format!("create mirror parent: {e}")))?;
90 }
91 // 022 umask → files 644, dirs 755: world-readable for the builder uid.
92 #[cfg(unix)]
93 let prev = libc_umask(0o022);
94 let r = run_git(
95 None,
96 &["clone", "--bare", repo_url, &mirror.to_string_lossy()],
97 &[],
98 FETCH_TIMEOUT,
99 )
100 .await;
101 #[cfg(unix)]
102 libc_umask(prev);
103 r.map(|_| ())?;
104 // Pin GC off: slots use this repo as an alternates source.
105 run_git(
106 Some(mirror),
107 &["config", "gc.auto", "0"],
108 &[],
109 GIT_TIMEOUT,
110 )
111 .await?;
112 run_git(
113 Some(mirror),
114 &["config", "gc.pruneExpire", "never"],
115 &[],
116 GIT_TIMEOUT,
117 )
118 .await?;
119 Ok(())
120}
121
122#[cfg(unix)]
123fn libc_umask(mask: u32) -> u32 {
124 // Minimal FFI to avoid a libc dependency.
125 extern "C" {
126 fn umask(mask: u32) -> u32;
127 }
128 unsafe { umask(mask) }
129}
130
131/// Refresh the mirror's `main` from upstream before each task.
132pub async fn fetch_main(mirror: &Path) -> Result<(), GitError> {
133 run_git(
134 Some(mirror),
135 &["fetch", "origin", "+refs/heads/main:refs/heads/main"],
136 &[],
137 FETCH_TIMEOUT,
138 )
139 .await
140 .map(|_| ())
141}
142
143/// Base SHA the task branch starts from (mirror's `main`).
144pub async fn main_sha(mirror: &Path) -> Result<String, GitError> {
145 let sha = run_git(Some(mirror), &["rev-parse", "refs/heads/main"], &[], GIT_TIMEOUT).await?;
146 Ok(sha.trim().to_string())
147}
148
149/// Push one local ref to the upstream branch with the scoped token via
150/// `http.extraHeader` (token in process env, never URL/argv/logs).
151/// Replaces the old `push_branch` (`refs/agent-out/*`): the review gate
152/// pushes `refs/agent-wip/<id>` directly.
153pub async fn push_ref(
154 mirror: &Path,
155 repo_url: &str,
156 src: &str,
157 dst: &str,
158 token: &str,
159) -> Result<(), GitError> {
160 let header_value = format!("Authorization: Bearer {token}");
161 // Env values are not argv; redact defensively anyway on error paths.
162 let r = run_git(
163 Some(mirror),
164 &["push", repo_url, &format!("+{src}:{dst}")],
165 &[
166 ("GIT_CONFIG_COUNT", "1"),
167 ("GIT_CONFIG_KEY_0", "http.extraHeader"),
168 ("GIT_CONFIG_VALUE_0", &header_value),
169 ],
170 PUSH_TIMEOUT,
171 )
172 .await;
173 match r {
174 Ok(_) => Ok(()),
175 Err(GitError(msg)) => Err(GitError(crate::agent::scrub_secrets(&format!(
176 "push {dst}: {msg}"
177 )))),
178 }
179}
180
181/// Import a downloaded slot bundle as the task's WIP ref
182/// (`refs/agent-wip/<id>`), returning the WIP commit sha. Same verify-then-
183/// fetch discipline as the old task-bundle import: a corrupt bundle fails, a
184/// missing prerequisite does not.
185///
186/// `branch` is the task's slot branch (the ref the bundle carries).
187pub async fn import_wip_bundle(
188 mirror: &Path,
189 bundle_file: &Path,
190 branch: &str,
191 task_id: i64,
192) -> Result<String, GitError> {
193 let dst = format!("refs/agent-wip/{task_id}");
194 let verify_err = run_git(
195 Some(mirror),
196 &["bundle", "verify", &bundle_file.to_string_lossy()],
197 &[],
198 GIT_TIMEOUT,
199 )
200 .await
201 .err()
202 .map(|e| e.0);
203 if let Err(e) = run_git(
204 Some(mirror),
205 &[
206 "fetch",
207 &bundle_file.to_string_lossy(),
208 &format!("+refs/heads/{branch}:{dst}"),
209 ],
210 &[],
211 FETCH_TIMEOUT,
212 )
213 .await
214 {
215 if let Some(v) = verify_err {
216 return Err(GitError(format!("wip bundle import failed ({e}); verify: {v}")));
217 }
218 return Err(GitError(format!("wip bundle import: {e}")));
219 }
220 let sha = run_git(Some(mirror), &["rev-parse", &dst], &[], GIT_TIMEOUT).await?;
221 Ok(sha.trim().to_string())
222}
223
224/// Does the WIP ref exist in the mirror, and what sha does it resolve to?
225pub async fn wip_ref_sha(mirror: &Path, task_id: i64) -> Result<Option<String>, GitError> {
226 let dst = format!("refs/agent-wip/{task_id}");
227 match run_git(Some(mirror), &["rev-parse", "--verify", &dst], &[], GIT_TIMEOUT).await {
228 Ok(sha) => Ok(Some(sha.trim().to_string())),
229 Err(_) => Ok(None),
230 }
231}
232
233/// Delete the local WIP ref (parked with no changes, discard, or after the
234/// work moved elsewhere). Missing ref is fine.
235pub async fn delete_wip_ref(mirror: &Path, task_id: i64) -> Result<(), GitError> {
236 let dst = format!("refs/agent-wip/{task_id}");
237 match run_git(
238 Some(mirror),
239 &["update-ref", "-d", &dst],
240 &[],
241 GIT_TIMEOUT,
242 )
243 .await
244 {
245 Ok(_) => Ok(()),
246 Err(e) => {
247 // Tolerate "not found" (already deleted / never created).
248 if wip_ref_sha(mirror, task_id).await?.is_none() {
249 Ok(())
250 } else {
251 Err(e)
252 }
253 }
254 }
255}