Full downloads are hashed while streaming and abort on a sha256 mismatch
Browse files at this commit5e60f59357d9657c0db35380aa6bf58bd10e013eParent: ecfdd29- fix
- full downloads are hashed while streaming and abort on a sha256 mismatch
6 changed files +97 -5
- crates/in-core/src/blob/mod.rs +73 -4
- crates/in-web/src/api/objects.rs +1 -0
- crates/in-web/src/pages/files.rs +1 -0
- crates/in-web/src/pages/public_share.rs +4 -0
- crates/in-web/src/pages/thumbs.rs +3 -0
- crates/in-web/src/serve_bytes.rs +15 -1
crates/in-core/src/blob/mod.rsmodified+73 -4
| @@ -14,7 +14,8 @@ use std::time::SystemTime; | |||
| 14 | 14 | ||
| 15 | use async_trait::async_trait; | 15 | use async_trait::async_trait; |
| 16 | use bytes::Bytes; | 16 | use bytes::Bytes; |
| 17 | -use futures_util::Stream; | 17 | +use futures_util::{Stream, StreamExt, stream}; |
| 18 | +use sha2::{Digest, Sha256}; | ||
| 18 | 19 | ||
| 19 | use crate::error::{Error, Result}; | 20 | use crate::error::{Error, Result}; |
| 20 | 21 | ||
| @@ -76,9 +77,6 @@ pub fn validate_key(key: &str) -> Result<()> { | |||
| 76 | /// The size and lower-case hex SHA-256 of the blob at `key`, read frame by frame. `None` when the key is | 77 | /// The size and lower-case hex SHA-256 of the blob at `key`, read frame by frame. `None` when the key is |
| 77 | /// absent. Used by `fsck`, the backup manifest and the export, so no caller buffers a whole file. | 78 | /// absent. Used by `fsck`, the backup manifest and the export, so no caller buffers a whole file. |
| 78 | pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result<Option<(u64, String)>> { | 79 | pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result<Option<(u64, String)>> { |
| 79 | - use futures_util::StreamExt; | ||
| 80 | - use sha2::{Digest, Sha256}; | ||
| 81 | - | ||
| 82 | let Some(size) = blobs.size(key).await? else { | 80 | let Some(size) = blobs.size(key).await? else { |
| 83 | return Ok(None); | 81 | return Ok(None); |
| 84 | }; | 82 | }; |
| @@ -99,6 +97,57 @@ pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result<Option<(u64, Str | |||
| 99 | Ok(Some((size, hex::encode(hasher.finalize())))) | 97 | Ok(Some((size, hex::encode(hasher.finalize())))) |
| 100 | } | 98 | } |
| 101 | 99 | ||
| 100 | +/// Checks a whole-blob stream against the lowercase hex SHA-256 its row names. Every frame passes through | ||
| 101 | +/// unchanged and is hashed on the way, so no extra buffer is kept. When the stream ends with the hash equal | ||
| 102 | +/// to `sha256`, it ends cleanly. When the hash differs, the stream yields one `InvalidData` error and then | ||
| 103 | +/// ends, so the HTTP body is aborted and the client does not take the bad bytes for a complete file. The | ||
| 104 | +/// mismatch is logged with the blob key, which is what `in fsck --hash` needs to find the blob. | ||
| 105 | +/// | ||
| 106 | +/// Only whole-blob streams can be checked: a range is a part of the file and has no hash to compare with. | ||
| 107 | +/// A short read is already an error from the backend (`UnexpectedEof`), so a length change is caught there. | ||
| 108 | +pub fn check_digest(stream: BlobStream, key: &str, sha256: &str) -> BlobStream { | ||
| 109 | + struct Checking { | ||
| 110 | + stream: BlobStream, | ||
| 111 | + hasher: Sha256, | ||
| 112 | + key: String, | ||
| 113 | + expected: String, | ||
| 114 | + } | ||
| 115 | + Box::pin(stream::unfold( | ||
| 116 | + Some(Checking { | ||
| 117 | + stream, | ||
| 118 | + hasher: Sha256::new(), | ||
| 119 | + key: key.to_string(), | ||
| 120 | + expected: sha256.to_string(), | ||
| 121 | + }), | ||
| 122 | + |state| async move { | ||
| 123 | + let mut state = state?; | ||
| 124 | + match state.stream.next().await { | ||
| 125 | + Some(Ok(frame)) => { | ||
| 126 | + state.hasher.update(&frame); | ||
| 127 | + Some((Ok(frame), Some(state))) | ||
| 128 | + } | ||
| 129 | + Some(Err(e)) => Some((Err(e), None)), | ||
| 130 | + None => { | ||
| 131 | + if hex::encode(state.hasher.finalize()) == state.expected { | ||
| 132 | + return None; | ||
| 133 | + } | ||
| 134 | + tracing::error!( | ||
| 135 | + blob_key = %state.key, | ||
| 136 | + "blob bytes do not match the sha256 of their row; run `in fsck --hash`" | ||
| 137 | + ); | ||
| 138 | + Some(( | ||
| 139 | + Err(Error::Io(std::io::Error::new( | ||
| 140 | + std::io::ErrorKind::InvalidData, | ||
| 141 | + "blob does not match its sha256", | ||
| 142 | + ))), | ||
| 143 | + None, | ||
| 144 | + )) | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + }, | ||
| 148 | + )) | ||
| 149 | +} | ||
| 150 | + | ||
| 102 | /// Splits a buffer into frames of at most [`FRAME_BYTES`]. Shared by both backends. | 151 | /// Splits a buffer into frames of at most [`FRAME_BYTES`]. Shared by both backends. |
| 103 | pub(crate) fn frames(bytes: Bytes) -> impl Iterator<Item = Bytes> { | 152 | pub(crate) fn frames(bytes: Bytes) -> impl Iterator<Item = Bytes> { |
| 104 | (0..bytes.len()) | 153 | (0..bytes.len()) |
| @@ -133,6 +182,26 @@ mod tests { | |||
| 133 | } | 182 | } |
| 134 | } | 183 | } |
| 135 | 184 | ||
| 185 | + #[tokio::test] | ||
| 186 | + async fn a_blob_changed_on_disk_with_the_same_length_ends_the_stream_with_an_error() { | ||
| 187 | + let dir = tempfile::tempdir().unwrap(); | ||
| 188 | + let blobs = local::LocalBlobs::new(dir.path().join("blobs")).unwrap(); | ||
| 189 | + let src = dir.path().join("staged.bin"); | ||
| 190 | + std::fs::write(&src, b"hello world").unwrap(); | ||
| 191 | + let sha = hex::encode(Sha256::digest(b"hello world")); | ||
| 192 | + blobs.put_file("files/ab/abcd", &src).await.unwrap(); | ||
| 193 | + // Same length, different bytes: what disk corruption or tampering looks like. | ||
| 194 | + std::fs::write(dir.path().join("blobs/files/ab/abcd"), b"hello_world").unwrap(); | ||
| 195 | + | ||
| 196 | + let stream = blobs.open_range("files/ab/abcd", 0, 11).await.unwrap(); | ||
| 197 | + let items: Vec<Result<Bytes>> = check_digest(stream, "files/ab/abcd", &sha).collect().await; | ||
| 198 | + assert!( | ||
| 199 | + matches!(items.last(), Some(Err(_))), | ||
| 200 | + "the body must end with an error" | ||
| 201 | + ); | ||
| 202 | + assert_eq!(items.iter().filter(|item| item.is_err()).count(), 1); | ||
| 203 | + } | ||
| 204 | + | ||
| 136 | #[test] | 205 | #[test] |
| 137 | fn frames_cover_the_whole_buffer_in_bounded_pieces() { | 206 | fn frames_cover_the_whole_buffer_in_bounded_pieces() { |
| 138 | let data = Bytes::from(vec![7u8; FRAME_BYTES * 2 + 5]); | 207 | let data = Bytes::from(vec![7u8; FRAME_BYTES * 2 + 5]); |
crates/in-web/src/api/objects.rsmodified+1 -0
| @@ -356,6 +356,7 @@ async fn get_object(cx: &Cx) -> Result<Response> { | |||
| 356 | blob_key: &object.blob_key, | 356 | blob_key: &object.blob_key, |
| 357 | size: object.size as u64, | 357 | size: object.size as u64, |
| 358 | sha256: &object.sha256, | 358 | sha256: &object.sha256, |
| 359 | + content_sha256: Some(&object.sha256), | ||
| 359 | mime: &object.content_type, | 360 | mime: &object.content_type, |
| 360 | name: &name, | 361 | name: &name, |
| 361 | }; | 362 | }; |
crates/in-web/src/pages/files.rsmodified+1 -0
| @@ -272,6 +272,7 @@ async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> { | |||
| 272 | blob_key: &file.blob_key, | 272 | blob_key: &file.blob_key, |
| 273 | size, | 273 | size, |
| 274 | sha256: &file.sha256, | 274 | sha256: &file.sha256, |
| 275 | + content_sha256: Some(&file.sha256), | ||
| 275 | mime: &file.mime, | 276 | mime: &file.mime, |
| 276 | name: &file.name, | 277 | name: &file.name, |
| 277 | }; | 278 | }; |
crates/in-web/src/pages/public_share.rsmodified+4 -0
| @@ -533,6 +533,7 @@ async fn public_file_bytes(cx: &Cx) -> Result<ByteAnswer> { | |||
| 533 | blob_key: &file.blob_key, | 533 | blob_key: &file.blob_key, |
| 534 | size, | 534 | size, |
| 535 | sha256: &file.sha256, | 535 | sha256: &file.sha256, |
| 536 | + content_sha256: Some(&file.sha256), | ||
| 536 | mime: &file.mime, | 537 | mime: &file.mime, |
| 537 | name: &file.name, | 538 | name: &file.name, |
| 538 | }; | 539 | }; |
| @@ -559,11 +560,14 @@ async fn public_thumb(cx: &Cx) -> Result<ByteAnswer> { | |||
| 559 | } | 560 | } |
| 560 | let key = thumb_blob_key(&file.id); | 561 | let key = thumb_blob_key(&file.id); |
| 561 | let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; | 562 | let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; |
| 563 | + // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so | ||
| 564 | + // the thumbnail body is not checked. | ||
| 562 | let validator = thumb_validator(&file.sha256); | 565 | let validator = thumb_validator(&file.sha256); |
| 563 | let source = ByteSource { | 566 | let source = ByteSource { |
| 564 | blob_key: &key, | 567 | blob_key: &key, |
| 565 | size, | 568 | size, |
| 566 | sha256: &validator, | 569 | sha256: &validator, |
| 570 | + content_sha256: None, | ||
| 567 | mime: "image/webp", | 571 | mime: "image/webp", |
| 568 | name: &file.name, | 572 | name: &file.name, |
| 569 | }; | 573 | }; |
crates/in-web/src/pages/thumbs.rsmodified+3 -0
| @@ -39,10 +39,13 @@ async fn thumb(cx: &Cx) -> Result<ByteAnswer> { | |||
| 39 | let key = thumb_blob_key(&file.id); | 39 | let key = thumb_blob_key(&file.id); |
| 40 | let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; | 40 | let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; |
| 41 | let validator = thumb_validator(&file.sha256); | 41 | let validator = thumb_validator(&file.sha256); |
| 42 | + // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so | ||
| 43 | + // the thumbnail body is not checked. | ||
| 42 | let source = ByteSource { | 44 | let source = ByteSource { |
| 43 | blob_key: &key, | 45 | blob_key: &key, |
| 44 | size, | 46 | size, |
| 45 | sha256: &validator, | 47 | sha256: &validator, |
| 48 | + content_sha256: None, | ||
| 46 | mime: "image/webp", | 49 | mime: "image/webp", |
| 47 | name: &file.name, | 50 | name: &file.name, |
| 48 | }; | 51 | }; |
crates/in-web/src/serve_bytes.rsmodified+15 -1
| @@ -8,6 +8,11 @@ | |||
| 8 | //! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of | 8 | //! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of |
| 9 | //! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole. | 9 | //! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole. |
| 10 | //! | 10 | //! |
| 11 | +//! Integrity rules: a full-body answer is hashed while it streams and aborted when the hash does not match | ||
| 12 | +//! the row (a changed blob, which the `ETag` would otherwise hide). A range answer is not checked: it is a | ||
| 13 | +//! part of the file, and a partial read cannot be compared with the whole-file hash. `in fsck --hash` | ||
| 14 | +//! checks every blob in full. | ||
| 15 | +//! | ||
| 11 | //! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the | 16 | //! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the |
| 12 | //! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with | 17 | //! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with |
| 13 | //! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole | 18 | //! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole |
| @@ -21,7 +26,7 @@ use http::header::{ | |||
| 21 | }; | 26 | }; |
| 22 | use http_body::Frame; | 27 | use http_body::Frame; |
| 23 | use http_body_util::StreamBody; | 28 | use http_body_util::StreamBody; |
| 24 | -use in_core::blob::BlobStore; | 29 | +use in_core::blob::{BlobStore, check_digest}; |
| 25 | use topcoat::Result; | 30 | use topcoat::Result; |
| 26 | use topcoat::context::Cx; | 31 | use topcoat::context::Cx; |
| 27 | use topcoat::router::request::headers; | 32 | use topcoat::router::request::headers; |
| @@ -45,6 +50,10 @@ pub struct ByteSource<'a> { | |||
| 45 | pub size: u64, | 50 | pub size: u64, |
| 46 | /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes. | 51 | /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes. |
| 47 | pub sha256: &'a str, | 52 | pub sha256: &'a str, |
| 53 | + /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer | ||
| 54 | + /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as | ||
| 55 | + /// thumbnails, whose `sha256` is a validator and not the hash of what is stored. | ||
| 56 | + pub content_sha256: Option<&'a str>, | ||
| 48 | /// The sniffed MIME type, as stored. It is never the uploader's claim. | 57 | /// The sniffed MIME type, as stored. It is never the uploader's claim. |
| 49 | pub mime: &'a str, | 58 | pub mime: &'a str, |
| 50 | /// The display name, used for the `Content-Disposition` file name. | 59 | /// The display name, used for the `Content-Disposition` file name. |
| @@ -360,6 +369,10 @@ pub async fn serve_bytes_with( | |||
| 360 | &source.size.to_string(), | 369 | &source.size.to_string(), |
| 361 | ); | 370 | ); |
| 362 | let stream = blobs.open_range(source.blob_key, 0, source.size).await?; | 371 | let stream = blobs.open_range(source.blob_key, 0, source.size).await?; |
| 372 | + let stream = match source.content_sha256 { | ||
| 373 | + Some(sha256) => check_digest(stream, source.blob_key, sha256), | ||
| 374 | + None => stream, | ||
| 375 | + }; | ||
| 363 | Ok((StatusCode::OK, answer_headers, streamed(stream))) | 376 | Ok((StatusCode::OK, answer_headers, streamed(stream))) |
| 364 | } | 377 | } |
| 365 | Ranged::Part { start, end } => { | 378 | Ranged::Part { start, end } => { |
| @@ -370,6 +383,7 @@ pub async fn serve_bytes_with( | |||
| 370 | CONTENT_RANGE, | 383 | CONTENT_RANGE, |
| 371 | &format!("bytes {start}-{end}/{}", source.size), | 384 | &format!("bytes {start}-{end}/{}", source.size), |
| 372 | ); | 385 | ); |
| 386 | + // Not checked: this is a part of the file, so its bytes have no hash to compare with here. | ||
| 373 | let stream = blobs.open_range(source.blob_key, start, length).await?; | 387 | let stream = blobs.open_range(source.blob_key, start, length).await?; |
| 374 | Ok(( | 388 | Ok(( |
| 375 | StatusCode::PARTIAL_CONTENT, | 389 | StatusCode::PARTIAL_CONTENT, |