diff --git a/crates/iz-core/src/store/attachments.rs b/crates/iz-core/src/store/attachments.rs index 06ffaaf..dc1edf2 100644 --- a/crates/iz-core/src/store/attachments.rs +++ b/crates/iz-core/src/store/attachments.rs @@ -167,7 +167,10 @@ fn map_attachment(row: &turso::Row) -> Result { /// longer than [`FILE_NAME_MAX`] bytes is refused. pub fn clean_name(raw: &str) -> Result { let last = raw.rsplit(['/', '\\']).next().unwrap_or(""); - let name = last.trim(); + // Stripped before the checks: a name that is only invisible characters is empty, and an extension hidden by + // a bidi override is the extension the name really has. + let stripped: String = last.chars().filter(|c| !is_invisible_or_bidi(*c)).collect(); + let name = stripped.trim(); if name.is_empty() || name == "." || name == ".." { return Err(Error::Invalid("name_empty".into())); } @@ -180,6 +183,24 @@ pub fn clean_name(raw: &str) -> Result { Ok(name.to_owned()) } +/// Whether `c` is an invisible formatting character or a bidi control, which changes how a name is shown: +/// U+202E makes `invoice\u{202E}fdp.exe` read as `invoice exe.pdf`. Upload names drop these characters. +/// The set is the one of `in`'s display-name rules (`in-core` `names.rs`); copied, not shared. U+200D stays: +/// emoji sequences need it, and it cannot reorder text. +fn is_invisible_or_bidi(c: char) -> bool { + matches!( + c, + '\u{200B}'..='\u{200C}' + | '\u{200E}'..='\u{200F}' + | '\u{202A}'..='\u{202E}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{2069}' + | '\u{FEFF}' + | '\u{2028}' + | '\u{2029}' + ) +} + /// The extension of a clean name, lowercase, without the dot. `None` when there is none or it is not a /// plain alphanumeric word. pub fn extension_of(name: &str) -> Option { @@ -629,6 +650,16 @@ mod tests { assert_eq!(clean_name(" note.txt ").expect("ok"), "note.txt"); assert!(clean_name("dir/").is_err()); assert!(clean_name("..").is_err()); + // A right-to-left override is stripped, so the name keeps the extension it shows. + assert_eq!( + clean_name("invoice\u{202E}fdp.exe").expect("ok"), + "invoicefdp.exe" + ); + assert_eq!( + clean_name("zero\u{200B}\u{200D}width.txt").expect("ok"), + "zero\u{200D}width.txt" + ); + assert!(clean_name("\u{FEFF}\u{2066}").is_err()); assert!(clean_name("a\r\nb.txt").is_err()); assert!(clean_name(&format!("{}.txt", "x".repeat(FILE_NAME_MAX))).is_err()); } diff --git a/crates/iz-web/src/cli/fsck.rs b/crates/iz-web/src/cli/fsck.rs index b6ef8fd..136f99a 100644 --- a/crates/iz-web/src/cli/fsck.rs +++ b/crates/iz-web/src/cli/fsck.rs @@ -3,23 +3,32 @@ //! It checks: `integrity_check` returns `ok`; the migration history is contiguous and known to this build; //! every attachment row with location `local` has its file at the expected path, a regular file whose size //! and SHA-256 match the row; no row is stuck in `moving`; and every file in `attachments/` is named by a -//! row (unnamed files are reported, not deleted). Rows with location `in` are counted, not checked: their -//! bytes are in another service. The database is opened read-only and never migrated. The lock file is the -//! only thing it may create. Exit status 0 when nothing is wrong, 1 when anything is. +//! row (unnamed files are reported, not deleted). Rows with location `in` are not checked by default: their +//! bytes are in another service, and the note says so. With `--remote` each of them is downloaded through the +//! Files-service client (the same one `iz serve` uses, so the same configuration and token) and its size and +//! SHA-256 are checked like a local file; the download is streamed and hashed, never held whole. The database +//! is opened read-only and never migrated. The lock file is the only thing it may create. Exit status 0 when +//! nothing is wrong, 1 when anything is. use std::collections::HashSet; use std::path::Path; use std::process::ExitCode; +use std::sync::Arc; +use futures_util::StreamExt; use iz_core::config::Config; use iz_core::manifest::digest_file; use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; use iz_core::store::export::{ReadOnly, migrations_problem}; +use sha2::{Digest, Sha256}; use super::{database_file, describe, existing_data_dir, fail, take_lock}; +use crate::in_store::InStore; +use crate::oidc::{self, OidcClient}; -/// Runs the check, prints the report, and maps the outcome to an exit status. -pub async fn run(config_path: &Path) -> ExitCode { +/// Runs the check, prints the report, and maps the outcome to an exit status. `remote` asks for the attachments +/// held at the Files service to be downloaded and checked as well. +pub async fn run(config_path: &Path, remote: bool) -> ExitCode { let config = match Config::load(config_path) { Ok(config) => config, Err(error) => return fail(describe(&error)), @@ -32,8 +41,16 @@ pub async fn run(config_path: &Path) -> ExitCode { Ok(lock) => lock, Err(code) => return code, }; + let remote = if remote { + match remote_store(&config) { + Ok(store) => Some(store), + Err(message) => return fail(message), + } + } else { + None + }; let mut report = Report::default(); - check(&config, &data_dir, &mut report).await; + check(&config, &data_dir, remote.as_ref(), &mut report).await; for line in &report.lines { println!("{line}"); } @@ -68,8 +85,48 @@ impl Report { } } +/// The Files-service client that `iz serve` would build (`boot.rs`), for `--remote`. Refused when the Files service +/// is not enabled, since then there is nothing to download. +fn remote_store(config: &Config) -> Result { + if !config.in_store.enabled { + return Err("--remote needs in_store.enabled = true in the configuration".into()); + } + let url = config + .in_store + .url + .as_deref() + .ok_or("--remote needs in_store.url in the configuration")?; + let oidc_config = config + .oidc + .as_ref() + .ok_or("--remote needs the [oidc] section in the configuration")?; + let secret = + oidc::read_client_secret(&oidc_config.client_secret_file).map_err(|e| describe(&e))?; + let client = + OidcClient::new(oidc_config, &config.base_url, secret).map_err(|e| describe(&e))?; + InStore::new(url, Arc::new(client)).map_err(|e| describe(&e)) +} + +/// Downloads object `id` from the Files service and returns its size and lowercase hex SHA-256. The bytes are hashed +/// as they arrive and never held whole. The error is the text for the report. +async fn digest_remote(store: &InStore, id: &str) -> Result<(u64, String), String> { + let response = store + .get(id, None) + .await + .map_err(|error| error.to_string())?; + let mut hasher = Sha256::new(); + let mut size: u64 = 0; + let mut chunks = response.bytes_stream(); + while let Some(chunk) = chunks.next().await { + let chunk = chunk.map_err(|error| error.to_string())?; + size += chunk.len() as u64; + hasher.update(&chunk); + } + Ok((size, hex::encode(hasher.finalize()))) +} + /// Runs every check. Nothing here writes to the data directory. -async fn check(config: &Config, data_dir: &Path, report: &mut Report) { +async fn check(config: &Config, data_dir: &Path, remote: Option<&InStore>, report: &mut Report) { let attachments_dir = data_dir.join(ATTACHMENTS_DIR); let database = match database_file(config) { Ok(path) => path, @@ -108,11 +165,29 @@ async fn check(config: &Config, data_dir: &Path, report: &mut Report) { let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); let mut local_ok = 0usize; let mut elsewhere = 0usize; + let mut remote_ok = 0usize; for row in &rows { match row.location.as_str() { "local" => {} "in" => { elsewhere += 1; + if let Some(store) = remote { + match digest_remote(store, &row.id).await { + Ok((size, _)) if size != row.size => report.problem(format!( + "attachment {} is {size} bytes at the Files service, the row says {}", + row.id, row.size + )), + Ok((_, digest)) if digest != row.sha256 => report.problem(format!( + "attachment {} fails its sha256 at the Files service", + row.id + )), + Ok(_) => remote_ok += 1, + Err(reason) => report.problem(format!( + "attachment {} cannot be read from the Files service: {reason}", + row.id + )), + } + } continue; } other => { @@ -161,9 +236,14 @@ async fn check(config: &Config, data_dir: &Path, report: &mut Report) { )), } } - report.ok(format!( - "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" - )); + match remote { + Some(_) => report.ok(format!( + "{local_ok} local attachments match their rows; {remote_ok} of {elsewhere} held at the Files service match their rows" + )), + None => report.ok(format!( + "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" + )), + } // Files in the attachments directory that no row names. They are reported; nothing is deleted. match std::fs::read_dir(&attachments_dir) { @@ -242,6 +322,7 @@ mod tests { check( &config, &data.canonicalize().expect("canonical"), + None, &mut clean, ) .await; @@ -256,6 +337,7 @@ mod tests { check( &config, &data.canonicalize().expect("canonical"), + None, &mut dirty, ) .await; diff --git a/crates/iz-web/src/cli/mod.rs b/crates/iz-web/src/cli/mod.rs index 4877ed6..5567c8b 100644 --- a/crates/iz-web/src/cli/mod.rs +++ b/crates/iz-web/src/cli/mod.rs @@ -70,8 +70,13 @@ pub enum Command { #[arg(long, value_name = "DIR")] from: PathBuf, }, - /// Checks the database and the attachments without changing anything. - Fsck, + /// Checks the database and the attachments without changing anything. `--remote` also downloads the + /// attachments held at the Files service and checks them, which needs the Files service configured. + Fsck { + /// Download and check the attachments held at the Files service. + #[arg(long)] + remote: bool, + }, } /// The configuration path: the flag, else `IZ_CONFIG`, else the default. diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 024c594..0bf9765 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -73,6 +73,6 @@ async fn main() -> ExitCode { Command::Serve => serve(&config).await, Command::Export { out } => cli::export::run(&config, &out).await, Command::Restore { from } => cli::restore::run(&config, &from).await, - Command::Fsck => cli::fsck::run(&config).await, + Command::Fsck { remote } => cli::fsck::run(&config, remote).await, } } diff --git a/crates/iz-web/src/pages/files.rs b/crates/iz-web/src/pages/files.rs index ef6ffdc..cca7df1 100644 --- a/crates/iz-web/src/pages/files.rs +++ b/crates/iz-web/src/pages/files.rs @@ -625,6 +625,7 @@ async fn file_bytes(cx: &Cx) -> Result { let path = blob_path(&state.config.data_dir, &attachment.id)?; let source = ByteSource { path: &path, + id: &attachment.id, size: attachment.size, sha256: &attachment.sha256, mime: &attachment.mime, diff --git a/crates/iz-web/src/serve.rs b/crates/iz-web/src/serve.rs index 6d685e7..e1fe231 100644 --- a/crates/iz-web/src/serve.rs +++ b/crates/iz-web/src/serve.rs @@ -9,15 +9,22 @@ //! [`FRAME_BYTES`]; nothing is buffered whole. //! //! 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 -//! file. +//! whole file with `200`. A `Range` header that is not valid syntax (or has another unit) is ignored, and the +//! 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 +//! 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. use std::io::{self, SeekFrom}; use std::path::Path; use bytes::Bytes; -use futures_util::StreamExt; +use futures_util::stream::{self, BoxStream}; +use futures_util::{Stream, StreamExt, TryStreamExt}; use http::header::{ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, @@ -25,6 +32,7 @@ use http::header::{ }; use http_body::Frame; use http_body_util::StreamBody; +use sha2::{Digest, Sha256}; use tokio::io::{AsyncReadExt, AsyncSeekExt}; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; @@ -48,6 +56,8 @@ pub const FRAME_BYTES: usize = 64 * 1024; pub struct ByteSource<'a> { /// The file on the disk, under `data_dir/attachments`. pub path: &'a Path, + /// The attachment id, named in the log when the bytes do not match their digest. + pub id: &'a str, /// Length of the bytes in bytes. pub size: u64, /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes. @@ -86,7 +96,7 @@ const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; /// The outcome of reading a `Range` header against a length. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Ranged { - /// Send the whole file (no range, or several ranges). + /// Send the whole file (no range, a header that is not valid syntax, or several ranges). Full, /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. Part { @@ -95,7 +105,8 @@ pub enum Ranged { /// Last byte, inclusive. end: u64, }, - /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`. + /// The header is valid but asks for nothing the file has (a first byte at or past the end, a suffix of + /// zero bytes, any range of an empty file). Answer `416`. Unsatisfiable, } @@ -103,23 +114,25 @@ pub enum Ranged { /// /// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last /// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give -/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value -/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end. +/// [`Ranged::Full`]. A header that is not valid syntax also gives [`Ranged::Full`], because RFC 9110 14.2 says +/// a server ignores a `Range` it cannot use: a missing or other unit, a non-digit, a reversed range (last byte +/// before first). Only a valid range that the file cannot satisfy is [`Ranged::Unsatisfiable`]: a first byte at +/// or past the end, a suffix of `0`, and any range of an empty file. pub fn parse_range(value: &str, len: u64) -> Ranged { let Some(spec) = value.trim().strip_prefix("bytes=") else { - return Ranged::Unsatisfiable; + return Ranged::Full; }; if spec.contains(',') { return Ranged::Full; } let Some((first, last)) = spec.trim().split_once('-') else { - return Ranged::Unsatisfiable; + return Ranged::Full; }; let (first, last) = (first.trim(), last.trim()); if first.is_empty() { // A suffix range: the last `n` bytes. let Some(n) = digits(last) else { - return Ranged::Unsatisfiable; + return Ranged::Full; }; if n == 0 || len == 0 { return Ranged::Unsatisfiable; @@ -131,14 +144,15 @@ pub fn parse_range(value: &str, len: u64) -> Ranged { }; } let Some(start) = digits(first) else { - return Ranged::Unsatisfiable; + return Ranged::Full; }; let end = if last.is_empty() { None } else { match digits(last) { Some(end) if end >= start => Some(end), - _ => return Ranged::Unsatisfiable, + // Reversed: not a valid byte-range-spec, so the header is ignored. + _ => return Ranged::Full, } }; if start >= len { @@ -148,12 +162,13 @@ pub fn parse_range(value: &str, len: u64) -> Ranged { Ranged::Part { start, end } } -/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`. +/// A non-empty run of ASCII digits as a number. Anything else is `None`. A run too large for `u64` is valid +/// syntax and saturates, so it reads as far past the end of the file rather than wrapping. fn digits(text: &str) -> Option { if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { return None; } - text.parse().ok() + Some(text.parse().unwrap_or(u64::MAX)) } /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong @@ -404,7 +419,7 @@ pub async fn serve_local( return Ok(Some(plan.answer(Body::empty()))); }; match open_streamed(source.path, span).await { - Ok(body) => Ok(Some(plan.answer(body))), + Ok(chunks) => Ok(Some(plan.answer(checked_body(chunks, span, source)))), Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), Err(error) => Err(error), } @@ -445,48 +460,115 @@ pub async fn serve_remote( } let limit = span.length; let mut sent: u64 = 0; - let frames = response.bytes_stream().map(move |chunk| { - let chunk = chunk.map_err(io::Error::other)?; - sent += chunk.len() as u64; - if sent > limit { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "the object is longer than its record", - )); - } - Ok(Frame::data(chunk)) - }); - Ok(plan.answer(Body::new(StreamBody::new(frames)))) + let chunks = response + .bytes_stream() + .map(move |chunk| { + let chunk = chunk.map_err(io::Error::other)?; + sent += chunk.len() as u64; + if sent > limit { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "the object is longer than its record", + )); + } + Ok(chunk) + }) + .boxed(); + Ok(plan.answer(checked_body(chunks, span, source))) +} + +/// The body of a byte answer. A whole-file body is verified as it streams (see [`verified`]). A range is sent as +/// it comes: its bytes cannot be checked against the whole-file digest (module doc). +fn checked_body( + chunks: BoxStream<'static, io::Result>, + span: Span, + source: &ByteSource<'_>, +) -> 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() + }; + 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`. +fn verified( + chunks: BoxStream<'static, io::Result>, + expected: String, + id: String, +) -> impl Stream>> + Send + 'static { + /// The state between two frames of one verified body. + struct Check { + chunks: BoxStream<'static, io::Result>, + hasher: Sha256, + expected: String, + id: String, + } + stream::unfold( + Some(Check { + chunks, + hasher: Sha256::new(), + expected, + id, + }), + |state| async move { + let mut check = state?; + match check.chunks.next().await { + Some(Ok(chunk)) => { + check.hasher.update(&chunk); + Some((Ok(Frame::data(chunk)), Some(check))) + } + Some(Err(error)) => Some((Err(error), None)), + 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, + )) + } + } + }, + ) } -/// Opens `path`, seeks to the span's start and streams its bytes. The open is the error that matters: a file -/// that is not there is `NotFound`. -async fn open_streamed(path: &Path, span: Span) -> io::Result { +/// 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( + path: &Path, + span: Span, +) -> io::Result>> { let mut file = tokio::fs::File::open(path).await?; if span.start > 0 { file.seek(SeekFrom::Start(span.start)).await?; } - let frames = - futures_util::stream::try_unfold((file, span.length), |(mut file, left)| async move { - if left == 0 { - return Ok(None); - } - let want = left.min(FRAME_BYTES as u64) as usize; - let mut buf = vec![0u8; want]; - let read = file.read(&mut buf).await?; - if read == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file is shorter than its record", - )); - } - buf.truncate(read); - Ok(Some(( - Frame::data(Bytes::from(buf)), - (file, left - read as u64), - ))) - }); - Ok(Body::new(StreamBody::new(frames))) + let chunks = stream::try_unfold((file, span.length), |(mut file, left)| async move { + if left == 0 { + return Ok(None); + } + let want = left.min(FRAME_BYTES as u64) as usize; + let mut buf = vec![0u8; want]; + let read = file.read(&mut buf).await?; + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the file is shorter than its record", + )); + } + buf.truncate(read); + Ok(Some((Bytes::from(buf), (file, left - read as u64)))) + }); + Ok(chunks.boxed()) } #[cfg(test)] @@ -510,24 +592,26 @@ mod tests { (" bytes=1 - 2 ", Part { start: 1, end: 2 }), // Several ranges: the whole file. ("bytes=0-1,5-6", Full), - // Unsatisfiable or malformed. + // Valid syntax the file cannot satisfy: 416. ("bytes=-0", Unsatisfiable), ("bytes=100-", Unsatisfiable), ("bytes=100-120", Unsatisfiable), - ("bytes=20-10", Unsatisfiable), - ("bytes=5-4", Unsatisfiable), - ("bytes=-", Unsatisfiable), - ("bytes=", Unsatisfiable), - ("bytes=-x", Unsatisfiable), - ("bytes=+1-2", Unsatisfiable), - ("bytes=1e2-", Unsatisfiable), - ("bytes=--1", Unsatisfiable), - ("items=0-1", Unsatisfiable), - ("0-1", Unsatisfiable), - // Overflow of u64 is refused, not wrapped. + // Not valid syntax (or another unit): the header is ignored, so the whole file. + ("bytes=20-10", Full), + ("bytes=5-4", Full), + ("bytes=-", Full), + ("bytes=", Full), + ("bytes=-x", Full), + ("bytes=+1-2", Full), + ("bytes=1e2-", Full), + ("bytes=--1", Full), + ("items=0-1", Full), + ("0-1", Full), + // A number too large for u64 is valid syntax: far past the end, so 416 for a first byte, and + // clamped for a last byte or a suffix. ("bytes=18446744073709551616-", Unsatisfiable), - ("bytes=0-18446744073709551616", Unsatisfiable), - ("bytes=-18446744073709551616", Unsatisfiable), + ("bytes=0-18446744073709551616", Part { start: 0, end: 99 }), + ("bytes=-18446744073709551616", Part { start: 0, end: 99 }), ]; for (header, want) in cases { assert_eq!(parse_range(header, 100), *want, "header {header:?}"); @@ -626,12 +710,14 @@ mod tests { .await; let (_dir, mut state) = test_state().await; state.in_store = Some(Arc::new(InStore::for_tests(&base))); + let digest = hex::encode(Sha256::digest(data)); let source = ByteSource { path: Path::new("/does/not/exist"), size: data.len() as u64, - sha256: "0000000000000000000000000000000000000000000000000000000000000000", + sha256: &digest, mime: "image/png", name: "a.png", + id: "01HZ0000000000000000000000", }; let store = state.in_store.as_deref().expect("client"); @@ -669,4 +755,47 @@ mod tests { assert_eq!(status, StatusCode::OK); 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. + #[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"); + let right = hex::encode(Sha256::digest(b"hello world")); + let wrong = "0".repeat(64); + let good = ByteSource { + path: &path, + size: 11, + sha256: &right, + mime: "image/png", + name: "a.png", + id: "01HZ0000000000000000000000", + }; + let (status, _, body) = serve_local(&HeaderMap::new(), &good, Disposition::Inline) + .await + .expect("io") + .expect("answer"); + assert_eq!(status, StatusCode::OK); + assert_eq!( + to_bytes(body, 1024).await.expect("body").as_ref(), + b"hello world" + ); + + let bad = ByteSource { + sha256: &wrong, + ..good + }; + let (status, _, body) = serve_local(&HeaderMap::new(), &bad, Disposition::Inline) + .await + .expect("io") + .expect("answer"); + assert_eq!(status, StatusCode::OK); + assert!( + to_bytes(body, 1024).await.is_err(), + "a mismatch aborts the body" + ); + } }