Skip to main content

prov_fixity/
lib.rs

1//! Fixity — content checksums that let prov detect *bit-rot*, not just
2//! broken links.
3//!
4//! Link validation in the higher-level `prov` crate answers "does the graph
5//! still hold together?"; fixity answers the other archival question: "are the
6//! bytes still the bytes?" A stored hash, recomputed on read and compared, catches the
7//! silent corruption an archive most fears — a flipped bit in a decade-old
8//! attachment that no link check would ever notice.
9//!
10//! ## Why SHA-256, and why hand-rolled
11//!
12//! The algorithm is **SHA-256**, and a hash is recorded as `sha256:<hex>` — the
13//! prefix names the algorithm, so the field is self-describing and a future one
14//! can be added without ambiguity. SHA-256 is the archival lingua franca: a
15//! prov workspace's fixity is verifiable by *anyone*, with standard tools
16//! (`sha256sum`, BagIt validators), not only by prov — the same
17//! tool-agnostic, self-describing ethos the whole crate is built on.
18//!
19//! It is implemented here rather than pulled from a crate for the same reason
20//! [`prov_graph::exec::block_on`] and the journal's FNV checksum are: prov keeps
21//! its dependency surface tiny and WASM-clean (no build-toolchain cost, nothing
22//! to audit). SHA-256 is a fully specified, deterministic function with published
23//! test vectors, so correctness is *checked*, not trusted — the tests below pin
24//! it to the NIST vectors and to what `sha256sum` produces.
25//!
26//! ## Not hashing what has not changed
27//!
28//! Hashing is cheap to describe and expensive to run, and a capture runs it over
29//! every file in the workspace. [`FixityCache`] is the device-local memory that
30//! lets a capture skip the files whose stat says they are untouched — and, just
31//! as importantly, the argument for which passes may consult it and which may
32//! never. See its module documentation; the short version is that the bit-rot
33//! check must not, because bit-rot is exactly the change a stat cannot see.
34
35mod cache;
36
37pub use cache::FixityCache;
38
39/// How far content checksums cover a workspace.
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
41pub enum Fixity {
42    /// No content checksums are recorded or verified.
43    Off,
44    /// Attachment payloads only.
45    #[default]
46    Payloads,
47    /// Attachment payloads and document bodies.
48    Full,
49}
50
51impl Fixity {
52    /// Whether attachment payloads are checksummed.
53    pub fn covers_payloads(self) -> bool {
54        matches!(self, Self::Payloads | Self::Full)
55    }
56
57    /// Whether document bodies are checksummed.
58    pub fn covers_bodies(self) -> bool {
59        matches!(self, Self::Full)
60    }
61
62    /// Parse the configuration spelling; unknown values return `None`.
63    pub fn from_config_str(value: &str) -> Option<Self> {
64        match value {
65            "off" => Some(Self::Off),
66            "attachments" => Some(Self::Payloads),
67            "all" => Some(Self::Full),
68            _ => None,
69        }
70    }
71
72    /// Return the configuration spelling.
73    pub fn as_config_str(self) -> &'static str {
74        match self {
75            Self::Off => "off",
76            Self::Payloads => "attachments",
77            Self::Full => "all",
78        }
79    }
80}
81
82/// The SHA-256 round constants — the first 32 bits of the fractional parts of
83/// the cube roots of the first 64 primes (FIPS 180-4 §4.2.2).
84#[rustfmt::skip]
85const K: [u32; 64] = [
86    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
87    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
88    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
89    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
90    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
91    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
92    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
93    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
94];
95
96/// The initial hash state — the first 32 bits of the fractional parts of the
97/// square roots of the first 8 primes (FIPS 180-4 §5.3.3).
98const H0: [u32; 8] = [
99    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
100];
101
102/// The raw SHA-256 digest of `bytes`, as 32 bytes.
103fn sha256(bytes: &[u8]) -> [u8; 32] {
104    let mut h = H0;
105
106    // Pad: the message, a 0x80 byte, zeros, then the bit-length as a 64-bit
107    // big-endian integer — to a multiple of 64 bytes (FIPS 180-4 §5.1.1).
108    let bit_len = (bytes.len() as u64).wrapping_mul(8);
109    let mut msg = bytes.to_vec();
110    msg.push(0x80);
111    while msg.len() % 64 != 56 {
112        msg.push(0);
113    }
114    msg.extend_from_slice(&bit_len.to_be_bytes());
115
116    // Compress each 512-bit block.
117    for block in msg.as_chunks::<64>().0 {
118        let mut w = [0u32; 64];
119        for (i, word) in block.as_chunks::<4>().0.iter().enumerate() {
120            w[i] = u32::from_be_bytes(*word);
121        }
122        for i in 16..64 {
123            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
124            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
125            w[i] = w[i - 16]
126                .wrapping_add(s0)
127                .wrapping_add(w[i - 7])
128                .wrapping_add(s1);
129        }
130
131        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
132        for i in 0..64 {
133            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
134            let ch = (e & f) ^ ((!e) & g);
135            let t1 = hh
136                .wrapping_add(s1)
137                .wrapping_add(ch)
138                .wrapping_add(K[i])
139                .wrapping_add(w[i]);
140            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
141            let maj = (a & b) ^ (a & c) ^ (b & c);
142            let t2 = s0.wrapping_add(maj);
143            hh = g;
144            g = f;
145            f = e;
146            e = d.wrapping_add(t1);
147            d = c;
148            c = b;
149            b = a;
150            a = t1.wrapping_add(t2);
151        }
152        for (slot, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
153            *slot = slot.wrapping_add(v);
154        }
155    }
156
157    let mut out = [0u8; 32];
158    for (chunk, word) in out.as_chunks_mut::<4>().0.iter_mut().zip(h) {
159        *chunk = word.to_be_bytes();
160    }
161    out
162}
163
164/// The fixity digest of `bytes`, spelled `sha256:<lowercase-hex>` — the form
165/// recorded in a sidecar, a frontmatter field, or a recycle-bin tombstone, and
166/// the form [`verify`] checks against. The `sha256:` prefix names the algorithm,
167/// so the record is self-describing and a future digest can be distinguished.
168pub fn digest(bytes: &[u8]) -> String {
169    let mut s = String::with_capacity(7 + 64);
170    s.push_str("sha256:");
171    for byte in sha256(bytes) {
172        s.push(char::from_digit((byte >> 4) as u32, 16).unwrap());
173        s.push(char::from_digit((byte & 0xf) as u32, 16).unwrap());
174    }
175    s
176}
177
178/// Whether `bytes` still hash to the `recorded` digest. `true` when the recorded
179/// value is empty — nothing was ever recorded, so there is nothing to contradict
180/// (a document predating fixity is not "corrupt"). A recorded value prov
181/// cannot recognize (a future algorithm) is treated as *unverifiable*, which is
182/// also `true`: fixity never raises a false alarm over a hash it does not
183/// understand, it simply cannot vouch for it.
184pub fn verify(bytes: &[u8], recorded: &str) -> bool {
185    match recorded.strip_prefix("sha256:") {
186        Some(_) => digest(bytes) == recorded,
187        None if recorded.is_empty() => true,
188        None => true,
189    }
190}
191
192/// Whether `recorded` is a fixity digest prov can actually check — the
193/// predicate that separates "verified" from "unverifiable" so a caller can tell
194/// a matching hash from one it had to take on faith.
195pub fn is_recognized(recorded: &str) -> bool {
196    recorded.starts_with("sha256:")
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    // The NIST / FIPS 180-4 known-answer vectors. If these pass, the
204    // implementation is SHA-256 — correctness is checked, not trusted.
205    #[test]
206    fn matches_the_published_sha256_vectors() {
207        assert_eq!(
208            digest(b""),
209            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
210        );
211        assert_eq!(
212            digest(b"abc"),
213            "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
214        );
215        assert_eq!(
216            digest(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
217            "sha256:248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
218        );
219    }
220
221    #[test]
222    fn crosses_a_block_boundary_correctly() {
223        // 1,000,000 'a's — the classic long vector that exercises multi-block
224        // compression and the length padding.
225        let million_a = vec![b'a'; 1_000_000];
226        assert_eq!(
227            digest(&million_a),
228            "sha256:cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
229        );
230    }
231
232    #[test]
233    fn verify_accepts_the_matching_digest_and_rejects_a_changed_byte() {
234        let recorded = digest(b"the original bytes");
235        assert!(verify(b"the original bytes", &recorded));
236        assert!(!verify(b"the corrupted bytes", &recorded));
237    }
238
239    #[test]
240    fn verify_never_cries_wolf_over_an_unrecorded_or_unknown_digest() {
241        // Nothing recorded → nothing to contradict.
242        assert!(verify(b"anything", ""));
243        // A digest from an algorithm prov does not know → unverifiable, not
244        // corrupt. `is_recognized` is how a caller tells the two apart.
245        assert!(verify(b"anything", "blake3:deadbeef"));
246        assert!(!is_recognized("blake3:deadbeef"));
247        assert!(is_recognized("sha256:e3b0c442"));
248    }
249}