nix_compat/nixhash/
mod.rs

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