arks-hash 1.3.8

In-engine Git object-format hashing (SHA-1-CD / SHA-256)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! In-engine hashing for Git object identity.
//!
//! Contract (M1): compute digests of uncompressed object bytes
//! (`type SP size NUL` + payload) matching stock Git for the claimed
//! object formats. No I/O. No `gix`. No `git` subprocess.
//!
//! SHA-1 uses Marc Stevens collision detection (`sha1collisiondetection`) —
//! **detect+refuse** on cryptanalytic collision attacks (OBJ-004 Claimed
//! slice). Absolute cryptographic **immunity** remains Impossible.
//!
//! Primary: <https://git-scm.com/docs/gitformat-loose>
//! Cite: `.spec/research/20261108071913-git-objects-pack.research.md`
//!       `.spec/research/20261110222000-remaining-gaps-ffi-external-unblock.research.md`

#![forbid(unsafe_code)]

/// Repository object-format hash algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ObjectFormat {
    /// Classic SHA-1 (20-byte OID) with collision detection (OBJ-004).
    Sha1,
    /// SHA-256 (32-byte OID).
    Sha256,
}

impl ObjectFormat {
    /// Digest length in bytes for this format.
    pub const fn digest_len(self) -> usize {
        match self {
            Self::Sha1 => 20,
            Self::Sha256 => 32,
        }
    }
}

/// Fixed-capacity digest bytes for either object format.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Digest {
    format: ObjectFormat,
    bytes: [u8; 32],
    len: u8,
}

impl Digest {
    pub fn format(self) -> ObjectFormat {
        self.format
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }

    pub fn from_bytes(format: ObjectFormat, bytes: &[u8]) -> Result<Self, HashError> {
        let need = format.digest_len();
        if bytes.len() != need {
            return Err(HashError::DigestLength {
                expected: need,
                actual: bytes.len(),
            });
        }
        let mut out = [0u8; 32];
        out[..need].copy_from_slice(bytes);
        Ok(Self {
            format,
            bytes: out,
            len: need as u8,
        })
    }
}

impl core::fmt::Debug for Digest {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Digest({:?}, ", self.format)?;
        for b in self.as_bytes() {
            write!(f, "{b:02x}")?;
        }
        write!(f, ")")
    }
}

/// Incremental hasher for a chosen object format.
#[derive(Clone)]
pub struct Hasher {
    inner: HasherInner,
}

#[derive(Clone)]
enum HasherInner {
    /// Collision-detecting SHA-1 (safe_hash off → explicit refuse via Err).
    /// Boxed: Sha1CD state is large (~2KiB); avoid `large_enum_variant`.
    Sha1(Box<sha1collisiondetection::Sha1CD>),
    Sha256(sha2::Sha256),
}

fn new_sha1cd() -> Box<sha1collisiondetection::Sha1CD> {
    // safe_hash(false): do not silently rewrite digests; callers refuse via Err.
    // detect_collisions(true): Claimed OBJ-004 detect path.
    Box::new(
        sha1collisiondetection::Builder::default()
            .safe_hash(false)
            .detect_collisions(true)
            .use_ubc(true)
            .build(),
    )
}

impl Hasher {
    pub fn new(format: ObjectFormat) -> Self {
        let inner = match format {
            ObjectFormat::Sha1 => HasherInner::Sha1(new_sha1cd()),
            ObjectFormat::Sha256 => {
                use sha2::Digest as _;
                HasherInner::Sha256(sha2::Sha256::new())
            }
        };
        Self { inner }
    }

    pub fn update(&mut self, data: &[u8]) {
        match &mut self.inner {
            HasherInner::Sha1(h) => {
                sha1collisiondetection::Digest::update(h.as_mut(), data);
            }
            HasherInner::Sha256(h) => {
                use sha2::Digest as _;
                h.update(data);
            }
        }
    }

    /// Finalize digest; **refuse** on detected SHA-1 collision attack (OBJ-004).
    pub fn finalize(self) -> Result<Digest, HashError> {
        match self.inner {
            HasherInner::Sha1(h) => {
                let out = h.finalize_cd().map_err(|_| HashError::Sha1Collision)?;
                Digest::from_bytes(ObjectFormat::Sha1, out.as_slice())
            }
            HasherInner::Sha256(h) => {
                use sha2::Digest as _;
                let out = h.finalize();
                Digest::from_bytes(ObjectFormat::Sha256, out.as_slice())
            }
        }
    }
}

/// Hash arbitrary bytes with the given object format (with OBJ-004 SHA-1 collision detection).
pub fn hash_bytes(format: ObjectFormat, data: &[u8]) -> Result<Digest, HashError> {
    let mut h = Hasher::new(format);
    h.update(data);
    h.finalize()
}

/// Fast container-trailer digest for non-object Git container files (`.git/index`,
/// `.pack`, `.idx`, `commit-graph`, `multi-pack-index`).
///
/// Uses runtime-dispatched hardware SHA-1 / SHA-256 (`ring::digest`, SHA-NI/AVX2/ARMv8)
/// without Marc Stevens collision-detection state tracking, matching stock Git's
/// separation between object-ID hashing and container integrity trailers.
///
/// **OBJ-004 invariant:** NEVER use this function to compute or verify Git object OIDs
/// (`blob`, `tree`, `commit`, `tag`). All Git object identity MUST use [`hash_object`]
/// or [`Hasher`] (`sha1collisiondetection`).
pub fn hash_container_bytes(format: ObjectFormat, data: &[u8]) -> Digest {
    match format {
        ObjectFormat::Sha1 => {
            let out = ring::digest::digest(&ring::digest::SHA1_FOR_LEGACY_USE_ONLY, data);
            Digest::from_bytes(ObjectFormat::Sha1, out.as_ref()).expect("20-byte sha1 digest")
        }
        ObjectFormat::Sha256 => {
            let out = ring::digest::digest(&ring::digest::SHA256, data);
            Digest::from_bytes(ObjectFormat::Sha256, out.as_ref()).expect("32-byte sha256 digest")
        }
    }
}

/// Hash uncompressed Git object bytes: `type SP size NUL` + `payload`.
///
/// `type_name` is the ASCII type token (`blob`, `tree`, `commit`, `tag`).
/// `payload` is the raw object body (not zlib-wrapped).
///
/// Refuses with [`HashError::Sha1Collision`] when a cryptanalytic SHA-1
/// collision attack is detected in the hashed stream (OBJ-004 Claimed detect).
pub fn hash_object(
    format: ObjectFormat,
    type_name: &str,
    payload: &[u8],
) -> Result<Digest, HashError> {
    let mut h = Hasher::new(format);
    h.update(type_name.as_bytes());
    h.update(b" ");
    let mut size_buf = [0u8; 20];
    let size = write_decimal(payload.len() as u64, &mut size_buf);
    h.update(size);
    h.update(&[0]);
    h.update(payload);
    h.finalize()
}

fn write_decimal(mut n: u64, buf: &mut [u8; 20]) -> &[u8] {
    if n == 0 {
        buf[19] = b'0';
        return &buf[19..];
    }
    let mut i = 20;
    while n > 0 {
        i -= 1;
        buf[i] = b'0' + (n % 10) as u8;
        n /= 10;
    }
    &buf[i..]
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum HashError {
    #[error("digest length mismatch: expected {expected}, got {actual}")]
    DigestLength { expected: usize, actual: usize },
    /// Cryptanalytic SHA-1 collision attack detected (OBJ-004 detect+refuse).
    /// Not a claim of absolute collision immunity.
    #[error(
        "SHA-1 collision attack detected (OBJ-004 detect+refuse; immunity Impossible — use sha256 repos for transition)"
    )]
    Sha1Collision,
}

#[cfg(test)]
mod tests {
    use super::*;

    const EMPTY_BLOB_SHA1: [u8; 20] = [
        0xe6, 0x9d, 0xe2, 0x9b, 0xb2, 0xd1, 0xd6, 0x43, 0x4b, 0x8b, 0x29, 0xae, 0x77, 0x5a, 0xd8,
        0xc2, 0xe4, 0x8c, 0x53, 0x91,
    ];

    #[test]
    fn empty_blob_sha1_matches_known_oid() {
        let d = hash_object(ObjectFormat::Sha1, "blob", b"").unwrap();
        assert_eq!(d.as_bytes(), &EMPTY_BLOB_SHA1);
    }

    #[test]
    fn hello_blob_sha1() {
        let d = hash_object(ObjectFormat::Sha1, "blob", b"hello").unwrap();
        assert_eq!(
            hex::encode_lower(d.as_bytes()),
            "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0"
        );
    }

    #[test]
    fn empty_blob_sha256_length_and_oid() {
        let d = hash_object(ObjectFormat::Sha256, "blob", b"").unwrap();
        assert_eq!(d.format(), ObjectFormat::Sha256);
        assert_eq!(d.as_bytes().len(), 32);
        assert_eq!(
            hex::encode_lower(d.as_bytes()),
            "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813"
        );
    }

    #[test]
    fn hasher_incremental_matches_one_shot() {
        let payload = b"incremental hashing must match one-shot";
        let one_shot = hash_bytes(ObjectFormat::Sha1, payload).unwrap();

        let mut h = Hasher::new(ObjectFormat::Sha1);
        h.update(&payload[..10]);
        h.update(&payload[10..20]);
        h.update(&payload[20..]);
        assert_eq!(h.finalize().unwrap(), one_shot);
    }

    #[test]
    fn hash_object_incremental_matches_one_shot() {
        let payload = b"split header and body updates";
        let whole = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();

        let mut h = Hasher::new(ObjectFormat::Sha1);
        h.update(b"blob");
        h.update(b" ");
        h.update(payload.len().to_string().as_bytes());
        h.update(&[0]);
        h.update(&payload[..payload.len() / 2]);
        h.update(&payload[payload.len() / 2..]);
        assert_eq!(h.finalize().unwrap(), whole);
    }

    #[test]
    fn digest_from_bytes_rejects_wrong_length() {
        assert_eq!(
            Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 19]),
            Err(HashError::DigestLength {
                expected: 20,
                actual: 19,
            })
        );
        assert_eq!(
            Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 31]),
            Err(HashError::DigestLength {
                expected: 32,
                actual: 31,
            })
        );
        assert!(Digest::from_bytes(ObjectFormat::Sha1, &EMPTY_BLOB_SHA1).is_ok());
    }

    #[test]
    fn nul_bytes_in_payload_are_hashed_as_payload() {
        let payload = b"before\x00after";
        let d = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
        let mut h = Hasher::new(ObjectFormat::Sha1);
        h.update(b"blob");
        h.update(b" ");
        h.update(payload.len().to_string().as_bytes());
        h.update(&[0]);
        h.update(payload);
        assert_eq!(d, h.finalize().unwrap());
        assert_ne!(
            d,
            hash_object(ObjectFormat::Sha1, "blob", b"before").unwrap()
        );
        assert_ne!(
            d,
            hash_object(ObjectFormat::Sha1, "blob", b"beforeafter").unwrap()
        );
    }

    #[test]
    fn large_payload_stress() {
        let payload: Vec<u8> = (0..64 * 1024).map(|i| (i % 251) as u8).collect();
        let whole = hash_object(ObjectFormat::Sha1, "blob", &payload).unwrap();

        let mut h = Hasher::new(ObjectFormat::Sha1);
        h.update(b"blob");
        h.update(b" ");
        h.update(payload.len().to_string().as_bytes());
        h.update(&[0]);
        for chunk in payload.chunks(4096) {
            h.update(chunk);
        }
        assert_eq!(h.finalize().unwrap(), whole);
    }

    #[test]
    fn object_format_digest_len() {
        assert_eq!(ObjectFormat::Sha1.digest_len(), 20);
        assert_eq!(ObjectFormat::Sha256.digest_len(), 32);
    }

    #[test]
    fn type_token_changes_oid() {
        let payload = b"same-bytes";
        let blob = hash_object(ObjectFormat::Sha1, "blob", payload).unwrap();
        let tree = hash_object(ObjectFormat::Sha1, "tree", payload).unwrap();
        let commit = hash_object(ObjectFormat::Sha1, "commit", payload).unwrap();
        let tag = hash_object(ObjectFormat::Sha1, "tag", payload).unwrap();
        assert_ne!(blob, tree);
        assert_ne!(blob, commit);
        assert_ne!(blob, tag);
        assert_ne!(tree, commit);
    }

    #[test]
    fn sha256_incremental_matches_one_shot() {
        let payload = b"sha256 split updates";
        let one = hash_bytes(ObjectFormat::Sha256, payload).unwrap();
        let mut h = Hasher::new(ObjectFormat::Sha256);
        h.update(&payload[..5]);
        h.update(&payload[5..]);
        assert_eq!(h.finalize().unwrap(), one);
        assert_eq!(one.as_bytes().len(), 32);
    }

    #[test]
    fn digest_wrong_format_length_pairs() {
        assert!(Digest::from_bytes(ObjectFormat::Sha1, &[0u8; 32]).is_err());
        assert!(Digest::from_bytes(ObjectFormat::Sha256, &[0u8; 20]).is_err());
    }

    #[test]
    fn sha1_collision_error_message_names_obj004() {
        let msg = HashError::Sha1Collision.to_string();
        assert!(msg.contains("OBJ-004"));
        assert!(msg.contains("detect+refuse"));
        assert!(msg.contains("Impossible"));
    }

    /// SHAttered PDF (file-level identical-prefix attack) must trip detect+refuse
    /// on the raw byte stream — proves `sha1collisiondetection` is wired.
    ///
    /// Honesty: wrapping the same PDF as `blob <size>\\0` + payload shifts
    /// SHA-1 block alignment, so this particular *file* collision may not flag
    /// as a *git-object* collision (and the two SHAttered PDFs also cease to
    /// share an OID once a common header is prefixed). Object-format attacks
    /// crafted against the header||payload stream are still refused when CD
    /// fires on that stream — same engine, Claimed detect+refuse.
    #[test]
    fn refuses_shattered_pdf_fixture_when_present() {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/shattered-1.pdf");
        if !path.is_file() {
            return;
        }
        let bytes = std::fs::read(&path).expect("read shattered fixture");
        let err = hash_bytes(ObjectFormat::Sha1, &bytes).expect_err("must detect collision");
        assert_eq!(err, HashError::Sha1Collision);
    }

    #[test]
    fn container_hash_matches_standard_sha1_and_sha256_across_boundaries() {
        for len in [0usize, 1, 3, 55, 56, 57, 63, 64, 65, 127, 128, 129, 65_536] {
            let data: Vec<u8> = (0..len).map(|i| ((i * 31 + 7) % 251) as u8).collect();
            assert_eq!(
                hash_container_bytes(ObjectFormat::Sha1, &data),
                hash_bytes(ObjectFormat::Sha1, &data).unwrap(),
                "sha1 mismatch at len={len}"
            );
            assert_eq!(
                hash_container_bytes(ObjectFormat::Sha256, &data),
                hash_bytes(ObjectFormat::Sha256, &data).unwrap(),
                "sha256 mismatch at len={len}"
            );
        }
    }
}

#[cfg(test)]
mod hex {
    pub fn encode_lower(bytes: &[u8]) -> String {
        let mut s = String::with_capacity(bytes.len() * 2);
        for b in bytes {
            s.push_str(&format!("{b:02x}"));
        }
        s
    }
}