1use blake2::Blake2b;
7use digest::consts::{U32, U48, U64};
8use digest::Digest;
9use sha1::Sha1;
10use sha2::{Sha256, Sha384, Sha512};
11use sha3::{Sha3_256, Sha3_384, Sha3_512};
12
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14
15use crate::enums::{ChecksumAlgorithm, EnumKnowledge};
16use crate::error::ModelError;
17
18type Blake2b256Hasher = Blake2b<U32>;
19type Blake2b384Hasher = Blake2b<U48>;
20type Blake2b512Hasher = Blake2b<U64>;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Checksum {
25 algorithm: ChecksumAlgorithm,
26 hex_value: String,
27}
28
29impl Checksum {
30 pub fn new(algorithm: ChecksumAlgorithm, hex_value: &str) -> Result<Self, ModelError> {
39 if !hex_value.bytes().all(|b| b.is_ascii_hexdigit())
40 || hex_value.bytes().any(|b| b.is_ascii_uppercase())
41 {
42 return Err(ModelError::Invalid(
43 "checksum algValue must be lowercase hexadecimal".into(),
44 ));
45 }
46 if let Some(len) = algorithm.digest_len() {
47 if hex_value.len() != len * 2 {
48 return Err(ModelError::Invalid(format!(
49 "checksum length for {} must be {} hexadecimal characters",
50 algorithm,
51 len * 2
52 )));
53 }
54 } else if !(40..=128).contains(&hex_value.len()) || !hex_value.len().is_multiple_of(2) {
55 return Err(ModelError::Invalid(
56 "unrecognized checksum must be an even lowercase hex string of 40 to 128 characters"
57 .into(),
58 ));
59 }
60 Ok(Self {
61 algorithm,
62 hex_value: hex_value.to_owned(),
63 })
64 }
65
66 #[must_use]
68 pub fn algorithm(&self) -> &ChecksumAlgorithm {
69 &self.algorithm
70 }
71
72 #[must_use]
74 pub fn hex_value(&self) -> &str {
75 &self.hex_value
76 }
77}
78
79#[derive(Deserialize)]
80struct ChecksumWire {
81 #[serde(rename = "algType")]
82 alg_type: String,
83 #[serde(rename = "algValue")]
84 alg_value: String,
85}
86
87impl Serialize for Checksum {
88 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
89 use serde::ser::SerializeStruct;
90 let mut state = serializer.serialize_struct("Checksum", 2)?;
91 state.serialize_field("algType", self.algorithm.as_str())?;
92 state.serialize_field("algValue", &self.hex_value)?;
93 state.end()
94 }
95}
96
97impl<'de> Deserialize<'de> for Checksum {
98 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
99 let wire = ChecksumWire::deserialize(deserializer)?;
100 Self::new(
101 ChecksumAlgorithm::from_wire(&wire.alg_type),
102 &wire.alg_value,
103 )
104 .map_err(serde::de::Error::custom)
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum IntegrityOutcome {
112 Verified,
115 Failed,
117 Unsupported,
119 Incomplete,
123 NotDeclared,
125 Weak,
131}
132
133#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct ChecksumPolicy {
137 pub allow_weak: bool,
141}
142
143impl ChecksumPolicy {
144 #[must_use]
146 pub fn new() -> Self {
147 Self::default()
148 }
149
150 #[must_use]
152 pub fn with_allow_weak(mut self, allow: bool) -> Self {
153 self.allow_weak = allow;
154 self
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160#[non_exhaustive]
161pub struct ChecksumCheck {
162 pub algorithm: String,
164 pub expected: String,
166 pub actual: Option<String>,
168 pub supported: bool,
170 pub matched: Option<bool>,
172 pub weak: bool,
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
179#[non_exhaustive]
180pub struct IntegrityReport {
181 pub outcome: IntegrityOutcome,
183 pub checks: Vec<ChecksumCheck>,
185}
186
187pub struct ChecksumVerifier {
189 items: Vec<Running>,
190 policy: ChecksumPolicy,
191}
192
193struct Running {
194 checksum: Checksum,
195 hasher: Option<RunningHasher>,
196}
197
198enum RunningHasher {
199 Sha1(Sha1),
200 Sha256(Sha256),
201 Sha384(Sha384),
202 Sha512(Sha512),
203 Sha3_256(Sha3_256),
204 Sha3_384(Sha3_384),
205 Sha3_512(Sha3_512),
206 Blake2b256(Blake2b256Hasher),
207 Blake2b384(Blake2b384Hasher),
208 Blake2b512(Blake2b512Hasher),
209 Blake3(Box<blake3::Hasher>),
210}
211
212impl ChecksumVerifier {
213 #[must_use]
218 pub fn new(checksums: &[Checksum]) -> Self {
219 Self::with_policy(checksums, ChecksumPolicy::default())
220 }
221
222 #[must_use]
224 pub fn with_policy(checksums: &[Checksum], policy: ChecksumPolicy) -> Self {
225 let items = checksums
226 .iter()
227 .map(|checksum| Running {
228 hasher: hasher_for(checksum.algorithm()),
229 checksum: checksum.clone(),
230 })
231 .collect();
232 Self { items, policy }
233 }
234
235 pub fn update(&mut self, bytes: &[u8]) {
237 for item in &mut self.items {
238 if let Some(hasher) = item.hasher.as_mut() {
239 hasher.update(bytes);
240 }
241 }
242 }
243
244 #[must_use]
246 pub fn finish(self) -> IntegrityReport {
247 if self.items.is_empty() {
248 return IntegrityReport {
249 outcome: IntegrityOutcome::NotDeclared,
250 checks: Vec::new(),
251 };
252 }
253 let mut checks = Vec::with_capacity(self.items.len());
254 for item in self.items {
255 let actual = item.hasher.map(RunningHasher::finish_hex);
256 let matched = actual
257 .as_ref()
258 .map(|value| value == &item.checksum.hex_value);
259 checks.push(ChecksumCheck {
260 algorithm: item.checksum.algorithm().as_str().to_owned(),
261 expected: item.checksum.hex_value().to_owned(),
262 supported: item.checksum.algorithm().knowledge() == EnumKnowledge::Known
263 && actual.is_some(),
264 actual,
265 matched,
266 weak: item.checksum.algorithm().is_weak(),
267 });
268 }
269 let any_failed = checks.iter().any(|check| check.matched == Some(false));
270 let any_unsupported = checks.iter().any(|check| !check.supported);
271 let all_matched = checks.iter().all(|check| check.matched == Some(true));
272 let outcome = if any_failed {
273 IntegrityOutcome::Failed
274 } else if all_matched {
275 if !self.policy.allow_weak && checks.iter().all(|check| check.weak) {
276 IntegrityOutcome::Weak
277 } else {
278 IntegrityOutcome::Verified
279 }
280 } else if any_unsupported && checks.iter().any(|check| check.matched == Some(true)) {
281 IntegrityOutcome::Incomplete
282 } else {
283 IntegrityOutcome::Unsupported
284 };
285 IntegrityReport { outcome, checks }
286 }
287}
288
289impl RunningHasher {
290 fn update(&mut self, bytes: &[u8]) {
291 match self {
292 Self::Sha1(hasher) => Digest::update(hasher, bytes),
293 Self::Sha256(hasher) => Digest::update(hasher, bytes),
294 Self::Sha384(hasher) => Digest::update(hasher, bytes),
295 Self::Sha512(hasher) => Digest::update(hasher, bytes),
296 Self::Sha3_256(hasher) => Digest::update(hasher, bytes),
297 Self::Sha3_384(hasher) => Digest::update(hasher, bytes),
298 Self::Sha3_512(hasher) => Digest::update(hasher, bytes),
299 Self::Blake2b256(hasher) => Digest::update(hasher, bytes),
300 Self::Blake2b384(hasher) => Digest::update(hasher, bytes),
301 Self::Blake2b512(hasher) => Digest::update(hasher, bytes),
302 Self::Blake3(hasher) => {
303 hasher.update(bytes);
304 }
305 }
306 }
307
308 fn finish_hex(self) -> String {
309 match self {
310 Self::Sha1(hasher) => hex_encode(&hasher.finalize()),
311 Self::Sha256(hasher) => hex_encode(&hasher.finalize()),
312 Self::Sha384(hasher) => hex_encode(&hasher.finalize()),
313 Self::Sha512(hasher) => hex_encode(&hasher.finalize()),
314 Self::Sha3_256(hasher) => hex_encode(&hasher.finalize()),
315 Self::Sha3_384(hasher) => hex_encode(&hasher.finalize()),
316 Self::Sha3_512(hasher) => hex_encode(&hasher.finalize()),
317 Self::Blake2b256(hasher) => hex_encode(&hasher.finalize()),
318 Self::Blake2b384(hasher) => hex_encode(&hasher.finalize()),
319 Self::Blake2b512(hasher) => hex_encode(&hasher.finalize()),
320 Self::Blake3(hasher) => hex_encode(hasher.finalize().as_bytes()),
321 }
322 }
323}
324
325fn hasher_for(algorithm: &ChecksumAlgorithm) -> Option<RunningHasher> {
326 Some(match algorithm {
327 ChecksumAlgorithm::Sha1 => RunningHasher::Sha1(Sha1::new()),
328 ChecksumAlgorithm::Sha256 => RunningHasher::Sha256(Sha256::new()),
329 ChecksumAlgorithm::Sha384 => RunningHasher::Sha384(Sha384::new()),
330 ChecksumAlgorithm::Sha512 => RunningHasher::Sha512(Sha512::new()),
331 ChecksumAlgorithm::Sha3_256 => RunningHasher::Sha3_256(Sha3_256::new()),
332 ChecksumAlgorithm::Sha3_384 => RunningHasher::Sha3_384(Sha3_384::new()),
333 ChecksumAlgorithm::Sha3_512 => RunningHasher::Sha3_512(Sha3_512::new()),
334 ChecksumAlgorithm::Blake2b256 => RunningHasher::Blake2b256(Blake2b256Hasher::new()),
335 ChecksumAlgorithm::Blake2b384 => RunningHasher::Blake2b384(Blake2b384Hasher::new()),
336 ChecksumAlgorithm::Blake2b512 => RunningHasher::Blake2b512(Blake2b512Hasher::new()),
337 ChecksumAlgorithm::Blake3 => RunningHasher::Blake3(Box::new(blake3::Hasher::new())),
338 ChecksumAlgorithm::Other(_) => return None,
339 })
340}
341
342fn hex_encode(bytes: &[u8]) -> String {
343 const HEX: &[u8; 16] = b"0123456789abcdef";
344 let mut out = String::with_capacity(bytes.len() * 2);
345 for byte in bytes {
346 out.push(char::from(HEX[usize::from(byte >> 4)]));
347 out.push(char::from(HEX[usize::from(byte & 0x0f)]));
348 }
349 out
350}
351
352#[must_use]
354pub fn verify_checksums(bytes: &[u8], checksums: &[Checksum]) -> IntegrityReport {
355 verify_checksums_with_policy(bytes, checksums, ChecksumPolicy::default())
356}
357
358#[must_use]
360pub fn verify_checksums_with_policy(
361 bytes: &[u8],
362 checksums: &[Checksum],
363 policy: ChecksumPolicy,
364) -> IntegrityReport {
365 let mut verifier = ChecksumVerifier::with_policy(checksums, policy);
366 verifier.update(bytes);
367 verifier.finish()
368}
369
370pub struct ContentDecoder {
376 inner: DecoderInner,
377 max_output: usize,
378 input_len: usize,
379}
380
381enum DecoderInner {
382 Plain(CappedBuf),
383 Gzip(flate2::write::GzDecoder<CappedBuf>),
384 Zlib(ZlibInflate),
385}
386
387struct ZlibInflate {
393 decompressor: flate2::Decompress,
394 output: CappedBuf,
395 ended: bool,
396}
397
398impl ZlibInflate {
399 fn new(max: usize) -> Self {
400 Self {
401 decompressor: flate2::Decompress::new(true),
402 output: CappedBuf::new(max),
403 ended: false,
404 }
405 }
406
407 fn push(&mut self, chunk: &[u8]) -> Result<(), ModelError> {
408 if self.ended {
409 return Err(ModelError::Invalid(
410 "content coding decode failed: trailing data after deflate stream".into(),
411 ));
412 }
413 if inflate(
414 &mut self.decompressor,
415 chunk,
416 &mut self.output,
417 flate2::FlushDecompress::None,
418 )? == flate2::Status::StreamEnd
419 {
420 self.ended = true;
421 }
422 Ok(())
423 }
424
425 fn finish(mut self) -> Result<Vec<u8>, ModelError> {
426 if !self.ended {
427 let status = inflate(
428 &mut self.decompressor,
429 &[],
430 &mut self.output,
431 flate2::FlushDecompress::Finish,
432 )?;
433 if status != flate2::Status::StreamEnd {
434 return Err(ModelError::Invalid(
435 "content coding decode failed: truncated deflate stream".into(),
436 ));
437 }
438 }
439 Ok(self.output.bytes)
440 }
441
442 fn len(&self) -> usize {
443 self.output.len()
444 }
445}
446
447fn inflate(
448 decompressor: &mut flate2::Decompress,
449 input: &[u8],
450 output: &mut CappedBuf,
451 flush: flate2::FlushDecompress,
452) -> Result<flate2::Status, ModelError> {
453 let mut offset = 0usize;
454 loop {
455 let mut buf = [0u8; 8192];
456 let in_before = decompressor.total_in();
457 let out_before = decompressor.total_out();
458 let available = if offset < input.len() {
459 &input[offset..]
460 } else {
461 &[]
462 };
463 let status = decompressor
464 .decompress(available, &mut buf, flush)
465 .map_err(|_| {
466 ModelError::Invalid("content coding decode failed: corrupt deflate stream".into())
467 })?;
468 let consumed = usize::try_from(decompressor.total_in() - in_before).unwrap_or(usize::MAX);
469 let produced = usize::try_from(decompressor.total_out() - out_before).unwrap_or(usize::MAX);
470 if consumed > available.len() || produced > buf.len() {
471 return Err(ModelError::Invalid(
472 "content coding decode failed: corrupt deflate stream".into(),
473 ));
474 }
475 if produced > 0 {
476 std::io::Write::write_all(output, &buf[..produced]).map_err(decode_error)?;
477 }
478 offset = offset.saturating_add(consumed);
479 if status == flate2::Status::StreamEnd {
480 if offset < input.len() {
481 return Err(ModelError::Invalid(
482 "content coding decode failed: trailing data after deflate stream".into(),
483 ));
484 }
485 return Ok(status);
486 }
487 if consumed == 0 && produced == 0 {
488 return Ok(status);
489 }
490 }
491}
492
493struct CappedBuf {
498 bytes: Vec<u8>,
499 taken: usize,
501 max: usize,
502}
503
504impl CappedBuf {
505 fn new(max: usize) -> Self {
506 Self {
507 bytes: Vec::new(),
508 taken: 0,
509 max,
510 }
511 }
512
513 fn len(&self) -> usize {
515 self.taken.saturating_add(self.bytes.len())
516 }
517
518 fn take(&mut self) -> Vec<u8> {
519 self.taken = self.taken.saturating_add(self.bytes.len());
520 std::mem::take(&mut self.bytes)
521 }
522}
523
524impl std::io::Write for CappedBuf {
525 fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
526 if self.len().saturating_add(data.len()) > self.max {
527 return Err(std::io::Error::new(
528 std::io::ErrorKind::InvalidData,
529 "decoded artifact exceeds the size limit",
530 ));
531 }
532 self.bytes.extend_from_slice(data);
533 Ok(data.len())
534 }
535
536 fn flush(&mut self) -> std::io::Result<()> {
537 Ok(())
538 }
539}
540
541impl ContentDecoder {
542 pub fn new(coding: Option<&str>, max_output: usize) -> Result<Self, ModelError> {
551 let inner = match coding.map(str::trim).filter(|value| !value.is_empty()) {
552 None => DecoderInner::Plain(CappedBuf::new(max_output)),
553 Some(coding) if coding.eq_ignore_ascii_case("identity") => {
554 DecoderInner::Plain(CappedBuf::new(max_output))
555 }
556 Some(coding) if coding.contains(',') => {
557 return Err(ModelError::Invalid(
558 "stacked content codings are rejected".into(),
559 ));
560 }
561 Some(coding)
562 if coding.eq_ignore_ascii_case("gzip") || coding.eq_ignore_ascii_case("x-gzip") =>
563 {
564 DecoderInner::Gzip(flate2::write::GzDecoder::new(CappedBuf::new(max_output)))
565 }
566 Some(coding) if coding.eq_ignore_ascii_case("deflate") => {
567 DecoderInner::Zlib(ZlibInflate::new(max_output))
568 }
569 Some(coding) => {
570 return Err(ModelError::Invalid(format!(
571 "unsupported HTTP content coding `{coding}`"
572 )));
573 }
574 };
575 Ok(Self {
576 inner,
577 max_output,
578 input_len: 0,
579 })
580 }
581
582 pub fn push(&mut self, chunk: &[u8]) -> Result<(), ModelError> {
589 if self.input_len.saturating_add(chunk.len()) > self.max_output {
590 return Err(ModelError::Invalid(
591 "encoded artifact exceeds the size limit".into(),
592 ));
593 }
594 self.input_len += chunk.len();
595 match &mut self.inner {
596 DecoderInner::Plain(output) => {
597 std::io::Write::write_all(output, chunk).map_err(decode_error)?;
598 }
599 DecoderInner::Gzip(decoder) => {
600 std::io::Write::write_all(decoder, chunk).map_err(decode_error)?;
601 }
602 DecoderInner::Zlib(decoder) => decoder.push(chunk)?,
603 }
604 if self.output_len() > self.max_output {
605 return Err(ModelError::Invalid(
606 "decoded artifact exceeds the size limit".into(),
607 ));
608 }
609 Ok(())
610 }
611
612 pub fn take_output(&mut self) -> Vec<u8> {
623 match &mut self.inner {
624 DecoderInner::Plain(output) => output.take(),
625 DecoderInner::Gzip(decoder) => decoder.get_mut().take(),
626 DecoderInner::Zlib(decoder) => decoder.output.take(),
627 }
628 }
629
630 pub fn finish(self) -> Result<Vec<u8>, ModelError> {
639 let output = match self.inner {
640 DecoderInner::Plain(output) => output.bytes,
641 DecoderInner::Gzip(decoder) => decoder.finish().map_err(decode_error)?.bytes,
642 DecoderInner::Zlib(decoder) => decoder.finish()?,
643 };
644 if output.len() > self.max_output {
645 return Err(ModelError::Invalid(
646 "decoded artifact exceeds the size limit".into(),
647 ));
648 }
649 Ok(output)
650 }
651
652 fn output_len(&self) -> usize {
653 match &self.inner {
654 DecoderInner::Plain(output) => output.len(),
655 DecoderInner::Gzip(decoder) => decoder.get_ref().len(),
656 DecoderInner::Zlib(decoder) => decoder.len(),
657 }
658 }
659}
660
661fn decode_error(err: std::io::Error) -> ModelError {
662 ModelError::Invalid(format!("content coding decode failed: {err}"))
663}
664
665pub fn decode_content_coding(
676 body: &[u8],
677 coding: Option<&str>,
678 max_output: usize,
679) -> Result<Vec<u8>, ModelError> {
680 let mut decoder = ContentDecoder::new(coding, max_output)?;
681 decoder.push(body)?;
682 decoder.finish()
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688
689 #[test]
690 fn sha256_matches_and_mismatch_is_not_success() {
691 let bytes = b"tea";
692 let good = Checksum::new(
693 ChecksumAlgorithm::Sha256,
694 "6ebf8529d78b9572b3c6b5a1b0c5c5c5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5",
695 );
696 let checksum = Checksum::new(ChecksumAlgorithm::Sha256, &{
698 let report_seed = Checksum::new(
699 ChecksumAlgorithm::Sha256,
700 "0000000000000000000000000000000000000000000000000000000000000000",
701 )
702 .unwrap();
703 let report = verify_checksums(bytes, &[report_seed]);
704 report.checks[0].actual.clone().unwrap()
705 })
706 .unwrap();
707 let ok = verify_checksums(bytes, std::slice::from_ref(&checksum));
708 assert_eq!(ok.outcome, IntegrityOutcome::Verified);
709 let bad = checksum;
710 let flipped = format!("0{}", &bad.hex_value()[1..]);
712 let bad_sum = Checksum::new(ChecksumAlgorithm::Sha256, &flipped).unwrap();
713 let failed = verify_checksums(bytes, &[bad_sum]);
714 assert_eq!(failed.outcome, IntegrityOutcome::Failed);
715 let _ = good;
716 let _ = bad;
717 }
718
719 #[test]
720 fn missing_and_unknown_algorithms_are_not_verified() {
721 let empty = verify_checksums(b"abc", &[]);
722 assert_eq!(empty.outcome, IntegrityOutcome::NotDeclared);
723 let unknown = Checksum::new(
724 ChecksumAlgorithm::Other("SHA-224".into()),
725 "0000000000000000000000000000000000000000000000000000000000000000",
726 )
727 .unwrap();
728 let report = verify_checksums(b"abc", &[unknown]);
729 assert_eq!(report.outcome, IntegrityOutcome::Unsupported);
730 }
731
732 #[test]
733 fn gzip_decoding_removes_content_coding_before_checksum() {
734 let raw = b"artifact-bytes";
735 let compressed = gzip_bytes(raw);
736 let decoded = decode_content_coding(&compressed, Some("gzip"), 1024).unwrap();
737 assert_eq!(decoded, raw);
738 let checksum = checksum_of(raw);
739 let report = verify_checksums(&decoded, std::slice::from_ref(&checksum));
740 assert_eq!(report.outcome, IntegrityOutcome::Verified);
741 }
742
743 #[test]
744 fn http_deflate_is_zlib_and_raw_deflate_is_rejected() {
745 let raw = b"artifact-bytes";
746 let zlib = zlib_bytes(raw);
747 let decoded = decode_content_coding(&zlib, Some("deflate"), 1024).unwrap();
748 assert_eq!(decoded, raw);
749 let checksum = checksum_of(raw);
750 let report = verify_checksums(&decoded, std::slice::from_ref(&checksum));
751 assert_eq!(report.outcome, IntegrityOutcome::Verified);
752
753 let raw_deflate = raw_deflate_bytes(raw);
754 assert!(decode_content_coding(&raw_deflate, Some("deflate"), 1024).is_err());
755 }
756
757 #[test]
758 fn gzip_expansion_is_capped() {
759 let raw = vec![b'a'; 64 * 1024];
760 let compressed = gzip_bytes(&raw);
761 assert!(compressed.len() < raw.len());
762 assert!(decode_content_coding(&compressed, Some("gzip"), 1024).is_err());
763 }
764
765 #[test]
766 fn truncated_gzip_and_zlib_are_rejected() {
767 let gzip = gzip_bytes(b"artifact-bytes");
768 let zlib = zlib_bytes(b"artifact-bytes");
769 assert!(gzip.len() > 8 && zlib.len() > 8);
770 assert!(decode_content_coding(&gzip[..gzip.len() / 2], Some("gzip"), 1024).is_err());
771 assert!(decode_content_coding(&zlib[..zlib.len() / 2], Some("deflate"), 1024).is_err());
772 assert!(decode_content_coding(&zlib[..zlib.len() - 4], Some("deflate"), 1024).is_err());
773 }
774
775 fn stream_in_chunks(
776 coding: Option<&str>,
777 body: &[u8],
778 step: usize,
779 max: usize,
780 ) -> Result<Vec<u8>, ModelError> {
781 let mut decoder = ContentDecoder::new(coding, max)?;
782 let mut all = Vec::new();
783 for chunk in body.chunks(step) {
784 decoder.push(chunk)?;
785 all.extend(decoder.take_output());
786 }
787 all.extend(decoder.finish()?);
788 Ok(all)
789 }
790
791 #[test]
792 fn take_output_streams_every_coding_to_the_same_bytes() {
793 let raw: Vec<u8> = (0..200_000u32).map(|n| (n % 251) as u8).collect();
794 for (coding, body) in [
795 (None, raw.clone()),
796 (Some("identity"), raw.clone()),
797 (Some("gzip"), gzip_bytes(&raw)),
798 (Some("deflate"), zlib_bytes(&raw)),
799 ] {
800 let got = stream_in_chunks(coding, &body, 997, raw.len()).unwrap();
801 assert_eq!(got, raw, "coding {coding:?}");
802 }
803 }
804
805 #[test]
806 fn the_size_cap_covers_bytes_already_taken() {
807 let raw = vec![7u8; 1000];
808 for (coding, body) in [
809 (None, raw.clone()),
810 (Some("gzip"), gzip_bytes(&raw)),
811 (Some("deflate"), zlib_bytes(&raw)),
812 ] {
813 assert!(
816 stream_in_chunks(coding, &body, 10, 1000).is_ok(),
817 "{coding:?}"
818 );
819 assert!(
820 stream_in_chunks(coding, &body, 10, 999).is_err(),
821 "{coding:?}"
822 );
823 }
824 }
825
826 fn flushed_pieces(coding: &str) -> (Vec<u8>, usize) {
829 let piece = vec![b'a'; 500];
830 let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
831 let mut zl = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
832 for _ in 0..20 {
833 if coding == "gzip" {
834 std::io::Write::write_all(&mut gz, &piece).unwrap();
835 std::io::Write::flush(&mut gz).unwrap();
836 } else {
837 std::io::Write::write_all(&mut zl, &piece).unwrap();
838 std::io::Write::flush(&mut zl).unwrap();
839 }
840 }
841 let body = if coding == "gzip" {
842 gz.finish().unwrap()
843 } else {
844 zl.finish().unwrap()
845 };
846 (body, 20 * 500)
847 }
848
849 #[test]
850 fn the_decoded_cap_covers_bytes_already_taken_when_output_arrives_gradually() {
851 for coding in ["gzip", "deflate"] {
852 let (body, decoded) = flushed_pieces(coding);
853 assert!(
854 body.len() < decoded / 4,
855 "{coding}: the body must compress well"
856 );
857 assert!(
859 stream_in_chunks(Some(coding), &body, 1, decoded).is_ok(),
860 "{coding}"
861 );
862 assert!(
863 stream_in_chunks(Some(coding), &body, 1, decoded - 1).is_err(),
864 "{coding}: total output over the cap must fail even though each take emptied the buffer"
865 );
866 }
867 }
868
869 #[test]
870 fn a_truncated_stream_fails_at_finish_after_bytes_were_taken() {
871 let raw = vec![1u8; 5000];
872 for (coding, body) in [
873 (Some("gzip"), gzip_bytes(&raw)),
874 (Some("deflate"), zlib_bytes(&raw)),
875 ] {
876 let cut = &body[..body.len() - 3];
877 assert!(
878 stream_in_chunks(coding, cut, 16, 10_000).is_err(),
879 "{coding:?}"
880 );
881 }
882 }
883
884 fn gzip_bytes(raw: &[u8]) -> Vec<u8> {
885 let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
886 std::io::Write::write_all(&mut encoder, raw).unwrap();
887 encoder.finish().unwrap()
888 }
889
890 fn zlib_bytes(raw: &[u8]) -> Vec<u8> {
891 let mut encoder =
892 flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
893 std::io::Write::write_all(&mut encoder, raw).unwrap();
894 encoder.finish().unwrap()
895 }
896
897 fn raw_deflate_bytes(raw: &[u8]) -> Vec<u8> {
898 let mut encoder =
899 flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
900 std::io::Write::write_all(&mut encoder, raw).unwrap();
901 encoder.finish().unwrap()
902 }
903
904 fn checksum_of(raw: &[u8]) -> Checksum {
905 let seed = Checksum::new(
906 ChecksumAlgorithm::Sha256,
907 "0000000000000000000000000000000000000000000000000000000000000000",
908 )
909 .unwrap();
910 let actual = verify_checksums(raw, &[seed]).checks[0]
911 .actual
912 .clone()
913 .unwrap();
914 Checksum::new(ChecksumAlgorithm::Sha256, &actual).unwrap()
915 }
916
917 fn digest_hex(algorithm: ChecksumAlgorithm, raw: &[u8]) -> String {
918 let zero = "0".repeat(algorithm.digest_len().unwrap_or(32) * 2);
919 let seed = Checksum::new(algorithm.clone(), &zero).unwrap();
920 verify_checksums(raw, &[seed]).checks[0]
921 .actual
922 .clone()
923 .unwrap()
924 }
925
926 #[test]
927 fn supported_algorithms_verify_decoded_bytes() {
928 let raw = b"algorithm-matrix";
929 for algorithm in [
930 ChecksumAlgorithm::Sha1,
931 ChecksumAlgorithm::Sha256,
932 ChecksumAlgorithm::Sha384,
933 ChecksumAlgorithm::Sha512,
934 ChecksumAlgorithm::Sha3_256,
935 ChecksumAlgorithm::Sha3_384,
936 ChecksumAlgorithm::Sha3_512,
937 ChecksumAlgorithm::Blake2b256,
938 ChecksumAlgorithm::Blake2b384,
939 ChecksumAlgorithm::Blake2b512,
940 ChecksumAlgorithm::Blake3,
941 ] {
942 let hex = digest_hex(algorithm.clone(), raw);
943 let weak = algorithm.is_weak();
944 let checksum = Checksum::new(algorithm, &hex).unwrap();
945 let report = verify_checksums(raw, std::slice::from_ref(&checksum));
946 let default_outcome = if weak {
947 IntegrityOutcome::Weak
948 } else {
949 IntegrityOutcome::Verified
950 };
951 assert_eq!(report.outcome, default_outcome);
952 let allowed = verify_checksums_with_policy(
953 raw,
954 &[checksum],
955 ChecksumPolicy::new().with_allow_weak(true),
956 );
957 assert_eq!(allowed.outcome, IntegrityOutcome::Verified);
958 }
959 }
960
961 #[test]
962 fn multiple_matching_checksums_verify_and_conflict_fails() {
963 let raw = b"multi";
964 let sha = Checksum::new(
965 ChecksumAlgorithm::Sha256,
966 &digest_hex(ChecksumAlgorithm::Sha256, raw),
967 )
968 .unwrap();
969 let blake = Checksum::new(
970 ChecksumAlgorithm::Blake3,
971 &digest_hex(ChecksumAlgorithm::Blake3, raw),
972 )
973 .unwrap();
974 assert_eq!(
975 verify_checksums(raw, &[sha.clone(), blake]).outcome,
976 IntegrityOutcome::Verified
977 );
978 let wrong = Checksum::new(
979 ChecksumAlgorithm::Sha256,
980 "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
981 )
982 .unwrap();
983 assert_eq!(
984 verify_checksums(raw, &[sha, wrong]).outcome,
985 IntegrityOutcome::Failed
986 );
987 }
988
989 #[test]
990 fn incomplete_when_one_matches_and_one_is_unknown() {
991 let raw = b"partial";
992 let sha = Checksum::new(
993 ChecksumAlgorithm::Sha256,
994 &digest_hex(ChecksumAlgorithm::Sha256, raw),
995 )
996 .unwrap();
997 let unknown = Checksum::new(
998 ChecksumAlgorithm::Other("SHA-224".into()),
999 "0000000000000000000000000000000000000000000000000000000000000000",
1000 )
1001 .unwrap();
1002 assert_eq!(
1003 verify_checksums(raw, &[sha, unknown]).outcome,
1004 IntegrityOutcome::Incomplete
1005 );
1006 }
1007
1008 #[test]
1009 fn uppercase_hex_is_rejected_at_construction() {
1010 assert!(Checksum::new(
1011 ChecksumAlgorithm::Sha256,
1012 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
1013 )
1014 .is_err());
1015 }
1016
1017 #[test]
1028 fn independent_known_answer_vectors_for_abc() {
1029 const MSG: &[u8] = b"abc";
1030 let cases: &[(ChecksumAlgorithm, &str)] = &[
1031 (
1032 ChecksumAlgorithm::Sha1,
1033 "a9993e364706816aba3e25717850c26c9cd0d89d",
1034 ),
1035 (
1036 ChecksumAlgorithm::Sha256,
1037 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
1038 ),
1039 (
1040 ChecksumAlgorithm::Sha384,
1041 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
10428086072ba1e7cc2358baeca134c825a7",
1043 ),
1044 (
1045 ChecksumAlgorithm::Sha512,
1046 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
10472192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
1048 ),
1049 (
1050 ChecksumAlgorithm::Sha3_256,
1051 "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532",
1052 ),
1053 (
1054 ChecksumAlgorithm::Sha3_384,
1055 "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b2\
105698d88cea927ac7f539f1edf228376d25",
1057 ),
1058 (
1059 ChecksumAlgorithm::Sha3_512,
1060 "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e\
106110e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0",
1062 ),
1063 (
1064 ChecksumAlgorithm::Blake2b256,
1065 "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319",
1066 ),
1067 (
1068 ChecksumAlgorithm::Blake2b384,
1069 "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6\
1070c66ba83be64b302d7cba6ce15bb556f4",
1071 ),
1072 (
1073 ChecksumAlgorithm::Blake2b512,
1074 "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1\
10757d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923",
1076 ),
1077 (
1078 ChecksumAlgorithm::Blake3,
1079 "6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85",
1080 ),
1081 ];
1082 for (algorithm, expected) in cases {
1083 let expected = expected.replace('\n', "");
1084 assert_eq!(
1085 expected.len(),
1086 algorithm.digest_len().unwrap() * 2,
1087 "{algorithm} digest length"
1088 );
1089 let checksum = Checksum::new(algorithm.clone(), &expected).unwrap();
1090 let report = verify_checksums_with_policy(
1093 MSG,
1094 &[checksum],
1095 ChecksumPolicy::new().with_allow_weak(true),
1096 );
1097 assert_eq!(
1098 report.outcome,
1099 IntegrityOutcome::Verified,
1100 "{algorithm} known-answer failed; actual={:?}",
1101 report.checks[0].actual
1102 );
1103 assert_eq!(report.checks[0].actual.as_deref(), Some(expected.as_str()));
1104
1105 assert!(
1107 Checksum::new(algorithm.clone(), &expected.to_ascii_uppercase()).is_err(),
1108 "{algorithm} must reject uppercase hex"
1109 );
1110 }
1111 }
1112}