diff --git a/crates/in-core/src/blob/mod.rs b/crates/in-core/src/blob/mod.rs
index 610e7ec..054c7a2 100644
--- a/crates/in-core/src/blob/mod.rs
+++ b/crates/in-core/src/blob/mod.rs
@@ -14,7 +14,8 @@ use std::time::SystemTime;
use async_trait::async_trait;
use bytes::Bytes;
-use futures_util::Stream;
+use futures_util::{Stream, StreamExt, stream};
+use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
@@ -76,9 +77,6 @@ pub fn validate_key(key: &str) -> Result<()> {
/// The size and lower-case hex SHA-256 of the blob at `key`, read frame by frame. `None` when the key is
/// absent. Used by `fsck`, the backup manifest and the export, so no caller buffers a whole file.
pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result> {
- use futures_util::StreamExt;
- use sha2::{Digest, Sha256};
-
let Some(size) = blobs.size(key).await? else {
return Ok(None);
};
@@ -99,6 +97,57 @@ pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result BlobStream {
+ struct Checking {
+ stream: BlobStream,
+ hasher: Sha256,
+ key: String,
+ expected: String,
+ }
+ Box::pin(stream::unfold(
+ Some(Checking {
+ stream,
+ hasher: Sha256::new(),
+ key: key.to_string(),
+ expected: sha256.to_string(),
+ }),
+ |state| async move {
+ let mut state = state?;
+ match state.stream.next().await {
+ Some(Ok(frame)) => {
+ state.hasher.update(&frame);
+ Some((Ok(frame), Some(state)))
+ }
+ Some(Err(e)) => Some((Err(e), None)),
+ None => {
+ if hex::encode(state.hasher.finalize()) == state.expected {
+ return None;
+ }
+ tracing::error!(
+ blob_key = %state.key,
+ "blob bytes do not match the sha256 of their row; run `in fsck --hash`"
+ );
+ Some((
+ Err(Error::Io(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ "blob does not match its sha256",
+ ))),
+ None,
+ ))
+ }
+ }
+ },
+ ))
+}
+
/// Splits a buffer into frames of at most [`FRAME_BYTES`]. Shared by both backends.
pub(crate) fn frames(bytes: Bytes) -> impl Iterator- {
(0..bytes.len())
@@ -133,6 +182,26 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn a_blob_changed_on_disk_with_the_same_length_ends_the_stream_with_an_error() {
+ let dir = tempfile::tempdir().unwrap();
+ let blobs = local::LocalBlobs::new(dir.path().join("blobs")).unwrap();
+ let src = dir.path().join("staged.bin");
+ std::fs::write(&src, b"hello world").unwrap();
+ let sha = hex::encode(Sha256::digest(b"hello world"));
+ blobs.put_file("files/ab/abcd", &src).await.unwrap();
+ // Same length, different bytes: what disk corruption or tampering looks like.
+ std::fs::write(dir.path().join("blobs/files/ab/abcd"), b"hello_world").unwrap();
+
+ let stream = blobs.open_range("files/ab/abcd", 0, 11).await.unwrap();
+ let items: Vec
> = check_digest(stream, "files/ab/abcd", &sha).collect().await;
+ assert!(
+ matches!(items.last(), Some(Err(_))),
+ "the body must end with an error"
+ );
+ assert_eq!(items.iter().filter(|item| item.is_err()).count(), 1);
+ }
+
#[test]
fn frames_cover_the_whole_buffer_in_bounded_pieces() {
let data = Bytes::from(vec![7u8; FRAME_BYTES * 2 + 5]);
diff --git a/crates/in-web/src/api/objects.rs b/crates/in-web/src/api/objects.rs
index 730cd1d..a46d58e 100644
--- a/crates/in-web/src/api/objects.rs
+++ b/crates/in-web/src/api/objects.rs
@@ -356,6 +356,7 @@ async fn get_object(cx: &Cx) -> Result {
blob_key: &object.blob_key,
size: object.size as u64,
sha256: &object.sha256,
+ content_sha256: Some(&object.sha256),
mime: &object.content_type,
name: &name,
};
diff --git a/crates/in-web/src/pages/files.rs b/crates/in-web/src/pages/files.rs
index aa21561..5f493ed 100644
--- a/crates/in-web/src/pages/files.rs
+++ b/crates/in-web/src/pages/files.rs
@@ -272,6 +272,7 @@ async fn file_bytes(cx: &Cx) -> Result {
blob_key: &file.blob_key,
size,
sha256: &file.sha256,
+ content_sha256: Some(&file.sha256),
mime: &file.mime,
name: &file.name,
};
diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs
index bb20ed9..55612ad 100644
--- a/crates/in-web/src/pages/public_share.rs
+++ b/crates/in-web/src/pages/public_share.rs
@@ -533,6 +533,7 @@ async fn public_file_bytes(cx: &Cx) -> Result {
blob_key: &file.blob_key,
size,
sha256: &file.sha256,
+ content_sha256: Some(&file.sha256),
mime: &file.mime,
name: &file.name,
};
@@ -559,11 +560,14 @@ async fn public_thumb(cx: &Cx) -> Result {
}
let key = thumb_blob_key(&file.id);
let size = state.blobs.size(&key).await?.ok_or_else(not_found)?;
+ // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so
+ // the thumbnail body is not checked.
let validator = thumb_validator(&file.sha256);
let source = ByteSource {
blob_key: &key,
size,
sha256: &validator,
+ content_sha256: None,
mime: "image/webp",
name: &file.name,
};
diff --git a/crates/in-web/src/pages/thumbs.rs b/crates/in-web/src/pages/thumbs.rs
index 41bc37e..56a4329 100644
--- a/crates/in-web/src/pages/thumbs.rs
+++ b/crates/in-web/src/pages/thumbs.rs
@@ -39,10 +39,13 @@ async fn thumb(cx: &Cx) -> Result {
let key = thumb_blob_key(&file.id);
let size = state.blobs.size(&key).await?.ok_or_else(not_found)?;
let validator = thumb_validator(&file.sha256);
+ // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so
+ // the thumbnail body is not checked.
let source = ByteSource {
blob_key: &key,
size,
sha256: &validator,
+ content_sha256: None,
mime: "image/webp",
name: &file.name,
};
diff --git a/crates/in-web/src/serve_bytes.rs b/crates/in-web/src/serve_bytes.rs
index 924fd98..485649e 100644
--- a/crates/in-web/src/serve_bytes.rs
+++ b/crates/in-web/src/serve_bytes.rs
@@ -8,6 +8,11 @@
//! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of
//! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole.
//!
+//! Integrity rules: a full-body answer is hashed while it streams and aborted when the hash does not match
+//! the row (a changed blob, which the `ETag` would otherwise hide). A range answer is not checked: it is a
+//! part of the file, and a partial read cannot be compared with the whole-file hash. `in fsck --hash`
+//! checks every blob in full.
+//!
//! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the
//! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with
//! `Content-Range: bytes */`. `If-Range` with a validator that is not the current one gets the whole
@@ -21,7 +26,7 @@ use http::header::{
};
use http_body::Frame;
use http_body_util::StreamBody;
-use in_core::blob::BlobStore;
+use in_core::blob::{BlobStore, check_digest};
use topcoat::Result;
use topcoat::context::Cx;
use topcoat::router::request::headers;
@@ -45,6 +50,10 @@ pub struct ByteSource<'a> {
pub size: u64,
/// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes.
pub sha256: &'a str,
+ /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer
+ /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as
+ /// thumbnails, whose `sha256` is a validator and not the hash of what is stored.
+ pub content_sha256: Option<&'a str>,
/// The sniffed MIME type, as stored. It is never the uploader's claim.
pub mime: &'a str,
/// The display name, used for the `Content-Disposition` file name.
@@ -360,6 +369,10 @@ pub async fn serve_bytes_with(
&source.size.to_string(),
);
let stream = blobs.open_range(source.blob_key, 0, source.size).await?;
+ let stream = match source.content_sha256 {
+ Some(sha256) => check_digest(stream, source.blob_key, sha256),
+ None => stream,
+ };
Ok((StatusCode::OK, answer_headers, streamed(stream)))
}
Ranged::Part { start, end } => {
@@ -370,6 +383,7 @@ pub async fn serve_bytes_with(
CONTENT_RANGE,
&format!("bytes {start}-{end}/{}", source.size),
);
+ // Not checked: this is a part of the file, so its bytes have no hash to compare with here.
let stream = blobs.open_range(source.blob_key, start, length).await?;
Ok((
StatusCode::PARTIAL_CONTENT,