From d59df070a5f1c46ae7f5a12f7632b05d6e48ecf8 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 16 Oct 2026 20:52:18 -0500 Subject: [PATCH 1/4] feat(git): H1 cut 1, native Git objects, packfiles, full-history read and export (#48) Part of #48 (ADR 0003 step 28, H1). The Git side of the bridge, natively in synapse-git, with the system git used only as a test oracle: - object: Git object kinds, IDs, tree entries, commit and tag links; every other commit and tag byte kept opaque. - inflate: RFC 1950/1951 decoder (stored, fixed, dynamic blocks), bounded, reports consumed input, typed refusals. - pack: pack v2 and index v2 codec per gitformat-pack: deterministic writer (whole objects in object ID order), reader through Git's index or native indexing, OFS and REF delta resolution, CRC-32 and SHA-1 trailers checked. - repo: read loose objects, packs, refs, packed-refs and HEAD; walk the full history; export an object set as a new bare repository with one pack. Fixture and two real repositories (synapse 1,784 objects, omega 29,635) export with identical object IDs and pass git fsck --full --strict. Red before green: six stubs in evidence/h1-git-bridge/red-green/red.txt. Remaining for #48 (cut 2): persistent GitOid map, native import (blobs, TreeDigest, revisions with stored original headers) and export from it. Co-Authored-By: Claude Opus 5.5 --- crates/synapse-git/src/inflate.rs | 343 ++++++++++ crates/synapse-git/src/lib.rs | 14 + crates/synapse-git/src/object.rs | 335 ++++++++++ crates/synapse-git/src/pack.rs | 730 +++++++++++++++++++++ crates/synapse-git/src/repo.rs | 334 ++++++++++ crates/synapse-git/tests/h1_git_bridge.rs | 563 ++++++++++++++++ docs/H1_GIT_BRIDGE.md | 62 ++ evidence/h1-git-bridge/SHA256SUMS | 2 + evidence/h1-git-bridge/red-green/green.txt | 39 ++ evidence/h1-git-bridge/red-green/red.txt | 105 +++ 10 files changed, 2527 insertions(+) create mode 100644 crates/synapse-git/src/inflate.rs create mode 100644 crates/synapse-git/src/object.rs create mode 100644 crates/synapse-git/src/pack.rs create mode 100644 crates/synapse-git/src/repo.rs create mode 100644 crates/synapse-git/tests/h1_git_bridge.rs create mode 100644 docs/H1_GIT_BRIDGE.md create mode 100644 evidence/h1-git-bridge/SHA256SUMS create mode 100644 evidence/h1-git-bridge/red-green/green.txt create mode 100644 evidence/h1-git-bridge/red-green/red.txt diff --git a/crates/synapse-git/src/inflate.rs b/crates/synapse-git/src/inflate.rs new file mode 100644 index 0000000..33dd092 --- /dev/null +++ b/crates/synapse-git/src/inflate.rs @@ -0,0 +1,343 @@ +//! Native RFC 1950 (zlib) and RFC 1951 (DEFLATE) decoder for reading Git objects (ADR 0003 +//! step H1). Git stores every loose object and every packed entry as a zlib stream +//! (`gitformat-pack`: "compressed data"); a pack entry does not record its compressed length, +//! so [`zlib_decompress`] reports how many input bytes the stream used. +//! +//! The decoder is bounded: output never grows past the caller's `max_out`, every read is +//! checked against the input that remains, and every malformed stream is refused with +//! `RefusalCode::GitObjectCorrupt`. It never panics on any input. + +use synapse_core::{RefusalCode, SynapseError, SynapseResult}; + +fn corrupt(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::GitObjectCorrupt, msg) +} + +/// Decompress one zlib stream at the start of `input` into at most `max_out` bytes. +/// Returns the decompressed bytes and the number of input bytes the stream used (header, +/// DEFLATE blocks, and the Adler-32 trailer). Refuses preset dictionaries, a bad header +/// check, an Adler-32 mismatch, and output over `max_out`. +pub fn zlib_decompress(input: &[u8], max_out: usize) -> SynapseResult<(Vec, usize)> { + if input.len() < 2 { + return Err(corrupt("zlib stream shorter than its 2-byte header")); + } + let (cmf, flg) = (input[0], input[1]); + if cmf & 0x0f != 8 || cmf >> 4 > 7 { + return Err(corrupt( + "zlib header is not DEFLATE with a window of at most 32 KiB", + )); + } + if (u16::from(cmf) << 8 | u16::from(flg)) % 31 != 0 { + return Err(corrupt("zlib header check bits are wrong")); + } + if flg & 0x20 != 0 { + return Err(corrupt("zlib preset dictionary is not used by Git")); + } + let mut inf = Inflater { + input, + pos: 2, + bit_buf: 0, + bit_count: 0, + out: Vec::new(), + max_out, + }; + inf.run()?; + // Discard the bits left in the last partial byte, then read the big-endian Adler-32. + let pos = inf.pos; + let trailer = input + .get(pos..pos + 4) + .ok_or_else(|| corrupt("zlib stream truncated before its Adler-32 trailer"))?; + let expected = u32::from_be_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]); + if crate::adler32(&inf.out) != expected { + return Err(corrupt("zlib Adler-32 checksum mismatch")); + } + Ok((inf.out, pos + 4)) +} + +const MAX_BITS: usize = 15; + +/// Canonical Huffman decoding table (RFC 1951 section 3.2.2): symbol counts per code length +/// and the symbols ordered by code. +struct Huffman { + counts: [u16; MAX_BITS + 1], + symbols: Vec, +} + +impl Huffman { + fn new(lengths: &[u8]) -> SynapseResult { + let mut counts = [0u16; MAX_BITS + 1]; + for &len in lengths { + counts[usize::from(len)] += 1; + } + // Over-subscribed code sets are refused; incomplete ones are allowed (RFC 1951 permits + // a single distance code), and an unused code then fails at decode time. + let mut left: i32 = 1; + for &count in &counts[1..] { + left <<= 1; + left -= i32::from(count); + if left < 0 { + return Err(corrupt("DEFLATE Huffman code set is over-subscribed")); + } + } + let mut offsets = [0u16; MAX_BITS + 2]; + for len in 1..=MAX_BITS { + offsets[len + 1] = offsets[len] + counts[len]; + } + let mut symbols = vec![0u16; lengths.len()]; + for (symbol, &len) in lengths.iter().enumerate() { + if len != 0 { + let slot = &mut offsets[usize::from(len)]; + symbols[usize::from(*slot)] = symbol as u16; + *slot += 1; + } + } + Ok(Self { counts, symbols }) + } +} + +const LENGTH_BASE: [u16; 29] = [ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, + 163, 195, 227, 258, +]; +const LENGTH_EXTRA: [u8; 29] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, +]; +const DIST_BASE: [u16; 30] = [ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, + 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, +]; +const DIST_EXTRA: [u8; 30] = [ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, + 13, +]; +/// Order in which code length code lengths are sent (RFC 1951 section 3.2.7). +const CLEN_ORDER: [usize; 19] = [ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15, +]; + +struct Inflater<'a> { + input: &'a [u8], + pos: usize, + bit_buf: u32, + bit_count: u32, + out: Vec, + max_out: usize, +} + +impl Inflater<'_> { + fn bits(&mut self, need: u32) -> SynapseResult { + while self.bit_count < need { + let byte = *self + .input + .get(self.pos) + .ok_or_else(|| corrupt("DEFLATE stream truncated"))?; + self.pos += 1; + self.bit_buf |= u32::from(byte) << self.bit_count; + self.bit_count += 8; + } + let value = self.bit_buf & ((1u32 << need) - 1); + self.bit_buf >>= need; + self.bit_count -= need; + Ok(value) + } + + fn push(&mut self, byte: u8) -> SynapseResult<()> { + if self.out.len() >= self.max_out { + return Err(corrupt(format!( + "decompressed data exceeds the declared {} bytes", + self.max_out + ))); + } + self.out.push(byte); + Ok(()) + } + + fn run(&mut self) -> SynapseResult<()> { + loop { + let last = self.bits(1)? == 1; + match self.bits(2)? { + 0 => self.stored()?, + 1 => { + let (lit, dist) = fixed_tables()?; + self.codes(&lit, &dist)?; + } + 2 => { + let (lit, dist) = self.dynamic_tables()?; + self.codes(&lit, &dist)?; + } + _ => return Err(corrupt("DEFLATE block type 3 is reserved")), + } + if last { + return Ok(()); + } + } + } + + fn stored(&mut self) -> SynapseResult<()> { + self.bit_buf = 0; + self.bit_count = 0; + let header = self + .input + .get(self.pos..self.pos + 4) + .ok_or_else(|| corrupt("DEFLATE stored block header truncated"))?; + let len = u16::from_le_bytes([header[0], header[1]]); + let nlen = u16::from_le_bytes([header[2], header[3]]); + if len != !nlen { + return Err(corrupt("DEFLATE stored block length check failed")); + } + self.pos += 4; + let len = usize::from(len); + let data = self + .input + .get(self.pos..self.pos + len) + .ok_or_else(|| corrupt("DEFLATE stored block truncated"))?; + if self.out.len() + len > self.max_out { + return Err(corrupt(format!( + "decompressed data exceeds the declared {} bytes", + self.max_out + ))); + } + self.out.extend_from_slice(data); + self.pos += len; + Ok(()) + } + + fn decode(&mut self, h: &Huffman) -> SynapseResult { + let (mut code, mut first, mut index) = (0i32, 0i32, 0i32); + for len in 1..=MAX_BITS { + code |= self.bits(1)? as i32; + let count = i32::from(h.counts[len]); + if code - count < first { + return Ok(h.symbols[(index + (code - first)) as usize]); + } + index += count; + first += count; + first <<= 1; + code <<= 1; + } + Err(corrupt("DEFLATE Huffman code is not in the code set")) + } + + fn dynamic_tables(&mut self) -> SynapseResult<(Huffman, Huffman)> { + let nlen = self.bits(5)? as usize + 257; + let ndist = self.bits(5)? as usize + 1; + let ncode = self.bits(4)? as usize + 4; + if nlen > 286 || ndist > 30 { + return Err(corrupt("DEFLATE dynamic block declares too many codes")); + } + let mut clen = [0u8; 19]; + for &slot in CLEN_ORDER.iter().take(ncode) { + clen[slot] = self.bits(3)? as u8; + } + let clen_code = Huffman::new(&clen)?; + let mut lengths = vec![0u8; nlen + ndist]; + let mut i = 0; + while i < nlen + ndist { + let symbol = self.decode(&clen_code)?; + let (value, repeat) = match symbol { + 0..=15 => (symbol as u8, 1), + 16 => { + if i == 0 { + return Err(corrupt("DEFLATE repeat with no previous length")); + } + (lengths[i - 1], 3 + self.bits(2)? as usize) + } + 17 => (0, 3 + self.bits(3)? as usize), + _ => (0, 11 + self.bits(7)? as usize), + }; + if i + repeat > nlen + ndist { + return Err(corrupt("DEFLATE code lengths overrun the declared count")); + } + lengths[i..i + repeat].fill(value); + i += repeat; + } + if lengths[256] == 0 { + return Err(corrupt("DEFLATE dynamic block has no end-of-block code")); + } + Ok(( + Huffman::new(&lengths[..nlen])?, + Huffman::new(&lengths[nlen..])?, + )) + } + + fn codes(&mut self, lit: &Huffman, dist: &Huffman) -> SynapseResult<()> { + loop { + let symbol = self.decode(lit)?; + match symbol { + 0..=255 => self.push(symbol as u8)?, + 256 => return Ok(()), + 257..=285 => { + let idx = usize::from(symbol - 257); + let len = usize::from(LENGTH_BASE[idx]) + + self.bits(u32::from(LENGTH_EXTRA[idx]))? as usize; + let dsym = usize::from(self.decode(dist)?); + if dsym >= 30 { + return Err(corrupt("DEFLATE distance code out of range")); + } + let distance = usize::from(DIST_BASE[dsym]) + + self.bits(u32::from(DIST_EXTRA[dsym]))? as usize; + if distance > self.out.len() { + return Err(corrupt("DEFLATE distance reaches before the output start")); + } + let start = self.out.len() - distance; + for k in 0..len { + let byte = self.out[start + k]; + self.push(byte)?; + } + } + _ => return Err(corrupt("DEFLATE length code out of range")), + } + } + } +} + +fn fixed_tables() -> SynapseResult<(Huffman, Huffman)> { + let mut lengths = [0u8; 288]; + lengths[..144].fill(8); + lengths[144..256].fill(9); + lengths[256..280].fill(7); + lengths[280..].fill(8); + Ok((Huffman::new(&lengths)?, Huffman::new(&[5u8; 30])?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::zlib_compress_store; + + #[test] + fn stored_blocks_round_trip_and_report_consumed_length() { + for len in [0usize, 1, 100, 65_535, 65_536, 200_000] { + let raw: Vec = (0..len).map(|i| (i * 7 % 251) as u8).collect(); + let mut z = zlib_compress_store(&raw); + let used = z.len(); + z.extend_from_slice(b"trailing pack bytes"); + let (out, consumed) = zlib_decompress(&z, len).unwrap(); + assert_eq!(out, raw); + assert_eq!(consumed, used); + } + } + + #[test] + fn output_over_the_declared_size_is_refused() { + let z = zlib_compress_store(b"0123456789"); + let err = zlib_decompress(&z, 9).unwrap_err(); + assert_eq!(err.code, RefusalCode::GitObjectCorrupt); + } + + #[test] + fn every_truncation_and_bit_flip_is_refused_or_exact_without_panic() { + let z = zlib_compress_store(b"tree data\nblob data\n"); + for cut in 0..z.len() { + assert!(zlib_decompress(&z[..cut], 1 << 16).is_err()); + } + for bit in 0..z.len() * 8 { + let mut d = z.clone(); + d[bit / 8] ^= 1 << (bit % 8); + if let Ok((out, _)) = zlib_decompress(&d, 1 << 16) { + // Only a flip the checksums cannot see may decode; it must still be exact. + assert_eq!(crate::adler32(&out).to_be_bytes(), d[d.len() - 4..]); + } + } + } +} diff --git a/crates/synapse-git/src/lib.rs b/crates/synapse-git/src/lib.rs index ed43932..9a35261 100644 --- a/crates/synapse-git/src/lib.rs +++ b/crates/synapse-git/src/lib.rs @@ -2,6 +2,20 @@ //! bidirectional `ChangesetId <-> GitOid` index, explicit ref namespace contract //! (`refs/synapse/*` vs human `refs/heads/*`), and GitHub Pull Request projection //! builder (`synapse-git`, Gate 3). +//! +//! ADR 0003 step H1 (the Git bridge) adds the native Git object layer: [`object`] (object +//! kinds, IDs and links), [`inflate`] (zlib and DEFLATE decoding), [`pack`] (version 2 packs +//! and indexes, delta resolution), and [`repo`] (reading a repository's full history and +//! exporting an object set as a new bare repository with one pack). + +pub mod inflate; +pub mod object; +pub mod pack; +pub mod repo; + +pub use object::{GitObject, GitTreeEntry, ObjectKind}; +pub use pack::{PackIndexEntry, PackReader, WrittenPack}; +pub use repo::{export_repository, ExportReceipt, GitHistory, GitRepository}; use serde::{Deserialize, Serialize}; use sha1::Sha1; diff --git a/crates/synapse-git/src/object.rs b/crates/synapse-git/src/object.rs new file mode 100644 index 0000000..cfc7928 --- /dev/null +++ b/crates/synapse-git/src/object.rs @@ -0,0 +1,335 @@ +//! Git object model for the bridge (ADR 0003 step H1): the four object kinds, object IDs, and +//! the links between objects (a tree's entries, a commit's tree and parents, a tag's target), +//! following `gitformat-pack` (object types) and Git's object encoding +//! (` \0`, SHA-1 of that). +//! +//! Parsers here read only what the bridge needs to walk history. Every other byte of a commit +//! or tag (author, committer, signatures, extra headers, message) is kept as opaque data and +//! never rewritten, so a stored object re-encodes to the same Git object ID. + +use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; + +fn corrupt(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::GitObjectCorrupt, msg) +} + +/// The four Git object kinds; the discriminant is the pack type number (`OBJ_COMMIT` = 1 to +/// `OBJ_TAG` = 4 in `gitformat-pack`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ObjectKind { + Commit = 1, + Tree = 2, + Blob = 3, + Tag = 4, +} + +impl ObjectKind { + /// The kind name in an object header (`commit`, `tree`, `blob`, `tag`). + pub fn name(self) -> &'static str { + match self { + Self::Commit => "commit", + Self::Tree => "tree", + Self::Blob => "blob", + Self::Tag => "tag", + } + } + + pub fn from_name(name: &[u8]) -> SynapseResult { + match name { + b"commit" => Ok(Self::Commit), + b"tree" => Ok(Self::Tree), + b"blob" => Ok(Self::Blob), + b"tag" => Ok(Self::Tag), + other => Err(corrupt(format!( + "unknown Git object kind {:?}", + String::from_utf8_lossy(other) + ))), + } + } + + /// The pack type number (1 to 4). + pub fn pack_type(self) -> u8 { + self as u8 + } + + pub fn from_pack_type(t: u8) -> SynapseResult { + match t { + 1 => Ok(Self::Commit), + 2 => Ok(Self::Tree), + 3 => Ok(Self::Blob), + 4 => Ok(Self::Tag), + other => Err(corrupt(format!( + "pack type {other} is not a base object kind" + ))), + } + } +} + +/// One Git object: its kind and payload (the bytes after the ` \0` header). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GitObject { + pub kind: ObjectKind, + pub payload: Vec, +} + +impl GitObject { + pub fn new(kind: ObjectKind, payload: Vec) -> Self { + Self { kind, payload } + } + + /// The object's SHA-1 Git object ID. + pub fn oid(&self) -> GitOid { + GitOid::compute_git_object(self.kind.name(), &self.payload) + } + + /// The loose object encoding ` \0` (before zlib). + pub fn encode_loose(&self) -> Vec { + let header = format!("{} {}\0", self.kind.name(), self.payload.len()); + let mut out = Vec::with_capacity(header.len() + self.payload.len()); + out.extend_from_slice(header.as_bytes()); + out.extend_from_slice(&self.payload); + out + } + + /// Parse a decompressed loose object ` \0`; the size must match. + pub fn decode_loose(raw: &[u8]) -> SynapseResult { + let nul = raw + .iter() + .position(|&b| b == 0) + .ok_or_else(|| corrupt("loose object header has no NUL"))?; + let header = &raw[..nul]; + let space = header + .iter() + .position(|&b| b == b' ') + .ok_or_else(|| corrupt("loose object header has no space"))?; + let kind = ObjectKind::from_name(&header[..space])?; + let size = parse_decimal(&header[space + 1..])?; + let payload = &raw[nul + 1..]; + if payload.len() as u64 != size { + return Err(corrupt(format!( + "loose object declares {size} bytes but holds {}", + payload.len() + ))); + } + Ok(Self::new(kind, payload.to_vec())) + } +} + +fn parse_decimal(digits: &[u8]) -> SynapseResult { + if digits.is_empty() || (digits.len() > 1 && digits[0] == b'0') { + return Err(corrupt("object size is not canonical decimal")); + } + let mut value: u64 = 0; + for &d in digits { + if !d.is_ascii_digit() { + return Err(corrupt("object size is not decimal")); + } + value = value + .checked_mul(10) + .and_then(|v| v.checked_add(u64::from(d - b'0'))) + .ok_or_else(|| corrupt("object size overflows u64"))?; + } + Ok(value) +} + +/// One entry of a Git tree: the mode exactly as written (ASCII octal), the name bytes, and the +/// object ID it names. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GitTreeEntry { + pub mode: Vec, + pub name: Vec, + pub oid: GitOid, +} + +impl GitTreeEntry { + /// The kind of object this entry names, from its mode: `40000` a tree, `160000` a commit + /// (a gitlink, never present in this repository's object store), anything else a blob. + pub fn target_kind(&self) -> ObjectKind { + match self.mode.as_slice() { + b"40000" | b"040000" => ObjectKind::Tree, + b"160000" => ObjectKind::Commit, + _ => ObjectKind::Blob, + } + } +} + +/// Parse a tree payload: `( \0<20-byte oid>)*`. +pub fn parse_tree(payload: &[u8]) -> SynapseResult> { + let mut entries = Vec::new(); + let mut rest = payload; + while !rest.is_empty() { + let space = rest + .iter() + .position(|&b| b == b' ') + .ok_or_else(|| corrupt("tree entry has no space after its mode"))?; + let mode = &rest[..space]; + if mode.is_empty() || !mode.iter().all(|b| (b'0'..=b'7').contains(b)) { + return Err(corrupt("tree entry mode is not octal")); + } + let after = &rest[space + 1..]; + let nul = after + .iter() + .position(|&b| b == 0) + .ok_or_else(|| corrupt("tree entry name has no NUL"))?; + let oid_bytes = after + .get(nul + 1..nul + 21) + .ok_or_else(|| corrupt("tree entry truncated before its object ID"))?; + let mut oid = [0u8; 20]; + oid.copy_from_slice(oid_bytes); + entries.push(GitTreeEntry { + mode: mode.to_vec(), + name: after[..nul].to_vec(), + oid: GitOid(oid), + }); + rest = &after[nul + 21..]; + } + Ok(entries) +} + +/// Encode tree entries in the order given (callers keep Git's tree order). +pub fn encode_tree(entries: &[GitTreeEntry]) -> Vec { + let mut out = Vec::new(); + for e in entries { + out.extend_from_slice(&e.mode); + out.push(b' '); + out.extend_from_slice(&e.name); + out.push(0); + out.extend_from_slice(&e.oid.0); + } + out +} + +fn header_oid(value: &[u8], what: &str) -> SynapseResult { + let hex = std::str::from_utf8(value).map_err(|_| corrupt(format!("{what} is not hex")))?; + if hex.len() != 40 || hex.bytes().any(|b| b.is_ascii_uppercase()) { + return Err(corrupt(format!("{what} is not 40 lowercase hex digits"))); + } + GitOid::from_hex(hex) +} + +/// Header lines of a commit or tag up to the blank line (continuation lines starting with a +/// space belong to the header above them and are skipped). +fn header_lines(payload: &[u8]) -> impl Iterator { + let end = payload + .windows(2) + .position(|w| w == b"\n\n") + .map_or(payload.len(), |p| p + 1); + payload[..end] + .split(|&b| b == b'\n') + .filter(|l| !l.is_empty() && l[0] != b' ') +} + +/// The links of a commit: its tree and parents in their written order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CommitLinks { + pub tree: GitOid, + pub parents: Vec, +} + +/// Parse a commit's `tree` line (first) and `parent` lines (immediately after, in order). +pub fn parse_commit_links(payload: &[u8]) -> SynapseResult { + let mut lines = header_lines(payload); + let tree = match lines.next() { + Some(l) if l.starts_with(b"tree ") => header_oid(&l[5..], "commit tree")?, + _ => return Err(corrupt("commit does not start with a tree line")), + }; + let mut parents = Vec::new(); + for l in lines { + if let Some(hex) = l.strip_prefix(b"parent ") { + parents.push(header_oid(hex, "commit parent")?); + } else { + break; + } + } + Ok(CommitLinks { tree, parents }) +} + +/// The target of an annotated tag: its `object` and `type` lines. +pub fn parse_tag_target(payload: &[u8]) -> SynapseResult<(GitOid, ObjectKind)> { + let mut lines = header_lines(payload); + let object = match lines.next() { + Some(l) if l.starts_with(b"object ") => header_oid(&l[7..], "tag object")?, + _ => return Err(corrupt("tag does not start with an object line")), + }; + let kind = match lines.next() { + Some(l) if l.starts_with(b"type ") => ObjectKind::from_name(&l[5..])?, + _ => return Err(corrupt("tag has no type line after its object line")), + }; + Ok((object, kind)) +} + +/// Every object ID `object` links to, with the kind it must have: tree entries (gitlinks +/// excluded: they name commits of another repository), a commit's tree and parents, a tag's +/// target. +pub fn object_links(object: &GitObject) -> SynapseResult> { + Ok(match object.kind { + ObjectKind::Blob => Vec::new(), + ObjectKind::Tree => parse_tree(&object.payload)? + .into_iter() + .filter(|e| e.target_kind() != ObjectKind::Commit) + .map(|e| { + let kind = e.target_kind(); + (e.oid, kind) + }) + .collect(), + ObjectKind::Commit => { + let links = parse_commit_links(&object.payload)?; + let mut out = vec![(links.tree, ObjectKind::Tree)]; + out.extend(links.parents.into_iter().map(|p| (p, ObjectKind::Commit))); + out + } + ObjectKind::Tag => vec![parse_tag_target(&object.payload)?], + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn loose_encoding_round_trips_and_ids_match_git_known_values() { + // `git hash-object -t blob /dev/null` and `git mktree < /dev/null`. + let empty_blob = GitObject::new(ObjectKind::Blob, Vec::new()); + assert_eq!( + empty_blob.oid().to_hex(), + "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" + ); + let empty_tree = GitObject::new(ObjectKind::Tree, Vec::new()); + assert_eq!( + empty_tree.oid().to_hex(), + "4b825dc642cb6eb9a060e54bf8d69288fbee4904" + ); + let raw = empty_blob.encode_loose(); + assert_eq!(GitObject::decode_loose(&raw).unwrap(), empty_blob); + assert!(GitObject::decode_loose(b"blob 01\0x").is_err()); + assert!(GitObject::decode_loose(b"blob 2\0x").is_err()); + assert!(GitObject::decode_loose(b"blub 1\0x").is_err()); + } + + #[test] + fn commit_and_tag_links_parse_and_keep_parent_order() { + let c = b"tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ +parent 2222222222222222222222222222222222222222\n\ +parent 1111111111111111111111111111111111111111\n\ +author A 1 +0000\ncommitter A 1 +0000\n\nparent ffff\n"; + let links = parse_commit_links(c).unwrap(); + assert_eq!(links.parents.len(), 2); + assert_eq!(links.parents[0].0[0], 0x22); + let t = b"object 4b825dc642cb6eb9a060e54bf8d69288fbee4904\ntype tree\ntag v\n\nmsg\n"; + assert_eq!(parse_tag_target(t).unwrap().1, ObjectKind::Tree); + assert!(parse_commit_links(b"parent x\n").is_err()); + } + + #[test] + fn tree_entries_parse_and_re_encode_exactly() { + let mut payload = Vec::new(); + payload.extend_from_slice(b"100644 a.txt\0"); + payload.extend_from_slice(&[1u8; 20]); + payload.extend_from_slice(b"40000 dir\0"); + payload.extend_from_slice(&[2u8; 20]); + let entries = parse_tree(&payload).unwrap(); + assert_eq!(entries[1].target_kind(), ObjectKind::Tree); + assert_eq!(encode_tree(&entries), payload); + assert!(parse_tree(&payload[..payload.len() - 1]).is_err()); + } +} diff --git a/crates/synapse-git/src/pack.rs b/crates/synapse-git/src/pack.rs new file mode 100644 index 0000000..77f561b --- /dev/null +++ b/crates/synapse-git/src/pack.rs @@ -0,0 +1,730 @@ +//! Native Git packfile (version 2) and pack index (version 2) codec for the bridge (ADR 0003 +//! step H1, section 5.10: "Export ... written as packfiles, not loose objects"). Formats follow +//! `gitformat-pack` (Git 2.43 manual on this host): `PACK`, version, object count, entries of +//! "n-byte type and length (3-bit type, (n-1)*7+4-bit length)" then zlib data, deltified +//! entries (`OBJ_OFS_DELTA` 6 with the "offset encoding", `OBJ_REF_DELTA` 7 with the base +//! object name), and a trailing SHA-1 of everything before it. The index is `\377tOc`, +//! version 2, a 256-entry fan-out, sorted object names, CRC-32 of each packed entry, 31-bit +//! offsets with an 8-byte table for offsets of 2 GiB and more, the pack checksum, and its own +//! SHA-1. +//! +//! The writer emits whole (undeltified) objects in object ID order, so the same object set +//! always gives the same pack and index bytes. Deltas are read, never written: ADR 0003 keeps +//! deltas "only on the bridge wire" (thin packs, step H2). The reader resolves both delta +//! kinds and checks every size, offset and checksum before it trusts them; malformed input is +//! refused with `RefusalCode::GitObjectCorrupt`. + +use crate::inflate::zlib_decompress; +use crate::object::{GitObject, ObjectKind}; +use crate::zlib_compress_store; +use sha1::{Digest, Sha1}; +use std::collections::{BTreeMap, HashMap}; +use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; + +fn corrupt(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::GitObjectCorrupt, msg) +} + +const PACK_SIGNATURE: &[u8; 4] = b"PACK"; +const PACK_VERSION: u32 = 2; +const IDX_MAGIC: [u8; 4] = [0xff, b't', b'O', b'c']; +const IDX_VERSION: u32 = 2; +const OBJ_OFS_DELTA: u8 = 6; +const OBJ_REF_DELTA: u8 = 7; +/// Most bytes one resolved object may hold while reading a pack (a declared size above it is +/// refused before anything is allocated). +pub const MAX_PACK_OBJECT_BYTES: u64 = 1 << 30; +/// Longest delta chain the reader follows (Git's own `pack.depth` maximum is 4095). +pub const MAX_DELTA_CHAIN: usize = 4096; + +/// CRC-32 (IEEE 802.3, reflected polynomial 0xEDB88320), the checksum `gitformat-pack` puts in +/// the version 2 index for each packed entry (the same CRC zlib's `crc32` computes). +pub fn crc32(data: &[u8]) -> u32 { + static TABLE: std::sync::OnceLock<[u32; 256]> = std::sync::OnceLock::new(); + let table = TABLE.get_or_init(|| { + let mut t = [0u32; 256]; + for (i, slot) in t.iter_mut().enumerate() { + let mut c = i as u32; + for _ in 0..8 { + c = if c & 1 != 0 { + 0xedb8_8320 ^ (c >> 1) + } else { + c >> 1 + }; + } + *slot = c; + } + t + }); + let mut crc = !0u32; + for &b in data { + crc = table[((crc ^ u32::from(b)) & 0xff) as usize] ^ (crc >> 8); + } + !crc +} + +/// One object's place in a pack: its ID, the offset of its entry header, and the CRC-32 of the +/// whole packed entry (header, delta base reference, and compressed data). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PackIndexEntry { + pub oid: GitOid, + pub offset: u64, + pub crc32: u32, +} + +/// A written pack and its index. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WrittenPack { + pub pack: Vec, + pub idx: Vec, + /// The pack's trailing SHA-1, which also names the files (`pack-.pack`). + pub checksum: GitOid, + pub entries: Vec, +} + +fn encode_entry_header(pack_type: u8, size: u64, out: &mut Vec) { + let mut byte = (pack_type << 4) | (size & 0x0f) as u8; + let mut rest = size >> 4; + while rest != 0 { + out.push(byte | 0x80); + byte = (rest & 0x7f) as u8; + rest >>= 7; + } + out.push(byte); +} + +/// Write `objects` (duplicates collapse) as one version 2 pack of whole objects in object ID +/// order, and its version 2 index. The output is a function of the object set alone. +pub fn write_pack(objects: &[GitObject]) -> WrittenPack { + let mut by_oid: BTreeMap = BTreeMap::new(); + for object in objects { + by_oid.entry(object.oid()).or_insert(object); + } + let mut pack = Vec::new(); + pack.extend_from_slice(PACK_SIGNATURE); + pack.extend_from_slice(&PACK_VERSION.to_be_bytes()); + pack.extend_from_slice(&(by_oid.len() as u32).to_be_bytes()); + let mut entries = Vec::with_capacity(by_oid.len()); + for (oid, object) in &by_oid { + let offset = pack.len(); + encode_entry_header( + object.kind.pack_type(), + object.payload.len() as u64, + &mut pack, + ); + pack.extend_from_slice(&zlib_compress_store(&object.payload)); + entries.push(PackIndexEntry { + oid: *oid, + offset: offset as u64, + crc32: crc32(&pack[offset..]), + }); + } + let checksum: [u8; 20] = Sha1::digest(&pack).into(); + pack.extend_from_slice(&checksum); + let checksum = GitOid(checksum); + let idx = write_idx(&entries, checksum); + WrittenPack { + pack, + idx, + checksum, + entries, + } +} + +/// Encode a version 2 pack index for `entries` (sorted by object ID here) of the pack whose +/// trailing checksum is `pack_checksum`. +pub fn write_idx(entries: &[PackIndexEntry], pack_checksum: GitOid) -> Vec { + let mut sorted = entries.to_vec(); + sorted.sort_by_key(|e| e.oid); + let mut idx = Vec::with_capacity(8 + 1024 + sorted.len() * 28 + 40); + idx.extend_from_slice(&IDX_MAGIC); + idx.extend_from_slice(&IDX_VERSION.to_be_bytes()); + let mut fanout = [0u32; 256]; + for e in &sorted { + fanout[usize::from(e.oid.0[0])] += 1; + } + let mut running = 0u32; + for count in fanout { + running += count; + idx.extend_from_slice(&running.to_be_bytes()); + } + for e in &sorted { + idx.extend_from_slice(&e.oid.0); + } + for e in &sorted { + idx.extend_from_slice(&e.crc32.to_be_bytes()); + } + let mut large = Vec::new(); + for e in &sorted { + if e.offset < 0x8000_0000 { + idx.extend_from_slice(&(e.offset as u32).to_be_bytes()); + } else { + idx.extend_from_slice(&(0x8000_0000u32 | large.len() as u32).to_be_bytes()); + large.push(e.offset); + } + } + for offset in large { + idx.extend_from_slice(&offset.to_be_bytes()); + } + idx.extend_from_slice(&pack_checksum.0); + let own: [u8; 20] = Sha1::digest(&idx).into(); + idx.extend_from_slice(&own); + idx +} + +/// Decode and check a version 2 pack index: magic, version, monotone fan-out that matches the +/// names, strictly ascending names, offsets (large ones through the 8-byte table), and the +/// index's own SHA-1. Returns the entries in name order and the pack checksum it records. +pub fn decode_idx(idx: &[u8]) -> SynapseResult<(Vec, GitOid)> { + if idx.len() < 8 + 1024 + 40 || idx[..4] != IDX_MAGIC { + return Err(corrupt( + "pack index is not version 2 (bad magic or too short)", + )); + } + if u32::from_be_bytes([idx[4], idx[5], idx[6], idx[7]]) != IDX_VERSION { + return Err(corrupt("pack index version is not 2")); + } + let body = &idx[..idx.len() - 20]; + let own: [u8; 20] = Sha1::digest(body).into(); + if own[..] != idx[idx.len() - 20..] { + return Err(corrupt("pack index checksum mismatch")); + } + let be32 = |at: usize| u32::from_be_bytes([idx[at], idx[at + 1], idx[at + 2], idx[at + 3]]); + let mut prev = 0u32; + for i in 0..256 { + let v = be32(8 + i * 4); + if v < prev { + return Err(corrupt("pack index fan-out is not monotone")); + } + prev = v; + } + let n = prev as usize; + let names_at = 8 + 1024; + let crcs_at = names_at + n * 20; + let offs_at = crcs_at + n * 4; + let large_at = offs_at + n * 4; + if large_at + 40 > idx.len() { + return Err(corrupt("pack index is shorter than its object count")); + } + let large_len = idx.len() - 40 - large_at; + if !large_len.is_multiple_of(8) { + return Err(corrupt( + "pack index large offset table is not whole entries", + )); + } + let mut entries = Vec::with_capacity(n); + let mut large_used = 0usize; + for i in 0..n { + let mut oid = [0u8; 20]; + oid.copy_from_slice(&idx[names_at + i * 20..names_at + i * 20 + 20]); + let oid = GitOid(oid); + if let Some(last) = entries.last().map(|e: &PackIndexEntry| e.oid) { + if oid <= last { + return Err(corrupt("pack index names are not strictly ascending")); + } + } + let first = usize::from(oid.0[0]); + let below = if first == 0 { + 0 + } else { + be32(8 + (first - 1) * 4) + }; + if (i as u32) < below || (i as u32) >= be32(8 + first * 4) { + return Err(corrupt("pack index fan-out does not match its names")); + } + let raw = be32(offs_at + i * 4); + let offset = if raw & 0x8000_0000 == 0 { + u64::from(raw) + } else { + let slot = (raw & 0x7fff_ffff) as usize; + if slot * 8 + 8 > large_len { + return Err(corrupt("pack index large offset slot out of range")); + } + large_used = large_used.max(slot + 1); + let at = large_at + slot * 8; + let mut b = [0u8; 8]; + b.copy_from_slice(&idx[at..at + 8]); + u64::from_be_bytes(b) + }; + entries.push(PackIndexEntry { + oid, + offset, + crc32: be32(crcs_at + i * 4), + }); + } + if large_used * 8 != large_len { + return Err(corrupt("pack index large offset table has unused entries")); + } + let mut checksum = [0u8; 20]; + checksum.copy_from_slice(&idx[idx.len() - 40..idx.len() - 20]); + Ok((entries, GitOid(checksum))) +} + +/// One raw pack entry before delta resolution. +enum RawEntry { + Whole(ObjectKind, Vec), + OfsDelta(u64, Vec), + RefDelta(GitOid, Vec), +} + +/// A version 2 (or 3) pack held in memory with its object ID to offset map. Objects are +/// resolved on demand (delta chains followed iteratively) and checked against the requested +/// object ID. +pub struct PackReader { + data: Vec, + by_oid: HashMap, + entries: Vec, + cache: HashMap>)>, + cache_bytes: usize, +} + +const CACHE_BOUND_BYTES: usize = 256 << 20; + +fn check_pack_framing(data: &[u8]) -> SynapseResult { + if data.len() < 12 + 20 || &data[..4] != PACK_SIGNATURE { + return Err(corrupt("not a Git pack (bad signature or too short)")); + } + let version = u32::from_be_bytes([data[4], data[5], data[6], data[7]]); + if version != 2 && version != 3 { + return Err(corrupt(format!("pack version {version} is not 2 or 3"))); + } + let body = &data[..data.len() - 20]; + let sum: [u8; 20] = Sha1::digest(body).into(); + if sum[..] != data[data.len() - 20..] { + return Err(corrupt("pack checksum mismatch")); + } + Ok(u32::from_be_bytes([data[8], data[9], data[10], data[11]])) +} + +impl PackReader { + /// Open a pack with its version 2 index (as Git writes them side by side). The index must + /// record this pack's checksum and name exactly the pack's object count; every offset must + /// fall inside the pack body. + pub fn with_index(data: Vec, idx: &[u8]) -> SynapseResult { + let count = check_pack_framing(&data)?; + let (entries, pack_sum) = decode_idx(idx)?; + if pack_sum.0[..] != data[data.len() - 20..] { + return Err(corrupt("pack index names a different pack checksum")); + } + if entries.len() != count as usize { + return Err(corrupt( + "pack index object count differs from the pack header", + )); + } + let body_end = (data.len() - 20) as u64; + let mut by_oid = HashMap::with_capacity(entries.len()); + for e in &entries { + if e.offset < 12 || e.offset >= body_end { + return Err(corrupt("pack index offset outside the pack body")); + } + by_oid.insert(e.oid, e.offset); + } + Ok(Self { + data, + by_oid, + entries, + cache: HashMap::new(), + cache_bytes: 0, + }) + } + + /// Index a pack with no index file (`git index-pack` done natively): walk every entry in + /// order, resolve it, and compute its object ID and CRC-32. The entries must end exactly at + /// the trailing checksum. Every `OBJ_REF_DELTA` base must be in the pack (a self-contained + /// pack, as `gitformat-pack` requires on disk). + pub fn index(data: Vec) -> SynapseResult { + let count = check_pack_framing(&data)?; + let body_end = data.len() - 20; + let mut offsets = Vec::with_capacity(count as usize); + let mut pos = 12usize; + for _ in 0..count { + if pos >= body_end { + return Err(corrupt("pack holds fewer entries than its header declares")); + } + let (_, next) = read_raw_entry(&data[..body_end], pos as u64)?; + offsets.push((pos as u64, crc32(&data[pos..next]))); + pos = next; + } + if pos != body_end { + return Err(corrupt( + "pack has bytes between its last entry and its checksum", + )); + } + let mut reader = Self { + data, + by_oid: HashMap::with_capacity(offsets.len()), + entries: Vec::with_capacity(offsets.len()), + cache: HashMap::new(), + cache_bytes: 0, + }; + // Whole objects and offset deltas resolve by position alone; reference deltas need + // their base's ID first, so repeat until every entry is resolved or nothing moves. + let mut pending: Vec<(u64, u32)> = offsets; + while !pending.is_empty() { + let mut next_round = Vec::new(); + for (offset, crc) in pending.iter().copied() { + match reader.resolve_at(offset) { + Ok((kind, payload)) => { + let oid = GitOid::compute_git_object(kind.name(), &payload); + if reader.by_oid.insert(oid, offset).is_some() { + return Err(corrupt(format!("pack holds object {oid} twice"))); + } + reader.entries.push(PackIndexEntry { + oid, + offset, + crc32: crc, + }); + } + Err(e) if e.message.starts_with(MISSING_REF_BASE) => { + next_round.push((offset, crc)) + } + Err(e) => return Err(e), + } + } + if next_round.len() == pending.len() { + return Err(corrupt( + "pack has reference deltas whose base is not in the pack (thin pack)", + )); + } + pending = next_round; + } + reader.entries.sort_by_key(|e| e.oid); + Ok(reader) + } + + /// Entries in object ID order. + pub fn entries(&self) -> &[PackIndexEntry] { + &self.entries + } + + pub fn contains(&self, oid: GitOid) -> bool { + self.by_oid.contains_key(&oid) + } + + /// Read and resolve object `oid`, checking that its content hashes to `oid`. + pub fn read(&mut self, oid: GitOid) -> SynapseResult> { + let Some(&offset) = self.by_oid.get(&oid) else { + return Ok(None); + }; + let (kind, payload) = self.resolve_at(offset)?; + let object = GitObject::new(kind, payload.as_ref().clone()); + if object.oid() != oid { + return Err(corrupt(format!( + "pack object at offset {offset} hashes to {} not {oid}", + object.oid() + ))); + } + Ok(Some(object)) + } + + fn remember(&mut self, offset: u64, kind: ObjectKind, payload: std::sync::Arc>) { + if self.cache_bytes + payload.len() > CACHE_BOUND_BYTES { + self.cache.clear(); + self.cache_bytes = 0; + } + self.cache_bytes += payload.len(); + self.cache.insert(offset, (kind, payload)); + } + + fn resolve_at(&mut self, offset: u64) -> SynapseResult<(ObjectKind, std::sync::Arc>)> { + let body_end = self.data.len() - 20; + let mut chain: Vec<(u64, Vec)> = Vec::new(); + let mut at = offset; + let (kind, mut payload) = loop { + if let Some((kind, payload)) = self.cache.get(&at) { + break (*kind, payload.clone()); + } + if chain.len() > MAX_DELTA_CHAIN { + return Err(corrupt( + "pack delta chain is longer than the reader follows", + )); + } + let (raw, _) = read_raw_entry(&self.data[..body_end], at)?; + match raw { + RawEntry::Whole(kind, payload) => break (kind, std::sync::Arc::new(payload)), + RawEntry::OfsDelta(base, delta) => { + chain.push((at, delta)); + at = base; + } + RawEntry::RefDelta(base_oid, delta) => { + let base = *self + .by_oid + .get(&base_oid) + .ok_or_else(|| corrupt(format!("{MISSING_REF_BASE} {base_oid}")))?; + chain.push((at, delta)); + at = base; + } + } + if chain.iter().any(|(o, _)| *o == at) { + return Err(corrupt("pack delta chain loops")); + } + }; + while let Some((at, delta)) = chain.pop() { + payload = std::sync::Arc::new(apply_delta(&payload, &delta)?); + self.remember(at, kind, payload.clone()); + } + Ok((kind, payload)) + } +} + +const MISSING_REF_BASE: &str = "pack reference delta base not found:"; + +fn read_size_encoding(data: &[u8], pos: &mut usize) -> SynapseResult { + let mut value = 0u64; + let mut shift = 0u32; + loop { + let byte = *data + .get(*pos) + .ok_or_else(|| corrupt("size encoding truncated"))?; + *pos += 1; + if shift > 63 || (shift == 63 && byte & 0x7e != 0) { + return Err(corrupt("size encoding overflows u64")); + } + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Ok(value); + } + shift += 7; + } +} + +/// Read the entry at `offset`: header, delta base, and decompressed data. Returns the entry +/// and the offset just past it. +fn read_raw_entry(body: &[u8], offset: u64) -> SynapseResult<(RawEntry, usize)> { + let mut pos = usize::try_from(offset).map_err(|_| corrupt("pack offset overflows"))?; + let first = *body + .get(pos) + .ok_or_else(|| corrupt("pack entry offset past the pack body"))?; + pos += 1; + let pack_type = (first >> 4) & 0x07; + let mut size = u64::from(first & 0x0f); + if first & 0x80 != 0 { + let rest = read_size_encoding(body, &mut pos)?; + if rest > (u64::MAX >> 4) { + return Err(corrupt("pack entry size overflows u64")); + } + size |= rest << 4; + } + if size > MAX_PACK_OBJECT_BYTES { + return Err(corrupt(format!( + "pack entry declares {size} bytes, over the {MAX_PACK_OBJECT_BYTES} byte cap" + ))); + } + let entry_start = offset; + let base = match pack_type { + 1..=4 => None, + OBJ_OFS_DELTA => { + let mut byte = *body + .get(pos) + .ok_or_else(|| corrupt("offset delta truncated"))?; + pos += 1; + let mut back = u64::from(byte & 0x7f); + while byte & 0x80 != 0 { + byte = *body + .get(pos) + .ok_or_else(|| corrupt("offset delta truncated"))?; + pos += 1; + back = back + .checked_add(1) + .and_then(|b| b.checked_mul(128)) + .map(|b| b | u64::from(byte & 0x7f)) + .ok_or_else(|| corrupt("offset delta overflows"))?; + } + if back == 0 || back > entry_start { + return Err(corrupt("offset delta base is not before the entry")); + } + Some(Ok(entry_start - back)) + } + OBJ_REF_DELTA => { + let raw = body + .get(pos..pos + 20) + .ok_or_else(|| corrupt("reference delta truncated"))?; + pos += 20; + let mut oid = [0u8; 20]; + oid.copy_from_slice(raw); + Some(Err(GitOid(oid))) + } + other => return Err(corrupt(format!("pack entry type {other} is invalid"))), + }; + let (data, used) = zlib_decompress(&body[pos..], size as usize)?; + if data.len() as u64 != size { + return Err(corrupt(format!( + "pack entry declares {size} bytes but inflates to {}", + data.len() + ))); + } + let entry = match base { + None => RawEntry::Whole(ObjectKind::from_pack_type(pack_type)?, data), + Some(Ok(base)) => RawEntry::OfsDelta(base, data), + Some(Err(oid)) => RawEntry::RefDelta(oid, data), + }; + Ok((entry, pos + used)) +} + +/// Apply a Git delta (`gitformat-pack`, "Deltified representation") to `base`. +pub fn apply_delta(base: &[u8], delta: &[u8]) -> SynapseResult> { + let mut pos = 0usize; + let base_size = read_size_encoding(delta, &mut pos)?; + if base_size != base.len() as u64 { + return Err(corrupt(format!( + "delta expects a {base_size} byte base, base has {}", + base.len() + ))); + } + let result_size = read_size_encoding(delta, &mut pos)?; + if result_size > MAX_PACK_OBJECT_BYTES { + return Err(corrupt("delta result is over the object byte cap")); + } + let mut out = Vec::with_capacity(result_size as usize); + while pos < delta.len() { + let op = delta[pos]; + pos += 1; + if op & 0x80 != 0 { + let mut fields = [0u64; 7]; + for (bit, field) in fields.iter_mut().enumerate() { + if op & (1 << bit) != 0 { + *field = u64::from( + *delta + .get(pos) + .ok_or_else(|| corrupt("delta copy instruction truncated"))?, + ); + pos += 1; + } + } + let offset = fields[0] | fields[1] << 8 | fields[2] << 16 | fields[3] << 24; + let mut size = fields[4] | fields[5] << 8 | fields[6] << 16; + if size == 0 { + size = 0x10000; + } + let end = offset + .checked_add(size) + .filter(|&e| e <= base.len() as u64) + .ok_or_else(|| corrupt("delta copy reaches past the base"))?; + out.extend_from_slice(&base[offset as usize..end as usize]); + } else if op != 0 { + let n = usize::from(op); + let data = delta + .get(pos..pos + n) + .ok_or_else(|| corrupt("delta insert instruction truncated"))?; + out.extend_from_slice(data); + pos += n; + } else { + return Err(corrupt("delta instruction 0 is reserved")); + } + if out.len() as u64 > result_size { + return Err(corrupt("delta output exceeds its declared size")); + } + } + if out.len() as u64 != result_size { + return Err(corrupt(format!( + "delta declares {result_size} bytes, produced {}", + out.len() + ))); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc32_matches_the_ieee_check_value() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + assert_eq!(crc32(b""), 0); + } + + #[test] + fn written_pack_indexes_back_to_the_same_entries_and_objects() { + let objects = vec![ + GitObject::new(ObjectKind::Blob, b"hello\n".to_vec()), + GitObject::new(ObjectKind::Blob, vec![7u8; 70_000]), + GitObject::new(ObjectKind::Tree, Vec::new()), + GitObject::new(ObjectKind::Blob, b"hello\n".to_vec()), + ]; + let written = write_pack(&objects); + assert_eq!(written.entries.len(), 3); + assert_eq!(write_pack(&objects), written, "deterministic"); + let mut reader = PackReader::index(written.pack.clone()).unwrap(); + assert_eq!(reader.entries(), &written.entries[..]); + let (decoded, sum) = decode_idx(&written.idx).unwrap(); + assert_eq!(decoded, written.entries); + assert_eq!(sum, written.checksum); + for o in &objects { + assert_eq!(reader.read(o.oid()).unwrap().as_ref(), Some(o)); + } + let mut with_idx = PackReader::with_index(written.pack.clone(), &written.idx).unwrap(); + assert_eq!( + with_idx.read(objects[1].oid()).unwrap().as_ref(), + Some(&objects[1]) + ); + } + + #[test] + fn large_offsets_use_the_eight_byte_table() { + let entries = vec![ + PackIndexEntry { + oid: GitOid([1; 20]), + offset: 12, + crc32: 5, + }, + PackIndexEntry { + oid: GitOid([2; 20]), + offset: 0x1_0000_0000, + crc32: 6, + }, + ]; + let idx = write_idx(&entries, GitOid([9; 20])); + assert_eq!(decode_idx(&idx).unwrap(), (entries, GitOid([9; 20]))); + } + + #[test] + fn delta_copy_and_insert_apply_and_bad_deltas_are_refused() { + let base = b"0123456789abcdef"; + // base 16, result 7: copy offset 10 size 3 ("abc"), insert "XYZ!"? (4 bytes). + let delta = [16u8, 7, 0x91, 10, 3, 4, b'X', b'Y', b'Z', b'!']; + assert_eq!(apply_delta(base, &delta).unwrap(), b"abcXYZ!"); + assert!( + apply_delta(base, &[15, 7, 0x91, 10, 3]).is_err(), + "base size" + ); + assert!( + apply_delta(base, &[16, 3, 0x91, 15, 3]).is_err(), + "copy past base" + ); + assert!(apply_delta(base, &[16, 3, 0x00]).is_err(), "reserved op"); + assert!( + apply_delta(base, &[16, 4, 0x91, 10, 3]).is_err(), + "short result" + ); + } + + #[test] + fn every_truncation_and_bit_flip_of_a_pack_is_refused_without_panic() { + let written = write_pack(&[ + GitObject::new(ObjectKind::Blob, b"a".to_vec()), + GitObject::new(ObjectKind::Tree, Vec::new()), + ]); + let p = &written.pack; + for cut in 0..p.len() { + assert!(PackReader::index(p[..cut].to_vec()).is_err()); + } + for bit in 0..p.len() * 8 { + let mut d = p.clone(); + d[bit / 8] ^= 1 << (bit % 8); + assert!(PackReader::index(d.clone()).is_err(), "flip {bit}"); + assert!( + PackReader::with_index(d, &written.idx).is_err(), + "flip {bit}" + ); + } + for bit in 0..written.idx.len() * 8 { + let mut d = written.idx.clone(); + d[bit / 8] ^= 1 << (bit % 8); + assert!( + PackReader::with_index(p.clone(), &d).is_err(), + "idx flip {bit}" + ); + } + } +} diff --git a/crates/synapse-git/src/repo.rs b/crates/synapse-git/src/repo.rs new file mode 100644 index 0000000..674bbad --- /dev/null +++ b/crates/synapse-git/src/repo.rs @@ -0,0 +1,334 @@ +//! Native Git repository reader and pack exporter for the bridge (ADR 0003 step H1). +//! +//! [`GitRepository`] reads a repository's object database directly: loose objects +//! (`objects/xx/<38 hex>`, zlib) and every `objects/pack/pack-*.pack` with its version 2 +//! `.idx`, resolving deltas natively; and its references (loose refs, `packed-refs`, `HEAD`). +//! [`GitRepository::full_history`] collects every object reachable from every reference, so an +//! import sees the whole history: merge parents, annotated tags (including tags of tags), +//! file modes, and signatures inside commit and tag headers. +//! +//! [`export_repository`] writes an object set into a new bare repository as one pack and its +//! index plus the references, never as loose objects. It refuses an existing destination, so it +//! can never move a human branch of a repository that already exists. +//! +//! No Git process is started here; the system `git` is used only by the tests, as an +//! independent oracle. + +use crate::inflate::zlib_decompress; +use crate::object::{object_links, GitObject, ObjectKind}; +use crate::pack::{write_pack, PackReader, WrittenPack}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fs::{self, File}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; + +fn corrupt(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::GitObjectCorrupt, msg) +} + +fn io(e: std::io::Error, what: &Path) -> SynapseError { + SynapseError::new(RefusalCode::IoFailure, format!("{}: {e}", what.display())) +} + +/// Most bytes a loose object may inflate to. +pub const MAX_LOOSE_OBJECT_BYTES: usize = 1 << 30; + +/// A Git repository opened for reading (its `.git` directory or a bare repository). +pub struct GitRepository { + git_dir: PathBuf, + packs: Vec, +} + +/// Every object reachable from a repository's references, with the references themselves. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GitHistory { + /// Reference name to object ID (`refs/...`), sorted by name. + pub refs: BTreeMap, + /// The branch `HEAD` names (`refs/heads/...`), or `None` for a detached or missing `HEAD`. + pub head: Option, + /// Every reachable object, keyed by ID. + pub objects: BTreeMap, +} + +impl GitRepository { + /// Open `git_dir` and load the index of every pack in `objects/pack` (a pack without its + /// `.idx` is ignored, as Git ignores it). + pub fn open(git_dir: &Path) -> SynapseResult { + let objects = git_dir.join("objects"); + if !objects.is_dir() { + return Err(SynapseError::new( + RefusalCode::PathInvalid, + format!("{} has no objects directory", git_dir.display()), + )); + } + if git_dir.join("objects/info/alternates").exists() { + return Err(corrupt( + "repositories with alternate object stores are not read by the bridge", + )); + } + let mut packs = Vec::new(); + let pack_dir = objects.join("pack"); + if pack_dir.is_dir() { + let mut names: Vec = fs::read_dir(&pack_dir) + .map_err(|e| io(e, &pack_dir))? + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.extension().is_some_and(|x| x == "idx")) + .collect(); + names.sort(); + for idx_path in names { + let pack_path = idx_path.with_extension("pack"); + if !pack_path.exists() { + continue; + } + let idx = fs::read(&idx_path).map_err(|e| io(e, &idx_path))?; + let data = fs::read(&pack_path).map_err(|e| io(e, &pack_path))?; + packs.push(PackReader::with_index(data, &idx)?); + } + } + Ok(Self { + git_dir: git_dir.to_path_buf(), + packs, + }) + } + + /// Read object `oid` from the packs or the loose store, checking that it hashes to `oid`. + pub fn read_object(&mut self, oid: GitOid) -> SynapseResult> { + for pack in &mut self.packs { + if let Some(object) = pack.read(oid)? { + return Ok(Some(object)); + } + } + let hex = oid.to_hex(); + let path = self.git_dir.join("objects").join(&hex[..2]).join(&hex[2..]); + let compressed = match fs::read(&path) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io(e, &path)), + }; + let (raw, used) = zlib_decompress(&compressed, MAX_LOOSE_OBJECT_BYTES)?; + if used != compressed.len() { + return Err(corrupt(format!("loose object {hex} has trailing bytes"))); + } + let object = GitObject::decode_loose(&raw)?; + if object.oid() != oid { + return Err(corrupt(format!( + "loose object {hex} hashes to {}", + object.oid() + ))); + } + Ok(Some(object)) + } + + /// Every reference: loose refs under `refs/` override `packed-refs`; peeled lines (`^`) + /// and comments are skipped. Also returns the branch `HEAD` points to, if symbolic. + pub fn refs(&self) -> SynapseResult<(BTreeMap, Option)> { + let mut refs = BTreeMap::new(); + let packed = self.git_dir.join("packed-refs"); + if packed.exists() { + let text = fs::read_to_string(&packed).map_err(|e| io(e, &packed))?; + for line in text.lines() { + if line.is_empty() || line.starts_with('#') || line.starts_with('^') { + continue; + } + let (hex, name) = line + .split_once(' ') + .ok_or_else(|| corrupt("malformed packed-refs line"))?; + refs.insert(name.to_string(), GitOid::from_hex(hex)?); + } + } + let mut stack = vec![self.git_dir.join("refs")]; + while let Some(dir) = stack.pop() { + if !dir.is_dir() { + continue; + } + for entry in fs::read_dir(&dir).map_err(|e| io(e, &dir))? { + let path = entry.map_err(|e| io(e, &dir))?.path(); + if path.is_dir() { + stack.push(path); + continue; + } + let rel = path + .strip_prefix(&self.git_dir) + .ok() + .and_then(|p| p.to_str()) + .ok_or_else(|| corrupt("reference name is not UTF-8"))? + .replace(std::path::MAIN_SEPARATOR, "/"); + let text = fs::read_to_string(&path).map_err(|e| io(e, &path))?; + let value = text.trim_end(); + if value.starts_with("ref: ") { + // Symbolic refs other than HEAD (for example refs/remotes/origin/HEAD) + // name another ref; the target is exported on its own. + continue; + } + refs.insert(rel, GitOid::from_hex(value)?); + } + } + let head_path = self.git_dir.join("HEAD"); + let head = match fs::read_to_string(&head_path) { + Ok(text) => text + .trim_end() + .strip_prefix("ref: ") + .map(|name| name.to_string()), + Err(_) => None, + }; + Ok((refs, head)) + } + + /// Collect every object reachable from every reference (breadth first). A missing object + /// or an object of the wrong kind for its link is refused (`GitObjectCorrupt`): a partial + /// or shallow repository cannot be imported as full history. + pub fn full_history(&mut self) -> SynapseResult { + if self.git_dir.join("shallow").exists() { + return Err(corrupt("shallow repositories do not hold full history")); + } + let (refs, head) = self.refs()?; + let mut objects = BTreeMap::new(); + let mut queued: BTreeSet = BTreeSet::new(); + let mut queue: VecDeque<(GitOid, Option)> = VecDeque::new(); + for oid in refs.values() { + if queued.insert(*oid) { + queue.push_back((*oid, None)); + } + } + while let Some((oid, expected)) = queue.pop_front() { + let object = self + .read_object(oid)? + .ok_or_else(|| corrupt(format!("object {oid} is missing")))?; + if let Some(kind) = expected { + if object.kind != kind { + return Err(corrupt(format!( + "object {oid} is a {} where a {} is linked", + object.kind.name(), + kind.name() + ))); + } + } + for (link, kind) in object_links(&object)? { + if queued.insert(link) { + queue.push_back((link, Some(kind))); + } + } + objects.insert(oid, object); + } + Ok(GitHistory { + refs, + head, + objects, + }) + } +} + +/// What [`export_repository`] wrote. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExportReceipt { + pub pack_path: PathBuf, + pub idx_path: PathBuf, + pub pack_checksum: GitOid, + pub object_count: usize, + pub pack_bytes: u64, +} + +fn write_file_synced(path: &Path, bytes: &[u8]) -> SynapseResult<()> { + let tmp = path.with_extension(format!("tmp.{}", std::process::id())); + { + let mut f = File::create(&tmp).map_err(|e| io(e, &tmp))?; + f.write_all(bytes).map_err(|e| io(e, &tmp))?; + f.sync_all().map_err(|e| io(e, &tmp))?; + } + fs::rename(&tmp, path).map_err(|e| io(e, path)) +} + +fn valid_ref_name(name: &str) -> bool { + name.starts_with("refs/") + && !name.ends_with('/') + && !name.ends_with(".lock") + && name + .split('/') + .all(|c| !c.is_empty() && !c.starts_with('.') && c != ".." && !c.contains("..")) + && !name + .bytes() + .any(|b| b < 0x20 || b == 0x7f || b" ~^:?*[\\".contains(&b)) +} + +/// Create the bare repository `dest` (which must not exist) holding `objects` as one version 2 +/// pack with its index, the references `refs`, and `HEAD` naming `head` (default +/// `refs/heads/main`). Every reference must name an object in the set. Returns where the pack +/// went; the same inputs always give the same pack bytes. +pub fn export_repository( + dest: &Path, + objects: &[GitObject], + refs: &BTreeMap, + head: Option<&str>, +) -> SynapseResult { + if dest.exists() { + return Err(SynapseError::new( + RefusalCode::PathInvalid, + format!( + "{} already exists; export writes only a new repository", + dest.display() + ), + )); + } + let present: BTreeSet = objects.iter().map(GitObject::oid).collect(); + for (name, oid) in refs { + if !valid_ref_name(name) { + return Err(SynapseError::new( + RefusalCode::PathInvalid, + format!("invalid reference name {name:?}"), + )); + } + if !present.contains(oid) { + return Err(corrupt(format!( + "reference {name} names {oid}, not exported" + ))); + } + } + let head = head.unwrap_or("refs/heads/main"); + if !valid_ref_name(head) { + return Err(SynapseError::new( + RefusalCode::PathInvalid, + format!("invalid HEAD target {head:?}"), + )); + } + let pack_dir = dest.join("objects/pack"); + for dir in [ + pack_dir.clone(), + dest.join("objects/info"), + dest.join("refs/heads"), + dest.join("refs/tags"), + ] { + fs::create_dir_all(&dir).map_err(|e| io(e, &dir))?; + } + write_file_synced( + &dest.join("config"), + b"[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n", + )?; + let WrittenPack { + pack, + idx, + checksum, + entries, + } = write_pack(objects); + let base = pack_dir.join(format!("pack-{}", checksum.to_hex())); + let pack_path = base.with_extension("pack"); + let idx_path = base.with_extension("idx"); + // The pack first, then its index: Git ignores a pack until its index exists. + write_file_synced(&pack_path, &pack)?; + write_file_synced(&idx_path, &idx)?; + for (name, oid) in refs { + let path = dest.join(name); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| io(e, parent))?; + } + write_file_synced(&path, format!("{}\n", oid.to_hex()).as_bytes())?; + } + write_file_synced(&dest.join("HEAD"), format!("ref: {head}\n").as_bytes())?; + Ok(ExportReceipt { + pack_path, + idx_path, + pack_checksum: checksum, + object_count: entries.len(), + pack_bytes: pack.len() as u64, + }) +} diff --git a/crates/synapse-git/tests/h1_git_bridge.rs b/crates/synapse-git/tests/h1_git_bridge.rs new file mode 100644 index 0000000..3f222f7 --- /dev/null +++ b/crates/synapse-git/tests/h1_git_bridge.rs @@ -0,0 +1,563 @@ +//! ADR 0003 step H1 (issue #48), first cut: the native Git object layer. The system `git` is +//! used here only as an independent oracle (it builds fixture history, then checks what the +//! native reader read and what the native exporter wrote: `cat-file`, `for-each-ref`, +//! `verify-pack`, `fsck --full --strict`, `clone`). Nothing in `synapse-git` starts a Git +//! process for these paths. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use synapse_core::{GitOid, RefusalCode}; +use synapse_git::pack::{decode_idx, PackReader}; +use synapse_git::{export_repository, GitHistory, GitObject, GitRepository, ObjectKind}; + +fn temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "synapse-h1-{label}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Run `git -C dir args` with no user or system configuration and fixed identities and dates, +/// so fixture history is the same on every host. +fn git_raw(dir: &Path, args: &[&str], stdin: Option<&[u8]>) -> Output { + let mut cmd = Command::new("git"); + cmd.arg("-C") + .arg(dir) + .args(args) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_AUTHOR_NAME", "Fixture Author") + .env("GIT_AUTHOR_EMAIL", "author@fixture.invalid") + .env("GIT_AUTHOR_DATE", "1700000000 +0000") + .env("GIT_COMMITTER_NAME", "Fixture Committer") + .env("GIT_COMMITTER_EMAIL", "committer@fixture.invalid") + .env("GIT_COMMITTER_DATE", "1700000000 +0000"); + if let Some(input) = stdin { + use std::io::Write; + cmd.stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + let mut child = cmd.spawn().unwrap(); + child.stdin.take().unwrap().write_all(input).unwrap(); + child.wait_with_output().unwrap() + } else { + cmd.output().unwrap() + } +} + +fn git(dir: &Path, args: &[&str]) -> Vec { + let out = git_raw(dir, args, None); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +fn git_text(dir: &Path, args: &[&str]) -> String { + String::from_utf8(git(dir, args)) + .unwrap() + .trim() + .to_string() +} + +fn write(dir: &Path, rel: &str, bytes: &[u8]) { + let path = dir.join(rel); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, bytes).unwrap(); +} + +fn commit_all(dir: &Path, msg: &str) { + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "--allow-empty", "-m", msg]); +} + +/// Deterministic pseudo-random bytes (xorshift), so the binary blob is incompressible. +fn noise(len: usize, seed: u64) -> Vec { + let mut x = seed | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +/// Real Git history with every shape the bridge must carry: nested trees, executable files, +/// a symlink, an empty file, an incompressible binary, a large compressible file revised many +/// times (delta material), a two-parent merge, an octopus merge, an empty commit, annotated +/// tags of a commit, a tree, a blob and another tag, a lightweight tag, and a commit with a +/// multi-line signature header and an `encoding` header. +fn build_fixture(dir: &Path) { + git(dir, &["init", "-q", "-b", "main"]); + let mut big = String::new(); + for i in 0..6000 { + big.push_str(&format!( + "line {i}: the quick brown fox jumps over the lazy dog\n" + )); + } + write(dir, "README.md", b"# fixture\n"); + write(dir, "src/lib.rs", b"pub fn one() -> u32 { 1 }\n"); + write(dir, "src/deep/nested/mod.rs", b"// nested\n"); + write(dir, "data/empty.txt", b""); + write(dir, "data/noise.bin", &noise(40_000, 7)); + write(dir, "docs/big.txt", big.as_bytes()); + write(dir, "tools/run.sh", b"#!/bin/sh\necho run\n"); + let mut perms = fs::metadata(dir.join("tools/run.sh")) + .unwrap() + .permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755); + fs::set_permissions(dir.join("tools/run.sh"), perms).unwrap(); + std::os::unix::fs::symlink("../README.md", dir.join("docs/readme-link")).unwrap(); + commit_all(dir, "initial"); + for rev in 0..12 { + let edited = big.replace( + &format!("line {}:", rev * 400), + &format!("LINE {} (rev {rev}):", rev * 400), + ); + write(dir, "docs/big.txt", edited.as_bytes()); + write( + dir, + "src/lib.rs", + format!("pub fn one() -> u32 {{ {rev} }}\n").as_bytes(), + ); + commit_all(dir, &format!("revision {rev}")); + } + git(dir, &["tag", "-a", "v1", "-m", "release v1"]); + git(dir, &["tag", "light"]); + git(dir, &["checkout", "-q", "-b", "feature"]); + write(dir, "src/feature.rs", b"pub fn feature() {}\n"); + commit_all(dir, "feature work"); + git(dir, &["checkout", "-q", "main"]); + write(dir, "src/main_only.rs", b"fn main_only() {}\n"); + commit_all(dir, "main work"); + git( + dir, + &["merge", "-q", "--no-ff", "feature", "-m", "merge feature"], + ); + for name in ["oct-a", "oct-b"] { + git(dir, &["checkout", "-q", "-b", name, "main"]); + write(dir, &format!("{name}.txt"), name.as_bytes()); + commit_all(dir, name); + } + git(dir, &["checkout", "-q", "main"]); + git( + dir, + &["merge", "-q", "--no-ff", "oct-a", "oct-b", "-m", "octopus"], + ); + commit_all(dir, "empty commit"); + let tree = git_text(dir, &["rev-parse", "HEAD^{tree}"]); + let blob = git_text(dir, &["rev-parse", "HEAD:README.md"]); + git( + dir, + &["tag", "-a", "tree-tag", &tree, "-m", "a tag of a tree"], + ); + git( + dir, + &["tag", "-a", "blob-tag", &blob, "-m", "a tag of a blob"], + ); + git( + dir, + &[ + "tag", + "-a", + "-f", + "nested-tag", + "v1", + "-m", + "a tag of a tag", + ], + ); + // Objects reachable only through a tag: a blob in no tree, and an inner tag whose own + // reference is deleted, so only the outer tag reaches it. + let out = git_raw( + dir, + &["hash-object", "-w", "--stdin"], + Some(b"reachable only through a tag\n"), + ); + let lone_blob = String::from_utf8(out.stdout).unwrap().trim().to_string(); + git( + dir, + &[ + "tag", + "-a", + "lone-blob-tag", + &lone_blob, + "-m", + "tag of a lone blob", + ], + ); + git(dir, &["tag", "-a", "inner", "v1", "-m", "inner tag"]); + git( + dir, + &["tag", "-a", "-f", "outer-only", "inner", "-m", "outer tag"], + ); + git(dir, &["tag", "-d", "inner"]); + // A commit with a multi-line signature header and an encoding header, written as raw + // bytes (no signing key is involved: the header is opaque data to Git and to the bridge). + let head = git_text(dir, &["rev-parse", "HEAD"]); + let raw = format!( + "tree {tree}\nparent {head}\n\ +author Fixture Author 1700000001 +0100\n\ +committer Fixture Committer 1700000002 -0230\n\ +encoding ISO-8859-1\n\ +gpgsig -----BEGIN PGP SIGNATURE-----\n \n iQEzBAABCAAdFiEEfixture\n =abcd\n -----END PGP SIGNATURE-----\n\ +\nsigned commit with caf\u{e9}\n" + ); + let out = git_raw( + dir, + &["hash-object", "-t", "commit", "-w", "--stdin"], + Some(raw.as_bytes()), + ); + assert!(out.status.success()); + let signed = String::from_utf8(out.stdout).unwrap().trim().to_string(); + git(dir, &["update-ref", "refs/heads/signed", &signed]); +} + +/// `git cat-file --batch-all-objects --batch`: every object in the database as (kind, payload). +fn git_all_objects(dir: &Path) -> BTreeMap)> { + let out = git(dir, &["cat-file", "--batch-all-objects", "--batch"]); + let mut objects = BTreeMap::new(); + let mut rest = &out[..]; + while !rest.is_empty() { + let nl = rest.iter().position(|&b| b == b'\n').unwrap(); + let header = std::str::from_utf8(&rest[..nl]).unwrap(); + let mut parts = header.split(' '); + let oid = GitOid::from_hex(parts.next().unwrap()).unwrap(); + let kind = parts.next().unwrap().to_string(); + let size: usize = parts.next().unwrap().parse().unwrap(); + let payload = rest[nl + 1..nl + 1 + size].to_vec(); + objects.insert(oid, (kind, payload)); + rest = &rest[nl + 1 + size + 1..]; + } + objects +} + +fn git_refs(dir: &Path) -> BTreeMap { + git_text(dir, &["for-each-ref", "--format=%(refname) %(objectname)"]) + .lines() + .map(|l| { + let (name, oid) = l.split_once(' ').unwrap(); + (name.to_string(), GitOid::from_hex(oid).unwrap()) + }) + .collect() +} + +fn assert_history_matches_git(history: &GitHistory, dir: &Path) { + let oracle = git_all_objects(dir); + let native: BTreeSet = history.objects.keys().copied().collect(); + let expected: BTreeSet = oracle.keys().copied().collect(); + assert_eq!( + native, expected, + "native reachable set != git object database" + ); + for (oid, object) in &history.objects { + let (kind, payload) = &oracle[oid]; + assert_eq!(object.kind.name(), kind, "kind of {oid}"); + assert_eq!(&object.payload, payload, "payload of {oid}"); + assert_eq!(object.oid(), *oid); + } + assert_eq!(history.refs, git_refs(dir), "references"); +} + +fn assert_fsck_strict_clean(dir: &Path) { + let out = git_raw(dir, &["fsck", "--full", "--strict", "--no-dangling"], None); + let stderr = String::from_utf8_lossy(&out.stderr); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success() && !stderr.contains("error") && !stderr.contains("warning"), + "git fsck --full --strict failed in {}:\n{stdout}\n{stderr}", + dir.display() + ); +} + +/// Number of entries whose pack type (`gitformat-pack`: 3 bits after the MSB of the first byte) is `t`. +fn count_entry_type(pack: &[u8], entries: &[synapse_git::PackIndexEntry], t: u8) -> usize { + entries + .iter() + .filter(|e| (pack[e.offset as usize] >> 4) & 0x07 == t) + .count() +} + +fn objects_of(history: &GitHistory) -> Vec { + history.objects.values().cloned().collect() +} + +#[test] +fn h1_native_reader_reads_every_loose_object_exactly_as_git() { + let dir = temp_dir("loose"); + build_fixture(&dir); + let packs = fs::read_dir(dir.join(".git/objects/pack")).unwrap().count(); + assert_eq!(packs, 0, "fixture must start with loose objects only"); + let history = GitRepository::open(&dir.join(".git")) + .unwrap() + .full_history() + .unwrap(); + assert_history_matches_git(&history, &dir); + assert_eq!(history.head.as_deref(), Some("refs/heads/main")); + let kinds: BTreeSet = history.objects.values().map(|o| o.kind).collect(); + assert_eq!(kinds.len(), 4, "commits, trees, blobs and tags present"); + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx() { + let dir = temp_dir("ofs"); + build_fixture(&dir); + git( + &dir, + &[ + "repack", + "-a", + "-d", + "-f", + "-q", + "--depth=50", + "--window=250", + ], + ); + git(&dir, &["pack-refs", "--all"]); + let pack_dir = dir.join(".git/objects/pack"); + let idx_path = fs::read_dir(&pack_dir) + .unwrap() + .map(|e| e.unwrap().path()) + .find(|p| p.extension().is_some_and(|x| x == "idx")) + .unwrap(); + let verify = git_text(&dir, &["verify-pack", "-v", idx_path.to_str().unwrap()]); + assert!( + verify.contains("chain length = "), + "fixture pack must hold deltas:\n{verify}" + ); + let history = GitRepository::open(&dir.join(".git")) + .unwrap() + .full_history() + .unwrap(); + assert_history_matches_git(&history, &dir); + // Native indexing of the same pack reproduces Git's own index: every name, offset, CRC. + let pack = fs::read(idx_path.with_extension("pack")).unwrap(); + let native = PackReader::index(pack.clone()).unwrap(); + assert!( + count_entry_type(&pack, native.entries(), 6) > 0, + "Git pack holds OBJ_OFS_DELTA entries" + ); + let (git_entries, _) = decode_idx(&fs::read(&idx_path).unwrap()).unwrap(); + assert_eq!(native.entries(), &git_entries[..]); + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn h1_native_indexer_resolves_reference_deltas_from_git_pack_objects() { + let dir = temp_dir("ref"); + build_fixture(&dir); + let list = git(&dir, &["rev-list", "--objects", "--all"]); + // Without --delta-base-offset, pack-objects writes OBJ_REF_DELTA entries. + let out = git_raw( + &dir, + &[ + "pack-objects", + "--stdout", + "-q", + "--window=250", + "--depth=50", + ], + Some(&list), + ); + assert!(out.status.success()); + let mut reader = PackReader::index(out.stdout.clone()).unwrap(); + assert!( + count_entry_type(&out.stdout, reader.entries(), 7) > 0, + "pack-objects output holds OBJ_REF_DELTA entries" + ); + let oracle = git_all_objects(&dir); + assert_eq!(reader.entries().len(), oracle.len()); + for (oid, (kind, payload)) in &oracle { + let object = reader.read(*oid).unwrap().unwrap(); + assert_eq!(object.kind.name(), kind); + assert_eq!(&object.payload, payload); + } + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean() { + let dir = temp_dir("export-src"); + build_fixture(&dir); + git(&dir, &["repack", "-a", "-d", "-q"]); + let history = GitRepository::open(&dir.join(".git")) + .unwrap() + .full_history() + .unwrap(); + let out = temp_dir("export-dst"); + let dest = out.join("exported.git"); + let receipt = export_repository( + &dest, + &objects_of(&history), + &history.refs, + history.head.as_deref(), + ) + .unwrap(); + assert_eq!(receipt.object_count, history.objects.len()); + // Only the pack and its index: no loose objects. + let loose: Vec<_> = fs::read_dir(dest.join("objects")) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .filter(|n| n != "pack" && n != "info") + .collect(); + assert!(loose.is_empty(), "loose object directories {loose:?}"); + git(&dest, &["verify-pack", receipt.idx_path.to_str().unwrap()]); + assert_fsck_strict_clean(&dest); + // Identical Git object IDs and references, by Git's own reading of both repositories. + let src_objects = git_all_objects(&dir); + let dst_objects = git_all_objects(&dest); + assert_eq!(src_objects, dst_objects, "object databases differ"); + assert_eq!(git_refs(&dir), git_refs(&dest), "references differ"); + assert_eq!( + git_text(&dir, &["rev-parse", "HEAD"]), + git_text(&dest, &["rev-parse", "HEAD"]) + ); + // And the exported repository works as a Git remote. + let clone = out.join("clone"); + let status = Command::new("git") + .args(["clone", "-q"]) + .arg(&dest) + .arg(&clone) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .status() + .unwrap(); + assert!(status.success()); + assert_eq!( + fs::read(clone.join("docs/big.txt")).unwrap(), + fs::read(dir.join("docs/big.txt")).unwrap() + ); + fs::remove_dir_all(&dir).unwrap(); + fs::remove_dir_all(&out).unwrap(); +} + +#[test] +fn h1_export_is_deterministic_and_never_overwrites_a_repository() { + let dir = temp_dir("det-src"); + build_fixture(&dir); + let history = GitRepository::open(&dir.join(".git")) + .unwrap() + .full_history() + .unwrap(); + let out = temp_dir("det-dst"); + let mut objects = objects_of(&history); + let a = export_repository(&out.join("a.git"), &objects, &history.refs, None).unwrap(); + objects.reverse(); + let b = export_repository(&out.join("b.git"), &objects, &history.refs, None).unwrap(); + assert_eq!(a.pack_checksum, b.pack_checksum); + assert_eq!( + fs::read(&a.pack_path).unwrap(), + fs::read(&b.pack_path).unwrap() + ); + assert_eq!( + fs::read(&a.idx_path).unwrap(), + fs::read(&b.idx_path).unwrap() + ); + let err = export_repository(&out.join("a.git"), &objects, &history.refs, None).unwrap_err(); + assert_eq!(err.code, RefusalCode::PathInvalid); + let err = export_repository(&dir.join(".git"), &objects, &history.refs, None).unwrap_err(); + assert_eq!( + err.code, + RefusalCode::PathInvalid, + "existing repository refused" + ); + let mut bad_refs = history.refs.clone(); + bad_refs.insert("refs/heads/missing".into(), GitOid([0xab; 20])); + let err = export_repository(&out.join("c.git"), &objects, &bad_refs, None).unwrap_err(); + assert_eq!(err.code, RefusalCode::GitObjectCorrupt); + fs::remove_dir_all(&dir).unwrap(); + fs::remove_dir_all(&out).unwrap(); +} + +#[test] +fn h1_damaged_or_incomplete_repositories_are_refused_typed() { + let dir = temp_dir("damaged"); + build_fixture(&dir); + let readme = git_text(&dir, &["rev-parse", "HEAD:README.md"]); + let path = dir + .join(".git/objects") + .join(&readme[..2]) + .join(&readme[2..]); + let mut bytes = fs::read(&path).unwrap(); + fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o644)).unwrap(); + let last = bytes.len() - 6; + bytes[last] ^= 0x01; + fs::write(&path, &bytes).unwrap(); + let mut repo = GitRepository::open(&dir.join(".git")).unwrap(); + let err = repo + .read_object(GitOid::from_hex(&readme).unwrap()) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::GitObjectCorrupt); + fs::remove_file(&path).unwrap(); + let err = repo.full_history().unwrap_err(); + assert_eq!(err.code, RefusalCode::GitObjectCorrupt); + assert!(err.message.contains("missing"), "{}", err.message); + fs::remove_dir_all(&dir).unwrap(); +} + +/// Full history of a real repository (path in `SYNAPSE_H1_REAL_REPO`, a full non-shallow +/// clone): native read, native export as one pack, then Git's own check that the export holds +/// the same object IDs and references and passes `fsck --full --strict`. Ignored by default +/// because CI has no such clone; run locally with `--ignored`. +#[test] +#[ignore] +fn h1_real_repository_full_history_round_trips_with_identical_object_ids() { + let Ok(src) = std::env::var("SYNAPSE_H1_REAL_REPO") else { + panic!("set SYNAPSE_H1_REAL_REPO to a full clone's git directory"); + }; + let src = PathBuf::from(src); + let history = GitRepository::open(&src).unwrap().full_history().unwrap(); + let out = temp_dir("real"); + let dest = out.join("exported.git"); + let receipt = export_repository( + &dest, + &objects_of(&history), + &history.refs, + history.head.as_deref(), + ) + .unwrap(); + assert_fsck_strict_clean(&dest); + // Every reference resolves to the same object in both; the exported database holds + // exactly the objects reachable in the source (`rev-list --objects --all`). + assert_eq!(git_refs(&src), git_refs(&dest)); + let reachable = |d: &Path| -> BTreeSet { + git_text(d, &["rev-list", "--objects", "--all"]) + .lines() + .map(|l| l[..40].to_string()) + .collect() + }; + let src_reachable = reachable(&src); + assert_eq!(src_reachable, reachable(&dest)); + let dst_all: BTreeSet = git_all_objects(&dest).keys().map(|o| o.to_hex()).collect(); + assert_eq!( + src_reachable, dst_all, + "export holds only reachable objects" + ); + let commits = history + .objects + .values() + .filter(|o| o.kind == ObjectKind::Commit) + .count(); + println!( + "real repository {}: {} objects ({commits} commits), {} refs, pack {} bytes", + src.display(), + history.objects.len(), + history.refs.len(), + receipt.pack_bytes + ); + fs::remove_dir_all(&out).unwrap(); +} diff --git a/docs/H1_GIT_BRIDGE.md b/docs/H1_GIT_BRIDGE.md new file mode 100644 index 0000000..340fddc --- /dev/null +++ b/docs/H1_GIT_BRIDGE.md @@ -0,0 +1,62 @@ +# H1: Git Bridge, Cut 1 of 2: Native Git Objects, Packfiles, Full-History Read and Export + +ADR 0003 section 9 step 28, H1 (issue aien-spark/synapse#48). Section 5.10: "Import: full history into native objects, with a persistent `GitOid` to (`ChangesetId`, `TreeDigest`) map; merge parents, tags, modes, and signatures preserved (signatures as opaque data). Export: ... written as packfiles, not loose objects". Section 4 adapts Git packfiles; section 6 keeps deltas "only on the bridge wire". + +H1 is delivered in two ordered cuts. This document covers **cut 1**, the Git side of the bridge: reading a real repository's whole object graph natively and writing an object set back as a pack that Git accepts byte for byte. **Cut 2** (not in this change) adds the persistent map and the native side: imported blobs into the store, Git trees to `TreeDigest`, commits to revisions with their original headers kept as opaque bridge data, and export of imported and native history from that stored state. + +Code: `crates/synapse-git/src/{object,inflate,pack,repo}.rs`. Tests: `crates/synapse-git/tests/h1_git_bridge.rs` and unit tests in each module. Evidence: `evidence/h1-git-bridge/`. + +## 1. What cut 1 provides + +| Part | Module | Rule | +| :--- | :--- | :--- | +| Object model | `object` | Kinds `commit`, `tree`, `blob`, `tag` (pack types 1 to 4); ID = SHA-1 of ` \0` (`GitOid::compute_git_object`, the `sha1` crate already in the workspace); tree entries, a commit's tree and parents in written order, a tag's target. Every other commit and tag byte (author, committer, `gpgsig`, `mergetag`, `encoding`, message) is opaque and never rewritten | +| zlib and DEFLATE decoder | `inflate` | RFC 1950 and 1951: stored, fixed and dynamic Huffman blocks; reports the input bytes a stream used (a pack entry does not record its compressed length); output bounded by the caller's cap; Adler-32 checked | +| Pack and index codec | `pack` | Pack version 2 (reads 2 and 3) and index version 2 per `gitformat-pack`: entry header, `OBJ_OFS_DELTA` offset encoding, `OBJ_REF_DELTA` base name, delta copy and insert instructions, CRC-32 (IEEE) per entry, 31-bit and 8-byte offsets, pack and index SHA-1 trailers. `PackReader::with_index` reads a pack through Git's index; `PackReader::index` indexes a pack with no index file (native `index-pack`) | +| Repository reader | `repo` | `GitRepository::open` reads loose objects and every `objects/pack/*.pack` with its `.idx`; refs from loose files and `packed-refs`; `HEAD`. `full_history` walks every object reachable from every reference, checking each object's kind against its link | +| Exporter | `repo` | `export_repository` creates a **new** bare repository holding the object set as one pack plus index (no loose objects), the references, and `HEAD`. An existing destination is refused, so it cannot move a branch of an existing repository | + +Writer determinism: the pack holds whole objects in object ID order, compressed as zlib stored blocks (the existing `zlib_compress_store`), so the bytes are a function of the object set alone; input order and duplicates do not matter. + +Every malformed input is refused with `RefusalCode::GitObjectCorrupt` and never panics: bad zlib header or checksum, truncated or over-declared streams, over-subscribed Huffman codes, distances before the output start, pack or index checksum mismatch, offsets outside the pack, non-monotone fan-out, unsorted names, delta size mismatches, copies past the base, delta chain loops or chains over 4096, reference-delta bases missing from the pack (thin packs), objects over 1 GiB, an object whose content does not hash to its ID, missing objects, shallow repositories, and alternates. + +The system `git` binary is used only by the tests, as an independent oracle. `synapse-git` starts no Git process on any cut 1 path. + +## 2. Acceptance status (issue #48) + +| Acceptance (issue #48) | Status | Evidence | +| :--- | :--- | :--- | +| Imported real repository history with no erased content exports with identical Git object IDs, using the stored original headers | Git side done: real full history read natively and exported with identical IDs. The native import and the stored-header path are cut 2 | `h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean`; real repositories below | +| Native revisions export deterministically (two exports give identical IDs) | Pack writer deterministic (two exports, either input order, give identical pack and index bytes). Native revisions are cut 2 | `h1_export_is_deterministic_and_never_overwrites_a_repository` | +| `git fsck --full --strict` clean | Done for every exported repository, fixture and real | same tests | + +Real repositories (`evidence/h1-git-bridge/red-green/green.txt`), each a `git clone --mirror` (full history, every reference including pull request refs): native read, native export, then Git checks that every reference resolves to the same object, that the exported database holds exactly the source's reachable objects (`rev-list --objects --all`), and `fsck --full --strict`: + +| Repository | Objects | Commits | References | Result | +| :--- | ---: | ---: | ---: | :--- | +| `aien-dev/synapse` (main `3d78efe`) | 1,784 | 165 | 69 | identical IDs, fsck strict clean | +| `aien-dev/omega` (main `f4a9849`) | 29,635 | 2,412 | 631 | identical IDs, fsck strict clean | + +The fixture (built by Git in the test) covers nested trees, executable files, a symlink, an empty file, an incompressible binary, a large text file revised twelve times (delta material), a two-parent merge, an octopus merge, an empty commit, annotated tags of a commit, a tree, a blob and another tag, a blob and an inner tag reachable only through a tag, a lightweight tag, and a commit with a multi-line `gpgsig` header and an `encoding` header. Git's own `cat-file --batch-all-objects` output is compared object by object (kind and payload) with what the native reader returns, from loose objects, from a `repack -f --depth=50` pack (offset deltas present, checked by entry type), and from a `pack-objects --stdout` pack (reference deltas present). The native index of Git's pack equals Git's `.idx` entry for entry (name, offset, CRC-32). + +## 3. Red before green + +`evidence/h1-git-bridge/red-green/red.txt`: six stubs, each removing one behaviour, run against the tests on base `3d78efe` before the first commit; every failure is an assertion or a typed refusal, no compile error: + +1. inflate refuses dynamic Huffman blocks: 6 of 6 fail. +2. the pack reader refuses offset deltas: the offset delta and export tests fail. +3. the pack reader refuses reference deltas: the reference delta test fails. +4. the history walk does not follow tags: 3 fail (objects reachable only through a tag are missed). +5. the pack writer records CRC-32 0 in the index: the export test fails (`git verify-pack`). +6. the pack writer keeps input order: the determinism test fails. + +`green.txt` holds the passing runs and the two real repository runs. + +## 4. Limits and what remains + +* **Cut 2 remains**: the persistent `GitOid` to (`ChangesetId`, `TreeDigest`) map; imported blobs stored natively; Git trees converted to `TreeDigest` and recomputed at export; commits as revisions whose original commit and tag headers are kept as opaque bridge data; export of imported history from stored headers and of native revisions with deterministic generated message and author fields (section 5.10). It needs a new WAL record kind; open PR #88 claims kind 9, so cut 2 will use kind 10. +* Exported packs are not compressed beyond zlib stored blocks and hold no deltas: the omega export is 374,712,257 bytes against 50,117 KiB for Git's own pack (`count-objects -v`). Correct and accepted by Git, but large; a native compressor is a later change. +* SHA-1 object format only. A SHA-256 Git repository (`extensions.objectformat = sha256`) is not read. +* The existing per-changeset `materialize_changeset_to_git` still writes loose objects; it is a legacy path and is replaced by the cut 2 export. +* `GitRepository` reads whole pack files into memory, and `full_history` holds every object; fine for the repositories above, not bounded for very large ones. +* No performance figure is claimed: none is part of this cut's acceptance and no run was measured against a section 6 bound. diff --git a/evidence/h1-git-bridge/SHA256SUMS b/evidence/h1-git-bridge/SHA256SUMS new file mode 100644 index 0000000..86f820d --- /dev/null +++ b/evidence/h1-git-bridge/SHA256SUMS @@ -0,0 +1,2 @@ +8f8591c3edcf0019bd2d6e0fdc491cd33cf3c5e353990ec45bd171f6197ad60e red-green/green.txt +5daa9e456ef3ef01f695894887674b23d40c8d906fb379cefdd6c5746cc77a61 red-green/red.txt diff --git a/evidence/h1-git-bridge/red-green/green.txt b/evidence/h1-git-bridge/red-green/green.txt new file mode 100644 index 0000000..d40970f --- /dev/null +++ b/evidence/h1-git-bridge/red-green/green.txt @@ -0,0 +1,39 @@ +# Green (2026-10-17, H1 cut 1 working tree on base 3d78efe, git 2.43.0 as oracle) +# Command: cargo test --locked -p synapse-git +test object::tests::commit_and_tag_links_parse_and_keep_parent_order ... ok +test inflate::tests::output_over_the_declared_size_is_refused ... ok +test object::tests::tree_entries_parse_and_re_encode_exactly ... ok +test object::tests::loose_encoding_round_trips_and_ids_match_git_known_values ... ok +test inflate::tests::every_truncation_and_bit_flip_is_refused_or_exact_without_panic ... ok +test pack::tests::crc32_matches_the_ieee_check_value ... ok +test pack::tests::delta_copy_and_insert_apply_and_bad_deltas_are_refused ... ok +test pack::tests::large_offsets_use_the_eight_byte_table ... ok +test inflate::tests::stored_blocks_round_trip_and_report_consumed_length ... ok +test pack::tests::written_pack_indexes_back_to_the_same_entries_and_objects ... ok +test tests::test_advance_human_branch_requires_publish_capability_and_rejects_bypass ... ok +test tests::test_git_materialization_fsck_clone_fetch_and_human_branch_protection ... ok +test pack::tests::every_truncation_and_bit_flip_of_a_pack_is_refused_without_panic ... ok +test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.39s +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_damaged_or_incomplete_repositories_are_refused_typed ... ok +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... ok +test h1_native_reader_reads_every_loose_object_exactly_as_git ... ok +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... ok +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... ok +test h1_export_is_deterministic_and_never_overwrites_a_repository ... ok +test result: ok. 6 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 1.80s +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +# +# Real repository: git clone --mirror https://github.com/aien-dev/synapse (full history, every ref) +# synapse.git refs/heads/main = 3d78efe83d5d08b67848e4b32a83112a95dd2a9d +# Command: SYNAPSE_H1_REAL_REPO= cargo test --locked --release -p synapse-git --test h1_git_bridge -- --ignored --nocapture +real repository synapse.git: 1784 objects (165 commits), 69 refs, pack 70129220 bytes +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 1.75s +# +# Real repository: git clone --mirror https://github.com/aien-dev/omega (full history, every ref) +# omega.git refs/heads/main = f4a9849fb127f8d2d664dfc56890752ad180c507 +# Command: SYNAPSE_H1_REAL_REPO= cargo test --locked --release -p synapse-git --test h1_git_bridge -- --ignored --nocapture +real repository omega.git: 29635 objects (2412 commits), 631 refs, pack 374712257 bytes +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 11.52s diff --git a/evidence/h1-git-bridge/red-green/red.txt b/evidence/h1-git-bridge/red-green/red.txt new file mode 100644 index 0000000..0e50e6f --- /dev/null +++ b/evidence/h1-git-bridge/red-green/red.txt @@ -0,0 +1,105 @@ +# Red (2026-10-17, H1 cut 1 working tree on base 3d78efe, before the first commit) +# Command: cargo test --locked --no-fail-fast -p synapse-git --test h1_git_bridge +# Each run applies one stub that removes one behaviour under test; every failure is an +# assertion or a typed refusal from the stubbed path (no compile error). Restored after each run. +# +# Red 1 stub: inflate refuses dynamic-Huffman DEFLATE blocks (inflate.rs run). +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_native_reader_reads_every_loose_object_exactly_as_git ... FAILED +test h1_damaged_or_incomplete_repositories_are_refused_typed ... FAILED +test h1_export_is_deterministic_and_never_overwrites_a_repository ... FAILED +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... FAILED +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... FAILED +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... FAILED +thread 'h1_native_reader_reads_every_loose_object_exactly_as_git' (758242) panicked at crates/synapse-git/tests/h1_git_bridge.rs:260:10: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: dynamic Huffman blocks unimplemented" } +thread 'h1_damaged_or_incomplete_repositories_are_refused_typed' (758238) panicked at crates/synapse-git/tests/h1_git_bridge.rs:443:5: +thread 'h1_export_is_deterministic_and_never_overwrites_a_repository' (758239) panicked at crates/synapse-git/tests/h1_git_bridge.rs:398:10: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: dynamic Huffman blocks unimplemented" } +thread 'h1_native_indexer_resolves_reference_deltas_from_git_pack_objects' (758241) panicked at crates/synapse-git/tests/h1_git_bridge.rs:317:60: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: dynamic Huffman blocks unimplemented" } +thread 'h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean' (758240) panicked at crates/synapse-git/tests/h1_git_bridge.rs:340:10: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: dynamic Huffman blocks unimplemented" } +thread 'h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx' (758243) panicked at crates/synapse-git/tests/h1_git_bridge.rs:291:10: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: dynamic Huffman blocks unimplemented" } +test result: FAILED. 0 passed; 6 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.33s +error: test failed, to rerun pass `-p synapse-git --test h1_git_bridge` +error: 1 target failed: +# +# Red 2 stub: pack reader refuses OBJ_OFS_DELTA entries (pack.rs resolve_at). +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_damaged_or_incomplete_repositories_are_refused_typed ... ok +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... FAILED +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... FAILED +test h1_native_reader_reads_every_loose_object_exactly_as_git ... ok +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... ok +test h1_export_is_deterministic_and_never_overwrites_a_repository ... ok +thread 'h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean' (760615) panicked at crates/synapse-git/tests/h1_git_bridge.rs:340:10: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: offset deltas unimplemented" } +thread 'h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx' (760618) panicked at crates/synapse-git/tests/h1_git_bridge.rs:291:10: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: offset deltas unimplemented" } +test result: FAILED. 4 passed; 2 failed; 1 ignored; 0 measured; 0 filtered out; finished in 1.80s +error: test failed, to rerun pass `-p synapse-git --test h1_git_bridge` +error: 1 target failed: +# +# Red 3 stub: pack reader refuses OBJ_REF_DELTA entries (pack.rs resolve_at). +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_damaged_or_incomplete_repositories_are_refused_typed ... ok +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... FAILED +test h1_native_reader_reads_every_loose_object_exactly_as_git ... ok +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... ok +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... ok +test h1_export_is_deterministic_and_never_overwrites_a_repository ... ok +thread 'h1_native_indexer_resolves_reference_deltas_from_git_pack_objects' (762378) panicked at crates/synapse-git/tests/h1_git_bridge.rs:317:60: +called `Result::unwrap()` on an `Err` value: SynapseError { code: GitObjectCorrupt, message: "RED STUB: reference deltas unimplemented" } +test result: FAILED. 5 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out; finished in 2.17s +error: test failed, to rerun pass `-p synapse-git --test h1_git_bridge` +error: 1 target failed: +# +# Red 4 stub: the history walk does not follow annotated tags to their targets (object.rs object_links). +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_damaged_or_incomplete_repositories_are_refused_typed ... ok +test h1_native_reader_reads_every_loose_object_exactly_as_git ... FAILED +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... FAILED +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... ok +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... FAILED +test h1_export_is_deterministic_and_never_overwrites_a_repository ... ok +thread 'h1_native_reader_reads_every_loose_object_exactly_as_git' (764295) panicked at crates/synapse-git/tests/h1_git_bridge.rs:218:5: +assertion `left == right` failed: native reachable set != git object database + left: {GitOid(048e62a0ea3c017650134e79d55c6c45c55adf33), GitOid(055e940f4410b8000990908448b9f864ec8a97c7), GitOid(065da59fc6bfe94c11cbb1f4754e33ba27b9e0be), GitOid(08095643742062b6003cf0a23b2b22a28b5eb993), GitOid(09264783560dca1b1e7c4dc54b7cd999c61bcf6c), GitOid(1214ae34249412735b429d46cd385417c6 +thread 'h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx' (764296) panicked at crates/synapse-git/tests/h1_git_bridge.rs:218:5: +assertion `left == right` failed: native reachable set != git object database + left: {GitOid(048e62a0ea3c017650134e79d55c6c45c55adf33), GitOid(055e940f4410b8000990908448b9f864ec8a97c7), GitOid(065da59fc6bfe94c11cbb1f4754e33ba27b9e0be), GitOid(08095643742062b6003cf0a23b2b22a28b5eb993), GitOid(09264783560dca1b1e7c4dc54b7cd999c61bcf6c), GitOid(1214ae34249412735b429d46cd385417c6 +thread 'h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean' (764293) panicked at crates/synapse-git/tests/h1_git_bridge.rs:232:5: +git fsck --full --strict failed in /tmp/synapse-h1-export-dst-764290-1792201733952236802/exported.git: +test result: FAILED. 3 passed; 3 failed; 1 ignored; 0 measured; 0 filtered out; finished in 2.67s +error: test failed, to rerun pass `-p synapse-git --test h1_git_bridge` +error: 1 target failed: +# +# Red 5 stub: the pack writer records CRC-32 0 for every entry in the index (pack.rs write_pack). +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_damaged_or_incomplete_repositories_are_refused_typed ... ok +test h1_native_reader_reads_every_loose_object_exactly_as_git ... ok +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... ok +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... ok +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... FAILED +test h1_export_is_deterministic_and_never_overwrites_a_repository ... ok +thread 'h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean' (769956) panicked at crates/synapse-git/tests/h1_git_bridge.rs:58:5: +test result: FAILED. 5 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out; finished in 2.18s +error: test failed, to rerun pass `-p synapse-git --test h1_git_bridge` +error: 1 target failed: +# +# Red 6 stub: the pack writer keeps the caller's object order instead of object ID order (pack.rs write_pack). +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ignored +test h1_damaged_or_incomplete_repositories_are_refused_typed ... ok +test h1_native_reader_reads_every_loose_object_exactly_as_git ... ok +test h1_native_indexer_resolves_reference_deltas_from_git_pack_objects ... ok +test h1_native_reader_resolves_offset_deltas_in_git_packs_and_matches_git_idx ... ok +test h1_full_history_exports_as_a_pack_with_identical_object_ids_and_fsck_strict_clean ... ok +test h1_export_is_deterministic_and_never_overwrites_a_repository ... FAILED +thread 'h1_export_is_deterministic_and_never_overwrites_a_repository' (775407) panicked at crates/synapse-git/tests/h1_git_bridge.rs:404:5: +assertion `left == right` failed + left: GitOid(110cae2138cf180d22011dd488d3140f543a60a2) +test result: FAILED. 5 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out; finished in 17.01s +error: test failed, to rerun pass `-p synapse-git --test h1_git_bridge` +error: 1 target failed: From c433ec723dcf50aa2bc09aff5ecd1ca4f06e894c Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 16 Oct 2026 21:19:56 -0500 Subject: [PATCH 2/4] fix(git): bound the native Git reader against hostile repositories (#48, review of #90) Review findings B1 and B2 on PR #90: B1: every repository file (loose refs, packed-refs, HEAD, loose objects, .pack, .idx) is now inspected with symlink_metadata and opened only if it is a regular file (same device and inode after open), read through take(cap + 1). Pipes, sockets, devices and symbolic links are refused with PathInvalid; the refs/ walk uses DirEntry::file_type and never follows links. Caps: ref file and HEAD 4 KiB, packed-refs 64 MiB, all pack files 2 GiB (QuotaPayloadTooLarge). B2: a total object budget (ReadLimits::max_total_object_bytes, default 1 GiB) is checked at open from the sizes every pack entry declares (entry headers plus the first 20 inflated bytes of each delta stream, nothing resolved) and for each loose object from its header before it is inflated. Per-object cap (default 1 GiB) on entries, delta streams, delta results and loose objects before allocation; apply_delta no longer reserves the declared result size up front. Also: *.lock files under refs/ skipped, detached HEAD commit collected (GitHistory::detached_head). Red: tests/h1_hostile_repo.rs run unchanged on b4fe463 fails 8 of 8 (pipes block to the 10 s deadline, /dev/zero link OOM under ulimit, outside link and 1 MiB ref accepted, 82 KB delta bomb resolves 5 x 256 MiB, detached HEAD commit dropped); stubs A (budget removed) and B (links followed) fail by assertion. Green: 357 passed, 0 failed, 2 ignored (workspace). Co-Authored-By: Claude Opus 5.5 --- crates/synapse-git/src/inflate.rs | 60 +++ crates/synapse-git/src/lib.rs | 2 +- crates/synapse-git/src/pack.rs | 150 +++++++- crates/synapse-git/src/repo.rs | 294 +++++++++++++-- crates/synapse-git/tests/h1_hostile_repo.rs | 344 ++++++++++++++++++ crates/synapse-git/tests/h1_read_limits.rs | 162 +++++++++ docs/H1_GIT_BRIDGE.md | 21 +- evidence/h1-git-bridge/SHA256SUMS | 2 + .../h1-git-bridge/red-green/hostile-green.txt | 41 +++ .../h1-git-bridge/red-green/hostile-red.txt | 134 +++++++ 10 files changed, 1152 insertions(+), 58 deletions(-) create mode 100644 crates/synapse-git/tests/h1_hostile_repo.rs create mode 100644 crates/synapse-git/tests/h1_read_limits.rs create mode 100644 evidence/h1-git-bridge/red-green/hostile-green.txt create mode 100644 evidence/h1-git-bridge/red-green/hostile-red.txt diff --git a/crates/synapse-git/src/inflate.rs b/crates/synapse-git/src/inflate.rs index 33dd092..831a7dd 100644 --- a/crates/synapse-git/src/inflate.rs +++ b/crates/synapse-git/src/inflate.rs @@ -40,6 +40,7 @@ pub fn zlib_decompress(input: &[u8], max_out: usize) -> SynapseResult<(Vec, bit_count: 0, out: Vec::new(), max_out, + prefix: false, }; inf.run()?; // Discard the bits left in the last partial byte, then read the big-endian Adler-32. @@ -54,6 +55,40 @@ pub fn zlib_decompress(input: &[u8], max_out: usize) -> SynapseResult<(Vec, Ok((inf.out, pos + 4)) } +/// Internal marker: a prefix decode filled its `n` bytes. +const PREFIX_FULL: &str = "zlib prefix decode reached its length"; + +/// Decompress only the first `n` bytes of the zlib stream at the start of `input` (fewer if the +/// stream ends sooner). Used to read a declared size (a loose object header, a delta's result +/// size) before anything is allocated for the whole object. The stream is not checked past +/// those bytes and the Adler-32 trailer is not read; a later full decode checks both. +pub fn zlib_inflate_prefix(input: &[u8], n: usize) -> SynapseResult> { + if input.len() < 2 { + return Err(corrupt("zlib stream shorter than its 2-byte header")); + } + let (cmf, flg) = (input[0], input[1]); + if cmf & 0x0f != 8 || cmf >> 4 > 7 || (u16::from(cmf) << 8 | u16::from(flg)) % 31 != 0 { + return Err(corrupt("zlib header is invalid")); + } + if flg & 0x20 != 0 { + return Err(corrupt("zlib preset dictionary is not used by Git")); + } + let mut inf = Inflater { + input, + pos: 2, + bit_buf: 0, + bit_count: 0, + out: Vec::with_capacity(n.min(4096)), + max_out: n, + prefix: true, + }; + match inf.run() { + Ok(()) => Ok(inf.out), + Err(e) if e.message == PREFIX_FULL => Ok(inf.out), + Err(e) => Err(e), + } +} + const MAX_BITS: usize = 15; /// Canonical Huffman decoding table (RFC 1951 section 3.2.2): symbol counts per code length @@ -122,6 +157,8 @@ struct Inflater<'a> { bit_count: u32, out: Vec, max_out: usize, + /// Stop with [`PREFIX_FULL`] once `max_out` bytes are out instead of refusing. + prefix: bool, } impl Inflater<'_> { @@ -143,6 +180,9 @@ impl Inflater<'_> { fn push(&mut self, byte: u8) -> SynapseResult<()> { if self.out.len() >= self.max_out { + if self.prefix { + return Err(corrupt(PREFIX_FULL)); + } return Err(corrupt(format!( "decompressed data exceeds the declared {} bytes", self.max_out @@ -192,6 +232,11 @@ impl Inflater<'_> { .get(self.pos..self.pos + len) .ok_or_else(|| corrupt("DEFLATE stored block truncated"))?; if self.out.len() + len > self.max_out { + if self.prefix { + let room = self.max_out - self.out.len(); + self.out.extend_from_slice(&data[..room]); + return Err(corrupt(PREFIX_FULL)); + } return Err(corrupt(format!( "decompressed data exceeds the declared {} bytes", self.max_out @@ -305,6 +350,21 @@ mod tests { use super::*; use crate::zlib_compress_store; + #[test] + fn prefix_decode_stops_at_its_length_without_inflating_the_rest() { + let raw: Vec = (0..200_000usize).map(|i| (i * 7 % 251) as u8).collect(); + let z = zlib_compress_store(&raw); + for n in [0usize, 1, 20, 65_535, 65_540, 199_999, 200_000, 300_000] { + let out = zlib_inflate_prefix(&z, n).unwrap(); + assert_eq!(out, raw[..n.min(raw.len())], "prefix {n}"); + } + assert!(zlib_inflate_prefix(&z[..1], 4).is_err(), "short header"); + assert!( + zlib_inflate_prefix(&[0x78, 0x00], 4).is_err(), + "bad check bits" + ); + } + #[test] fn stored_blocks_round_trip_and_report_consumed_length() { for len in [0usize, 1, 100, 65_535, 65_536, 200_000] { diff --git a/crates/synapse-git/src/lib.rs b/crates/synapse-git/src/lib.rs index 9a35261..6e53959 100644 --- a/crates/synapse-git/src/lib.rs +++ b/crates/synapse-git/src/lib.rs @@ -15,7 +15,7 @@ pub mod repo; pub use object::{GitObject, GitTreeEntry, ObjectKind}; pub use pack::{PackIndexEntry, PackReader, WrittenPack}; -pub use repo::{export_repository, ExportReceipt, GitHistory, GitRepository}; +pub use repo::{export_repository, ExportReceipt, GitHistory, GitRepository, ReadLimits}; use serde::{Deserialize, Serialize}; use sha1::Sha1; diff --git a/crates/synapse-git/src/pack.rs b/crates/synapse-git/src/pack.rs index 77f561b..90fa070 100644 --- a/crates/synapse-git/src/pack.rs +++ b/crates/synapse-git/src/pack.rs @@ -14,7 +14,7 @@ //! kinds and checks every size, offset and checksum before it trusts them; malformed input is //! refused with `RefusalCode::GitObjectCorrupt`. -use crate::inflate::zlib_decompress; +use crate::inflate::{zlib_decompress, zlib_inflate_prefix}; use crate::object::{GitObject, ObjectKind}; use crate::zlib_compress_store; use sha1::{Digest, Sha1}; @@ -25,14 +25,21 @@ fn corrupt(msg: impl Into) -> SynapseError { SynapseError::new(RefusalCode::GitObjectCorrupt, msg) } +fn over_cap(what: &str, size: u64, cap: u64) -> SynapseError { + SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + format!("{what} declares {size} bytes, over the {cap} byte cap"), + ) +} + const PACK_SIGNATURE: &[u8; 4] = b"PACK"; const PACK_VERSION: u32 = 2; const IDX_MAGIC: [u8; 4] = [0xff, b't', b'O', b'c']; const IDX_VERSION: u32 = 2; const OBJ_OFS_DELTA: u8 = 6; const OBJ_REF_DELTA: u8 = 7; -/// Most bytes one resolved object may hold while reading a pack (a declared size above it is -/// refused before anything is allocated). +/// Default for the most bytes one resolved object may hold while reading a pack (a declared size +/// above the cap is refused with `QuotaPayloadTooLarge` before anything is allocated). pub const MAX_PACK_OBJECT_BYTES: u64 = 1 << 30; /// Longest delta chain the reader follows (Git's own `pack.depth` maximum is 4095). pub const MAX_DELTA_CHAIN: usize = 4096; @@ -276,6 +283,7 @@ pub struct PackReader { entries: Vec, cache: HashMap>)>, cache_bytes: usize, + max_object_bytes: u64, } const CACHE_BOUND_BYTES: usize = 256 << 20; @@ -301,6 +309,16 @@ impl PackReader { /// record this pack's checksum and name exactly the pack's object count; every offset must /// fall inside the pack body. pub fn with_index(data: Vec, idx: &[u8]) -> SynapseResult { + Self::with_index_limited(data, idx, MAX_PACK_OBJECT_BYTES) + } + + /// [`Self::with_index`] with a per-object cap: no entry, delta stream or delta result may + /// declare more than `max_object_bytes`. + pub fn with_index_limited( + data: Vec, + idx: &[u8], + max_object_bytes: u64, + ) -> SynapseResult { let count = check_pack_framing(&data)?; let (entries, pack_sum) = decode_idx(idx)?; if pack_sum.0[..] != data[data.len() - 20..] { @@ -325,6 +343,7 @@ impl PackReader { entries, cache: HashMap::new(), cache_bytes: 0, + max_object_bytes, }) } @@ -341,7 +360,7 @@ impl PackReader { if pos >= body_end { return Err(corrupt("pack holds fewer entries than its header declares")); } - let (_, next) = read_raw_entry(&data[..body_end], pos as u64)?; + let (_, next) = read_raw_entry(&data[..body_end], pos as u64, MAX_PACK_OBJECT_BYTES)?; offsets.push((pos as u64, crc32(&data[pos..next]))); pos = next; } @@ -356,6 +375,7 @@ impl PackReader { entries: Vec::with_capacity(offsets.len()), cache: HashMap::new(), cache_bytes: 0, + max_object_bytes: MAX_PACK_OBJECT_BYTES, }; // Whole objects and offset deltas resolve by position alone; reference deltas need // their base's ID first, so repeat until every entry is resolved or nothing moves. @@ -401,6 +421,22 @@ impl PackReader { self.by_oid.contains_key(&oid) } + /// Sum of the sizes every entry declares it resolves to, read from entry headers and the + /// first bytes of each delta stream without resolving anything. Resolving an entry + /// produces exactly its declared size (checked on every read), so this bounds what reading + /// the whole pack can hold. An entry over the per-object cap is refused. + pub fn declared_bytes(&self) -> SynapseResult { + let body = &self.data[..self.data.len() - 20]; + let mut total = 0u64; + for e in &self.entries { + let size = declared_object_size(body, e.offset, self.max_object_bytes)?; + total = total + .checked_add(size) + .ok_or_else(|| corrupt("pack declared sizes overflow u64"))?; + } + Ok(total) + } + /// Read and resolve object `oid`, checking that its content hashes to `oid`. pub fn read(&mut self, oid: GitOid) -> SynapseResult> { let Some(&offset) = self.by_oid.get(&oid) else { @@ -439,7 +475,7 @@ impl PackReader { "pack delta chain is longer than the reader follows", )); } - let (raw, _) = read_raw_entry(&self.data[..body_end], at)?; + let (raw, _) = read_raw_entry(&self.data[..body_end], at, self.max_object_bytes)?; match raw { RawEntry::Whole(kind, payload) => break (kind, std::sync::Arc::new(payload)), RawEntry::OfsDelta(base, delta) => { @@ -460,7 +496,11 @@ impl PackReader { } }; while let Some((at, delta)) = chain.pop() { - payload = std::sync::Arc::new(apply_delta(&payload, &delta)?); + payload = std::sync::Arc::new(apply_delta_limited( + &payload, + &delta, + self.max_object_bytes, + )?); self.remember(at, kind, payload.clone()); } Ok((kind, payload)) @@ -488,9 +528,23 @@ fn read_size_encoding(data: &[u8], pos: &mut usize) -> SynapseResult { } } -/// Read the entry at `offset`: header, delta base, and decompressed data. Returns the entry -/// and the offset just past it. -fn read_raw_entry(body: &[u8], offset: u64) -> SynapseResult<(RawEntry, usize)> { +/// A pack entry's header: its pack type, declared size (the object's size for whole entries, +/// the delta stream's size for deltas), delta base (offset, or object ID for a reference +/// delta), and where its zlib data starts. +struct EntryHeader { + pack_type: u8, + size: u64, + base: Option>, + data_pos: usize, +} + +/// Parse the header of the entry at `offset`. A declared size over `max_object_bytes` is +/// refused (`QuotaPayloadTooLarge`) before anything is allocated. +fn read_entry_header( + body: &[u8], + offset: u64, + max_object_bytes: u64, +) -> SynapseResult { let mut pos = usize::try_from(offset).map_err(|_| corrupt("pack offset overflows"))?; let first = *body .get(pos) @@ -505,10 +559,8 @@ fn read_raw_entry(body: &[u8], offset: u64) -> SynapseResult<(RawEntry, usize)> } size |= rest << 4; } - if size > MAX_PACK_OBJECT_BYTES { - return Err(corrupt(format!( - "pack entry declares {size} bytes, over the {MAX_PACK_OBJECT_BYTES} byte cap" - ))); + if size > max_object_bytes { + return Err(over_cap("pack entry", size, max_object_bytes)); } let entry_start = offset; let base = match pack_type { @@ -546,6 +598,49 @@ fn read_raw_entry(body: &[u8], offset: u64) -> SynapseResult<(RawEntry, usize)> } other => return Err(corrupt(format!("pack entry type {other} is invalid"))), }; + if pos > body.len() { + return Err(corrupt("pack entry truncated")); + } + Ok(EntryHeader { + pack_type, + size, + base, + data_pos: pos, + }) +} + +/// The size of the object the entry at `offset` resolves to, read without resolving it: the +/// header's size for a whole entry, the result size at the start of the delta stream for a +/// delta (only its first bytes are inflated). Over `max_object_bytes` is refused. +fn declared_object_size(body: &[u8], offset: u64, max_object_bytes: u64) -> SynapseResult { + let h = read_entry_header(body, offset, max_object_bytes)?; + if h.base.is_none() { + return Ok(h.size); + } + // Two size encodings of at most 10 bytes each start every delta stream. + let head = zlib_inflate_prefix(&body[h.data_pos..], 20)?; + let mut pos = 0usize; + read_size_encoding(&head, &mut pos)?; + let result_size = read_size_encoding(&head, &mut pos)?; + if result_size > max_object_bytes { + return Err(over_cap("delta result", result_size, max_object_bytes)); + } + Ok(result_size) +} + +/// Read the entry at `offset`: header, delta base, and decompressed data. Returns the entry +/// and the offset just past it. +fn read_raw_entry( + body: &[u8], + offset: u64, + max_object_bytes: u64, +) -> SynapseResult<(RawEntry, usize)> { + let EntryHeader { + pack_type, + size, + base, + data_pos: pos, + } = read_entry_header(body, offset, max_object_bytes)?; let (data, used) = zlib_decompress(&body[pos..], size as usize)?; if data.len() as u64 != size { return Err(corrupt(format!( @@ -561,8 +656,20 @@ fn read_raw_entry(body: &[u8], offset: u64) -> SynapseResult<(RawEntry, usize)> Ok((entry, pos + used)) } -/// Apply a Git delta (`gitformat-pack`, "Deltified representation") to `base`. +/// Apply a Git delta (`gitformat-pack`, "Deltified representation") to `base`, with the +/// default per-object cap. pub fn apply_delta(base: &[u8], delta: &[u8]) -> SynapseResult> { + apply_delta_limited(base, delta, MAX_PACK_OBJECT_BYTES) +} + +/// [`apply_delta`] refusing a declared result over `max_object_bytes` before any allocation. +/// The output grows as instructions produce bytes (never reserved up front past what the +/// base and delta could give in one pass) and may never pass the declared result size. +pub fn apply_delta_limited( + base: &[u8], + delta: &[u8], + max_object_bytes: u64, +) -> SynapseResult> { let mut pos = 0usize; let base_size = read_size_encoding(delta, &mut pos)?; if base_size != base.len() as u64 { @@ -572,10 +679,10 @@ pub fn apply_delta(base: &[u8], delta: &[u8]) -> SynapseResult> { ))); } let result_size = read_size_encoding(delta, &mut pos)?; - if result_size > MAX_PACK_OBJECT_BYTES { - return Err(corrupt("delta result is over the object byte cap")); + if result_size > max_object_bytes { + return Err(over_cap("delta result", result_size, max_object_bytes)); } - let mut out = Vec::with_capacity(result_size as usize); + let mut out = Vec::with_capacity(result_size.min((base.len() + delta.len()) as u64) as usize); while pos < delta.len() { let op = delta[pos]; pos += 1; @@ -697,6 +804,15 @@ mod tests { apply_delta(base, &[16, 4, 0x91, 10, 3]).is_err(), "short result" ); + // A declared result over the cap is refused before any output is produced. + let e = apply_delta_limited(base, &[16, 7, 0x91, 10, 3, 4, b'X', b'Y', b'Z', b'!'], 6) + .unwrap_err(); + assert_eq!(e.code, RefusalCode::QuotaPayloadTooLarge); + assert_eq!( + apply_delta_limited(base, &delta, 7).unwrap(), + b"abcXYZ!", + "exactly at the cap" + ); } #[test] diff --git a/crates/synapse-git/src/repo.rs b/crates/synapse-git/src/repo.rs index 674bbad..4f74d4e 100644 --- a/crates/synapse-git/src/repo.rs +++ b/crates/synapse-git/src/repo.rs @@ -14,12 +14,12 @@ //! No Git process is started here; the system `git` is used only by the tests, as an //! independent oracle. -use crate::inflate::zlib_decompress; +use crate::inflate::{zlib_decompress, zlib_inflate_prefix}; use crate::object::{object_links, GitObject, ObjectKind}; use crate::pack::{write_pack, PackReader, WrittenPack}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::fs::{self, File}; -use std::io::Write; +use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; @@ -31,13 +31,128 @@ fn io(e: std::io::Error, what: &Path) -> SynapseError { SynapseError::new(RefusalCode::IoFailure, format!("{}: {e}", what.display())) } -/// Most bytes a loose object may inflate to. +fn over_cap(what: &Path, size: u64, cap: u64) -> SynapseError { + SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + format!( + "{} holds {size} bytes, over the {cap} byte cap", + what.display() + ), + ) +} + +fn not_regular(what: &Path, detail: &str) -> SynapseError { + SynapseError::new( + RefusalCode::PathInvalid, + format!( + "{} is {detail}; the bridge reads only regular files and directories inside the repository", + what.display() + ), + ) +} + +fn describe(t: fs::FileType) -> &'static str { + if t.is_symlink() { + "a symbolic link" + } else if t.is_dir() { + "a directory" + } else { + "not a regular file (a pipe, socket or device)" + } +} + +/// Most bytes a loose object may inflate to by default. pub const MAX_LOOSE_OBJECT_BYTES: usize = 1 << 30; +/// Default cap on a loose reference file and on `HEAD` (a 40-hex ID or `ref: `). +pub const DEFAULT_MAX_REF_FILE_BYTES: u64 = 4096; +/// Default cap on `packed-refs`. +pub const DEFAULT_MAX_PACKED_REFS_BYTES: u64 = 64 << 20; +/// Default cap on all `.pack` and `.idx` files together (they are held in memory). +pub const DEFAULT_MAX_PACK_FILES_BYTES: u64 = 2 << 30; +/// Default budget for the inflated bytes of every object a read may hold. +pub const DEFAULT_MAX_TOTAL_OBJECT_BYTES: u64 = 1 << 30; + +/// What reading a repository may cost. Every limit is checked before the bytes it bounds are +/// allocated, and an excess is refused with `QuotaPayloadTooLarge`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReadLimits { + /// A loose reference file or `HEAD`. + pub max_ref_file_bytes: u64, + /// `packed-refs`. + pub max_packed_refs_bytes: u64, + /// Every `.pack` and `.idx` file together. + pub max_pack_files_bytes: u64, + /// One object (whole, delta stream, or delta result), packed or loose. + pub max_object_bytes: u64, + /// The objects of the whole read: the sizes every pack entry declares (counted at + /// [`GitRepository::open_with_limits`]) plus every loose object read. + pub max_total_object_bytes: u64, +} + +impl Default for ReadLimits { + fn default() -> Self { + Self { + max_ref_file_bytes: DEFAULT_MAX_REF_FILE_BYTES, + max_packed_refs_bytes: DEFAULT_MAX_PACKED_REFS_BYTES, + max_pack_files_bytes: DEFAULT_MAX_PACK_FILES_BYTES, + max_object_bytes: MAX_LOOSE_OBJECT_BYTES as u64, + max_total_object_bytes: DEFAULT_MAX_TOTAL_OBJECT_BYTES, + } + } +} + +/// Read `path` if it is a regular file of at most `max` bytes. `Ok(None)` when it does not +/// exist. A symbolic link, directory, pipe, socket or device is refused (`PathInvalid`) +/// without being opened, so a pipe cannot block the reader and a link cannot lead outside the +/// repository; the opened file must still be the one inspected, and at most `max + 1` bytes +/// are read even if it grows. +pub(crate) fn read_regular(path: &Path, max: u64) -> SynapseResult>> { + use std::os::unix::fs::MetadataExt; + let meta = match fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io(e, path)), + }; + if !meta.file_type().is_file() { + return Err(not_regular(path, describe(meta.file_type()))); + } + if meta.len() > max { + return Err(over_cap(path, meta.len(), max)); + } + let file = File::open(path).map_err(|e| io(e, path))?; + let opened = file.metadata().map_err(|e| io(e, path))?; + if !opened.file_type().is_file() || opened.ino() != meta.ino() || opened.dev() != meta.dev() { + return Err(not_regular(path, "a file that changed while being opened")); + } + let mut bytes = Vec::with_capacity(opened.len().min(max) as usize); + file.take(max.saturating_add(1)) + .read_to_end(&mut bytes) + .map_err(|e| io(e, path))?; + if bytes.len() as u64 > max { + return Err(over_cap(path, bytes.len() as u64, max)); + } + Ok(Some(bytes)) +} + +/// `Ok(true)` if `path` is a real directory, `Ok(false)` if it does not exist; a symbolic link +/// or any other file type is refused. +fn real_dir(path: &Path) -> SynapseResult { + match fs::symlink_metadata(path) { + Ok(m) if m.file_type().is_dir() => Ok(true), + Ok(m) => Err(not_regular(path, describe(m.file_type()))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(io(e, path)), + } +} + /// A Git repository opened for reading (its `.git` directory or a bare repository). pub struct GitRepository { git_dir: PathBuf, packs: Vec, + limits: ReadLimits, + /// Object bytes counted against `limits.max_total_object_bytes` so far. + object_bytes: u64, } /// Every object reachable from a repository's references, with the references themselves. @@ -47,29 +162,47 @@ pub struct GitHistory { pub refs: BTreeMap, /// The branch `HEAD` names (`refs/heads/...`), or `None` for a detached or missing `HEAD`. pub head: Option, + /// The commit a detached `HEAD` names (its history is collected too). + pub detached_head: Option, /// Every reachable object, keyed by ID. pub objects: BTreeMap, } +/// What `HEAD` holds. +enum HeadState { + Missing, + Symbolic(String), + Detached(GitOid), +} + impl GitRepository { - /// Open `git_dir` and load the index of every pack in `objects/pack` (a pack without its - /// `.idx` is ignored, as Git ignores it). + /// Open `git_dir` with the default [`ReadLimits`]. pub fn open(git_dir: &Path) -> SynapseResult { + Self::open_with_limits(git_dir, ReadLimits::default()) + } + + /// Open `git_dir` and load the index of every pack in `objects/pack` (a pack without its + /// `.idx` is ignored, as Git ignores it). The pack and index files must be regular files + /// within `limits.max_pack_files_bytes` together, and the sizes their entries declare must + /// fit `limits.max_total_object_bytes`; both are checked before any object is resolved. + pub fn open_with_limits(git_dir: &Path, limits: ReadLimits) -> SynapseResult { let objects = git_dir.join("objects"); - if !objects.is_dir() { + if !real_dir(&objects)? { return Err(SynapseError::new( RefusalCode::PathInvalid, format!("{} has no objects directory", git_dir.display()), )); } - if git_dir.join("objects/info/alternates").exists() { + if fs::symlink_metadata(git_dir.join("objects/info/alternates")).is_ok() { return Err(corrupt( "repositories with alternate object stores are not read by the bridge", )); } let mut packs = Vec::new(); + let mut file_bytes = 0u64; + let mut object_bytes = 0u64; let pack_dir = objects.join("pack"); - if pack_dir.is_dir() { + if real_dir(&pack_dir)? { let mut names: Vec = fs::read_dir(&pack_dir) .map_err(|e| io(e, &pack_dir))? .filter_map(|e| e.ok().map(|e| e.path())) @@ -78,21 +211,42 @@ impl GitRepository { names.sort(); for idx_path in names { let pack_path = idx_path.with_extension("pack"); - if !pack_path.exists() { + if fs::symlink_metadata(&pack_path).is_err() { continue; } - let idx = fs::read(&idx_path).map_err(|e| io(e, &idx_path))?; - let data = fs::read(&pack_path).map_err(|e| io(e, &pack_path))?; - packs.push(PackReader::with_index(data, &idx)?); + let room = limits.max_pack_files_bytes - file_bytes; + let idx = read_regular(&idx_path, room)? + .ok_or_else(|| corrupt(format!("{} vanished", idx_path.display())))?; + file_bytes += idx.len() as u64; + let room = limits.max_pack_files_bytes - file_bytes; + let data = read_regular(&pack_path, room)? + .ok_or_else(|| corrupt(format!("{} vanished", pack_path.display())))?; + file_bytes += data.len() as u64; + let pack = PackReader::with_index_limited(data, &idx, limits.max_object_bytes)?; + object_bytes = object_bytes.saturating_add(pack.declared_bytes()?); + if object_bytes > limits.max_total_object_bytes { + return Err(SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + format!( + "pack objects declare {object_bytes} bytes, over the {} byte budget", + limits.max_total_object_bytes + ), + )); + } + packs.push(pack); } } Ok(Self { git_dir: git_dir.to_path_buf(), packs, + limits, + object_bytes, }) } /// Read object `oid` from the packs or the loose store, checking that it hashes to `oid`. + /// A loose object's declared size is read from the first bytes of its stream and checked + /// against the per-object cap and the remaining budget before it is inflated. pub fn read_object(&mut self, oid: GitOid) -> SynapseResult> { for pack in &mut self.packs { if let Some(object) = pack.read(oid)? { @@ -101,12 +255,37 @@ impl GitRepository { } let hex = oid.to_hex(); let path = self.git_dir.join("objects").join(&hex[..2]).join(&hex[2..]); - let compressed = match fs::read(&path) { - Ok(bytes) => bytes, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(e) => return Err(io(e, &path)), + // An incompressible object stored as zlib grows by 5 bytes per 65,535-byte block plus + // 6; allow the object cap plus 1/64 and 1 KiB for that and the object header. + let max_file = self.limits.max_object_bytes / 64 * 65 + 1024; + let Some(compressed) = read_regular(&path, max_file)? else { + return Ok(None); }; - let (raw, used) = zlib_decompress(&compressed, MAX_LOOSE_OBJECT_BYTES)?; + let head = zlib_inflate_prefix(&compressed, 64)?; + let nul = head + .iter() + .position(|&b| b == 0) + .ok_or_else(|| corrupt(format!("loose object {hex} has no header")))?; + let size: u64 = std::str::from_utf8(&head[..nul]) + .ok() + .and_then(|h| h.split_once(' ')) + .and_then(|(_, n)| n.parse().ok()) + .ok_or_else(|| corrupt(format!("loose object {hex} has a malformed header")))?; + if size > self.limits.max_object_bytes { + return Err(over_cap(&path, size, self.limits.max_object_bytes)); + } + let total = self.object_bytes.saturating_add(size); + if total > self.limits.max_total_object_bytes { + return Err(SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + format!( + "loose object {hex} brings the read to {total} bytes, over the {} byte budget", + self.limits.max_total_object_bytes + ), + )); + } + self.object_bytes = total; + let (raw, used) = zlib_decompress(&compressed, nul + 1 + size as usize)?; if used != compressed.len() { return Err(corrupt(format!("loose object {hex} has trailing bytes"))); } @@ -120,13 +299,31 @@ impl GitRepository { Ok(Some(object)) } + fn head_state(&self) -> SynapseResult { + let path = self.git_dir.join("HEAD"); + let Some(bytes) = read_regular(&path, self.limits.max_ref_file_bytes)? else { + return Ok(HeadState::Missing); + }; + let text = std::str::from_utf8(&bytes).map_err(|_| corrupt("HEAD is not UTF-8"))?; + let value = text.trim_end(); + if let Some(name) = value.strip_prefix("ref: ") { + return Ok(HeadState::Symbolic(name.to_string())); + } + Ok(HeadState::Detached(GitOid::from_hex(value).map_err( + |_| corrupt("HEAD is neither a symbolic reference nor an object ID"), + )?)) + } + /// Every reference: loose refs under `refs/` override `packed-refs`; peeled lines (`^`) - /// and comments are skipped. Also returns the branch `HEAD` points to, if symbolic. + /// and comments are skipped, as are `*.lock` files (Git's in-progress updates). Also + /// returns the branch `HEAD` points to, if symbolic. Every file read must be a regular file + /// within its cap; a symbolic link, pipe or device anywhere under `refs/` is refused. pub fn refs(&self) -> SynapseResult<(BTreeMap, Option)> { let mut refs = BTreeMap::new(); let packed = self.git_dir.join("packed-refs"); - if packed.exists() { - let text = fs::read_to_string(&packed).map_err(|e| io(e, &packed))?; + if let Some(bytes) = read_regular(&packed, self.limits.max_packed_refs_bytes)? { + let text = + std::str::from_utf8(&bytes).map_err(|_| corrupt("packed-refs is not UTF-8"))?; for line in text.lines() { if line.is_empty() || line.starts_with('#') || line.starts_with('^') { continue; @@ -137,24 +334,38 @@ impl GitRepository { refs.insert(name.to_string(), GitOid::from_hex(hex)?); } } - let mut stack = vec![self.git_dir.join("refs")]; + let root = self.git_dir.join("refs"); + let mut stack = if real_dir(&root)? { + vec![root] + } else { + Vec::new() + }; while let Some(dir) = stack.pop() { - if !dir.is_dir() { - continue; - } for entry in fs::read_dir(&dir).map_err(|e| io(e, &dir))? { - let path = entry.map_err(|e| io(e, &dir))?.path(); - if path.is_dir() { + let entry = entry.map_err(|e| io(e, &dir))?; + let path = entry.path(); + // `DirEntry::file_type` does not follow symbolic links. + let file_type = entry.file_type().map_err(|e| io(e, &path))?; + if file_type.is_dir() { stack.push(path); continue; } + if !file_type.is_file() { + return Err(not_regular(&path, describe(file_type))); + } + if path.extension().is_some_and(|x| x == "lock") { + continue; + } let rel = path .strip_prefix(&self.git_dir) .ok() .and_then(|p| p.to_str()) .ok_or_else(|| corrupt("reference name is not UTF-8"))? .replace(std::path::MAIN_SEPARATOR, "/"); - let text = fs::read_to_string(&path).map_err(|e| io(e, &path))?; + let bytes = read_regular(&path, self.limits.max_ref_file_bytes)? + .ok_or_else(|| corrupt(format!("reference {rel} vanished")))?; + let text = std::str::from_utf8(&bytes) + .map_err(|_| corrupt(format!("reference {rel} is not UTF-8")))?; let value = text.trim_end(); if value.starts_with("ref: ") { // Symbolic refs other than HEAD (for example refs/remotes/origin/HEAD) @@ -164,25 +375,26 @@ impl GitRepository { refs.insert(rel, GitOid::from_hex(value)?); } } - let head_path = self.git_dir.join("HEAD"); - let head = match fs::read_to_string(&head_path) { - Ok(text) => text - .trim_end() - .strip_prefix("ref: ") - .map(|name| name.to_string()), - Err(_) => None, + let head = match self.head_state()? { + HeadState::Symbolic(name) => Some(name), + HeadState::Missing | HeadState::Detached(_) => None, }; Ok((refs, head)) } - /// Collect every object reachable from every reference (breadth first). A missing object - /// or an object of the wrong kind for its link is refused (`GitObjectCorrupt`): a partial - /// or shallow repository cannot be imported as full history. + /// Collect every object reachable from every reference and from a detached `HEAD` + /// (breadth first). A missing object or an object of the wrong kind for its link is + /// refused (`GitObjectCorrupt`): a partial or shallow repository cannot be imported as + /// full history. pub fn full_history(&mut self) -> SynapseResult { - if self.git_dir.join("shallow").exists() { + if fs::symlink_metadata(self.git_dir.join("shallow")).is_ok() { return Err(corrupt("shallow repositories do not hold full history")); } let (refs, head) = self.refs()?; + let detached_head = match self.head_state()? { + HeadState::Detached(oid) => Some(oid), + _ => None, + }; let mut objects = BTreeMap::new(); let mut queued: BTreeSet = BTreeSet::new(); let mut queue: VecDeque<(GitOid, Option)> = VecDeque::new(); @@ -191,6 +403,11 @@ impl GitRepository { queue.push_back((*oid, None)); } } + if let Some(oid) = detached_head { + if queued.insert(oid) { + queue.push_back((oid, Some(ObjectKind::Commit))); + } + } while let Some((oid, expected)) = queue.pop_front() { let object = self .read_object(oid)? @@ -214,6 +431,7 @@ impl GitRepository { Ok(GitHistory { refs, head, + detached_head, objects, }) } diff --git a/crates/synapse-git/tests/h1_hostile_repo.rs b/crates/synapse-git/tests/h1_hostile_repo.rs new file mode 100644 index 0000000..b4a9b15 --- /dev/null +++ b/crates/synapse-git/tests/h1_hostile_repo.rs @@ -0,0 +1,344 @@ +//! ADR 0003 step H1 (issue #48): a crafted repository must not hang the native reader, make +//! it read outside the repository, or make it allocate without bound (review of PR #90, +//! findings B1 and B2). Every case calls only `GitRepository::open` and `full_history`, the +//! import entry points. The system `git` builds ordinary fixture history; the hostile parts +//! (a pipe, links, a delta bomb pack) are made by hand. +//! +//! A case that would block (a pipe) runs in a thread with a deadline, so a regression fails +//! the test instead of hanging the test runner. + +use sha1::{Digest, Sha1}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::mpsc; +use std::time::Duration; +use synapse_core::{GitOid, RefusalCode, SynapseResult}; +use synapse_git::pack::{crc32, write_idx, PackIndexEntry}; +use synapse_git::{zlib_compress_store, GitRepository}; + +fn temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "synapse-h1-hostile-{label}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_AUTHOR_NAME", "Fixture Author") + .env("GIT_AUTHOR_EMAIL", "author@fixture.invalid") + .env("GIT_AUTHOR_DATE", "1700000000 +0000") + .env("GIT_COMMITTER_NAME", "Fixture Committer") + .env("GIT_COMMITTER_EMAIL", "committer@fixture.invalid") + .env("GIT_COMMITTER_DATE", "1700000000 +0000") + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).unwrap().trim().to_string() +} + +/// A small repository with two commits on `main`; returns its `.git` directory and the tip. +fn small_repo(label: &str) -> (PathBuf, PathBuf, String) { + let root = temp_dir(label); + let work = root.join("work"); + fs::create_dir_all(&work).unwrap(); + git(&work, &["init", "-q", "-b", "main"]); + fs::write(work.join("a.txt"), b"one\n").unwrap(); + git(&work, &["add", "-A"]); + git(&work, &["commit", "-q", "-m", "one"]); + fs::write(work.join("a.txt"), b"two\n").unwrap(); + git(&work, &["add", "-A"]); + git(&work, &["commit", "-q", "-m", "two"]); + let tip = git(&work, &["rev-parse", "HEAD"]); + (root, work.join(".git"), tip) +} + +fn read_history(git_dir: &Path) -> SynapseResult { + let mut repo = GitRepository::open(git_dir)?; + Ok(repo.full_history()?.objects.len()) +} + +fn assert_refused(result: SynapseResult, code: RefusalCode, case: &str) { + match result { + Err(e) => assert_eq!(e.code, code, "{case}: refused with the wrong code: {e}"), + Ok(n) => panic!("{case}: read {n} objects instead of refusing"), + } +} + +/// Run `full_history` on `git_dir` in a thread. If it has not returned within `deadline`, +/// open `pipe` for writing (which releases a reader blocked opening it) and fail. +fn read_history_with_deadline(git_dir: &Path, pipe: &Path, case: &str) -> SynapseResult { + let (tx, rx) = mpsc::channel(); + let dir = git_dir.to_path_buf(); + let handle = std::thread::spawn(move || { + let _ = tx.send(read_history(&dir)); + }); + match rx.recv_timeout(Duration::from_secs(10)) { + Ok(result) => { + handle.join().unwrap(); + result + } + Err(_) => { + // Release the blocked open so the thread ends, then fail. + drop(fs::OpenOptions::new().write(true).open(pipe)); + let _ = rx.recv_timeout(Duration::from_secs(10)); + panic!("{case}: full_history blocked on a pipe for more than 10 s"); + } + } +} + +fn mkfifo(path: &Path) { + let status = Command::new("mkfifo").arg(path).status().unwrap(); + assert!(status.success(), "mkfifo {}", path.display()); +} + +#[test] +fn h1_hostile_fifo_reference_is_refused_without_blocking() { + let (_root, git_dir, _) = small_repo("fifo-ref"); + let pipe = git_dir.join("refs/heads/pipe"); + mkfifo(&pipe); + let result = read_history_with_deadline(&git_dir, &pipe, "FIFO ref"); + assert_refused(result, RefusalCode::PathInvalid, "FIFO ref"); +} + +#[test] +fn h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking() { + for name in ["packed-refs", "HEAD"] { + let (_root, git_dir, _) = small_repo("fifo-file"); + let pipe = git_dir.join(name); + let _ = fs::remove_file(&pipe); + mkfifo(&pipe); + let result = read_history_with_deadline(&git_dir, &pipe, name); + assert_refused(result, RefusalCode::PathInvalid, name); + } +} + +#[test] +fn h1_hostile_fifo_loose_object_is_refused_without_blocking() { + let (_root, git_dir, tip) = small_repo("fifo-object"); + let path = git_dir.join("objects").join(&tip[..2]).join(&tip[2..]); + fs::remove_file(&path).unwrap(); + mkfifo(&path); + let result = read_history_with_deadline(&git_dir, &path, "FIFO loose object"); + assert_refused(result, RefusalCode::PathInvalid, "FIFO loose object"); +} + +#[test] +fn h1_hostile_reference_linked_to_dev_zero_is_refused() { + let (_root, git_dir, _) = small_repo("dev-zero"); + std::os::unix::fs::symlink("/dev/zero", git_dir.join("refs/heads/zero")).unwrap(); + assert_refused( + read_history(&git_dir), + RefusalCode::PathInvalid, + "ref -> /dev/zero", + ); +} + +#[test] +fn h1_hostile_reference_linked_outside_the_repository_is_refused() { + let (root, git_dir, tip) = small_repo("outside-link"); + // A file outside the repository that holds a valid object ID: following the link would + // read it as a reference. + let outside = root.join("outside-ref"); + fs::write(&outside, format!("{tip}\n")).unwrap(); + std::os::unix::fs::symlink(&outside, git_dir.join("refs/heads/out")).unwrap(); + assert_refused( + read_history(&git_dir), + RefusalCode::PathInvalid, + "ref -> file outside", + ); + // A linked directory under refs/ is refused the same way (no walk into the host tree). + let (_root2, git_dir2, _) = small_repo("outside-dir"); + std::os::unix::fs::symlink("/dev", git_dir2.join("refs/dev")).unwrap(); + assert_refused( + read_history(&git_dir2), + RefusalCode::PathInvalid, + "refs/dev -> /dev", + ); +} + +#[test] +fn h1_hostile_oversized_reference_file_is_refused() { + let (_root, git_dir, tip) = small_repo("big-ref"); + let mut text = format!("{tip}\n"); + text.push_str(&" ".repeat(1 << 20)); + fs::write(git_dir.join("refs/heads/big"), text).unwrap(); + assert_refused( + read_history(&git_dir), + RefusalCode::QuotaPayloadTooLarge, + "1 MiB ref", + ); +} + +#[test] +fn h1_detached_head_commit_is_collected() { + let (_root, git_dir, _) = small_repo("detached"); + let work = git_dir.parent().unwrap(); + git(work, &["checkout", "-q", "--detach"]); + fs::write(work.join("a.txt"), b"detached\n").unwrap(); + git(work, &["add", "-A"]); + git(work, &["commit", "-q", "-m", "only on a detached HEAD"]); + let detached = GitOid::from_hex(&git(work, &["rev-parse", "HEAD"])).unwrap(); + let mut repo = GitRepository::open(&git_dir).unwrap(); + let history = repo.full_history().unwrap(); + assert!( + history.objects.contains_key(&detached), + "a commit reachable only from a detached HEAD was dropped" + ); + // Git's own view of everything reachable includes it. + let all = git(work, &["rev-list", "--all", "--objects"]); + assert_eq!(all.lines().count(), history.objects.len()); +} + +/// The Git blob ID of `base` repeated `copies` times then the byte `tail`, from the system +/// `git hash-object` (the oracle; hashing 256 MiB natively in a debug test build is slow). +fn git_hash_blob(base: &[u8], copies: u64, tail: u8) -> GitOid { + use std::io::Write; + let mut child = Command::new("git") + .args(["hash-object", "--stdin"]) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + { + let mut stdin = child.stdin.take().unwrap(); + for _ in 0..copies { + stdin.write_all(base).unwrap(); + } + stdin.write_all(&[tail]).unwrap(); + } + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + GitOid::from_hex(String::from_utf8(out.stdout).unwrap().trim()).unwrap() +} + +fn entry_header(pack_type: u8, size: u64) -> Vec { + let mut out = vec![(pack_type << 4) | (size & 0x0f) as u8]; + let mut rest = size >> 4; + while rest != 0 { + *out.last_mut().unwrap() |= 0x80; + out.push((rest & 0x7f) as u8); + rest >>= 7; + } + out +} + +fn size_varint(mut n: u64, out: &mut Vec) { + loop { + let byte = (n & 0x7f) as u8; + n >>= 7; + if n == 0 { + out.push(byte); + return; + } + out.push(byte | 0x80); + } +} + +fn ofs_back(back: u64) -> Vec { + let mut n = back; + let mut out = vec![(n & 0x7f) as u8]; + n >>= 7; + while n != 0 { + n -= 1; + out.push(0x80 | (n & 0x7f) as u8); + n >>= 7; + } + out.reverse(); + out +} + +/// A bare repository whose one pack holds a 64 KiB blob and `deltas` offset deltas against it, +/// each about 4 KiB long and resolving to 256 MiB plus one distinguishing byte, each named by +/// a tag. Returns the repository and the pack's size in bytes. +fn delta_bomb(label: &str, deltas: u8) -> (PathBuf, usize) { + let dir = temp_dir(label); + let base: Vec = (0..65_536u32).map(|i| (i * 7 % 251) as u8).collect(); + let copies = 4096u64; + let result_size = copies * base.len() as u64 + 1; + let mut pack = b"PACK".to_vec(); + pack.extend_from_slice(&2u32.to_be_bytes()); + pack.extend_from_slice(&(1 + u32::from(deltas)).to_be_bytes()); + let mut entries = Vec::new(); + + let start = pack.len(); + pack.extend_from_slice(&entry_header(3, base.len() as u64)); + pack.extend_from_slice(&zlib_compress_store(&base)); + entries.push(PackIndexEntry { + oid: GitOid::compute_git_object("blob", &base), + offset: start as u64, + crc32: crc32(&pack[start..]), + }); + let mut refs = Vec::new(); + for i in 0..deltas { + let mut delta = Vec::new(); + size_varint(base.len() as u64, &mut delta); + size_varint(result_size, &mut delta); + // Copy op with no offset or size bytes: copy 0x10000 bytes from offset 0. + delta.extend(std::iter::repeat_n(0x80u8, copies as usize)); + delta.extend_from_slice(&[1, i]); + let at = pack.len(); + pack.extend_from_slice(&entry_header(6, delta.len() as u64)); + pack.extend_from_slice(&ofs_back((at - start) as u64)); + pack.extend_from_slice(&zlib_compress_store(&delta)); + let oid = git_hash_blob(&base, copies, i); + entries.push(PackIndexEntry { + oid, + offset: at as u64, + crc32: crc32(&pack[at..]), + }); + refs.push((format!("refs/tags/t{i}"), oid)); + } + let checksum: [u8; 20] = Sha1::digest(&pack).into(); + pack.extend_from_slice(&checksum); + let idx = write_idx(&entries, GitOid(checksum)); + let pack_dir = dir.join("objects/pack"); + fs::create_dir_all(&pack_dir).unwrap(); + fs::create_dir_all(dir.join("refs/tags")).unwrap(); + let name = format!("pack-{}", GitOid(checksum).to_hex()); + fs::write(pack_dir.join(format!("{name}.pack")), &pack).unwrap(); + fs::write(pack_dir.join(format!("{name}.idx")), &idx).unwrap(); + for (name, oid) in refs { + fs::write(dir.join(name), format!("{}\n", oid.to_hex())).unwrap(); + } + fs::write(dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap(); + (dir, pack.len()) +} + +#[test] +fn h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved() { + // Five deltas of 256 MiB each from a pack under 100 KB: 1.25 GiB declared, over the + // default 1 GiB budget. The refusal must come from the declared sizes, before anything + // is resolved, so this test allocates almost nothing. + let (dir, pack_bytes) = delta_bomb("delta-bomb", 5); + assert!(pack_bytes < 100_000, "bomb pack is {pack_bytes} bytes"); + let started = std::time::Instant::now(); + assert_refused( + read_history(&dir), + RefusalCode::QuotaPayloadTooLarge, + "delta bomb", + ); + assert!( + started.elapsed() < Duration::from_secs(5), + "refusal took {:?}; it must not resolve the deltas", + started.elapsed() + ); +} diff --git a/crates/synapse-git/tests/h1_read_limits.rs b/crates/synapse-git/tests/h1_read_limits.rs new file mode 100644 index 0000000..0db931d --- /dev/null +++ b/crates/synapse-git/tests/h1_read_limits.rs @@ -0,0 +1,162 @@ +//! ADR 0003 step H1 (issue #48): the configurable read limits of the native Git reader +//! (`ReadLimits`, review of PR #90 finding B2). The system `git` only builds fixture history. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; +use synapse_core::RefusalCode; +use synapse_git::{GitRepository, ReadLimits}; + +fn temp_dir(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "synapse-h1-limits-{label}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_AUTHOR_NAME", "Fixture Author") + .env("GIT_AUTHOR_EMAIL", "author@fixture.invalid") + .env("GIT_AUTHOR_DATE", "1700000000 +0000") + .env("GIT_COMMITTER_NAME", "Fixture Committer") + .env("GIT_COMMITTER_EMAIL", "committer@fixture.invalid") + .env("GIT_COMMITTER_DATE", "1700000000 +0000") + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).unwrap().trim().to_string() +} + +/// A repository with a few commits; packed (`git gc`) or loose. Returns its `.git` directory +/// and the total size of its reachable objects as Git reports it. +fn repo(label: &str, packed: bool) -> (PathBuf, u64) { + let work = temp_dir(label); + git(&work, &["init", "-q", "-b", "main"]); + for i in 0..4 { + fs::write(work.join("f.txt"), format!("version {i}\n").repeat(200)).unwrap(); + git(&work, &["add", "-A"]); + git(&work, &["commit", "-q", "-m", &format!("c{i}")]); + } + if packed { + git(&work, &["gc", "-q", "--aggressive", "--prune=now"]); + } + let sizes = git( + &work, + &[ + "cat-file", + "--batch-all-objects", + "--batch-check=%(objectsize)", + ], + ); + let total = sizes.lines().map(|l| l.parse::().unwrap()).sum(); + (work.join(".git"), total) +} + +fn code_of(git_dir: &Path, limits: ReadLimits) -> Option { + GitRepository::open_with_limits(git_dir, limits) + .and_then(|mut r| r.full_history()) + .err() + .map(|e| e.code) +} + +#[test] +fn h1_total_object_budget_is_enforced_for_packed_and_loose_objects() { + for packed in [true, false] { + let (dir, total) = repo( + if packed { + "budget-packed" + } else { + "budget-loose" + }, + packed, + ); + let fits = ReadLimits { + max_total_object_bytes: total, + ..ReadLimits::default() + }; + assert_eq!(code_of(&dir, fits), None, "packed={packed}: exact budget"); + let short = ReadLimits { + max_total_object_bytes: total - 1, + ..ReadLimits::default() + }; + assert_eq!( + code_of(&dir, short), + Some(RefusalCode::QuotaPayloadTooLarge), + "packed={packed}: one byte short" + ); + } +} + +#[test] +fn h1_per_object_cap_is_enforced_for_packed_and_loose_objects() { + for packed in [true, false] { + let (dir, _) = repo(if packed { "cap-packed" } else { "cap-loose" }, packed); + let limits = ReadLimits { + max_object_bytes: 100, + ..ReadLimits::default() + }; + assert_eq!( + code_of(&dir, limits), + Some(RefusalCode::QuotaPayloadTooLarge), + "packed={packed}" + ); + } +} + +#[test] +fn h1_pack_file_and_ref_file_caps_are_enforced() { + let (dir, _) = repo("file-caps", true); + let limits = ReadLimits { + max_pack_files_bytes: 64, + ..ReadLimits::default() + }; + assert_eq!( + code_of(&dir, limits), + Some(RefusalCode::QuotaPayloadTooLarge) + ); + let limits = ReadLimits { + max_packed_refs_bytes: 8, + ..ReadLimits::default() + }; + assert_eq!( + code_of(&dir, limits), + Some(RefusalCode::QuotaPayloadTooLarge), + "packed-refs over its cap" + ); + let limits = ReadLimits { + max_ref_file_bytes: 8, + ..ReadLimits::default() + }; + assert_eq!( + code_of(&dir, limits), + Some(RefusalCode::QuotaPayloadTooLarge), + "HEAD over its cap" + ); +} + +#[test] +fn h1_lock_files_under_refs_are_skipped() { + let (dir, _) = repo("lock", false); + let tip = fs::read_to_string(dir.join("refs/heads/main")).unwrap(); + fs::write(dir.join("refs/heads/main.lock"), tip).unwrap(); + let mut r = GitRepository::open(&dir).unwrap(); + let (refs, _) = r.refs().unwrap(); + assert_eq!(refs.keys().collect::>(), ["refs/heads/main"]); + r.full_history().unwrap(); +} diff --git a/docs/H1_GIT_BRIDGE.md b/docs/H1_GIT_BRIDGE.md index 340fddc..f60bc91 100644 --- a/docs/H1_GIT_BRIDGE.md +++ b/docs/H1_GIT_BRIDGE.md @@ -18,10 +18,25 @@ Code: `crates/synapse-git/src/{object,inflate,pack,repo}.rs`. Tests: `crates/syn Writer determinism: the pack holds whole objects in object ID order, compressed as zlib stored blocks (the existing `zlib_compress_store`), so the bytes are a function of the object set alone; input order and duplicates do not matter. -Every malformed input is refused with `RefusalCode::GitObjectCorrupt` and never panics: bad zlib header or checksum, truncated or over-declared streams, over-subscribed Huffman codes, distances before the output start, pack or index checksum mismatch, offsets outside the pack, non-monotone fan-out, unsorted names, delta size mismatches, copies past the base, delta chain loops or chains over 4096, reference-delta bases missing from the pack (thin packs), objects over 1 GiB, an object whose content does not hash to its ID, missing objects, shallow repositories, and alternates. +Every malformed input is refused with `RefusalCode::GitObjectCorrupt` and never panics: bad zlib header or checksum, truncated or over-declared streams, over-subscribed Huffman codes, distances before the output start, pack or index checksum mismatch, offsets outside the pack, non-monotone fan-out, unsorted names, delta size mismatches, copies past the base, delta chain loops or chains over 4096, reference-delta bases missing from the pack (thin packs), an object whose content does not hash to its ID, missing objects, shallow repositories, and alternates. Exceeding a read limit is refused with `QuotaPayloadTooLarge` and a non-regular file with `PathInvalid` (section 1a). The system `git` binary is used only by the tests, as an independent oracle. `synapse-git` starts no Git process on any cut 1 path. +## 1a. Hostile repositories (review of PR #90, findings B1 and B2) + +A repository handed to the bridge is untrusted input. The reader may not hang on it, read outside it, or allocate without bound because of it: + +| Threat | Rule | Refusal | +| :--- | :--- | :--- | +| A reference, `packed-refs`, `HEAD`, loose object, `.pack` or `.idx` that is a pipe, socket, device or symbolic link (a pipe blocks a reader forever; a link to `/dev/zero` reads without end; a link can lead outside the repository) | Every file is inspected with `symlink_metadata` and opened only if it is a regular file; the opened file must be the inspected one (same device and inode); at most cap + 1 bytes are read even if it grows. The `refs/` walk uses `DirEntry::file_type`, which does not follow links; `refs/`, `objects/` and `objects/pack/` must be real directories | `PathInvalid` | +| Oversized small files | Loose reference and `HEAD` at most 4 KiB, `packed-refs` at most 64 MiB, every `.pack` and `.idx` together at most 2 GiB (held in memory) | `QuotaPayloadTooLarge` | +| Delta amplification (a 4 KiB delta copying a 64 KiB base 4,096 times resolves to 256 MiB) | **Total budget**: at `open`, the size every pack entry declares it resolves to is summed from the entry headers and the first 20 inflated bytes of each delta stream (`PackReader::declared_bytes`, nothing resolved); each loose object's declared size is read from the first 64 inflated bytes before it is inflated. The sum may not pass `max_total_object_bytes`, **default 1 GiB** (omega, the largest repository the bridge has read, holds 374,301,457 bytes of objects). A resolved entry always has exactly its declared size (checked on every read), so the budget bounds what a read holds | `QuotaPayloadTooLarge` | +| One huge object | Per-object cap `max_object_bytes`, default 1 GiB, on every whole entry, delta stream, delta result and loose object, checked against the declared size before allocation. `apply_delta` no longer reserves the declared result size up front: it reserves at most base + delta length and grows as instructions produce bytes, never past the declared size | `QuotaPayloadTooLarge` | + +All five limits are fields of `ReadLimits` (`GitRepository::open_with_limits`); `GitRepository::open` uses the defaults. Also from the review: `*.lock` files under `refs/` are skipped as Git skips them, and a detached `HEAD`'s commit is collected with its history (`GitHistory::detached_head`). A symbolic link as `HEAD` is now refused instead of read as "no `HEAD`". + +Residual, stated: the file checks assume the repository is not being changed while it is read. An attacker who swaps a regular file for a pipe between the `symlink_metadata` check and the `open` can still block that `open` (the inode check runs after it). Closing that needs `O_NOFOLLOW | O_NONBLOCK`, which `std` does not name portably; not done here. + ## 2. Acceptance status (issue #48) | Acceptance (issue #48) | Status | Evidence | @@ -52,11 +67,13 @@ The fixture (built by Git in the test) covers nested trees, executable files, a `green.txt` holds the passing runs and the two real repository runs. +`evidence/h1-git-bridge/red-green/hostile-red.txt` (review findings B1 and B2): `tests/h1_hostile_repo.rs` uses only `GitRepository::open` and `full_history`, so the same file runs unchanged against the reviewed head `b4fe463`. There all 8 cases fail: the pipe cases (a reference, `packed-refs`, a loose object) block until the test's 10 s deadline releases them, the `/dev/zero` link fails with `IoFailure: out of memory` under the run's `ulimit -v 4000000` guard, the link to a file outside the repository and the 1 MiB reference are read as references, the 82 KB delta bomb resolves 5 objects of 256 MiB, and the detached `HEAD` commit is missing. Two further stubs on the fixed code: (A) the total budget check removed: the budget test fails; (B) links followed (`metadata` instead of `symlink_metadata`, and in the `refs/` walk): the outside-link test fails. `hostile-green.txt` holds the passing runs. + ## 4. Limits and what remains * **Cut 2 remains**: the persistent `GitOid` to (`ChangesetId`, `TreeDigest`) map; imported blobs stored natively; Git trees converted to `TreeDigest` and recomputed at export; commits as revisions whose original commit and tag headers are kept as opaque bridge data; export of imported history from stored headers and of native revisions with deterministic generated message and author fields (section 5.10). It needs a new WAL record kind; open PR #88 claims kind 9, so cut 2 will use kind 10. * Exported packs are not compressed beyond zlib stored blocks and hold no deltas: the omega export is 374,712,257 bytes against 50,117 KiB for Git's own pack (`count-objects -v`). Correct and accepted by Git, but large; a native compressor is a later change. * SHA-1 object format only. A SHA-256 Git repository (`extensions.objectformat = sha256`) is not read. * The existing per-changeset `materialize_changeset_to_git` still writes loose objects; it is a legacy path and is replaced by the cut 2 export. -* `GitRepository` reads whole pack files into memory, and `full_history` holds every object; fine for the repositories above, not bounded for very large ones. +* `GitRepository` reads whole pack files into memory and `full_history` holds every object, both bounded by `ReadLimits` (section 1a). A repository larger than the defaults needs the caller to raise them. Peak RSS of the test process for the omega round trip with the defaults: 1,114,576 KiB (`/usr/bin/time -v`). * No performance figure is claimed: none is part of this cut's acceptance and no run was measured against a section 6 bound. diff --git a/evidence/h1-git-bridge/SHA256SUMS b/evidence/h1-git-bridge/SHA256SUMS index 86f820d..9954211 100644 --- a/evidence/h1-git-bridge/SHA256SUMS +++ b/evidence/h1-git-bridge/SHA256SUMS @@ -1,2 +1,4 @@ 8f8591c3edcf0019bd2d6e0fdc491cd33cf3c5e353990ec45bd171f6197ad60e red-green/green.txt +877ed1eeb33e46031532ddcbd0aec394630663703d12281d7dbff201773ffbe4 red-green/hostile-green.txt +80439ea1571ad877d410d2ca12521c57dc8aaed0c3725f85e24f171a56de379e red-green/hostile-red.txt 5daa9e456ef3ef01f695894887674b23d40c8d906fb379cefdd6c5746cc77a61 red-green/red.txt diff --git a/evidence/h1-git-bridge/red-green/hostile-green.txt b/evidence/h1-git-bridge/red-green/hostile-green.txt new file mode 100644 index 0000000..1b61dbe --- /dev/null +++ b/evidence/h1-git-bridge/red-green/hostile-green.txt @@ -0,0 +1,41 @@ +# Green (2026-10-17, review of PR #90 findings B1 and B2, fixed code) +# Command: cargo test --locked -p synapse-git --test h1_hostile_repo --test h1_read_limits + +running 8 tests +test h1_hostile_oversized_reference_file_is_refused ... ok +test h1_hostile_fifo_reference_is_refused_without_blocking ... ok +test h1_hostile_fifo_loose_object_is_refused_without_blocking ... ok +test h1_hostile_reference_linked_to_dev_zero_is_refused ... ok +test h1_detached_head_commit_is_collected ... ok +test h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking ... ok +test h1_hostile_reference_linked_outside_the_repository_is_refused ... ok +test h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved ... ok + +test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.66s + + +running 4 tests +test h1_lock_files_under_refs_are_skipped ... ok +test h1_pack_file_and_ref_file_caps_are_enforced ... ok +test h1_per_object_cap_is_enforced_for_packed_and_loose_objects ... ok +test h1_total_object_budget_is_enforced_for_packed_and_loose_objects ... ok + +test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.11s + +# Command: cargo test --locked --workspace (357 passed, 0 failed, 2 ignored, 46 test binaries) + +# Real repository with default ReadLimits: git clone --mirror https://github.com/aien-dev/synapse +# Command: SYNAPSE_H1_REAL_REPO= /usr/bin/time -v cargo test --locked -p synapse-git --test h1_git_bridge -- --ignored --nocapture h1_real_repository +real repository synapse.git: 1915 objects (180 commits), 75 refs, pack 72477923 bytes +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 15.35s +Maximum resident set size (kbytes): 225996 + +# Real repository with default ReadLimits: git clone --mirror https://github.com/aien-dev/omega +# Command: SYNAPSE_H1_REAL_REPO= /usr/bin/time -v cargo test --locked -p synapse-git --test h1_git_bridge -- --ignored --nocapture h1_real_repository +test h1_real_repository_full_history_round_trips_with_identical_object_ids has been running for over 60 seconds +real repository omega.git: 29636 objects (2413 commits), 633 refs, pack 374713444 bytes +test h1_real_repository_full_history_round_trips_with_identical_object_ids ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 76.19s +Maximum resident set size (kbytes): 1114576 + diff --git a/evidence/h1-git-bridge/red-green/hostile-red.txt b/evidence/h1-git-bridge/red-green/hostile-red.txt new file mode 100644 index 0000000..4f7b325 --- /dev/null +++ b/evidence/h1-git-bridge/red-green/hostile-red.txt @@ -0,0 +1,134 @@ +# Red (2026-10-17, review of PR #90 findings B1 and B2) +# Run 1: tests/h1_hostile_repo.rs copied unchanged into a detached worktree of the reviewed head b4fe463. +# Command: (ulimit -v 4000000; cargo test --locked -p synapse-git --test h1_hostile_repo -- --test-threads=1) +# The ulimit guards the /dev/zero case; pipe cases end at the test's own 10 s deadline. +# + +running 8 tests +test h1_detached_head_commit_is_collected ... FAILED +test h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved ... FAILED +test h1_hostile_fifo_loose_object_is_refused_without_blocking ... FAILED +test h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking ... FAILED +test h1_hostile_fifo_reference_is_refused_without_blocking ... FAILED +test h1_hostile_oversized_reference_file_is_refused ... FAILED +test h1_hostile_reference_linked_outside_the_repository_is_refused ... FAILED +test h1_hostile_reference_linked_to_dev_zero_is_refused ... FAILED + +failures: + +---- h1_detached_head_commit_is_collected stdout ---- + +thread 'h1_detached_head_commit_is_collected' (1645995) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:200:5: +a commit reachable only from a detached HEAD was dropped + +---- h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved stdout ---- + +thread 'h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved' (1646017) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:80:18: +delta bomb: read 5 objects instead of refusing + +---- h1_hostile_fifo_loose_object_is_refused_without_blocking stdout ---- + +thread 'h1_hostile_fifo_loose_object_is_refused_without_blocking' (1658200) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:101:13: +FIFO loose object: full_history blocked on a pipe for more than 10 s + +---- h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking stdout ---- + +thread 'h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking' (1660665) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:101:13: +packed-refs: full_history blocked on a pipe for more than 10 s + +---- h1_hostile_fifo_reference_is_refused_without_blocking stdout ---- + +thread 'h1_hostile_fifo_reference_is_refused_without_blocking' (1662315) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:101:13: +FIFO ref: full_history blocked on a pipe for more than 10 s + +---- h1_hostile_oversized_reference_file_is_refused stdout ---- + +thread 'h1_hostile_oversized_reference_file_is_refused' (1664201) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:80:18: +1 MiB ref: read 6 objects instead of refusing + +---- h1_hostile_reference_linked_outside_the_repository_is_refused stdout ---- + +thread 'h1_hostile_reference_linked_outside_the_repository_is_refused' (1664210) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:80:18: +ref -> file outside: read 6 objects instead of refusing + +---- h1_hostile_reference_linked_to_dev_zero_is_refused stdout ---- + +thread 'h1_hostile_reference_linked_to_dev_zero_is_refused' (1664219) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:79:19: +assertion `left == right` failed: ref -> /dev/zero: refused with the wrong code: IoFailure: /tmp/synapse-h1-hostile-dev-zero-1645989-1792203297294672641/work/.git/refs/heads/zero: out of memory + left: IoFailure + right: PathInvalid + + +failures: + h1_detached_head_commit_is_collected + h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved + h1_hostile_fifo_loose_object_is_refused_without_blocking + h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking + h1_hostile_fifo_reference_is_refused_without_blocking + h1_hostile_oversized_reference_file_is_refused + h1_hostile_reference_linked_outside_the_repository_is_refused + h1_hostile_reference_linked_to_dev_zero_is_refused + +test result: FAILED. 0 passed; 8 failed; 0 ignored; 0 measured; 0 filtered out; finished in 75.66s + +error: test failed, to rerun pass `-p synapse-git --test h1_hostile_repo` +Command exited with non-zero status 101 +Maximum resident set size (kbytes): 2100860 + +# Run 2, stub A on the fixed code: the total object budget check removed (open_with_limits and loose reads). +# Command: cargo test --locked --no-fail-fast -p synapse-git --test h1_read_limits + +running 4 tests +test h1_lock_files_under_refs_are_skipped ... ok +test h1_pack_file_and_ref_file_caps_are_enforced ... ok +test h1_total_object_budget_is_enforced_for_packed_and_loose_objects ... FAILED +test h1_per_object_cap_is_enforced_for_packed_and_loose_objects ... ok + +failures: + +---- h1_total_object_budget_is_enforced_for_packed_and_loose_objects stdout ---- + +thread 'h1_total_object_budget_is_enforced_for_packed_and_loose_objects' (1668568) panicked at crates/synapse-git/tests/h1_read_limits.rs:87:9: +assertion `left == right` failed: packed=true: one byte short + left: None + right: Some(QuotaPayloadTooLarge) + + +failures: + h1_total_object_budget_is_enforced_for_packed_and_loose_objects + +test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s + +error: test failed, to rerun pass `-p synapse-git --test h1_read_limits` +error: 1 target failed: + `-p synapse-git --test h1_read_limits` + +# Run 3, stub B on the fixed code: links followed (fs::metadata in read_regular, real_dir and the refs/ walk). +# Command: cargo test --locked --no-fail-fast -p synapse-git --test h1_hostile_repo + +running 8 tests +test h1_hostile_fifo_reference_is_refused_without_blocking ... ok +test h1_hostile_reference_linked_to_dev_zero_is_refused ... ok +test h1_hostile_fifo_loose_object_is_refused_without_blocking ... ok +test h1_hostile_oversized_reference_file_is_refused ... ok +test h1_hostile_reference_linked_outside_the_repository_is_refused ... FAILED +test h1_detached_head_commit_is_collected ... ok +test h1_hostile_fifo_packed_refs_and_head_are_refused_without_blocking ... ok +test h1_hostile_delta_bomb_pack_is_refused_before_it_is_resolved ... ok + +failures: + +---- h1_hostile_reference_linked_outside_the_repository_is_refused stdout ---- + +thread 'h1_hostile_reference_linked_outside_the_repository_is_refused' (1671877) panicked at crates/synapse-git/tests/h1_hostile_repo.rs:80:18: +ref -> file outside: read 6 objects instead of refusing + + +failures: + h1_hostile_reference_linked_outside_the_repository_is_refused + +test result: FAILED. 7 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.57s + +error: test failed, to rerun pass `-p synapse-git --test h1_hostile_repo` +error: 1 target failed: + `-p synapse-git --test h1_hostile_repo` From 77227b6b132bbd9ca2d0fbd86bffd84b3c509dbc Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 16 Oct 2026 21:23:58 -0500 Subject: [PATCH 3/4] fix(git): open repository files with O_NOFOLLOW | O_NONBLOCK (#48, review of #90) Closes the residual check-then-open race: a link swapped in after the symlink_metadata check fails with ELOOP, a pipe swapped in opens at once and fails the regular-file, device and inode check. libc is already a workspace dependency (synapse-bench, synapse-coord); Cargo.lock gains only the synapse-git edge. Red: stub C (custom_flags(0)) blocks on the pipe until the unit test's 10 s deadline. Green: 358 passed, 0 failed, 2 ignored (workspace). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/synapse-git/Cargo.toml | 1 + crates/synapse-git/src/repo.rs | 90 +++++++++++++++++-- docs/H1_GIT_BRIDGE.md | 4 +- evidence/h1-git-bridge/SHA256SUMS | 4 +- .../h1-git-bridge/red-green/hostile-green.txt | 2 +- .../h1-git-bridge/red-green/hostile-red.txt | 23 +++++ 7 files changed, 112 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 10ac157..70b130d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -464,6 +464,7 @@ version = "0.1.0" dependencies = [ "ed25519-dalek", "hex", + "libc", "serde", "serde_json", "sha1", diff --git a/crates/synapse-git/Cargo.toml b/crates/synapse-git/Cargo.toml index 0247287..3e8a4c6 100644 --- a/crates/synapse-git/Cargo.toml +++ b/crates/synapse-git/Cargo.toml @@ -10,6 +10,7 @@ description = "Deterministic Git loose object materialization, bidirectional Cha [dependencies] ed25519-dalek.workspace = true hex.workspace = true +libc.workspace = true serde.workspace = true serde_json.workspace = true sha1.workspace = true diff --git a/crates/synapse-git/src/repo.rs b/crates/synapse-git/src/repo.rs index 4f74d4e..3b6e86e 100644 --- a/crates/synapse-git/src/repo.rs +++ b/crates/synapse-git/src/repo.rs @@ -105,10 +105,10 @@ impl Default for ReadLimits { /// Read `path` if it is a regular file of at most `max` bytes. `Ok(None)` when it does not /// exist. A symbolic link, directory, pipe, socket or device is refused (`PathInvalid`) /// without being opened, so a pipe cannot block the reader and a link cannot lead outside the -/// repository; the opened file must still be the one inspected, and at most `max + 1` bytes -/// are read even if it grows. +/// repository. The open itself uses `O_NOFOLLOW | O_NONBLOCK` and the opened file must be the +/// regular file inspected (same device and inode), so a file swapped between the check and the +/// open is refused too; at most `max + 1` bytes are read even if it grows. pub(crate) fn read_regular(path: &Path, max: u64) -> SynapseResult>> { - use std::os::unix::fs::MetadataExt; let meta = match fs::symlink_metadata(path) { Ok(m) => m, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), @@ -120,11 +120,7 @@ pub(crate) fn read_regular(path: &Path, max: u64) -> SynapseResult max { return Err(over_cap(path, meta.len(), max)); } - let file = File::open(path).map_err(|e| io(e, path))?; - let opened = file.metadata().map_err(|e| io(e, path))?; - if !opened.file_type().is_file() || opened.ino() != meta.ino() || opened.dev() != meta.dev() { - return Err(not_regular(path, "a file that changed while being opened")); - } + let (file, opened) = open_inspected(path, &meta)?; let mut bytes = Vec::with_capacity(opened.len().min(max) as usize); file.take(max.saturating_add(1)) .read_to_end(&mut bytes) @@ -135,6 +131,27 @@ pub(crate) fn read_regular(path: &Path, max: u64) -> SynapseResult SynapseResult<(File, fs::Metadata)> { + use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; + let file = fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + .map_err(|e| match e.raw_os_error() { + Some(libc::ELOOP) => not_regular(path, "a symbolic link"), + _ => io(e, path), + })?; + let opened = file.metadata().map_err(|e| io(e, path))?; + if !opened.file_type().is_file() || opened.ino() != meta.ino() || opened.dev() != meta.dev() { + return Err(not_regular(path, "a file that changed while being opened")); + } + Ok((file, opened)) +} + /// `Ok(true)` if `path` is a real directory, `Ok(false)` if it does not exist; a symbolic link /// or any other file type is refused. fn real_dir(path: &Path) -> SynapseResult { @@ -550,3 +567,60 @@ pub fn export_repository( pack_bytes: pack.len() as u64, }) } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + use std::time::Duration; + + fn scratch(label: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "synapse-h1-open-{label}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + /// The file is inspected as a regular file, then swapped before the open (the race the + /// `symlink_metadata` check alone cannot close). The open must refuse it at once. + #[test] + fn a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking() { + for swap in ["pipe", "link"] { + let dir = scratch(swap); + let path = dir.join("ref"); + fs::write(&path, b"0000000000000000000000000000000000000000\n").unwrap(); + let meta = fs::symlink_metadata(&path).unwrap(); + fs::remove_file(&path).unwrap(); + if swap == "pipe" { + let ok = std::process::Command::new("mkfifo") + .arg(&path) + .status() + .unwrap() + .success(); + assert!(ok); + } else { + fs::write(dir.join("elsewhere"), b"x").unwrap(); + std::os::unix::fs::symlink(dir.join("elsewhere"), &path).unwrap(); + } + let (tx, rx) = mpsc::channel(); + let p = path.clone(); + std::thread::spawn(move || { + let _ = tx.send(open_inspected(&p, &meta).map(|_| ())); + }); + let result = match rx.recv_timeout(Duration::from_secs(10)) { + Ok(r) => r, + Err(_) => { + drop(fs::OpenOptions::new().write(true).open(&path)); + panic!("{swap}: open blocked for more than 10 s"); + } + }; + assert_eq!(result.unwrap_err().code, RefusalCode::PathInvalid, "{swap}"); + } + } +} diff --git a/docs/H1_GIT_BRIDGE.md b/docs/H1_GIT_BRIDGE.md index f60bc91..359d773 100644 --- a/docs/H1_GIT_BRIDGE.md +++ b/docs/H1_GIT_BRIDGE.md @@ -35,7 +35,7 @@ A repository handed to the bridge is untrusted input. The reader may not hang on All five limits are fields of `ReadLimits` (`GitRepository::open_with_limits`); `GitRepository::open` uses the defaults. Also from the review: `*.lock` files under `refs/` are skipped as Git skips them, and a detached `HEAD`'s commit is collected with its history (`GitHistory::detached_head`). A symbolic link as `HEAD` is now refused instead of read as "no `HEAD`". -Residual, stated: the file checks assume the repository is not being changed while it is read. An attacker who swaps a regular file for a pipe between the `symlink_metadata` check and the `open` can still block that `open` (the inode check runs after it). Closing that needs `O_NOFOLLOW | O_NONBLOCK`, which `std` does not name portably; not done here. +A file swapped between the check and the open is refused too: the open uses `O_NOFOLLOW | O_NONBLOCK` (`OpenOptionsExt::custom_flags`, constants from the workspace `libc` dependency), so a swapped-in link fails with `ELOOP` and a swapped-in pipe opens at once and fails the device, inode and regular-file check (unit test `a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking`). ## 2. Acceptance status (issue #48) @@ -67,7 +67,7 @@ The fixture (built by Git in the test) covers nested trees, executable files, a `green.txt` holds the passing runs and the two real repository runs. -`evidence/h1-git-bridge/red-green/hostile-red.txt` (review findings B1 and B2): `tests/h1_hostile_repo.rs` uses only `GitRepository::open` and `full_history`, so the same file runs unchanged against the reviewed head `b4fe463`. There all 8 cases fail: the pipe cases (a reference, `packed-refs`, a loose object) block until the test's 10 s deadline releases them, the `/dev/zero` link fails with `IoFailure: out of memory` under the run's `ulimit -v 4000000` guard, the link to a file outside the repository and the 1 MiB reference are read as references, the 82 KB delta bomb resolves 5 objects of 256 MiB, and the detached `HEAD` commit is missing. Two further stubs on the fixed code: (A) the total budget check removed: the budget test fails; (B) links followed (`metadata` instead of `symlink_metadata`, and in the `refs/` walk): the outside-link test fails. `hostile-green.txt` holds the passing runs. +`evidence/h1-git-bridge/red-green/hostile-red.txt` (review findings B1 and B2): `tests/h1_hostile_repo.rs` uses only `GitRepository::open` and `full_history`, so the same file runs unchanged against the reviewed head `b4fe463`. There all 8 cases fail: the pipe cases (a reference, `packed-refs`, a loose object) block until the test's 10 s deadline releases them, the `/dev/zero` link fails with `IoFailure: out of memory` under the run's `ulimit -v 4000000` guard, the link to a file outside the repository and the 1 MiB reference are read as references, the 82 KB delta bomb resolves 5 objects of 256 MiB, and the detached `HEAD` commit is missing. Three further stubs on the fixed code: (A) the total budget check removed: the budget test fails; (B) links followed (`metadata` instead of `symlink_metadata`, and in the `refs/` walk): the outside-link test fails; (C) files opened without `O_NOFOLLOW | O_NONBLOCK`: the swap test blocks on the pipe until its 10 s deadline. `hostile-green.txt` holds the passing runs. ## 4. Limits and what remains diff --git a/evidence/h1-git-bridge/SHA256SUMS b/evidence/h1-git-bridge/SHA256SUMS index 9954211..b650bcb 100644 --- a/evidence/h1-git-bridge/SHA256SUMS +++ b/evidence/h1-git-bridge/SHA256SUMS @@ -1,4 +1,4 @@ 8f8591c3edcf0019bd2d6e0fdc491cd33cf3c5e353990ec45bd171f6197ad60e red-green/green.txt -877ed1eeb33e46031532ddcbd0aec394630663703d12281d7dbff201773ffbe4 red-green/hostile-green.txt -80439ea1571ad877d410d2ca12521c57dc8aaed0c3725f85e24f171a56de379e red-green/hostile-red.txt +41088f6a7ba636697b9a239e9c37517eb9e442164e6f1f011f8e04649e1896f4 red-green/hostile-green.txt +aaa6b740c5e1f28e2989e9e45dd50c2a97ce38d826426abf472a5cd7939297b7 red-green/hostile-red.txt 5daa9e456ef3ef01f695894887674b23d40c8d906fb379cefdd6c5746cc77a61 red-green/red.txt diff --git a/evidence/h1-git-bridge/red-green/hostile-green.txt b/evidence/h1-git-bridge/red-green/hostile-green.txt index 1b61dbe..691932a 100644 --- a/evidence/h1-git-bridge/red-green/hostile-green.txt +++ b/evidence/h1-git-bridge/red-green/hostile-green.txt @@ -22,7 +22,7 @@ test h1_total_object_budget_is_enforced_for_packed_and_loose_objects ... ok test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.11s -# Command: cargo test --locked --workspace (357 passed, 0 failed, 2 ignored, 46 test binaries) +# Command: cargo test --locked --workspace (358 passed, 0 failed, 2 ignored, 46 test binaries; includes the unit test a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking) # Real repository with default ReadLimits: git clone --mirror https://github.com/aien-dev/synapse # Command: SYNAPSE_H1_REAL_REPO= /usr/bin/time -v cargo test --locked -p synapse-git --test h1_git_bridge -- --ignored --nocapture h1_real_repository diff --git a/evidence/h1-git-bridge/red-green/hostile-red.txt b/evidence/h1-git-bridge/red-green/hostile-red.txt index 4f7b325..83231de 100644 --- a/evidence/h1-git-bridge/red-green/hostile-red.txt +++ b/evidence/h1-git-bridge/red-green/hostile-red.txt @@ -132,3 +132,26 @@ test result: FAILED. 7 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; error: test failed, to rerun pass `-p synapse-git --test h1_hostile_repo` error: 1 target failed: `-p synapse-git --test h1_hostile_repo` + +# Run 4, stub C on the fixed code: repository files opened without O_NOFOLLOW | O_NONBLOCK (custom_flags(0)). +# Command: cargo test --locked --no-fail-fast -p synapse-git --lib -- a_file_swapped + +running 1 test +test repo::tests::a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking ... FAILED + +failures: + +---- repo::tests::a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking stdout ---- + +thread 'repo::tests::a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking' (1921050) panicked at crates/synapse-git/src/repo.rs:620:21: +pipe: open blocked for more than 10 s + + +failures: + repo::tests::a_file_swapped_for_a_pipe_or_link_after_the_check_is_refused_without_blocking + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 14 filtered out; finished in 10.00s + +error: test failed, to rerun pass `-p synapse-git --lib` +error: 1 target failed: + `-p synapse-git --lib` From 090aa70844b703e1d52cf82596a978ed54b43506 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 17 Oct 2026 07:02:46 -0500 Subject: [PATCH 4/4] crumb: recompile for H1 cut 1 rebased on B5 (crumb.lock d0f0b95) Co-Authored-By: Claude Sonnet 5.5 --- .crumb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.crumb b/.crumb index b241b63..6a12dd2 100644 --- a/.crumb +++ b/.crumb @@ -45,14 +45,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-17T11:53:58Z", + "compiled_at": "2026-10-17T12:02:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:02c07846431e14591967857e7fa02a5123c36d0b7ee1637234a816c911981ce0", - "evidence_files": 257, - "evidence_root": "sha256:209cf73b94ce79f2c68b46628b4936c950ceb96ebc3d93c0575d7510b3bcf2d6", - "files": 443, - "generated_at_commit": "1cf99e0f4c57a6e07158f92f113664b695a8e004", - "source_tree": "sha256:876e335d9234ad209f8621813a3040ec5cbe0a3a2f705f2857245151fd6bfd8f" + "digest": "sha256:fb301066e5ae4d15cead28f810814b4f4772e79638563bee1c13b56c86c3a501", + "evidence_files": 262, + "evidence_root": "sha256:b25d2fcc4dd431ffce85a91a08342766e8f5d4b0309e16df46c008083835d98a", + "files": 456, + "generated_at_commit": "77227b6b132bbd9ca2d0fbd86bffd84b3c509dbc", + "source_tree": "sha256:0b135d43305597f16d1212342c522b05be78f06b5fa8befc2e645c28cb31e584" }, "synapse": { "component_paths": {