Skip to main content

dort_core/
git.rs

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