Skip to main content

ostrya_core/
checksum.rs

1//! The 32-byte SHA-256 object identity and its representations.
2//!
3//! ostree names objects by a SHA-256 digest rendered several ways: 64-char
4//! lowercase hex (refs, loose paths, object strings), the raw 32-byte `ay`
5//! (inside commit and dirtree variants), and modified-base64 (static-delta
6//! directory names). The hex, standard base64, and modified base64 codecs are
7//! hand-rolled to the RFC 4648 alphabet; the digest itself is computed with
8//! the `sha2` crate.
9
10use ostrya_gvariant::{GvEncode, GvType};
11
12use crate::error::{Error, Result};
13
14/// A 32-byte SHA-256 object id.
15///
16/// Byte-wise ordering matches lexicographic ordering of the lowercase hex
17/// form, so sorting `Checksum` values reproduces the ASCII-checksum sort order
18/// the on-disk format uses (for example `ostree.sizes` entry order).
19#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub struct Checksum([u8; 32]);
21
22const STD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23const MOD_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_";
24
25impl Checksum {
26    /// Wrap raw digest bytes.
27    pub fn from_bytes(b: [u8; 32]) -> Checksum {
28        Checksum(b)
29    }
30
31    /// The SHA-256 digest of `data`. This is the object identity of a
32    /// metadata object, whose hashed bytes are its serialized GVariant form.
33    pub fn sha256(data: &[u8]) -> Checksum {
34        use sha2::{Digest, Sha256};
35        Checksum(Sha256::digest(data).into())
36    }
37
38    /// The raw digest bytes.
39    pub fn as_bytes(&self) -> &[u8; 32] {
40        &self.0
41    }
42
43    /// Parse 64 hex chars in the lowercase rendering [`to_hex`](Checksum::to_hex)
44    /// emits, refusing an uppercase character.
45    ///
46    /// This is the rule a revision is read by: a 64-character name is a
47    /// checksum in lowercase hex alone, and an uppercase or mixed-case name of
48    /// that length is a ref name (`docs/format-reference.md`, "Revision
49    /// syntax"). The lenient [`from_hex`](Checksum::from_hex) stays where a
50    /// checksum arrives as stored bytes rather than as a name.
51    pub fn from_hex_lower(s: &str) -> Result<Checksum> {
52        if s.bytes().any(|b| b.is_ascii_uppercase()) {
53            return Err(Error::InvalidChecksum("hex checksum is not lowercase"));
54        }
55        Checksum::from_hex(s)
56    }
57
58    /// Parse 64 hex chars. Accepts either case; emits lowercase.
59    pub fn from_hex(s: &str) -> Result<Checksum> {
60        let bytes = s.as_bytes();
61        if bytes.len() != 64 {
62            return Err(Error::InvalidChecksum("hex checksum is not 64 characters"));
63        }
64        let mut out = [0u8; 32];
65        for (i, pair) in bytes.chunks_exact(2).enumerate() {
66            let hi = hex_val(pair[0])?;
67            let lo = hex_val(pair[1])?;
68            out[i] = (hi << 4) | lo;
69        }
70        Ok(Checksum(out))
71    }
72
73    /// Render as 64 lowercase hex chars.
74    pub fn to_hex(&self) -> String {
75        const HEX: &[u8; 16] = b"0123456789abcdef";
76        let mut s = String::with_capacity(64);
77        for &b in &self.0 {
78            s.push(HEX[(b >> 4) as usize] as char);
79            s.push(HEX[(b & 0x0f) as usize] as char);
80        }
81        s
82    }
83
84    /// Interpret a GVariant `ay` payload as a checksum; the array must be
85    /// exactly 32 bytes.
86    pub fn from_ay(b: &[u8]) -> Result<Checksum> {
87        let arr: [u8; 32] = b
88            .try_into()
89            .map_err(|_| Error::InvalidChecksum("ay checksum is not 32 bytes"))?;
90        Ok(Checksum(arr))
91    }
92
93    /// Render as standard, padded base64 (44 chars).
94    pub fn to_base64(&self) -> String {
95        base64_encode(&self.0, STD_ALPHABET, true)
96    }
97
98    /// Parse standard, padded base64 (exactly 44 chars ending in `=`).
99    pub fn from_base64(s: &str) -> Result<Checksum> {
100        Ok(Checksum(base64_decode_checksum(s, STD_ALPHABET, true)?))
101    }
102
103    /// Render as modified base64 (standard base64 with `/` replaced by `_` and
104    /// trailing `=` dropped, 43 chars), used for static-delta directory names.
105    pub fn to_base64_modified(&self) -> String {
106        base64_encode(&self.0, MOD_ALPHABET, false)
107    }
108
109    /// Parse modified base64 (exactly 43 unpadded chars).
110    pub fn from_base64_modified(s: &str) -> Result<Checksum> {
111        Ok(Checksum(base64_decode_checksum(s, MOD_ALPHABET, false)?))
112    }
113}
114
115fn hex_val(c: u8) -> Result<u8> {
116    match c {
117        b'0'..=b'9' => Ok(c - b'0'),
118        b'a'..=b'f' => Ok(c - b'a' + 10),
119        b'A'..=b'F' => Ok(c - b'A' + 10),
120        _ => Err(Error::InvalidChecksum(
121            "hex checksum has a non-hex character",
122        )),
123    }
124}
125
126fn base64_encode(input: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
127    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
128    for chunk in input.chunks(3) {
129        let b0 = chunk[0];
130        out.push(alphabet[(b0 >> 2) as usize] as char);
131        match chunk.len() {
132            1 => {
133                out.push(alphabet[((b0 & 0x03) << 4) as usize] as char);
134                if pad {
135                    out.push_str("==");
136                }
137            }
138            2 => {
139                let b1 = chunk[1];
140                out.push(alphabet[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
141                out.push(alphabet[((b1 & 0x0f) << 2) as usize] as char);
142                if pad {
143                    out.push('=');
144                }
145            }
146            _ => {
147                let (b1, b2) = (chunk[1], chunk[2]);
148                out.push(alphabet[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
149                out.push(alphabet[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
150                out.push(alphabet[(b2 & 0x3f) as usize] as char);
151            }
152        }
153    }
154    out
155}
156
157/// Decode exactly one 32-byte checksum, reading sextets against `alphabet`.
158///
159/// A 32-byte digest is 43 significant base64 characters: ten 4-char groups
160/// (30 bytes) followed by a 3-char group (2 bytes). The standard form appends
161/// one `=` pad for a total of 44 characters; the modified form is the bare 43.
162/// Decoding is strict: length is exact, every character must be in `alphabet`
163/// (so the standard `/` and modified `_` do not alias), and the two unused low
164/// bits of the final significant sextet must be zero, so each distinct
165/// checksum has exactly one accepted spelling.
166fn base64_decode_checksum(s: &str, alphabet: &[u8; 64], padded: bool) -> Result<[u8; 32]> {
167    let bytes = s.as_bytes();
168    let expected = if padded { 44 } else { 43 };
169    if bytes.len() != expected {
170        return Err(Error::InvalidChecksum(
171            "base64 checksum has the wrong length",
172        ));
173    }
174    if padded && bytes[43] != b'=' {
175        return Err(Error::InvalidChecksum("base64 checksum is missing its pad"));
176    }
177    let data = &bytes[..43];
178    let mut out = [0u8; 32];
179    for (group, chunk) in data[..40].chunks_exact(4).enumerate() {
180        let s0 = base64_val(chunk[0], alphabet)?;
181        let s1 = base64_val(chunk[1], alphabet)?;
182        let s2 = base64_val(chunk[2], alphabet)?;
183        let s3 = base64_val(chunk[3], alphabet)?;
184        out[group * 3] = (s0 << 2) | (s1 >> 4);
185        out[group * 3 + 1] = (s1 << 4) | (s2 >> 2);
186        out[group * 3 + 2] = (s2 << 6) | s3;
187    }
188    let s0 = base64_val(data[40], alphabet)?;
189    let s1 = base64_val(data[41], alphabet)?;
190    let s2 = base64_val(data[42], alphabet)?;
191    if s2 & 0x03 != 0 {
192        return Err(Error::InvalidChecksum(
193            "base64 checksum has nonzero trailing bits",
194        ));
195    }
196    out[30] = (s0 << 2) | (s1 >> 4);
197    out[31] = (s1 << 4) | (s2 >> 2);
198    Ok(out)
199}
200
201fn base64_val(c: u8, alphabet: &[u8; 64]) -> Result<u8> {
202    match c {
203        b'A'..=b'Z' => Ok(c - b'A'),
204        b'a'..=b'z' => Ok(c - b'a' + 26),
205        b'0'..=b'9' => Ok(c - b'0' + 52),
206        b'+' => Ok(62),
207        // The only alphabet-specific glyph is index 63: `/` (standard) or `_`
208        // (modified). Accept whichever this call was given, rejecting the other.
209        _ if c == alphabet[63] => Ok(63),
210        _ => Err(Error::InvalidChecksum("base64 has an invalid character")),
211    }
212}
213
214impl std::fmt::Display for Checksum {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        f.write_str(&self.to_hex())
217    }
218}
219
220impl std::fmt::Debug for Checksum {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        write!(f, "Checksum({})", self.to_hex())
223    }
224}
225
226impl std::str::FromStr for Checksum {
227    type Err = Error;
228    fn from_str(s: &str) -> Result<Checksum> {
229        Checksum::from_hex(s)
230    }
231}
232
233impl GvType for Checksum {
234    const SIGNATURE: &'static str = "ay";
235    const ALIGNMENT: usize = 1;
236    const FIXED_SIZE: Option<usize> = None;
237}
238
239/// A checksum encodes as its raw 32-byte `ay`. Decoding is done through
240/// [`Checksum::from_ay`], which reports [`Error::InvalidChecksum`] on a wrong
241/// width, so no `GvDecode` impl is provided.
242impl GvEncode for Checksum {
243    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
244        out.extend_from_slice(&self.0);
245        Ok(())
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    // The commit checksum the fixture generator recorded in
254    // tests/fixtures/generated/MANIFEST.
255    const FIXTURE_COMMIT: &str = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
256
257    #[test]
258    fn hex_round_trips_and_is_lowercase() {
259        let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
260        assert_eq!(c.to_hex(), FIXTURE_COMMIT);
261        // Uppercase input parses to the same value.
262        let upper = Checksum::from_hex(&FIXTURE_COMMIT.to_uppercase()).unwrap();
263        assert_eq!(upper, c);
264    }
265
266    #[test]
267    fn hex_rejects_bad_length_and_characters() {
268        assert!(Checksum::from_hex("abcd").is_err());
269        assert!(Checksum::from_hex(&"g".repeat(64)).is_err());
270    }
271
272    #[test]
273    fn lowercase_hex_refuses_an_uppercase_character() {
274        let c = Checksum::from_hex_lower(FIXTURE_COMMIT).unwrap();
275        assert_eq!(c.to_hex(), FIXTURE_COMMIT);
276        assert!(Checksum::from_hex_lower(&FIXTURE_COMMIT.to_uppercase()).is_err());
277        // One uppercase character is enough, and the length rule still holds.
278        let mixed = format!("B{}", &FIXTURE_COMMIT[1..]);
279        assert!(Checksum::from_hex_lower(&mixed).is_err());
280        assert!(Checksum::from_hex_lower("abcd").is_err());
281    }
282
283    #[test]
284    fn ay_conversion_validates_length() {
285        let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
286        assert_eq!(Checksum::from_ay(c.as_bytes()).unwrap(), c);
287        assert!(Checksum::from_ay(&[0u8; 31]).is_err());
288        assert!(Checksum::from_ay(&[0u8; 33]).is_err());
289    }
290
291    #[test]
292    fn base64_reference_vectors() {
293        // 32 zero bytes: 43 'A' sextets, one '=' pad under standard base64.
294        let zero = Checksum::from_bytes([0u8; 32]);
295        assert_eq!(zero.to_base64_modified(), "A".repeat(43));
296        assert_eq!(zero.to_base64(), format!("{}=", "A".repeat(43)));
297
298        // 32 0xff bytes exercise the high sextets and the '_'-for-'/' swap.
299        // Ten full 0xffffff groups give index-63 sextets ('_' modified, '/'
300        // standard); the trailing two bytes give '_' '_' '8'.
301        let ones = Checksum::from_bytes([0xffu8; 32]);
302        assert_eq!(ones.to_base64_modified(), format!("{}8", "_".repeat(42)));
303        assert_eq!(ones.to_base64(), format!("{}8=", "/".repeat(42)));
304        // The two alphabets differ only in the index-63 glyph.
305        assert_eq!(
306            ones.to_base64_modified(),
307            ones.to_base64().trim_end_matches('=').replace('/', "_")
308        );
309    }
310
311    #[test]
312    fn base64_round_trips_both_alphabets() {
313        let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
314        assert_eq!(Checksum::from_base64(&c.to_base64()).unwrap(), c);
315        assert_eq!(
316            Checksum::from_base64_modified(&c.to_base64_modified()).unwrap(),
317            c
318        );
319        assert_eq!(c.to_base64_modified().len(), 43);
320        assert_eq!(c.to_base64().len(), 44);
321    }
322
323    // A spread of checksums for the strict-decoding round-trip checks.
324    fn sample_checksums() -> Vec<Checksum> {
325        let mut v = vec![
326            Checksum::from_bytes([0u8; 32]),
327            Checksum::from_bytes([0xffu8; 32]),
328            Checksum::from_hex(FIXTURE_COMMIT).unwrap(),
329        ];
330        // A few deterministic byte patterns exercise varied final sextets.
331        for seed in [1u8, 7, 31, 63, 128, 200, 254] {
332            let mut b = [0u8; 32];
333            for (i, x) in b.iter_mut().enumerate() {
334                *x = seed.wrapping_mul(i as u8).wrapping_add(seed);
335            }
336            v.push(Checksum::from_bytes(b));
337        }
338        v
339    }
340
341    #[test]
342    fn base64_parse_then_render_is_identity_for_accepted_strings() {
343        for c in sample_checksums() {
344            let std = c.to_base64();
345            assert_eq!(Checksum::from_base64(&std).unwrap().to_base64(), std);
346            let modified = c.to_base64_modified();
347            assert_eq!(
348                Checksum::from_base64_modified(&modified)
349                    .unwrap()
350                    .to_base64_modified(),
351                modified
352            );
353        }
354    }
355
356    #[test]
357    fn base64_rejects_cross_alphabet_glyphs() {
358        // The modified rendering of all-ones carries '_', invalid in standard.
359        let modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
360        assert!(modified.contains('_'));
361        assert!(Checksum::from_base64(&modified).is_err());
362        // The standard rendering carries '/', invalid in the modified alphabet;
363        // trim its pad first so only the alphabet mismatch is under test.
364        let std = Checksum::from_bytes([0xffu8; 32]).to_base64();
365        assert!(std.contains('/'));
366        assert!(Checksum::from_base64_modified(std.trim_end_matches('=')).is_err());
367    }
368
369    #[test]
370    fn base64_rejects_nonzero_trailing_bits() {
371        // The final significant sextet of a 32-byte checksum has two unused low
372        // bits; a glyph that sets them ('9' = sextet 61) must be rejected.
373        let mut modified = Checksum::from_bytes([0xffu8; 32]).to_base64_modified();
374        modified.pop();
375        modified.push('9');
376        assert!(Checksum::from_base64_modified(&modified).is_err());
377
378        let mut std = Checksum::from_bytes([0u8; 32]).to_base64();
379        // Replace the last data character (index 42), before the '=' pad.
380        std.replace_range(42..43, "9");
381        assert!(Checksum::from_base64(&std).is_err());
382    }
383
384    #[test]
385    fn base64_rejects_wrong_length_and_stray_padding() {
386        let c = Checksum::from_hex(FIXTURE_COMMIT).unwrap();
387        // Standard requires the single trailing pad; the unpadded 43-char form
388        // and a double-padded 45-char form are both rejected.
389        assert!(Checksum::from_base64(c.to_base64().trim_end_matches('=')).is_err());
390        assert!(Checksum::from_base64(&format!("{}=", c.to_base64())).is_err());
391        // Modified takes exactly 43 unpadded chars; a stray pad or a padded
392        // standard-length string is rejected.
393        assert!(Checksum::from_base64_modified(&format!("{}=", c.to_base64_modified())).is_err());
394        assert!(Checksum::from_base64_modified(&c.to_base64()).is_err());
395    }
396
397    #[test]
398    fn sha256_matches_the_empty_input_vector() {
399        // The well-known SHA-256 digest of the empty input.
400        assert_eq!(
401            Checksum::sha256(b"").to_hex(),
402            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
403        );
404    }
405
406    #[test]
407    fn ordering_matches_hex_ordering() {
408        let a = Checksum::from_hex(&"00".repeat(32)).unwrap();
409        let b = Checksum::from_hex(&"ff".repeat(32)).unwrap();
410        assert!(a < b);
411        assert!(a.to_hex() < b.to_hex());
412    }
413}