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("Tvix 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!(
356        "ab40d0be3541f0774bba7815d13d10b03252e96e95f7dbb4ee99a3b431c21662fd6971a020160e39848aa5f305b9be0f78727b2b0789e39f124d21e92b8f39ef"
357    );
358    const DIGEST_MD5: [u8; 16] = hex!("c4874a8897440b393d862d8fd459073f");
359
360    fn to_base16(digest: &[u8]) -> String {
361        HEXLOWER.encode(digest)
362    }
363
364    fn to_nixbase32(digest: &[u8]) -> String {
365        nixbase32::encode(digest)
366    }
367
368    fn to_base64(digest: &[u8]) -> String {
369        BASE64.encode(digest)
370    }
371
372    fn to_base64_nopad(digest: &[u8]) -> String {
373        BASE64_NOPAD.encode(digest)
374    }
375
376    // TODO
377    fn make_nixhash(algo: &HashAlgo, digest_encoded: String) -> String {
378        format!("{algo}:{digest_encoded}")
379    }
380    fn make_sri_string(algo: &HashAlgo, digest_encoded: String) -> String {
381        format!("{algo}-{digest_encoded}")
382    }
383
384    /// Test parsing a hash string in various formats, and also when/how the out-of-band algo is needed.
385    #[rstest]
386    #[case::sha1(&NixHash::Sha1(DIGEST_SHA1))]
387    #[case::sha256(&NixHash::Sha256(DIGEST_SHA256))]
388    #[case::sha512(&NixHash::Sha512(Box::new(DIGEST_SHA512)))]
389    #[case::md5(&NixHash::Md5(DIGEST_MD5))]
390    fn from_str(#[case] expected_hash: &NixHash) {
391        let algo = &expected_hash.algo();
392        let digest = expected_hash.digest_as_bytes();
393        // parse SRI
394        {
395            // base64 without out-of-band algo
396            let s = make_sri_string(algo, to_base64(digest));
397            let h = nixhash::from_str(&s, None).expect("must succeed");
398            assert_eq!(expected_hash, &h);
399
400            // base64 with out-of-band-algo
401            let s = make_sri_string(algo, to_base64(digest));
402            let h = nixhash::from_str(&s, Some(&expected_hash.algo().to_string()))
403                .expect("must succeed");
404            assert_eq!(expected_hash, &h);
405
406            // base64_nopad without out-of-band algo
407            let s = make_sri_string(algo, to_base64_nopad(digest));
408            let h = nixhash::from_str(&s, None).expect("must succeed");
409            assert_eq!(expected_hash, &h);
410
411            // base64_nopad with out-of-band-algo
412            let s = make_sri_string(algo, to_base64_nopad(digest));
413            let h = nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed");
414            assert_eq!(expected_hash, &h);
415        }
416
417        // parse plain base16. should succeed with algo out-of-band, but fail without.
418        {
419            let s = to_base16(digest);
420            nixhash::from_str(&s, None).expect_err("must fail");
421            let h = nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed");
422            assert_eq!(expected_hash, &h);
423        }
424
425        // parse plain nixbase32. should succeed with algo out-of-band, but fail without.
426        {
427            let s = to_nixbase32(digest);
428            nixhash::from_str(&s, None).expect_err("must fail");
429            let h = nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed");
430            assert_eq!(expected_hash, &h);
431        }
432
433        // parse plain base64. should succeed with algo out-of-band, but fail without.
434        {
435            let s = to_base64(digest);
436            nixhash::from_str(&s, None).expect_err("must fail");
437            let h = nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed");
438            assert_eq!(expected_hash, &h);
439        }
440
441        // parse Nix hash strings
442        {
443            // base16. should succeed with both algo out-of-band and in-band.
444            {
445                let s = make_nixhash(algo, to_base16(digest));
446                assert_eq!(
447                    expected_hash,
448                    &nixhash::from_str(&s, None).expect("must succeed")
449                );
450                assert_eq!(
451                    expected_hash,
452                    &nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed")
453                );
454            }
455            // nixbase32. should succeed with both algo out-of-band and in-band.
456            {
457                let s = make_nixhash(algo, to_nixbase32(digest));
458                assert_eq!(
459                    expected_hash,
460                    &nixhash::from_str(&s, None).expect("must succeed")
461                );
462                assert_eq!(
463                    expected_hash,
464                    &nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed")
465                );
466            }
467            // base64. should succeed with both algo out-of-band and in-band.
468            {
469                let s = make_nixhash(algo, to_base64(digest));
470                assert_eq!(
471                    expected_hash,
472                    &nixhash::from_str(&s, None).expect("must succeed")
473                );
474                assert_eq!(
475                    expected_hash,
476                    &nixhash::from_str(&s, Some(&algo.to_string())).expect("must succeed")
477                );
478            }
479        }
480    }
481
482    /// Test parsing an SRI hash via the [nixhash::from_sri_str] method.
483    #[test]
484    fn from_sri_str() {
485        let nix_hash = nixhash::from_sri_str("sha256-pc6cFV7Qk5dhRkbJcX/HzZSxAj17drYY1Ank/v1unTk=")
486            .expect("must succeed");
487
488        assert_eq!(HashAlgo::Sha256, nix_hash.algo());
489        assert_eq!(
490            &hex!("a5ce9c155ed09397614646c9717fc7cd94b1023d7b76b618d409e4fefd6e9d39"),
491            nix_hash.digest_as_bytes()
492        )
493    }
494
495    /// Test parsing sha512 SRI hash with various paddings, Nix accepts all of them.
496    #[rstest]
497    #[case::no_padding(
498        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ"
499    )]
500    #[case::too_little_padding(
501        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ="
502    )]
503    #[case::correct_padding(
504        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ=="
505    )]
506    #[case::too_much_padding(
507        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ==="
508    )]
509    #[case::additional_suffix_ignored(
510        "sha512-7g91TBvYoYQorRTqo+rYD/i5YnWvUBLnqDhPHxBJDaBW7smuPMeRp6E6JOFuVN9bzN0QnH1ToUU0u9c2CjALEQ== cheesecake"
511    )]
512    fn from_sri_str_sha512_paddings(#[case] sri_str: &str) {
513        let nix_hash = nixhash::from_sri_str(sri_str).expect("must succeed");
514
515        assert_eq!(HashAlgo::Sha512, nix_hash.algo());
516        assert_eq!(
517            &hex!(
518                "ee0f754c1bd8a18428ad14eaa3ead80ff8b96275af5012e7a8384f1f10490da056eec9ae3cc791a7a13a24e16e54df5bccdd109c7d53a14534bbd7360a300b11"
519            ),
520            nix_hash.digest_as_bytes()
521        )
522    }
523
524    /// Ensure we detect truncated base64 digests, where the digest size
525    /// doesn't match what's expected from that hash function.
526    #[test]
527    fn from_sri_str_truncated() {
528        nixhash::from_sri_str("sha256-pc6cFV7Qk5dhRkbJcX/HzZSxAj17drYY1Ank")
529            .expect_err("must fail");
530    }
531
532    /// Ensure we fail on SRI hashes that Nix doesn't support.
533    #[test]
534    fn from_sri_str_unsupported() {
535        nixhash::from_sri_str(
536            "sha384-o4UVSl89mIB0sFUK+3jQbG+C9Zc9dRlV/Xd3KAvXEbhqxu0J5OAdg6b6VHKHwQ7U",
537        )
538        .expect_err("must fail");
539    }
540
541    /// Ensure we reject invalid base64 encoding
542    #[test]
543    fn from_sri_str_invalid_base64() {
544        nixhash::from_sri_str("sha256-invalid=base64").expect_err("must fail");
545    }
546
547    /// Nix also accepts SRI strings with missing padding, but only in case the
548    /// string is expressed as SRI, so it still needs to have a `sha256-` prefix.
549    ///
550    /// This both seems to work if it is passed with and without specifying the
551    /// hash algo out-of-band (hash = "sha256-…" or sha256 = "sha256-…")
552    ///
553    /// Passing the same broken base64 string, but not as SRI, while passing
554    /// the hash algo out-of-band does not work.
555    #[test]
556    fn sha256_broken_padding() {
557        let broken_base64 = "fgIr3TyFGDAXP5+qoAaiMKDg/a1MlT6Fv/S/DaA24S8";
558        // if padded with a trailing '='
559        let expected_digest =
560            hex!("7e022bdd3c851830173f9faaa006a230a0e0fdad4c953e85bff4bf0da036e12f");
561
562        // passing hash algo out of band should succeed
563        let nix_hash = nixhash::from_str(&format!("sha256-{}", &broken_base64), Some("sha256"))
564            .expect("must succeed");
565        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
566
567        // not passing hash algo out of band should succeed
568        let nix_hash =
569            nixhash::from_str(&format!("sha256-{}", &broken_base64), None).expect("must succeed");
570        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
571
572        // not passing SRI, but hash algo out of band should fail
573        nixhash::from_str(broken_base64, Some("sha256")).expect_err("must fail");
574    }
575
576    /// As we decided to pass our hashes by trimming `=` completely,
577    /// we need to take into account hashes with padding requirements which
578    /// contains trailing bits which would be checked by `BASE64_NOPAD` and would
579    /// make the verification crash.
580    ///
581    /// This base64 has a trailing non-zero bit at bit 42.
582    #[test]
583    fn sha256_weird_base64() {
584        let weird_base64 = "syceJMUEknBDCHK8eGs6rUU3IQn+HnQfURfCrDxYPa9=";
585        let expected_digest =
586            hex!("b3271e24c5049270430872bc786b3aad45372109fe1e741f5117c2ac3c583daf");
587
588        let nix_hash = nixhash::from_str(&format!("sha256-{}", &weird_base64), Some("sha256"))
589            .expect("must succeed");
590        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
591
592        // not passing hash algo out of band should succeed
593        let nix_hash =
594            nixhash::from_str(&format!("sha256-{}", &weird_base64), None).expect("must succeed");
595        assert_eq!(&expected_digest, &nix_hash.digest_as_bytes());
596
597        // not passing SRI, but hash algo out of band should fail
598        nixhash::from_str(weird_base64, Some("sha256")).expect_err("must fail");
599    }
600
601    #[test]
602    fn serialize_deserialize() {
603        let nixhash_actual = NixHash::Sha256(hex!(
604            "b3271e24c5049270430872bc786b3aad45372109fe1e741f5117c2ac3c583daf"
605        ));
606        let nixhash_str_json = "\"sha256-syceJMUEknBDCHK8eGs6rUU3IQn+HnQfURfCrDxYPa8=\"";
607
608        let serialized = serde_json::to_string(&nixhash_actual).expect("can serialize");
609
610        assert_eq!(nixhash_str_json, &serialized);
611
612        let deserialized: NixHash =
613            serde_json::from_str(nixhash_str_json).expect("must deserialize");
614        assert_eq!(&nixhash_actual, &deserialized);
615    }
616}