diff --git a/crates/iz-web/src/serve.rs b/crates/iz-web/src/serve.rs index e1fe231..548f436 100644 --- a/crates/iz-web/src/serve.rs +++ b/crates/iz-web/src/serve.rs @@ -13,9 +13,11 @@ //! whole file is sent with `200` (RFC 9110 14.2). A valid range that the file cannot satisfy gets `416` with //! `Content-Range: bytes */`. `If-Range` with a validator that is not the current one gets the whole file. //! -//! Integrity: a whole-file (`200`) body is hashed while it streams. When the digest at its end is not the row's -//! `sha256`, the body fails with an error instead of ending cleanly, so the browser reports a failed download, -//! and the log names the attachment id. A range (`206`) is not checked: its bytes cannot be compared with a +//! Integrity: a whole-file (`200`) body is hashed while it streams. The digest is final on the frame that brings +//! the count to the file's size, and it is compared before that frame is sent: a mismatch sends an error in its +//! place, so the body is cut short, the browser reports a failed download, and the log names the attachment id. +//! The check does not wait for the body to end, because a response with `Content-Length` is not polled after +//! its last byte. A range (`206`) is not checked: its bytes cannot be compared with a //! whole-file digest without reading the whole file, which a range request exists to avoid. Ranges are //! therefore served from a file whose whole-file check has not run. A whole-file answer is always checked. @@ -487,15 +489,27 @@ fn checked_body( let frames: BoxStream<'static, io::Result>> = if span.ranged { chunks.map_ok(Frame::data).boxed() } else { - verified(chunks, source.sha256.to_owned(), source.id.to_owned()).boxed() + verified( + chunks, + source.size, + source.sha256.to_owned(), + source.id.to_owned(), + ) + .boxed() }; Body::new(StreamBody::new(frames)) } -/// Hashes the chunks as they go out. The stream ends cleanly only when the digest of every byte equals `expected`. -/// Otherwise its last item is an error, which aborts the body, and the mismatch is logged with the attachment `id`. +/// Hashes the chunks as they go out, for a whole file of `size` bytes whose digest must be `expected`. +/// +/// The frame that brings the count to `size` is checked before it is yielded: on a match it is sent and the +/// stream ends there, without polling the source again; on a mismatch the mismatch is logged with the attachment +/// `id` and an error is sent in place of the frame. More bytes than `size` are an error, and so is a source that +/// ends before `size`. The stream never waits for an end-of-stream to decide the digest, because a +/// `Content-Length` body is not polled after its last byte. fn verified( chunks: BoxStream<'static, io::Result>, + size: u64, expected: String, id: String, ) -> impl Stream>> + Send + 'static { @@ -503,6 +517,8 @@ fn verified( struct Check { chunks: BoxStream<'static, io::Result>, hasher: Sha256, + size: u64, + seen: u64, expected: String, id: String, } @@ -510,6 +526,8 @@ fn verified( Some(Check { chunks, hasher: Sha256::new(), + size, + seen: 0, expected, id, }), @@ -517,31 +535,62 @@ fn verified( let mut check = state?; match check.chunks.next().await { Some(Ok(chunk)) => { + check.seen += chunk.len() as u64; + if check.seen > check.size { + return Some(( + Err(io::Error::new( + io::ErrorKind::InvalidData, + "the bytes are longer than the recorded size", + )), + None, + )); + } check.hasher.update(&chunk); - Some((Ok(Frame::data(chunk)), Some(check))) + if check.seen < check.size { + return Some((Ok(Frame::data(chunk)), Some(check))); + } + if hex::encode(check.hasher.finalize()) == check.expected { + // The last frame: the state is `None`, so the source is never polled again. + Some((Ok(Frame::data(chunk)), None)) + } else { + Some((Err(digest_mismatch(&check.id)), None)) + } } Some(Err(error)) => Some((Err(error), None)), None => { + // Reached only for an empty file, or a source that ended before `size`. + if check.seen != check.size { + return Some(( + Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the bytes are shorter than the recorded size", + )), + None, + )); + } if hex::encode(check.hasher.finalize()) == check.expected { return None; } - tracing::error!( - attachment = %check.id, - "the bytes of an attachment do not match its sha256; the download is aborted" - ); - Some(( - Err(io::Error::new( - io::ErrorKind::InvalidData, - "the bytes do not match the recorded sha256", - )), - None, - )) + Some((Err(digest_mismatch(&check.id)), None)) } } }, ) } +/// The error that cuts a whole-file body short when its bytes do not match the row's digest. It logs the +/// attachment `id`, so the operator can find the row; the browser sees a failed download. +fn digest_mismatch(id: &str) -> io::Error { + tracing::error!( + attachment = %id, + "the bytes of an attachment do not match its sha256; the download is aborted" + ); + io::Error::new( + io::ErrorKind::InvalidData, + "the bytes do not match the recorded sha256", + ) +} + /// Opens `path`, seeks to the span's start and yields the span's bytes in pieces of [`FRAME_BYTES`]. The open is /// the error that matters: a file that is not there is `NotFound`. async fn open_streamed( @@ -756,11 +805,30 @@ mod tests { assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data); } - /// A whole-file answer is verified: the right digest sends every byte, a wrong one fails the body at its end. + /// Reads a body the way the HTTP layer reads a `Content-Length` answer: frames are polled until `size` bytes + /// have arrived, and the body is never polled again, so its end is never asked for. + async fn read_content_length(mut body: Body, size: usize) -> Result, String> { + use http_body_util::BodyExt; + + let mut out = Vec::new(); + while out.len() < size { + match body.frame().await { + Some(Ok(frame)) => { + if let Ok(data) = frame.into_data() { + out.extend_from_slice(&data); + } + } + Some(Err(error)) => return Err(error.to_string()), + None => return Err("the body ended early".into()), + } + } + Ok(out) + } + + /// A whole-file answer is checked before its last frame: the right digest sends every byte, a wrong one + /// sends an error in place of the frame, so the body is cut short. Nothing waits for the end of the body. #[tokio::test] async fn a_whole_file_is_ended_only_when_its_digest_matches() { - use topcoat::router::to_bytes; - let dir = tempfile::tempdir().expect("temp dir"); let path = dir.path().join("blob"); std::fs::write(&path, b"hello world").expect("bytes"); @@ -780,7 +848,7 @@ mod tests { .expect("answer"); assert_eq!(status, StatusCode::OK); assert_eq!( - to_bytes(body, 1024).await.expect("body").as_ref(), + read_content_length(body, 11).await.expect("bytes"), b"hello world" ); @@ -794,8 +862,8 @@ mod tests { .expect("answer"); assert_eq!(status, StatusCode::OK); assert!( - to_bytes(body, 1024).await.is_err(), - "a mismatch aborts the body" + read_content_length(body, 11).await.is_err(), + "a mismatch aborts the body before its last byte" ); } }