1use crate::{Error, Result};
3use serde::Serialize;
4use std::{
5 io::Read,
6 os::unix::{ffi::OsStrExt, process::CommandExt},
7 path::{Path, PathBuf},
8 process::{Command, Stdio},
9 thread,
10 time::{Duration, Instant},
11};
12
13const LIMIT: usize = 4 * 1024 * 1024;
14const TIMEOUT: Duration = Duration::from_secs(10);
15const DIFF_ARGS: &[&str] = &[
16 "diff",
17 "--no-ext-diff",
18 "--no-textconv",
19 "--no-color",
20 "--no-renames",
21 "--ignore-submodules=all",
22 "--submodule=short",
23];
24const PATCH_ARGS: &[&str] = &["--patch", "--unified=3", "--"];
25
26fn failure(message: &'static str) -> Error {
27 Error::Invalid(message.into())
28}
29
30pub struct Git {
32 executable: PathBuf,
33}
34
35#[derive(Debug, Serialize)]
36pub struct Status {
37 pub schema: u32,
38 pub read_only: bool,
39 pub branch: Vec<String>,
40 pub entries: Vec<StatusEntry>,
41}
42
43#[derive(Debug, Serialize)]
44pub struct StatusEntry {
45 pub kind: String,
46 pub xy: Option<String>,
47 pub path: String,
48 pub original_path: Option<String>,
49}
50
51#[derive(Serialize)]
52pub struct Diff {
53 pub schema: u32,
54 pub read_only: bool,
55 pub staged: bool,
56 pub entries: Vec<DiffEntry>,
57 #[serde(skip_serializing_if = "Option::is_none")]
59 pub patch: Option<String>,
60}
61
62impl std::fmt::Debug for Diff {
65 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 formatter
67 .debug_struct("Diff")
68 .field("schema", &self.schema)
69 .field("read_only", &self.read_only)
70 .field("staged", &self.staged)
71 .field("entries", &self.entries)
72 .field("patch_requested", &self.patch.is_some())
73 .finish()
74 }
75}
76
77#[derive(Debug, Serialize)]
78pub struct DiffEntry {
79 pub change: String,
80 pub old_mode: String,
81 pub new_mode: String,
82 pub path: String,
83}
84
85impl Git {
86 pub fn new(executable: PathBuf) -> Result<Self> {
87 if !executable.is_absolute() {
88 return Err(failure("Git executable must be an absolute trusted path"));
89 }
90 Ok(Self { executable })
91 }
92
93 pub fn status(&self, repository: &Path) -> Result<Status> {
94 let root = self.preflight(repository)?;
95 let bytes = self.checked(
96 &root,
97 &[
98 "status",
99 "--porcelain=v2",
100 "-z",
101 "--branch",
102 "--untracked-files=all",
103 "--ignore-submodules=all",
104 ],
105 )?;
106 parse_status(&bytes)
107 }
108
109 pub fn diff(&self, repository: &Path, staged: bool, patch: bool) -> Result<Diff> {
110 let root = self.preflight(repository)?;
111 let mut args = DIFF_ARGS.to_vec();
112 if staged {
113 args.push("--cached");
114 }
115 args.extend(["--raw", "-z", "--abbrev=64", "--"]);
116 let entries = parse_diff(&self.checked(&root, &args)?)?;
117 let patch = if patch {
118 self.preflight(&root)?;
121 args.truncate(args.len() - 4);
122 args.extend_from_slice(PATCH_ARGS);
124 Some(escape_patch(&self.checked(&root, &args)?))
125 } else {
126 None
127 };
128 Ok(Diff {
129 schema: 1,
130 read_only: true,
131 staged,
132 entries,
133 patch,
134 })
135 }
136
137 pub fn selected_patch(
138 &self,
139 repository: &Path,
140 staged: bool,
141 path: &str,
142 original_path: Option<&str>,
143 ) -> Result<String> {
144 if let Some(old) = original_path
145 && (path.strip_prefix(old).is_some_and(|p| p.starts_with('/'))
146 || old.strip_prefix(path).is_some_and(|p| p.starts_with('/')))
147 {
148 let mut patch = self.selected_patch(repository, staged, old, None)?;
149 patch.push_str(&self.selected_patch(repository, staged, path, None)?);
150 return Ok(patch);
151 }
152 let mut pathspecs = Vec::new();
153 for path in [Some(path), original_path].into_iter().flatten() {
154 if path.contains('\0') || path.split('/').any(|p| matches!(p, "" | "." | "..")) {
155 return Err(failure("invalid Git file path"));
156 }
157 pathspecs.push(format!(":(top,literal){path}"));
158 pathspecs.push(format!(":(top,exclude,literal){path}/"));
161 }
162 let root = self.preflight(repository)?;
163 let mut args = DIFF_ARGS.to_vec();
164 if staged {
165 args.push("--cached");
166 }
167 args.extend_from_slice(PATCH_ARGS);
168 args.extend(pathspecs.iter().map(String::as_str));
169 Ok(escape_patch(&self.checked(&root, &args)?))
170 }
171 pub(crate) fn initialize_private(executable: PathBuf, stage: &Path) -> Result<()> {
173 let backend = Self::new(executable)?;
174 let output = backend.run(
175 stage,
176 &[
177 "init",
178 "--quiet",
179 "--template=",
180 "--initial-branch=main",
181 "--object-format=sha1",
182 ".",
183 ],
184 )?;
185 if output.code != Some(0) {
186 return Err(failure("private Git initialization failed"));
187 }
188 backend.preflight(stage)?;
189 Ok(())
190 }
191
192 fn preflight(&self, repository: &Path) -> Result<PathBuf> {
193 if !repository.is_absolute() {
194 return Err(failure("Git repository must be an absolute path"));
195 }
196 let root = repository
197 .canonicalize()
198 .map_err(|_| failure("Git repository is not an accessible directory"))?;
199 if !root.is_dir() {
200 return Err(failure("Git repository is not a directory"));
201 }
202 let config = self.run(
205 &root,
206 &[
207 "config",
208 "--includes",
209 "--null",
210 "--name-only",
211 "--get-regexp",
212 "^filter\\.|^extensions\\.partialclone$|^remote\\..*\\.promisor$",
213 ],
214 )?;
215 match config.code {
216 Some(1) if config.stdout.is_empty() => {}
217 Some(0) if !config.stdout.is_empty() => {
218 return Err(failure(
219 "Git read refused: configured content filters or partial clone/promisor settings",
220 ));
221 }
222 _ => return Err(failure("Git configuration inspection failed")),
223 }
224 let top = self.checked(&root, &["rev-parse", "--show-toplevel"])?;
225 let top = top
227 .strip_suffix(b"\n")
228 .ok_or_else(|| failure("invalid Git root response"))?;
229 if top != root.as_os_str().as_bytes() {
230 return Err(failure(
231 "--repo must name the exact non-bare Git working-tree root",
232 ));
233 }
234 Ok(root)
235 }
236
237 fn checked(&self, root: &Path, args: &[&str]) -> Result<Vec<u8>> {
238 let output = self.run(root, args)?;
239 if output.code != Some(0) {
240 return Err(failure(
242 "Git read failed (invalid repository, unsupported Git, or read error)",
243 ));
244 }
245 Ok(output.stdout)
246 }
247
248 fn run(&self, root: &Path, args: &[&str]) -> Result<Output> {
249 let mut command = Command::new(&self.executable);
250 command
251 .env_clear()
252 .env("HOME", "/no-external-programs")
253 .env("XDG_CONFIG_HOME", "/no-external-programs")
254 .env("PATH", "/no-external-programs")
255 .env("GIT_EXEC_PATH", "/no-external-programs")
256 .env("GIT_CONFIG_NOSYSTEM", "1")
257 .env("GIT_CONFIG_SYSTEM", "/dev/null")
258 .env("GIT_CONFIG_GLOBAL", "/dev/null")
259 .env("GIT_ATTR_NOSYSTEM", "1")
260 .env("GIT_OPTIONAL_LOCKS", "0")
261 .env("GIT_TERMINAL_PROMPT", "0")
262 .env("GIT_NO_LAZY_FETCH", "1")
263 .env("GIT_NO_REPLACE_OBJECTS", "1")
264 .env("LC_ALL", "C")
265 .env("LANG", "C")
266 .current_dir(root)
267 .args(["--no-pager", "--no-optional-locks"]);
268 for setting in [
269 "core.fsmonitor=false",
270 "core.untrackedCache=false",
271 "core.hooksPath=/dev/null",
272 "core.attributesFile=/dev/null",
273 "core.excludesFile=/dev/null",
274 "diff.external=",
275 "diff.autoRefreshIndex=false",
276 "diff.ignoreSubmodules=all",
277 "submodule.recurse=false",
278 "core.quotePath=true",
279 "color.ui=false",
280 ] {
281 command.args(["-c", setting]);
282 }
283 command.args(args);
284 run_bounded(command, LIMIT, TIMEOUT)
285 }
286}
287
288struct Output {
289 code: Option<i32>,
290 stdout: Vec<u8>,
291}
292
293fn run_bounded(mut command: Command, limit: usize, timeout: Duration) -> Result<Output> {
297 command
298 .stdin(Stdio::null())
299 .stdout(Stdio::piped())
300 .stderr(Stdio::piped())
301 .process_group(0);
302 let mut child = command
303 .spawn()
304 .map_err(|_| failure("Git executable unavailable or could not start"))?;
305 let result = (|| {
306 let mut stdout = child
307 .stdout
308 .take()
309 .ok_or_else(|| failure("Git stdout unavailable"))?;
310 let mut stderr = child
311 .stderr
312 .take()
313 .ok_or_else(|| failure("Git stderr unavailable"))?;
314 use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
315 for pipe in [&stdout as &dyn std::os::fd::AsFd, &stderr] {
316 let flags = fcntl_getfl(pipe).map_err(|_| failure("Git pipe setup failed"))?;
317 fcntl_setfl(pipe, flags | OFlags::NONBLOCK)
318 .map_err(|_| failure("Git pipe setup failed"))?;
319 }
320 let start = Instant::now();
321 let mut bytes = Vec::new();
322 let mut total = 0usize;
323 let mut out_done = false;
324 let mut err_done = false;
325 loop {
326 if start.elapsed() >= timeout {
327 return Err(failure("Git read exceeded time limit"));
328 }
329 for (pipe, done, keep) in [
331 (&mut stdout as &mut dyn Read, &mut out_done, true),
332 (&mut stderr as &mut dyn Read, &mut err_done, false),
333 ] {
334 if *done {
335 continue;
336 }
337 let mut buffer = [0; 8192];
338 match pipe.read(&mut buffer) {
339 Ok(0) => *done = true,
340 Ok(count) => {
341 total += count;
342 if total > limit {
343 return Err(failure("Git read exceeded output limit"));
344 }
345 if keep {
346 bytes.extend_from_slice(&buffer[..count]);
347 }
348 }
349 Err(error)
350 if matches!(
351 error.kind(),
352 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
353 ) => {}
354 Err(_) => return Err(failure("Git pipe read failed")),
355 }
356 }
357 if let Some(status) = child.try_wait().map_err(|_| failure("Git wait failed"))?
358 && out_done
359 && err_done
360 {
361 return Ok(Output {
362 code: status.code(),
363 stdout: bytes,
364 });
365 }
366 thread::sleep(Duration::from_millis(1));
367 }
368 })();
369 if result.is_err()
372 && let Some(pid) = rustix::process::Pid::from_raw(child.id() as i32)
373 {
374 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
375 }
376 let _ = child.wait();
377 result
378}
379
380fn text(bytes: &[u8]) -> Result<&str> {
381 std::str::from_utf8(bytes).map_err(|_| failure("Git report contains non-UTF-8 metadata/path"))
382}
383
384fn records(bytes: &[u8]) -> Result<Vec<&[u8]>> {
385 if bytes.is_empty() {
386 return Ok(Vec::new());
387 }
388 if !bytes.ends_with(&[0]) {
389 return Err(failure("malformed Git NUL protocol"));
390 }
391 Ok(bytes[..bytes.len() - 1].split(|b| *b == 0).collect())
392}
393
394fn parse_status(bytes: &[u8]) -> Result<Status> {
395 let records = records(bytes)?;
396 let mut branch = Vec::new();
397 let mut entries = Vec::new();
398 let mut index = 0;
399 while index < records.len() {
400 let record = text(records[index])?;
401 index += 1;
402 if let Some(header) = record.strip_prefix("# branch.") {
403 branch.push(header.to_owned());
404 continue;
405 }
406 let (kind, fields) = match record.as_bytes().first() {
407 Some(b'1') => ("ordinary", 8),
408 Some(b'2') => ("rename_or_copy", 9),
409 Some(b'u') => ("unmerged", 10),
410 Some(b'?') => ("untracked", 1),
411 _ => return Err(failure("malformed Git status record")),
412 };
413 let parts: Vec<_> = record.splitn(fields + 1, ' ').collect();
414 if parts.len() != fields + 1 || parts[fields].is_empty() || parts[..fields].contains(&"") {
415 return Err(failure("malformed Git status fields"));
416 }
417 let xy = if fields > 1 {
418 let sub = parts[2].as_bytes();
419 let valid_sub = sub == b"N..."
420 || (sub.len() == 4
421 && sub[0] == b'S'
422 && b".C".contains(&sub[1])
423 && b".M".contains(&sub[2])
424 && b".U".contains(&sub[3]));
425 let (modes, hashes) = if kind == "unmerged" {
426 (&parts[3..7], &parts[7..10])
427 } else {
428 (&parts[3..6], &parts[6..8])
429 };
430 if !valid_sub
431 || !modes.iter().all(|m| valid_mode(m))
432 || !hashes.iter().all(|h| valid_hash(h))
433 {
434 return Err(failure("malformed Git status metadata"));
435 }
436 if kind == "rename_or_copy" {
437 let score = parts[8];
438 if !score.starts_with(['R', 'C'])
439 || score[1..].parse::<u8>().ok().is_none_or(|n| n > 100)
440 {
441 return Err(failure("malformed Git rename score"));
442 }
443 }
444 let xy = parts[1];
445 if xy.len() != 2 || !xy.bytes().all(|b| b".MADRCUT?!".contains(&b)) {
446 return Err(failure("malformed Git status change code"));
447 }
448 Some(xy.to_owned())
449 } else {
450 None
451 };
452 let original_path = if kind == "rename_or_copy" {
453 let old = records
454 .get(index)
455 .ok_or_else(|| failure("missing Git rename path"))?;
456 index += 1;
457 let old = text(old)?;
458 if old.is_empty() {
459 return Err(failure("empty Git rename path"));
460 }
461 Some(old.to_owned())
462 } else {
463 None
464 };
465 entries.push(StatusEntry {
466 kind: kind.into(),
467 xy,
468 path: parts[fields].into(),
469 original_path,
470 });
471 }
472 Ok(Status {
473 schema: 1,
474 read_only: true,
475 branch,
476 entries,
477 })
478}
479
480fn valid_mode(mode: &str) -> bool {
481 mode.len() == 6 && mode.bytes().all(|b| (b'0'..=b'7').contains(&b))
482}
483
484fn valid_hash(hash: &str) -> bool {
485 matches!(hash.len(), 40 | 64) && hash.bytes().all(|b| b.is_ascii_hexdigit())
486}
487
488fn parse_diff(bytes: &[u8]) -> Result<Vec<DiffEntry>> {
489 let records = records(bytes)?;
490 if records.len() % 2 != 0 {
491 return Err(failure("malformed Git raw diff"));
492 }
493 records
494 .as_chunks::<2>()
495 .0
496 .iter()
497 .map(|pair| {
498 let header = text(pair[0])?
499 .strip_prefix(':')
500 .ok_or_else(|| failure("malformed Git raw header"))?;
501 let parts: Vec<_> = header.split(' ').collect();
502 if parts.len() != 5
503 || !parts[0..2].iter().all(|m| valid_mode(m))
504 || !parts[2..4].iter().all(|h| valid_hash(h))
505 || parts[4].len() != 1
506 || !b"ACDMTUXB".contains(&parts[4].as_bytes()[0])
507 {
508 return Err(failure("malformed Git raw diff fields"));
509 }
510 let path = text(pair[1])?;
511 if path.is_empty() {
512 return Err(failure("empty Git diff path"));
513 }
514 Ok(DiffEntry {
515 change: parts[4].into(),
516 old_mode: parts[0].into(),
517 new_mode: parts[1].into(),
518 path: path.into(),
519 })
520 })
521 .collect()
522}
523
524fn escape_patch(bytes: &[u8]) -> String {
527 use std::fmt::Write;
528 let mut output = String::new();
529 for byte in bytes {
530 match byte {
531 b'\n' => output.push('\n'),
532 b'\\' => output.push_str("\\\\"),
533 0x20..=0x7e => output.push(char::from(*byte)),
534 _ => {
535 let _ = write!(output, "\\x{byte:02x}");
536 }
537 }
538 }
539 output
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545 #[test]
546 fn nul_parsers_and_escaping_fail_closed() {
547 let status = parse_status(b"# branch.head (detached)\0? line\nname\0").unwrap();
548 assert_eq!(status.entries[0].path, "line\nname");
549 assert!(parse_status(b"? x").is_err());
550 assert!(parse_status(b"? \xff\0").is_err());
551 assert!(parse_status(b"2 R. N... 100644 100644 100644 a b R100 new\0").is_err());
552 assert!(parse_diff(b":100644 100644 bad bad M\0x\0").is_err());
553 assert_eq!(
554 escape_patch(b"a\x1b\r\t\xff\\\n"),
555 "a\\x1b\\x0d\\x09\\xff\\\\\n"
556 );
557 }
558
559 #[test]
560 fn runner_bounds_both_streams_deadlines_and_redacts_errors() {
561 let command = |script: &str| {
562 let mut command = Command::new("/bin/sh");
563 command.env_clear().args(["-c", script]);
564 command
565 };
566 for script in [
567 "while :; do printf secret; done",
568 "while :; do printf secret >&2; done",
569 ] {
570 let error = run_bounded(command(script), 1024, Duration::from_secs(2))
571 .err()
572 .unwrap();
573 assert!(error.to_string().contains("output limit"));
574 assert!(!error.to_string().contains("secret"));
575 }
576 let start = Instant::now();
577 assert!(
578 run_bounded(
579 command("while :; do :; done"),
580 1024,
581 Duration::from_millis(30)
582 )
583 .is_err()
584 );
585 assert!(start.elapsed() < Duration::from_secs(2));
586 assert!(
588 run_bounded(
589 command("(while :; do :; done) & exit 0"),
590 1024,
591 Duration::from_millis(30)
592 )
593 .is_err()
594 );
595 }
596}