forge
Explore
Log in

Don't you dare go Hollow

Download digest compared on the last byte, so Content-Length bodies are checked

Browse files at this commit

0307c6baea87f36d50e82fb3963cea7843106d3bAhmet Kaan GümüşParent: 31dcd14
  • fix
    • download digest compared on the last byte, so Content-Length bodies are checked
Show full message
🐛 fix: download digest compared on the last byte, so Content-Length bodies are checked
crates/iz-web/src/serve.rsmodified+92 -24
@@ -13,9 +13,11 @@
13 //! whole file is sent with `200` (RFC 9110 14.2). A valid range that the file cannot satisfy gets `416` with13 //! whole file is sent with `200` (RFC 9110 14.2). A valid range that the file cannot satisfy gets `416` with
14 //! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole file.14 //! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole file.
15 //!15 //!
16-//! Integrity: a whole-file (`200`) body is hashed while it streams. When the digest at its end is not the row's16+//! Integrity: a whole-file (`200`) body is hashed while it streams. The digest is final on the frame that brings
17-//! `sha256`, the body fails with an error instead of ending cleanly, so the browser reports a failed download,17+//! the count to the file's size, and it is compared before that frame is sent: a mismatch sends an error in its
18-//! and the log names the attachment id. A range (`206`) is not checked: its bytes cannot be compared with a18+//! place, so the body is cut short, the browser reports a failed download, and the log names the attachment id.
19+//! The check does not wait for the body to end, because a response with `Content-Length` is not polled after
20+//! its last byte. A range (`206`) is not checked: its bytes cannot be compared with a
19 //! whole-file digest without reading the whole file, which a range request exists to avoid. Ranges are21 //! whole-file digest without reading the whole file, which a range request exists to avoid. Ranges are
20 //! therefore served from a file whose whole-file check has not run. A whole-file answer is always checked.22 //! therefore served from a file whose whole-file check has not run. A whole-file answer is always checked.
21 23
@@ -487,15 +489,27 @@ fn checked_body(
487 let frames: BoxStream<'static, io::Result<Frame<Bytes>>> = if span.ranged {489 let frames: BoxStream<'static, io::Result<Frame<Bytes>>> = if span.ranged {
488 chunks.map_ok(Frame::data).boxed()490 chunks.map_ok(Frame::data).boxed()
489 } else {491 } else {
490- verified(chunks, source.sha256.to_owned(), source.id.to_owned()).boxed()492+ verified(
493+ chunks,
494+ source.size,
495+ source.sha256.to_owned(),
496+ source.id.to_owned(),
497+ )
498+ .boxed()
491 };499 };
492 Body::new(StreamBody::new(frames))500 Body::new(StreamBody::new(frames))
493 }501 }
494 502
495-/// Hashes the chunks as they go out. The stream ends cleanly only when the digest of every byte equals `expected`.503+/// Hashes the chunks as they go out, for a whole file of `size` bytes whose digest must be `expected`.
496-/// Otherwise its last item is an error, which aborts the body, and the mismatch is logged with the attachment `id`.504+///
505+/// The frame that brings the count to `size` is checked before it is yielded: on a match it is sent and the
506+/// stream ends there, without polling the source again; on a mismatch the mismatch is logged with the attachment
507+/// `id` and an error is sent in place of the frame. More bytes than `size` are an error, and so is a source that
508+/// ends before `size`. The stream never waits for an end-of-stream to decide the digest, because a
509+/// `Content-Length` body is not polled after its last byte.
497 fn verified(510 fn verified(
498 chunks: BoxStream<'static, io::Result<Bytes>>,511 chunks: BoxStream<'static, io::Result<Bytes>>,
512+ size: u64,
499 expected: String,513 expected: String,
500 id: String,514 id: String,
501 ) -> impl Stream<Item = io::Result<Frame<Bytes>>> + Send + 'static {515 ) -> impl Stream<Item = io::Result<Frame<Bytes>>> + Send + 'static {
@@ -503,6 +517,8 @@ fn verified(
503 struct Check {517 struct Check {
504 chunks: BoxStream<'static, io::Result<Bytes>>,518 chunks: BoxStream<'static, io::Result<Bytes>>,
505 hasher: Sha256,519 hasher: Sha256,
520+ size: u64,
521+ seen: u64,
506 expected: String,522 expected: String,
507 id: String,523 id: String,
508 }524 }
@@ -510,6 +526,8 @@ fn verified(
510 Some(Check {526 Some(Check {
511 chunks,527 chunks,
512 hasher: Sha256::new(),528 hasher: Sha256::new(),
529+ size,
530+ seen: 0,
513 expected,531 expected,
514 id,532 id,
515 }),533 }),
@@ -517,31 +535,62 @@ fn verified(
517 let mut check = state?;535 let mut check = state?;
518 match check.chunks.next().await {536 match check.chunks.next().await {
519 Some(Ok(chunk)) => {537 Some(Ok(chunk)) => {
538+ check.seen += chunk.len() as u64;
539+ if check.seen > check.size {
540+ return Some((
541+ Err(io::Error::new(
542+ io::ErrorKind::InvalidData,
543+ "the bytes are longer than the recorded size",
544+ )),
545+ None,
546+ ));
547+ }
520 check.hasher.update(&chunk);548 check.hasher.update(&chunk);
521- Some((Ok(Frame::data(chunk)), Some(check)))549+ if check.seen < check.size {
550+ return Some((Ok(Frame::data(chunk)), Some(check)));
551+ }
552+ if hex::encode(check.hasher.finalize()) == check.expected {
553+ // The last frame: the state is `None`, so the source is never polled again.
554+ Some((Ok(Frame::data(chunk)), None))
555+ } else {
556+ Some((Err(digest_mismatch(&check.id)), None))
557+ }
522 }558 }
523 Some(Err(error)) => Some((Err(error), None)),559 Some(Err(error)) => Some((Err(error), None)),
524 None => {560 None => {
561+ // Reached only for an empty file, or a source that ended before `size`.
562+ if check.seen != check.size {
563+ return Some((
564+ Err(io::Error::new(
565+ io::ErrorKind::UnexpectedEof,
566+ "the bytes are shorter than the recorded size",
567+ )),
568+ None,
569+ ));
570+ }
525 if hex::encode(check.hasher.finalize()) == check.expected {571 if hex::encode(check.hasher.finalize()) == check.expected {
526 return None;572 return None;
527 }573 }
528- tracing::error!(574+ Some((Err(digest_mismatch(&check.id)), None))
529- attachment = %check.id,
530- "the bytes of an attachment do not match its sha256; the download is aborted"
531- );
532- Some((
533- Err(io::Error::new(
534- io::ErrorKind::InvalidData,
535- "the bytes do not match the recorded sha256",
536- )),
537- None,
538- ))
539 }575 }
540 }576 }
541 },577 },
542 )578 )
543 }579 }
544 580
581+/// The error that cuts a whole-file body short when its bytes do not match the row's digest. It logs the
582+/// attachment `id`, so the operator can find the row; the browser sees a failed download.
583+fn digest_mismatch(id: &str) -> io::Error {
584+ tracing::error!(
585+ attachment = %id,
586+ "the bytes of an attachment do not match its sha256; the download is aborted"
587+ );
588+ io::Error::new(
589+ io::ErrorKind::InvalidData,
590+ "the bytes do not match the recorded sha256",
591+ )
592+}
593+
545 /// Opens `path`, seeks to the span's start and yields the span's bytes in pieces of [`FRAME_BYTES`]. The open is594 /// Opens `path`, seeks to the span's start and yields the span's bytes in pieces of [`FRAME_BYTES`]. The open is
546 /// the error that matters: a file that is not there is `NotFound`.595 /// the error that matters: a file that is not there is `NotFound`.
547 async fn open_streamed(596 async fn open_streamed(
@@ -756,11 +805,30 @@ mod tests {
756 assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data);805 assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data);
757 }806 }
758 807
759- /// A whole-file answer is verified: the right digest sends every byte, a wrong one fails the body at its end.808+ /// Reads a body the way the HTTP layer reads a `Content-Length` answer: frames are polled until `size` bytes
809+ /// have arrived, and the body is never polled again, so its end is never asked for.
810+ async fn read_content_length(mut body: Body, size: usize) -> Result<Vec<u8>, String> {
811+ use http_body_util::BodyExt;
812+
813+ let mut out = Vec::new();
814+ while out.len() < size {
815+ match body.frame().await {
816+ Some(Ok(frame)) => {
817+ if let Ok(data) = frame.into_data() {
818+ out.extend_from_slice(&data);
819+ }
820+ }
821+ Some(Err(error)) => return Err(error.to_string()),
822+ None => return Err("the body ended early".into()),
823+ }
824+ }
825+ Ok(out)
826+ }
827+
828+ /// A whole-file answer is checked before its last frame: the right digest sends every byte, a wrong one
829+ /// sends an error in place of the frame, so the body is cut short. Nothing waits for the end of the body.
760 #[tokio::test]830 #[tokio::test]
761 async fn a_whole_file_is_ended_only_when_its_digest_matches() {831 async fn a_whole_file_is_ended_only_when_its_digest_matches() {
762- use topcoat::router::to_bytes;
763-
764 let dir = tempfile::tempdir().expect("temp dir");832 let dir = tempfile::tempdir().expect("temp dir");
765 let path = dir.path().join("blob");833 let path = dir.path().join("blob");
766 std::fs::write(&path, b"hello world").expect("bytes");834 std::fs::write(&path, b"hello world").expect("bytes");
@@ -780,7 +848,7 @@ mod tests {
780 .expect("answer");848 .expect("answer");
781 assert_eq!(status, StatusCode::OK);849 assert_eq!(status, StatusCode::OK);
782 assert_eq!(850 assert_eq!(
783- to_bytes(body, 1024).await.expect("body").as_ref(),851+ read_content_length(body, 11).await.expect("bytes"),
784 b"hello world"852 b"hello world"
785 );853 );
786 854
@@ -794,8 +862,8 @@ mod tests {
794 .expect("answer");862 .expect("answer");
795 assert_eq!(status, StatusCode::OK);863 assert_eq!(status, StatusCode::OK);
796 assert!(864 assert!(
797- to_bytes(body, 1024).await.is_err(),865+ read_content_length(body, 11).await.is_err(),
798- "a mismatch aborts the body"866+ "a mismatch aborts the body before its last byte"
799 );867 );
800 }868 }
801 }869 }