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 pub(crate) 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 pub(crate) fn clone_private(&self, stage: &Path, source: &str) -> Result<()> {
249 let mut command = self.command(stage);
250 command.env_remove("GIT_EXEC_PATH");
251 command.args([
252 "-c",
253 "protocol.allow=never",
254 "-c",
255 if source.starts_with("https://") {
256 "protocol.https.allow=always"
257 } else {
258 "protocol.file.allow=always"
259 },
260 "-c",
261 "http.followRedirects=false",
262 "-c",
263 "credential.helper=",
264 "clone",
265 "--quiet",
266 "--no-local",
267 "--no-recurse-submodules",
268 "--template=",
269 "--",
270 source,
271 ".",
272 ]);
273 if run_bounded(command, LIMIT, Duration::from_secs(120))?.code != Some(0) {
274 return Err(failure("Git clone failed. Check the source and access."));
275 }
276 self.preflight(stage)?;
277 Ok(())
278 }
279
280 fn run(&self, root: &Path, args: &[&str]) -> Result<Output> {
281 let mut command = self.command(root);
282 command.args(args);
283 run_bounded(command, LIMIT, TIMEOUT)
284 }
285
286 fn command(&self, root: &Path) -> Command {
287 let mut command = Command::new(&self.executable);
288 command
289 .env_clear()
290 .env("HOME", "/no-external-programs")
291 .env("XDG_CONFIG_HOME", "/no-external-programs")
292 .env("PATH", "/no-external-programs")
293 .env("GIT_EXEC_PATH", "/no-external-programs")
294 .env("GIT_CONFIG_NOSYSTEM", "1")
295 .env("GIT_CONFIG_SYSTEM", "/dev/null")
296 .env("GIT_CONFIG_GLOBAL", "/dev/null")
297 .env("GIT_ATTR_NOSYSTEM", "1")
298 .env("GIT_OPTIONAL_LOCKS", "0")
299 .env("GIT_TERMINAL_PROMPT", "0")
300 .env("GIT_NO_LAZY_FETCH", "1")
301 .env("GIT_NO_REPLACE_OBJECTS", "1")
302 .env("LC_ALL", "C")
303 .env("LANG", "C")
304 .current_dir(root)
305 .args(["--no-pager", "--no-optional-locks"]);
306 for setting in [
307 "core.fsmonitor=false",
308 "core.untrackedCache=false",
309 "core.hooksPath=/dev/null",
310 "core.attributesFile=/dev/null",
311 "core.excludesFile=/dev/null",
312 "diff.external=",
313 "diff.autoRefreshIndex=false",
314 "diff.ignoreSubmodules=all",
315 "submodule.recurse=false",
316 "core.quotePath=true",
317 "color.ui=false",
318 ] {
319 command.args(["-c", setting]);
320 }
321 command
322 }
323}
324
325struct Output {
326 code: Option<i32>,
327 stdout: Vec<u8>,
328}
329
330fn run_bounded(mut command: Command, limit: usize, timeout: Duration) -> Result<Output> {
334 command
335 .stdin(Stdio::null())
336 .stdout(Stdio::piped())
337 .stderr(Stdio::piped())
338 .process_group(0);
339 let mut child = command
340 .spawn()
341 .map_err(|_| failure("Git executable unavailable or could not start"))?;
342 let result = (|| {
343 let mut stdout = child
344 .stdout
345 .take()
346 .ok_or_else(|| failure("Git stdout unavailable"))?;
347 let mut stderr = child
348 .stderr
349 .take()
350 .ok_or_else(|| failure("Git stderr unavailable"))?;
351 use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
352 for pipe in [&stdout as &dyn std::os::fd::AsFd, &stderr] {
353 let flags = fcntl_getfl(pipe).map_err(|_| failure("Git pipe setup failed"))?;
354 fcntl_setfl(pipe, flags | OFlags::NONBLOCK)
355 .map_err(|_| failure("Git pipe setup failed"))?;
356 }
357 let start = Instant::now();
358 let mut bytes = Vec::new();
359 let mut total = 0usize;
360 let mut out_done = false;
361 let mut err_done = false;
362 loop {
363 if start.elapsed() >= timeout {
364 return Err(failure("Git read exceeded time limit"));
365 }
366 for (pipe, done, keep) in [
368 (&mut stdout as &mut dyn Read, &mut out_done, true),
369 (&mut stderr as &mut dyn Read, &mut err_done, false),
370 ] {
371 if *done {
372 continue;
373 }
374 let mut buffer = [0; 8192];
375 match pipe.read(&mut buffer) {
376 Ok(0) => *done = true,
377 Ok(count) => {
378 total += count;
379 if total > limit {
380 return Err(failure("Git read exceeded output limit"));
381 }
382 if keep {
383 bytes.extend_from_slice(&buffer[..count]);
384 }
385 }
386 Err(error)
387 if matches!(
388 error.kind(),
389 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
390 ) => {}
391 Err(_) => return Err(failure("Git pipe read failed")),
392 }
393 }
394 if let Some(status) = child.try_wait().map_err(|_| failure("Git wait failed"))?
395 && out_done
396 && err_done
397 {
398 return Ok(Output {
399 code: status.code(),
400 stdout: bytes,
401 });
402 }
403 thread::sleep(Duration::from_millis(1));
404 }
405 })();
406 if result.is_err()
409 && let Some(pid) = rustix::process::Pid::from_raw(child.id() as i32)
410 {
411 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
412 }
413 let _ = child.wait();
414 result
415}
416
417fn text(bytes: &[u8]) -> Result<&str> {
418 std::str::from_utf8(bytes).map_err(|_| failure("Git report contains non-UTF-8 metadata/path"))
419}
420
421fn records(bytes: &[u8]) -> Result<Vec<&[u8]>> {
422 if bytes.is_empty() {
423 return Ok(Vec::new());
424 }
425 if !bytes.ends_with(&[0]) {
426 return Err(failure("malformed Git NUL protocol"));
427 }
428 Ok(bytes[..bytes.len() - 1].split(|b| *b == 0).collect())
429}
430
431fn parse_status(bytes: &[u8]) -> Result<Status> {
432 let records = records(bytes)?;
433 let mut branch = Vec::new();
434 let mut entries = Vec::new();
435 let mut index = 0;
436 while index < records.len() {
437 let record = text(records[index])?;
438 index += 1;
439 if let Some(header) = record.strip_prefix("# branch.") {
440 branch.push(header.to_owned());
441 continue;
442 }
443 let (kind, fields) = match record.as_bytes().first() {
444 Some(b'1') => ("ordinary", 8),
445 Some(b'2') => ("rename_or_copy", 9),
446 Some(b'u') => ("unmerged", 10),
447 Some(b'?') => ("untracked", 1),
448 _ => return Err(failure("malformed Git status record")),
449 };
450 let parts: Vec<_> = record.splitn(fields + 1, ' ').collect();
451 if parts.len() != fields + 1 || parts[fields].is_empty() || parts[..fields].contains(&"") {
452 return Err(failure("malformed Git status fields"));
453 }
454 let xy = if fields > 1 {
455 let sub = parts[2].as_bytes();
456 let valid_sub = sub == b"N..."
457 || (sub.len() == 4
458 && sub[0] == b'S'
459 && b".C".contains(&sub[1])
460 && b".M".contains(&sub[2])
461 && b".U".contains(&sub[3]));
462 let (modes, hashes) = if kind == "unmerged" {
463 (&parts[3..7], &parts[7..10])
464 } else {
465 (&parts[3..6], &parts[6..8])
466 };
467 if !valid_sub
468 || !modes.iter().all(|m| valid_mode(m))
469 || !hashes.iter().all(|h| valid_hash(h))
470 {
471 return Err(failure("malformed Git status metadata"));
472 }
473 if kind == "rename_or_copy" {
474 let score = parts[8];
475 if !score.starts_with(['R', 'C'])
476 || score[1..].parse::<u8>().ok().is_none_or(|n| n > 100)
477 {
478 return Err(failure("malformed Git rename score"));
479 }
480 }
481 let xy = parts[1];
482 if xy.len() != 2 || !xy.bytes().all(|b| b".MADRCUT?!".contains(&b)) {
483 return Err(failure("malformed Git status change code"));
484 }
485 Some(xy.to_owned())
486 } else {
487 None
488 };
489 let original_path = if kind == "rename_or_copy" {
490 let old = records
491 .get(index)
492 .ok_or_else(|| failure("missing Git rename path"))?;
493 index += 1;
494 let old = text(old)?;
495 if old.is_empty() {
496 return Err(failure("empty Git rename path"));
497 }
498 Some(old.to_owned())
499 } else {
500 None
501 };
502 entries.push(StatusEntry {
503 kind: kind.into(),
504 xy,
505 path: parts[fields].into(),
506 original_path,
507 });
508 }
509 Ok(Status {
510 schema: 1,
511 read_only: true,
512 branch,
513 entries,
514 })
515}
516
517fn valid_mode(mode: &str) -> bool {
518 mode.len() == 6 && mode.bytes().all(|b| (b'0'..=b'7').contains(&b))
519}
520
521fn valid_hash(hash: &str) -> bool {
522 matches!(hash.len(), 40 | 64) && hash.bytes().all(|b| b.is_ascii_hexdigit())
523}
524
525fn parse_diff(bytes: &[u8]) -> Result<Vec<DiffEntry>> {
526 let records = records(bytes)?;
527 if records.len() % 2 != 0 {
528 return Err(failure("malformed Git raw diff"));
529 }
530 records
531 .as_chunks::<2>()
532 .0
533 .iter()
534 .map(|pair| {
535 let header = text(pair[0])?
536 .strip_prefix(':')
537 .ok_or_else(|| failure("malformed Git raw header"))?;
538 let parts: Vec<_> = header.split(' ').collect();
539 if parts.len() != 5
540 || !parts[0..2].iter().all(|m| valid_mode(m))
541 || !parts[2..4].iter().all(|h| valid_hash(h))
542 || parts[4].len() != 1
543 || !b"ACDMTUXB".contains(&parts[4].as_bytes()[0])
544 {
545 return Err(failure("malformed Git raw diff fields"));
546 }
547 let path = text(pair[1])?;
548 if path.is_empty() {
549 return Err(failure("empty Git diff path"));
550 }
551 Ok(DiffEntry {
552 change: parts[4].into(),
553 old_mode: parts[0].into(),
554 new_mode: parts[1].into(),
555 path: path.into(),
556 })
557 })
558 .collect()
559}
560
561fn escape_patch(bytes: &[u8]) -> String {
564 use std::fmt::Write;
565 let mut output = String::new();
566 for byte in bytes {
567 match byte {
568 b'\n' => output.push('\n'),
569 b'\\' => output.push_str("\\\\"),
570 0x20..=0x7e => output.push(char::from(*byte)),
571 _ => {
572 let _ = write!(output, "\\x{byte:02x}");
573 }
574 }
575 }
576 output
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582 #[test]
583 fn nul_parsers_and_escaping_fail_closed() {
584 let status = parse_status(b"# branch.head (detached)\0? line\nname\0").unwrap();
585 assert_eq!(status.entries[0].path, "line\nname");
586 assert!(parse_status(b"? x").is_err());
587 assert!(parse_status(b"? \xff\0").is_err());
588 assert!(parse_status(b"2 R. N... 100644 100644 100644 a b R100 new\0").is_err());
589 assert!(parse_diff(b":100644 100644 bad bad M\0x\0").is_err());
590 assert_eq!(
591 escape_patch(b"a\x1b\r\t\xff\\\n"),
592 "a\\x1b\\x0d\\x09\\xff\\\\\n"
593 );
594 }
595
596 #[test]
597 fn runner_bounds_both_streams_deadlines_and_redacts_errors() {
598 let command = |script: &str| {
599 let mut command = Command::new("/bin/sh");
600 command.env_clear().args(["-c", script]);
601 command
602 };
603 for script in [
604 "while :; do printf secret; done",
605 "while :; do printf secret >&2; done",
606 ] {
607 let error = run_bounded(command(script), 1024, Duration::from_secs(2))
608 .err()
609 .unwrap();
610 assert!(error.to_string().contains("output limit"));
611 assert!(!error.to_string().contains("secret"));
612 }
613 let start = Instant::now();
614 assert!(
615 run_bounded(
616 command("while :; do :; done"),
617 1024,
618 Duration::from_millis(30)
619 )
620 .is_err()
621 );
622 assert!(start.elapsed() < Duration::from_secs(2));
623 assert!(
625 run_bounded(
626 command("(while :; do :; done) & exit 0"),
627 1024,
628 Duration::from_millis(30)
629 )
630 .is_err()
631 );
632 }
633}