Skip to main content

nix_compat/nixhash/
mod.rs

1use crate::nixbase32;
2use bstr::ByteSlice;
3use data_encoding::{BASE64, BASE64_NOPAD, HEXLOWER};
4use std::cmp::Ordering;
5use std::fmt::Display;
6use thiserror;
7
8mod algos;
9mod ca_hash;
10mod digester;
11#[cfg(feature = "async")]
12mod io;
13#[cfg(feature = "serde")]
14pub mod serde;
15mod sha256;
16
17pub use algos::HashAlgo;
18pub use ca_hash::CAHash;
19pub use ca_hash::HashMode as CAHashMode;
20pub use digester::NixHashDigester;
21#[cfg(feature = "async")]
22pub use io::{copy_buf_hashed, copy_buf_sha256, copy_hashed, copy_sha256};
23pub use sha256::{Sha256, Sha256Digester};
24
25/// NixHash represents hashes known by Nix (md5/sha1/sha256/sha512).
26///
27/// Internally, these are represented as an enum of 4 kinds (the latter being
28/// boxed for size reasons, as we rarely use sha512, having a pointer there
29/// is fine).
30///
31/// There's [Self::algo] and [Self::digest_as_bytes] accessors,
32/// as well as a [Self::from_algo_and_digest] constructor.
33///
34/// A few methods to parse (`from_$format_$encoding`) and emit
35/// (`to_$format_$encoding`) various formats and encodings Nix uses.
36///
37/// # Formats
38/// The following formats exist:
39///
40/// ## Nix Format
41/// Lowercase algo, followed by a colon, then the digest.
42///
43/// ## SRI Format
44/// Uses the lowercase algo, followed by a `-`, then the digest (base64-encoded).
45/// This is also used in the Display implementation.
46///
47/// Contrary to the SRI spec, Nix doesn't have an understanding of passing
48/// multiple hashes (with different algos) in SRI hashes.
49/// It instead simply cuts everything off after the expected length for the
50/// specified algo, and tries to parse the rest in permissive base64 (allowing
51/// missing padding).
52///
53/// ## Digest only
54/// It's possible to not specify the algo at all. In that case, the expected
55/// NixHash algo MUST be provided externally.
56///
57/// # Encodings
58/// For "Nix" and "Digest only" formats, the following encodings are supported:
59///
60/// - lowerhex,
61/// - nixbase32,
62/// - base64 (StdEncoding)
63#[derive(Clone, Debug, Eq, PartialEq)]
64pub enum NixHash {
65    Md5([u8; 16]),
66    Sha1([u8; 20]),
67    Sha256([u8; 32]),
68    Sha512(Box<[u8; 64]>),
69}
70
71/// Same order as sorting the corresponding nixbase32 strings.
72///
73/// This order is used in the ATerm serialization of a derivation
74/// and thus affects the calculated output hash.
75impl Ord for NixHash {
76    fn cmp(&self, other: &NixHash) -> Ordering {
77        self.digest_as_bytes().cmp(other.digest_as_bytes())
78    }
79}
80
81// See Ord for reason to implement this manually.
82impl PartialOrd for NixHash {
83    fn partial_cmp(&self, other: &NixHash) -> Option<Ordering> {
84        Some(self.cmp(other))
85    }
86}
87
88// This provides a Display impl, which happens to be SRI right now.
89// If you explicitly care about the format, use [NixHash::to_sri_string]
90// or [NixHash::write_sri_str].
91impl Display for NixHash {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
93        self.write_sri_str(f)
94    }
95}
96
97impl NixHash {
98    /// returns the algo as [HashAlgo].
99    pub const fn algo(&self) -> HashAlgo {
100        match self {
101            NixHash::Md5(_) => HashAlgo::Md5,
102            NixHash::Sha1(_) => HashAlgo::Sha1,
103            NixHash::Sha256(_) => HashAlgo::Sha256,
104            NixHash::Sha512(_) => HashAlgo::Sha512,
105        }
106    }
107
108    /// returns the digest as variable-length byte slice.
109    pub fn digest_as_bytes(&self) -> &[u8] {
110        match self {
111            NixHash::Md5(digest) => digest,
112            NixHash::Sha1(digest) => digest,
113            NixHash::Sha256(digest) => digest,
114            NixHash::Sha512(digest) => digest.as_ref(),
115        }
116    }
117
118    /// Constructs a new [NixHash] by specifying [HashAlgo] and digest.
119    /// It can fail if the passed digest length doesn't match what's expected for
120    /// the passed algo.
121    pub fn from_algo_and_digest(algo: HashAlgo, digest: &[u8]) -> Result<NixHash, Error> {
122        if digest.len() != algo.digest_length() {
123            return Err(Error::InvalidDigestLength(algo));
124        }
125
126        Ok(match algo {
127            HashAlgo::Md5 => NixHash::Md5(digest.try_into().unwrap()),
128            HashAlgo::Sha1 => NixHash::Sha1(digest.try_into().unwrap()),
129            HashAlgo::Sha256 => NixHash::Sha256(digest.try_into().unwrap()),
130            HashAlgo::Sha512 => NixHash::Sha512(Box::new(digest.try_into().unwrap())),
131        })
132    }
133
134    /// Constructs a new [NixHash] from the Nix default hash format,
135    /// the inverse of [Self::to_nix_nixbase32].
136    pub fn from_nix_nixbase32(s: &str) -> Option<Self> {
137        let (tag, digest) = s.split_once(':')?;
138
139        (match tag {
140            "md5" => nixbase32::decode_fixed(digest).map(NixHash::Md5),
141            "sha1" => nixbase32::decode_fixed(digest).map(NixHash::Sha1),
142            "sha256" => nixbase32::decode_fixed(digest).map(NixHash::Sha256),
143            "sha512" => nixbase32::decode_fixed(digest)
144                .map(Box::new)
145                .map(NixHash::Sha512),
146            _ => return None,
147        })
148        .ok()
149    }
150
151    /// Formats a [NixHash] in the Nix nixbase32 format.
152    pub fn to_nix_nixbase32(&self) -> String {
153        format!(
154            "{}:{}",
155            self.algo(),
156            nixbase32::encode(self.digest_as_bytes())
157        )
158    }
159
160    /// Parses a Nix SRI string to a NixHash.
161    /// (See caveats in [Self] on the deviations from the SRI spec)
162    pub fn from_sri(s: &str) -> Result<NixHash, Error> {
163        // split at the first occurrence of "-"
164        let (algo_str, digest_str) = s.split_once('-').ok_or(Error::InvalidSRI)?;
165
166        // try to map the part before that `-` to a supported hash algo:
167        let algo: HashAlgo = algo_str.try_into()?;
168
169        // For the digest string, Nix ignores everything after the expected BASE64
170        // (with padding) length, to account for the fact SRI allows specifying more
171        // than one checksum, so shorten it.
172        let digest_str = {
173            let encoded_max_len = BASE64.encode_len(algo.digest_length());
174            if digest_str.len() > encoded_max_len {
175                &digest_str.as_bytes()[..encoded_max_len]
176            } else {
177                digest_str.as_bytes()
178            }
179        };
180
181        // if the digest string is too small to fit even the BASE64_NOPAD version, bail out.
182        if digest_str.len() < BASE64_NOPAD.encode_len(algo.digest_length()) {
183            return Err(Error::InvalidDigestLength(algo));
184        }
185
186        // trim potential padding, and use a version that does not do trailing bit
187        // checking.
188        let mut spec = BASE64_NOPAD.specification();
189        spec.check_trailing_bits = false;
190        let encoding = spec
191            .encoding()
192            .expect("Snix bug: failed to get the special base64 encoder for Nix SRI hashes");
193
194        let digest = encoding
195            .decode(digest_str.trim_end_with(|c| c == '='))
196            .map_err(Error::InvalidBase64Encoding)?;
197
198        Self::from_algo_and_digest(algo, &digest)
199    }
200
201    /// Writes a [NixHash] in SRI format to a [std::fmt::Write].
202    pub fn write_sri_str(&self, w: &mut impl std::fmt::Write) -> Result<(), std::fmt::Error> {
203        write!(
204            w,
205            "{}-{}",
206            self.algo(),
207            BASE64.encode(self.digest_as_bytes())
208        )
209    }
210
211    /// Formats a [NixHash] to an SRI string.
212    pub fn to_sri_string(&self) -> String {
213        let mut s = String::new();
214        self.write_sri_str(&mut s).unwrap();
215
216        s
217    }
218
219    /// Formats a [NixHash] in the Nix lowerhex format.
220    pub fn as_nix_lowerhex_string_fmt(&self) -> impl std::fmt::Display + '_ {
221        std::fmt::from_fn(|f| {
222            write!(
223                f,
224                "{}:{}",
225                self.algo(),
226                HEXLOWER.encode_display(self.digest_as_bytes())
227            )
228        })
229    }
230
231    /// This parses all known output formats for NixHash.
232    /// See [NixHash] for a list.
233    /// An optional algo needs to be provided, which is mandatory to be specified if
234    /// the "digest only" format is used.
235    /// In other cases, consistency of an optionally externally configured algo
236    /// with the one parsed is ensured.
237    pub fn from_str(s: &str, want_algo: Option<HashAlgo>) -> Result<NixHash, Error> {
238        // Check for SRI hashes.
239        if let Ok(parsed_nixhash) = Self::from_sri(s) {
240            // ensure the algo matches with what has been passed externally, if so.
241            if let Some(algo) = want_algo
242                && algo != parsed_nixhash.algo()
243            {
244                return Err(Error::ConflictingHashAlgos(algo, parsed_nixhash.algo()));
245            }
246            return Ok(parsed_nixhash);
247        }
248
249        // Check for $algo:$digest style NixHash.
250        if let Some(parsed_nixhash) = {
251            if let Some(rest) = s.strip_prefix("sha1:") {
252                Some(decode_digest(rest.as_bytes(), HashAlgo::Sha1)?)
253            } else if let Some(rest) = s.strip_prefix("sha256:") {
254                Some(decode_digest(rest.as_bytes(), HashAlgo::Sha256)?)
255            } else if let Some(rest) = s.strip_prefix("sha512:") {
256                Some(decode_digest(rest.as_bytes(), HashAlgo::Sha512)?)
257            } else if let Some(rest) = s.strip_prefix("md5:") {
258                Some(decode_digest(rest.as_bytes(), HashAlgo::Md5)?)
259            } else {
260                None
261            }
262        } {
263            // ensure the algo matches with what has been passed externally, if so.
264            if let Some(algo) = want_algo
265                && algo != parsed_nixhash.algo()
266            {
267                return Err(Error::ConflictingHashAlgos(algo, parsed_nixhash.algo()));
268            }
269
270            return Ok(parsed_nixhash);
271        }
272
273        // We're left with the bare digest case, so there MUST be an externally-passed algo.
274        let algo = want_algo.ok_or_else(|| Error::MissingInlineHashAlgo(s.to_string()))?;
275        decode_digest(s.as_bytes(), algo)
276    }
277}
278
279/// Errors related to NixHash construction.
280#[derive(Debug, Eq, PartialEq, thiserror::Error)]
281pub enum Error {
282    #[error("invalid hash algo: '{0}'")]
283    InvalidAlgo(String),
284    #[error("invalid SRI string")]
285    InvalidSRI,
286    #[error("invalid digest length for algo {0}")]
287    InvalidDigestLength(HashAlgo),
288    #[error("invalid base16 encoding: {0}")]
289    InvalidBase16Encoding(data_encoding::DecodeError),
290    #[error("invalid base32 encoding: {0}")]
291    InvalidBase32Encoding(data_encoding::DecodeError),
292    #[error("invalid base64 encoding: {0}")]
293    InvalidBase64Encoding(data_encoding::DecodeError),
294    #[error("conflicting hash algo: {0} (hash_algo) vs {1} (inline)")]
295    ConflictingHashAlgos(HashAlgo, HashAlgo),
296    #[error("missing inline hash algo, but no externally-specified algo: {0:?}")]
297    MissingInlineHashAlgo(String),
298}
299
300/// Decode a plain digest depending on the hash algo specified externally.
301/// hexlower, nixbase32 and base64 encodings are supported - the encoding is
302/// inferred from the input length.
303fn decode_digest(s: &[u8], algo: HashAlgo) -> Result<NixHash, Error> {
304    // for the chosen hash algo, calculate the expected (decoded) digest length
305    // (as bytes)
306    let digest = if s.len() == HEXLOWER.encode_len(algo.digest_length()) {
307        HEXLOWER
308            .decode(s.as_ref())
309            .map_err(Error::InvalidBase16Encoding)?
310    } else if s.len() == nixbase32::encode_len(algo.digest_length()) {
311        nixbase32::decode(s).map_err(Error::InvalidBase32Encoding)?
312    } else if s.len() == BASE64.encode_len(algo.digest_length()) {
313        BASE64
314            .decode(s.as_ref())
315            .map_err(Error::InvalidBase64Encoding)?
316    } else {
317        Err(Error::InvalidDigestLength(algo))?
318    };
319
320    Ok(NixHash::from_algo_and_digest(algo, &digest).unwrap())
321}
322
323#[cfg(test)]
324mod tests {
325    use crate::nixhash::{HashAlgo, NixHash};
326    use hex_literal::hex;
327    use rstest::rstest;
328    use std::sync::LazyLock;
329
330    const NIXHASH_SHA1: NixHash = NixHash::Sha1(hex!("6016777997c30ab02413cf5095622cd7924283ac"));
331    const NIXHASH_SHA256: NixHash = NixHash::Sha256(hex!(
332        "a5ce9c155ed09397614646c9717fc7cd94b1023d7b76b618d409e4fefd6e9d39"
333    ));
334    static NIXHASH_SHA512: LazyLock<NixHash> = LazyLock::new(|| {
335        NixHash::Sha512(Box::new(hex!(
336            "ab40d0be3541f0774bba7815d13d10b03252e96e95f7dbb4ee99a3b431c21662fd6971a020160e39848aa5f305b9be0f78727b2b0789e39f124d21e92b8f39ef"
337        )))
338    });
339    const NIXHASH_MD5: NixHash = NixHash::Md5(hex!("c4874a8897440b393d862d8fd459073f"));
340
341    /// Test parsing a hash string in various formats, and also when/how the out-of-band algo is needed.
342    #[rstest]
343    // regular SRI hashes. We test some funny encoding edge cases in a separate test.
344    #[case::sri_sha1("sha1-YBZ3eZfDCrAkE89QlWIs15JCg6w=", HashAlgo::Sha1, NIXHASH_SHA1)]
345    #[case::sri_sha256(
346        "sha256-pc6cFV7Qk5dhRkbJcX/HzZSxAj17drYY1Ank/v1unTk=",
347        HashAlgo::Sha256,
348        NIXHASH_SHA256
349    )]
350    #[case::sri_sha512(
351        "sha512-q0DQvjVB8HdLungV0T0QsDJS6W6V99u07pmjtDHCFmL9aXGgIBYOOYSKpfMFub4PeHJ7KweJ458STSHpK4857w==",
352        HashAlgo::Sha512,
353        (*NIXHASH_SHA512).clone()
354    )]
355    // lowerhex
356    #[case::lowerhex_sha1(
357        "sha1:6016777997c30ab02413cf5095622cd7924283ac",
358        HashAlgo::Sha1,
359        NIXHASH_SHA1
360    )]
361    #[case::lowerhex_sha256(
362        "sha256:a5ce9c155ed09397614646c9717fc7cd94b1023d7b76b618d409e4fefd6e9d39",
363        HashAlgo::Sha256,
364        NIXHASH_SHA256
365    )]
366    #[case::lowerhex_sha512("sha512:ab40d0be3541f0774bba7815d13d10b03252e96e95f7dbb4ee99a3b431c21662fd6971a020160e39848aa5f305b9be0f78727b2b0789e39f124d21e92b8f39ef", HashAlgo::Sha512, (*NIXHASH_SHA512).clone())]
367    #[case::lowerhex_md5("md5:c4874a8897440b393d862d8fd459073f", HashAlgo::Md5, NIXHASH_MD5)]
368    #[case::lowerhex_md5("md5-xIdKiJdECzk9hi2P1FkHPw==", HashAlgo::Md5, NIXHASH_MD5)]
369    // base64
370    #[case::base64_sha1("sha1:YBZ3eZfDCrAkE89QlWIs15JCg6w=", HashAlgo::Sha1, NIXHASH_SHA1)]
371    #[case::base64_sha256(
372        "sha256:pc6cFV7Qk5dhRkbJcX/HzZSxAj17drYY1Ank/v1unTk=",
373        HashAlgo::Sha256,
374        NIXHASH_SHA256
375    )]
376    #[case::base64_sha512("sha512:q0DQvjVB8HdLungV0T0QsDJS6W6V99u07pmjtDHCFmL9aXGgIBYOOYSKpfMFub4PeHJ7KweJ458STSHpK4857w==", HashAlgo::Sha512, (*NIXHASH_SHA512).clone())]
377    #[case::base64_md5("md5:xIdKiJdECzk9hi2P1FkHPw==", HashAlgo::Md5, NIXHASH_MD5)]
378    // nixbase32
379    #[case::nixbase32_sha1("sha1:mj1l54np5ii9al6g2cjb02n3jxwpf5k0", HashAlgo::Sha1, NIXHASH_SHA1)]
380    #[case::nixbase32_sha256(
381        "sha256:0fcxdvyzxr09shcbcxkv7l1b356dqxzp3ja68rhrg4yhbqarrkm5",
382        HashAlgo::Sha256,
383        NIXHASH_SHA256
384    )]
385    #[case::nixbase32_sha512("sha512:3pkk3rbx4hls4lzwf4hfavvf9w0zgmr0prsb2l47471c850f5lzsqhnq8qv98wrxssdpxwmdvlm4cmh20yx25bqp95pgw216nzd0h5b", HashAlgo::Sha512, (*NIXHASH_SHA512).clone())]
386    #[case::nixbase32_md5("md5:1z0xcx93rdhqykj2s4jy44m1y4", HashAlgo::Md5, NIXHASH_MD5)]
387    fn from_str(#[case] s: &str, #[case] algo: HashAlgo, #[case] expected: NixHash) {
388        assert_eq!(
389            expected,
390            NixHash::from_str(s, Some(algo)).expect("must parse"),
391            "should parse"
392        );
393
394        // We expect all s to contain an algo in-band, so expect it to parse without an algo too.
395        assert_eq!(
396            expected,
397            NixHash::from_str(s, None).expect("must parse without algo too"),
398            "should parse"
399        );
400
401        // Whenever we encounter a hash with a `$algo:` prefix, we pop that prefix
402        // and test it parses without it if the algo is passed in externally, but fails if not.
403        // We do this for a subset of inputs here in the testcase, rather than adding 12 new testcases (4 algos x 3 encodings)
404        if let Some(digest_str) = s
405            .strip_prefix("sha1:")
406            .or(s.strip_prefix("sha256:"))
407            .or(s.strip_prefix("sha512:"))
408            .or(s.strip_prefix("sha512:"))
409        {
410            assert_eq!(
411                expected,
412                NixHash::from_str(digest_str, Some(algo))
413                    .expect("must parse digest-only if algo specified")
414            );
415            NixHash::from_str(digest_str, None)
416                .expect_err("must fail parsing digest-only if algo not specified");
417        }
418    }
419
420    // Test parsing a hash specifying another algo than what's passed externally fails.
421    #[test]
422    fn test_want_algo() {
423        NixHash::from_str("sha1-YBZ3eZfDCrAkE89QlWIs15JCg6w=", Some(HashAlgo::Md5))
424            .expect_err("parsing with conflicting want_algo should fail");
425
426        NixHash::from_str("sha1:YBZ3eZfDCrAkE89QlWIs15JCg6w=", Some(HashAlgo::Md5))
427            .expect_err("parsing with conflicting want_algo should fail");
428    }
429
430    /// Test parsing an SRI hash via the [nixhash::from_sri_str] method.
431    #[test]
432    fn from_sri_str() {
433        let nix_hash = NixHash::from_sri("sha256-pc6cFV7Qk5dhRkbJcX/HzZSxAj17drYY1Ank/v1unTk=")
434            .expect("must succeed");
435
436        assert_eq!(HashAlgo::Sha256, nix_hash.algo());
437        assert_eq!(
438            &hex!("a5ce9c155ed09397614646c9717fc7cd94b1023d7b76b618d409e4fefd6e9d39"),
439            nix_hash.digest_as_bytes()
440        )
441    }
442
443    /// Test parsing sha512 SRI hash with various paddings, Nix accepts all of them.
444    #[rstest]
445    #[case::no_padding(
446        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ"
447    )]
448    #[case::too_little_padding(
449        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ="
450    )]
451    #[case::correct_padding(
452        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ=="
453    )]
454    #[case::too_much_padding(
455        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ==="
456    )]
457    #[case::additional_suffix_ignored(
458        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ== cheesecake"
459    )]
460    fn from_sri_str_sha512_paddings(#[case] sri_str: &str) {
461        let nix_hash = NixHash::from_sri(sri_str).expect("must succeed");
462
463        assert_eq!(HashAlgo::Sha512, nix_hash.algo());
464        assert_eq!(
465            &hex!(
466                "ee0f754c1bd8a18428ad14eaa3ead80ff8b96275af5012e7a8384f1f10490da056eec9ae3cc791a7a13a24e16e54df5bccdd109c7d53a14534bbd7360a300b11"
467            ),
468            nix_hash.digest_as_bytes()
469        )
470    }
471
472    /// Ensure we detect truncated base64 digests, where the digest size
473    /// doesn't match what's expected from that hash function.
474    #[test]
475    fn from_sri_str_truncated() {
476        NixHash::from_sri("sha256-pc6cFV7Qk5dhRkbJcX/HzZSxAj17drYY1Ank").expect_err("must fail");
477    }
478
479    /// Ensure we fail on SRI hashes that Nix doesn't support.
480    #[test]
481    fn from_sri_str_unsupported() {
482        NixHash::from_sri(
483            "sha384-o4UVSl89mIB0sFUK+3jQbG+C9Zc9dRlV/Xd3KAvXEbhqxu0J5OAdg6b6VHKHwQ7U",
484        )
485        .expect_err("must fail");
486    }
487
488    /// Ensure we reject invalid base64 encoding
489    #[test]
490    fn from_sri_str_invalid_base64() {
491        NixHash::from_sri("sha256-invalid=base64").expect_err("must fail");
492    }
493
494    /// Nix also accepts SRI strings with missing padding, but only in case the
495    /// string is expressed as SRI, so it still needs to have a `sha256-` prefix.
496    ///
497    /// This both seems to work if it is passed with and without specifying the
498    /// hash algo out-of-band (hash = "sha256-…" or sha256 = "sha256-…")
499    ///
500    /// Passing the same broken base64 string, but not as SRI, while passing
501    /// the hash algo out-of-band does not work.
502    #[test]
503    fn sha256_broken_padding() {
504        let broken_base64 = "fgIr3TyFGDAXP5+qoAaiMKDg/a1MlT6Fv/S/DaA24S8";
505        // if padded with a trailing '='
506        let expected_digest =
507            hex!("7e022bdd3c851830173f9faaa006a230a0e0fdad4c953e85bff4bf0da036e12f");
508
509        // passing hash algo out of band should succeed
510        let nix_hash = NixHash::from_str(
511            &format!("sha256-{}", &broken_base64),
512            Some(HashAlgo::Sha256),
513        )
514        .expect("must succeed");
515        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
516
517        // not passing hash algo out of band should succeed
518        let nix_hash =
519            NixHash::from_str(&format!("sha256-{}", &broken_base64), None).expect("must succeed");
520        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
521
522        // not passing SRI, but hash algo out of band should fail
523        NixHash::from_str(broken_base64, Some(HashAlgo::Sha256)).expect_err("must fail");
524    }
525
526    /// As we decided to pass our hashes by trimming `=` completely,
527    /// we need to take into account hashes with padding requirements which
528    /// contains trailing bits which would be checked by `BASE64_NOPAD` and would
529    /// make the verification crash.
530    ///
531    /// This base64 has a trailing non-zero bit at bit 42.
532    #[test]
533    fn sha256_weird_base64() {
534        let weird_base64 = "syceJMUEknBDCHK8eGs6rUU3IQn+HnQfURfCrDxYPa9=";
535        let expected_digest =
536            hex!("b3271e24c5049270430872bc786b3aad45372109fe1e741f5117c2ac3c583daf");
537
538        let nix_hash =
539            NixHash::from_str(&format!("sha256-{}", &weird_base64), Some(HashAlgo::Sha256))
540                .expect("must succeed");
541        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
542
543        // not passing hash algo out of band should succeed
544        let nix_hash =
545            NixHash::from_str(&format!("sha256-{}", &weird_base64), None).expect("must succeed");
546        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
547
548        // not passing SRI, but hash algo out of band should fail
549        NixHash::from_str(weird_base64, Some(HashAlgo::Sha256)).expect_err("must fail");
550    }
551
552    #[cfg(feature = "serde")]
553    #[test]
554    fn serialize_deserialize() {
555        let nixhash_actual = NixHash::Sha256(hex!(
556            "b3271e24c5049270430872bc786b3aad45372109fe1e741f5117c2ac3c583daf"
557        ));
558        let nixhash_str_json = "\"sha256-syceJMUEknBDCHK8eGs6rUU3IQn+HnQfURfCrDxYPa8=\"";
559
560        let serialized = serde_json::to_string(&nixhash_actual).expect("can serialize");
561
562        assert_eq!(nixhash_str_json, &serialized);
563
564        let deserialized: NixHash =
565            serde_json::from_str(nixhash_str_json).expect("must deserialize");
566        assert_eq!(&nixhash_actual, &deserialized);
567    }
568}