Downloads verified against sha256 while streaming, fsck --remote checks in-held attachments, bidi stripped from upload names, malformed Range ignored
Browse files at this commita049e43621d9c8bb1c1c3ab3006bd97608ddb076Parent: a8aaba7- fix
- downloads verified against sha256 while streaming, fsck --remote checks in-held attachments, bidi stripped from upload names, malformed Range ignored
6 changed files +329 -81
- crates/iz-core/src/store/attachments.rs +32 -1
- crates/iz-web/src/cli/fsck.rs +92 -10
- crates/iz-web/src/cli/mod.rs +7 -2
- crates/iz-web/src/main.rs +1 -1
- crates/iz-web/src/pages/files.rs +1 -0
- crates/iz-web/src/serve.rs +196 -67
crates/iz-core/src/store/attachments.rsmodified+32 -1
| @@ -167,7 +167,10 @@ fn map_attachment(row: &turso::Row) -> Result<Attachment> { | |||
| 167 | /// longer than [`FILE_NAME_MAX`] bytes is refused. | 167 | /// longer than [`FILE_NAME_MAX`] bytes is refused. |
| 168 | pub fn clean_name(raw: &str) -> Result<String> { | 168 | pub fn clean_name(raw: &str) -> Result<String> { |
| 169 | let last = raw.rsplit(['/', '\\']).next().unwrap_or(""); | 169 | let last = raw.rsplit(['/', '\\']).next().unwrap_or(""); |
| 170 | - let name = last.trim(); | 170 | + // Stripped before the checks: a name that is only invisible characters is empty, and an extension hidden by |
| 171 | + // a bidi override is the extension the name really has. | ||
| 172 | + let stripped: String = last.chars().filter(|c| !is_invisible_or_bidi(*c)).collect(); | ||
| 173 | + let name = stripped.trim(); | ||
| 171 | if name.is_empty() || name == "." || name == ".." { | 174 | if name.is_empty() || name == "." || name == ".." { |
| 172 | return Err(Error::Invalid("name_empty".into())); | 175 | return Err(Error::Invalid("name_empty".into())); |
| 173 | } | 176 | } |
| @@ -180,6 +183,24 @@ pub fn clean_name(raw: &str) -> Result<String> { | |||
| 180 | Ok(name.to_owned()) | 183 | Ok(name.to_owned()) |
| 181 | } | 184 | } |
| 182 | 185 | ||
| 186 | +/// Whether `c` is an invisible formatting character or a bidi control, which changes how a name is shown: | ||
| 187 | +/// U+202E makes `invoice\u{202E}fdp.exe` read as `invoice exe.pdf`. Upload names drop these characters. | ||
| 188 | +/// The set is the one of `in`'s display-name rules (`in-core` `names.rs`); copied, not shared. U+200D stays: | ||
| 189 | +/// emoji sequences need it, and it cannot reorder text. | ||
| 190 | +fn is_invisible_or_bidi(c: char) -> bool { | ||
| 191 | + matches!( | ||
| 192 | + c, | ||
| 193 | + '\u{200B}'..='\u{200C}' | ||
| 194 | + | '\u{200E}'..='\u{200F}' | ||
| 195 | + | '\u{202A}'..='\u{202E}' | ||
| 196 | + | '\u{2060}'..='\u{2064}' | ||
| 197 | + | '\u{2066}'..='\u{2069}' | ||
| 198 | + | '\u{FEFF}' | ||
| 199 | + | '\u{2028}' | ||
| 200 | + | '\u{2029}' | ||
| 201 | + ) | ||
| 202 | +} | ||
| 203 | + | ||
| 183 | /// The extension of a clean name, lowercase, without the dot. `None` when there is none or it is not a | 204 | /// The extension of a clean name, lowercase, without the dot. `None` when there is none or it is not a |
| 184 | /// plain alphanumeric word. | 205 | /// plain alphanumeric word. |
| 185 | pub fn extension_of(name: &str) -> Option<String> { | 206 | pub fn extension_of(name: &str) -> Option<String> { |
| @@ -629,6 +650,16 @@ mod tests { | |||
| 629 | assert_eq!(clean_name(" note.txt ").expect("ok"), "note.txt"); | 650 | assert_eq!(clean_name(" note.txt ").expect("ok"), "note.txt"); |
| 630 | assert!(clean_name("dir/").is_err()); | 651 | assert!(clean_name("dir/").is_err()); |
| 631 | assert!(clean_name("..").is_err()); | 652 | assert!(clean_name("..").is_err()); |
| 653 | + // A right-to-left override is stripped, so the name keeps the extension it shows. | ||
| 654 | + assert_eq!( | ||
| 655 | + clean_name("invoice\u{202E}fdp.exe").expect("ok"), | ||
| 656 | + "invoicefdp.exe" | ||
| 657 | + ); | ||
| 658 | + assert_eq!( | ||
| 659 | + clean_name("zero\u{200B}\u{200D}width.txt").expect("ok"), | ||
| 660 | + "zero\u{200D}width.txt" | ||
| 661 | + ); | ||
| 662 | + assert!(clean_name("\u{FEFF}\u{2066}").is_err()); | ||
| 632 | assert!(clean_name("a\r\nb.txt").is_err()); | 663 | assert!(clean_name("a\r\nb.txt").is_err()); |
| 633 | assert!(clean_name(&format!("{}.txt", "x".repeat(FILE_NAME_MAX))).is_err()); | 664 | assert!(clean_name(&format!("{}.txt", "x".repeat(FILE_NAME_MAX))).is_err()); |
| 634 | } | 665 | } |
crates/iz-web/src/cli/fsck.rsmodified+92 -10
| @@ -3,23 +3,32 @@ | |||
| 3 | //! It checks: `integrity_check` returns `ok`; the migration history is contiguous and known to this build; | 3 | //! It checks: `integrity_check` returns `ok`; the migration history is contiguous and known to this build; |
| 4 | //! every attachment row with location `local` has its file at the expected path, a regular file whose size | 4 | //! every attachment row with location `local` has its file at the expected path, a regular file whose size |
| 5 | //! and SHA-256 match the row; no row is stuck in `moving`; and every file in `attachments/` is named by a | 5 | //! and SHA-256 match the row; no row is stuck in `moving`; and every file in `attachments/` is named by a |
| 6 | -//! row (unnamed files are reported, not deleted). Rows with location `in` are counted, not checked: their | 6 | +//! row (unnamed files are reported, not deleted). Rows with location `in` are not checked by default: their |
| 7 | -//! bytes are in another service. The database is opened read-only and never migrated. The lock file is the | 7 | +//! bytes are in another service, and the note says so. With `--remote` each of them is downloaded through the |
| 8 | -//! only thing it may create. Exit status 0 when nothing is wrong, 1 when anything is. | 8 | +//! Files-service client (the same one `iz serve` uses, so the same configuration and token) and its size and |
| 9 | +//! SHA-256 are checked like a local file; the download is streamed and hashed, never held whole. The database | ||
| 10 | +//! is opened read-only and never migrated. The lock file is the only thing it may create. Exit status 0 when | ||
| 11 | +//! nothing is wrong, 1 when anything is. | ||
| 9 | 12 | ||
| 10 | use std::collections::HashSet; | 13 | use std::collections::HashSet; |
| 11 | use std::path::Path; | 14 | use std::path::Path; |
| 12 | use std::process::ExitCode; | 15 | use std::process::ExitCode; |
| 16 | +use std::sync::Arc; | ||
| 13 | 17 | ||
| 18 | +use futures_util::StreamExt; | ||
| 14 | use iz_core::config::Config; | 19 | use iz_core::config::Config; |
| 15 | use iz_core::manifest::digest_file; | 20 | use iz_core::manifest::digest_file; |
| 16 | use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; | 21 | use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; |
| 17 | use iz_core::store::export::{ReadOnly, migrations_problem}; | 22 | use iz_core::store::export::{ReadOnly, migrations_problem}; |
| 23 | +use sha2::{Digest, Sha256}; | ||
| 18 | 24 | ||
| 19 | use super::{database_file, describe, existing_data_dir, fail, take_lock}; | 25 | use super::{database_file, describe, existing_data_dir, fail, take_lock}; |
| 26 | +use crate::in_store::InStore; | ||
| 27 | +use crate::oidc::{self, OidcClient}; | ||
| 20 | 28 | ||
| 21 | -/// Runs the check, prints the report, and maps the outcome to an exit status. | 29 | +/// Runs the check, prints the report, and maps the outcome to an exit status. `remote` asks for the attachments |
| 22 | -pub async fn run(config_path: &Path) -> ExitCode { | 30 | +/// held at the Files service to be downloaded and checked as well. |
| 31 | +pub async fn run(config_path: &Path, remote: bool) -> ExitCode { | ||
| 23 | let config = match Config::load(config_path) { | 32 | let config = match Config::load(config_path) { |
| 24 | Ok(config) => config, | 33 | Ok(config) => config, |
| 25 | Err(error) => return fail(describe(&error)), | 34 | Err(error) => return fail(describe(&error)), |
| @@ -32,8 +41,16 @@ pub async fn run(config_path: &Path) -> ExitCode { | |||
| 32 | Ok(lock) => lock, | 41 | Ok(lock) => lock, |
| 33 | Err(code) => return code, | 42 | Err(code) => return code, |
| 34 | }; | 43 | }; |
| 44 | + let remote = if remote { | ||
| 45 | + match remote_store(&config) { | ||
| 46 | + Ok(store) => Some(store), | ||
| 47 | + Err(message) => return fail(message), | ||
| 48 | + } | ||
| 49 | + } else { | ||
| 50 | + None | ||
| 51 | + }; | ||
| 35 | let mut report = Report::default(); | 52 | let mut report = Report::default(); |
| 36 | - check(&config, &data_dir, &mut report).await; | 53 | + check(&config, &data_dir, remote.as_ref(), &mut report).await; |
| 37 | for line in &report.lines { | 54 | for line in &report.lines { |
| 38 | println!("{line}"); | 55 | println!("{line}"); |
| 39 | } | 56 | } |
| @@ -68,8 +85,48 @@ impl Report { | |||
| 68 | } | 85 | } |
| 69 | } | 86 | } |
| 70 | 87 | ||
| 88 | +/// The Files-service client that `iz serve` would build (`boot.rs`), for `--remote`. Refused when the Files service | ||
| 89 | +/// is not enabled, since then there is nothing to download. | ||
| 90 | +fn remote_store(config: &Config) -> Result<InStore, String> { | ||
| 91 | + if !config.in_store.enabled { | ||
| 92 | + return Err("--remote needs in_store.enabled = true in the configuration".into()); | ||
| 93 | + } | ||
| 94 | + let url = config | ||
| 95 | + .in_store | ||
| 96 | + .url | ||
| 97 | + .as_deref() | ||
| 98 | + .ok_or("--remote needs in_store.url in the configuration")?; | ||
| 99 | + let oidc_config = config | ||
| 100 | + .oidc | ||
| 101 | + .as_ref() | ||
| 102 | + .ok_or("--remote needs the [oidc] section in the configuration")?; | ||
| 103 | + let secret = | ||
| 104 | + oidc::read_client_secret(&oidc_config.client_secret_file).map_err(|e| describe(&e))?; | ||
| 105 | + let client = | ||
| 106 | + OidcClient::new(oidc_config, &config.base_url, secret).map_err(|e| describe(&e))?; | ||
| 107 | + InStore::new(url, Arc::new(client)).map_err(|e| describe(&e)) | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Downloads object `id` from the Files service and returns its size and lowercase hex SHA-256. The bytes are hashed | ||
| 111 | +/// as they arrive and never held whole. The error is the text for the report. | ||
| 112 | +async fn digest_remote(store: &InStore, id: &str) -> Result<(u64, String), String> { | ||
| 113 | + let response = store | ||
| 114 | + .get(id, None) | ||
| 115 | + .await | ||
| 116 | + .map_err(|error| error.to_string())?; | ||
| 117 | + let mut hasher = Sha256::new(); | ||
| 118 | + let mut size: u64 = 0; | ||
| 119 | + let mut chunks = response.bytes_stream(); | ||
| 120 | + while let Some(chunk) = chunks.next().await { | ||
| 121 | + let chunk = chunk.map_err(|error| error.to_string())?; | ||
| 122 | + size += chunk.len() as u64; | ||
| 123 | + hasher.update(&chunk); | ||
| 124 | + } | ||
| 125 | + Ok((size, hex::encode(hasher.finalize()))) | ||
| 126 | +} | ||
| 127 | + | ||
| 71 | /// Runs every check. Nothing here writes to the data directory. | 128 | /// Runs every check. Nothing here writes to the data directory. |
| 72 | -async fn check(config: &Config, data_dir: &Path, report: &mut Report) { | 129 | +async fn check(config: &Config, data_dir: &Path, remote: Option<&InStore>, report: &mut Report) { |
| 73 | let attachments_dir = data_dir.join(ATTACHMENTS_DIR); | 130 | let attachments_dir = data_dir.join(ATTACHMENTS_DIR); |
| 74 | let database = match database_file(config) { | 131 | let database = match database_file(config) { |
| 75 | Ok(path) => path, | 132 | Ok(path) => path, |
| @@ -108,11 +165,29 @@ async fn check(config: &Config, data_dir: &Path, report: &mut Report) { | |||
| 108 | let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); | 165 | let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); |
| 109 | let mut local_ok = 0usize; | 166 | let mut local_ok = 0usize; |
| 110 | let mut elsewhere = 0usize; | 167 | let mut elsewhere = 0usize; |
| 168 | + let mut remote_ok = 0usize; | ||
| 111 | for row in &rows { | 169 | for row in &rows { |
| 112 | match row.location.as_str() { | 170 | match row.location.as_str() { |
| 113 | "local" => {} | 171 | "local" => {} |
| 114 | "in" => { | 172 | "in" => { |
| 115 | elsewhere += 1; | 173 | elsewhere += 1; |
| 174 | + if let Some(store) = remote { | ||
| 175 | + match digest_remote(store, &row.id).await { | ||
| 176 | + Ok((size, _)) if size != row.size => report.problem(format!( | ||
| 177 | + "attachment {} is {size} bytes at the Files service, the row says {}", | ||
| 178 | + row.id, row.size | ||
| 179 | + )), | ||
| 180 | + Ok((_, digest)) if digest != row.sha256 => report.problem(format!( | ||
| 181 | + "attachment {} fails its sha256 at the Files service", | ||
| 182 | + row.id | ||
| 183 | + )), | ||
| 184 | + Ok(_) => remote_ok += 1, | ||
| 185 | + Err(reason) => report.problem(format!( | ||
| 186 | + "attachment {} cannot be read from the Files service: {reason}", | ||
| 187 | + row.id | ||
| 188 | + )), | ||
| 189 | + } | ||
| 190 | + } | ||
| 116 | continue; | 191 | continue; |
| 117 | } | 192 | } |
| 118 | other => { | 193 | other => { |
| @@ -161,9 +236,14 @@ async fn check(config: &Config, data_dir: &Path, report: &mut Report) { | |||
| 161 | )), | 236 | )), |
| 162 | } | 237 | } |
| 163 | } | 238 | } |
| 164 | - report.ok(format!( | 239 | + match remote { |
| 165 | - "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" | 240 | + Some(_) => report.ok(format!( |
| 166 | - )); | 241 | + "{local_ok} local attachments match their rows; {remote_ok} of {elsewhere} held at the Files service match their rows" |
| 242 | + )), | ||
| 243 | + None => report.ok(format!( | ||
| 244 | + "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" | ||
| 245 | + )), | ||
| 246 | + } | ||
| 167 | 247 | ||
| 168 | // Files in the attachments directory that no row names. They are reported; nothing is deleted. | 248 | // Files in the attachments directory that no row names. They are reported; nothing is deleted. |
| 169 | match std::fs::read_dir(&attachments_dir) { | 249 | match std::fs::read_dir(&attachments_dir) { |
| @@ -242,6 +322,7 @@ mod tests { | |||
| 242 | check( | 322 | check( |
| 243 | &config, | 323 | &config, |
| 244 | &data.canonicalize().expect("canonical"), | 324 | &data.canonicalize().expect("canonical"), |
| 325 | + None, | ||
| 245 | &mut clean, | 326 | &mut clean, |
| 246 | ) | 327 | ) |
| 247 | .await; | 328 | .await; |
| @@ -256,6 +337,7 @@ mod tests { | |||
| 256 | check( | 337 | check( |
| 257 | &config, | 338 | &config, |
| 258 | &data.canonicalize().expect("canonical"), | 339 | &data.canonicalize().expect("canonical"), |
| 340 | + None, | ||
| 259 | &mut dirty, | 341 | &mut dirty, |
| 260 | ) | 342 | ) |
| 261 | .await; | 343 | .await; |
crates/iz-web/src/cli/mod.rsmodified+7 -2
| @@ -70,8 +70,13 @@ pub enum Command { | |||
| 70 | #[arg(long, value_name = "DIR")] | 70 | #[arg(long, value_name = "DIR")] |
| 71 | from: PathBuf, | 71 | from: PathBuf, |
| 72 | }, | 72 | }, |
| 73 | - /// Checks the database and the attachments without changing anything. | 73 | + /// Checks the database and the attachments without changing anything. `--remote` also downloads the |
| 74 | - Fsck, | 74 | + /// attachments held at the Files service and checks them, which needs the Files service configured. |
| 75 | + Fsck { | ||
| 76 | + /// Download and check the attachments held at the Files service. | ||
| 77 | + #[arg(long)] | ||
| 78 | + remote: bool, | ||
| 79 | + }, | ||
| 75 | } | 80 | } |
| 76 | 81 | ||
| 77 | /// The configuration path: the flag, else `IZ_CONFIG`, else the default. | 82 | /// The configuration path: the flag, else `IZ_CONFIG`, else the default. |
crates/iz-web/src/main.rsmodified+1 -1
| @@ -73,6 +73,6 @@ async fn main() -> ExitCode { | |||
| 73 | Command::Serve => serve(&config).await, | 73 | Command::Serve => serve(&config).await, |
| 74 | Command::Export { out } => cli::export::run(&config, &out).await, | 74 | Command::Export { out } => cli::export::run(&config, &out).await, |
| 75 | Command::Restore { from } => cli::restore::run(&config, &from).await, | 75 | Command::Restore { from } => cli::restore::run(&config, &from).await, |
| 76 | - Command::Fsck => cli::fsck::run(&config).await, | 76 | + Command::Fsck { remote } => cli::fsck::run(&config, remote).await, |
| 77 | } | 77 | } |
| 78 | } | 78 | } |
crates/iz-web/src/pages/files.rsmodified+1 -0
| @@ -625,6 +625,7 @@ async fn file_bytes(cx: &Cx) -> Result<Response> { | |||
| 625 | let path = blob_path(&state.config.data_dir, &attachment.id)?; | 625 | let path = blob_path(&state.config.data_dir, &attachment.id)?; |
| 626 | let source = ByteSource { | 626 | let source = ByteSource { |
| 627 | path: &path, | 627 | path: &path, |
| 628 | + id: &attachment.id, | ||
| 628 | size: attachment.size, | 629 | size: attachment.size, |
| 629 | sha256: &attachment.sha256, | 630 | sha256: &attachment.sha256, |
| 630 | mime: &attachment.mime, | 631 | mime: &attachment.mime, |
crates/iz-web/src/serve.rsmodified+196 -67
| @@ -9,15 +9,22 @@ | |||
| 9 | //! [`FRAME_BYTES`]; nothing is buffered whole. | 9 | //! [`FRAME_BYTES`]; nothing is buffered whole. |
| 10 | //! | 10 | //! |
| 11 | //! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the | 11 | //! 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 | 12 | +//! whole file with `200`. A `Range` header that is not valid syntax (or has another unit) is ignored, and the |
| 13 | -//! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole | 13 | +//! whole file is sent with `200` (RFC 9110 14.2). A valid range that the file cannot satisfy gets `416` with |
| 14 | -//! file. | 14 | +//! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole file. |
| 15 | +//! | ||
| 16 | +//! Integrity: a whole-file (`200`) body is hashed while it streams. When the digest at its end is not the row's | ||
| 17 | +//! `sha256`, the body fails with an error instead of ending cleanly, so the browser reports a failed download, | ||
| 18 | +//! and the log names the attachment id. 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 are | ||
| 20 | +//! therefore served from a file whose whole-file check has not run. A whole-file answer is always checked. | ||
| 15 | 21 | ||
| 16 | use std::io::{self, SeekFrom}; | 22 | use std::io::{self, SeekFrom}; |
| 17 | use std::path::Path; | 23 | use std::path::Path; |
| 18 | 24 | ||
| 19 | use bytes::Bytes; | 25 | use bytes::Bytes; |
| 20 | -use futures_util::StreamExt; | 26 | +use futures_util::stream::{self, BoxStream}; |
| 27 | +use futures_util::{Stream, StreamExt, TryStreamExt}; | ||
| 21 | use http::header::{ | 28 | use http::header::{ |
| 22 | ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, | 29 | ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, |
| 23 | CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, | 30 | CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, |
| @@ -25,6 +32,7 @@ use http::header::{ | |||
| 25 | }; | 32 | }; |
| 26 | use http_body::Frame; | 33 | use http_body::Frame; |
| 27 | use http_body_util::StreamBody; | 34 | use http_body_util::StreamBody; |
| 35 | +use sha2::{Digest, Sha256}; | ||
| 28 | use tokio::io::{AsyncReadExt, AsyncSeekExt}; | 36 | use tokio::io::{AsyncReadExt, AsyncSeekExt}; |
| 29 | use topcoat::router::response::Response; | 37 | use topcoat::router::response::Response; |
| 30 | use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; | 38 | use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; |
| @@ -48,6 +56,8 @@ pub const FRAME_BYTES: usize = 64 * 1024; | |||
| 48 | pub struct ByteSource<'a> { | 56 | pub struct ByteSource<'a> { |
| 49 | /// The file on the disk, under `data_dir/attachments`. | 57 | /// The file on the disk, under `data_dir/attachments`. |
| 50 | pub path: &'a Path, | 58 | pub path: &'a Path, |
| 59 | + /// The attachment id, named in the log when the bytes do not match their digest. | ||
| 60 | + pub id: &'a str, | ||
| 51 | /// Length of the bytes in bytes. | 61 | /// Length of the bytes in bytes. |
| 52 | pub size: u64, | 62 | pub size: u64, |
| 53 | /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes. | 63 | /// 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"; | |||
| 86 | /// The outcome of reading a `Range` header against a length. | 96 | /// The outcome of reading a `Range` header against a length. |
| 87 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 97 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 88 | pub enum Ranged { | 98 | pub enum Ranged { |
| 89 | - /// Send the whole file (no range, or several ranges). | 99 | + /// Send the whole file (no range, a header that is not valid syntax, or several ranges). |
| 90 | Full, | 100 | Full, |
| 91 | /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. | 101 | /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. |
| 92 | Part { | 102 | Part { |
| @@ -95,7 +105,8 @@ pub enum Ranged { | |||
| 95 | /// Last byte, inclusive. | 105 | /// Last byte, inclusive. |
| 96 | end: u64, | 106 | end: u64, |
| 97 | }, | 107 | }, |
| 98 | - /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`. | 108 | + /// The header is valid but asks for nothing the file has (a first byte at or past the end, a suffix of |
| 109 | + /// zero bytes, any range of an empty file). Answer `416`. | ||
| 99 | Unsatisfiable, | 110 | Unsatisfiable, |
| 100 | } | 111 | } |
| 101 | 112 | ||
| @@ -103,23 +114,25 @@ pub enum Ranged { | |||
| 103 | /// | 114 | /// |
| 104 | /// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last | 115 | /// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last |
| 105 | /// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give | 116 | /// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give |
| 106 | -/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value | 117 | +/// [`Ranged::Full`]. A header that is not valid syntax also gives [`Ranged::Full`], because RFC 9110 14.2 says |
| 107 | -/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end. | 118 | +/// a server ignores a `Range` it cannot use: a missing or other unit, a non-digit, a reversed range (last byte |
| 119 | +/// before first). Only a valid range that the file cannot satisfy is [`Ranged::Unsatisfiable`]: a first byte at | ||
| 120 | +/// or past the end, a suffix of `0`, and any range of an empty file. | ||
| 108 | pub fn parse_range(value: &str, len: u64) -> Ranged { | 121 | pub fn parse_range(value: &str, len: u64) -> Ranged { |
| 109 | let Some(spec) = value.trim().strip_prefix("bytes=") else { | 122 | let Some(spec) = value.trim().strip_prefix("bytes=") else { |
| 110 | - return Ranged::Unsatisfiable; | 123 | + return Ranged::Full; |
| 111 | }; | 124 | }; |
| 112 | if spec.contains(',') { | 125 | if spec.contains(',') { |
| 113 | return Ranged::Full; | 126 | return Ranged::Full; |
| 114 | } | 127 | } |
| 115 | let Some((first, last)) = spec.trim().split_once('-') else { | 128 | let Some((first, last)) = spec.trim().split_once('-') else { |
| 116 | - return Ranged::Unsatisfiable; | 129 | + return Ranged::Full; |
| 117 | }; | 130 | }; |
| 118 | let (first, last) = (first.trim(), last.trim()); | 131 | let (first, last) = (first.trim(), last.trim()); |
| 119 | if first.is_empty() { | 132 | if first.is_empty() { |
| 120 | // A suffix range: the last `n` bytes. | 133 | // A suffix range: the last `n` bytes. |
| 121 | let Some(n) = digits(last) else { | 134 | let Some(n) = digits(last) else { |
| 122 | - return Ranged::Unsatisfiable; | 135 | + return Ranged::Full; |
| 123 | }; | 136 | }; |
| 124 | if n == 0 || len == 0 { | 137 | if n == 0 || len == 0 { |
| 125 | return Ranged::Unsatisfiable; | 138 | return Ranged::Unsatisfiable; |
| @@ -131,14 +144,15 @@ pub fn parse_range(value: &str, len: u64) -> Ranged { | |||
| 131 | }; | 144 | }; |
| 132 | } | 145 | } |
| 133 | let Some(start) = digits(first) else { | 146 | let Some(start) = digits(first) else { |
| 134 | - return Ranged::Unsatisfiable; | 147 | + return Ranged::Full; |
| 135 | }; | 148 | }; |
| 136 | let end = if last.is_empty() { | 149 | let end = if last.is_empty() { |
| 137 | None | 150 | None |
| 138 | } else { | 151 | } else { |
| 139 | match digits(last) { | 152 | match digits(last) { |
| 140 | Some(end) if end >= start => Some(end), | 153 | Some(end) if end >= start => Some(end), |
| 141 | - _ => return Ranged::Unsatisfiable, | 154 | + // Reversed: not a valid byte-range-spec, so the header is ignored. |
| 155 | + _ => return Ranged::Full, | ||
| 142 | } | 156 | } |
| 143 | }; | 157 | }; |
| 144 | if start >= len { | 158 | if start >= len { |
| @@ -148,12 +162,13 @@ pub fn parse_range(value: &str, len: u64) -> Ranged { | |||
| 148 | Ranged::Part { start, end } | 162 | Ranged::Part { start, end } |
| 149 | } | 163 | } |
| 150 | 164 | ||
| 151 | -/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`. | 165 | +/// A non-empty run of ASCII digits as a number. Anything else is `None`. A run too large for `u64` is valid |
| 166 | +/// syntax and saturates, so it reads as far past the end of the file rather than wrapping. | ||
| 152 | fn digits(text: &str) -> Option<u64> { | 167 | fn digits(text: &str) -> Option<u64> { |
| 153 | if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { | 168 | if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { |
| 154 | return None; | 169 | return None; |
| 155 | } | 170 | } |
| 156 | - text.parse().ok() | 171 | + Some(text.parse().unwrap_or(u64::MAX)) |
| 157 | } | 172 | } |
| 158 | 173 | ||
| 159 | /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong | 174 | /// 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( | |||
| 404 | return Ok(Some(plan.answer(Body::empty()))); | 419 | return Ok(Some(plan.answer(Body::empty()))); |
| 405 | }; | 420 | }; |
| 406 | match open_streamed(source.path, span).await { | 421 | match open_streamed(source.path, span).await { |
| 407 | - Ok(body) => Ok(Some(plan.answer(body))), | 422 | + Ok(chunks) => Ok(Some(plan.answer(checked_body(chunks, span, source)))), |
| 408 | Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), | 423 | Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), |
| 409 | Err(error) => Err(error), | 424 | Err(error) => Err(error), |
| 410 | } | 425 | } |
| @@ -445,48 +460,115 @@ pub async fn serve_remote( | |||
| 445 | } | 460 | } |
| 446 | let limit = span.length; | 461 | let limit = span.length; |
| 447 | let mut sent: u64 = 0; | 462 | let mut sent: u64 = 0; |
| 448 | - let frames = response.bytes_stream().map(move |chunk| { | 463 | + let chunks = response |
| 449 | - let chunk = chunk.map_err(io::Error::other)?; | 464 | + .bytes_stream() |
| 450 | - sent += chunk.len() as u64; | 465 | + .map(move |chunk| { |
| 451 | - if sent > limit { | 466 | + let chunk = chunk.map_err(io::Error::other)?; |
| 452 | - return Err(io::Error::new( | 467 | + sent += chunk.len() as u64; |
| 453 | - io::ErrorKind::InvalidData, | 468 | + if sent > limit { |
| 454 | - "the object is longer than its record", | 469 | + return Err(io::Error::new( |
| 455 | - )); | 470 | + io::ErrorKind::InvalidData, |
| 456 | - } | 471 | + "the object is longer than its record", |
| 457 | - Ok(Frame::data(chunk)) | 472 | + )); |
| 458 | - }); | 473 | + } |
| 459 | - Ok(plan.answer(Body::new(StreamBody::new(frames)))) | 474 | + Ok(chunk) |
| 475 | + }) | ||
| 476 | + .boxed(); | ||
| 477 | + Ok(plan.answer(checked_body(chunks, span, source))) | ||
| 478 | +} | ||
| 479 | + | ||
| 480 | +/// The body of a byte answer. A whole-file body is verified as it streams (see [`verified`]). A range is sent as | ||
| 481 | +/// it comes: its bytes cannot be checked against the whole-file digest (module doc). | ||
| 482 | +fn checked_body( | ||
| 483 | + chunks: BoxStream<'static, io::Result<Bytes>>, | ||
| 484 | + span: Span, | ||
| 485 | + source: &ByteSource<'_>, | ||
| 486 | +) -> Body { | ||
| 487 | + let frames: BoxStream<'static, io::Result<Frame<Bytes>>> = if span.ranged { | ||
| 488 | + chunks.map_ok(Frame::data).boxed() | ||
| 489 | + } else { | ||
| 490 | + verified(chunks, source.sha256.to_owned(), source.id.to_owned()).boxed() | ||
| 491 | + }; | ||
| 492 | + Body::new(StreamBody::new(frames)) | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +/// Hashes the chunks as they go out. The stream ends cleanly only when the digest of every byte equals `expected`. | ||
| 496 | +/// Otherwise its last item is an error, which aborts the body, and the mismatch is logged with the attachment `id`. | ||
| 497 | +fn verified( | ||
| 498 | + chunks: BoxStream<'static, io::Result<Bytes>>, | ||
| 499 | + expected: String, | ||
| 500 | + id: String, | ||
| 501 | +) -> impl Stream<Item = io::Result<Frame<Bytes>>> + Send + 'static { | ||
| 502 | + /// The state between two frames of one verified body. | ||
| 503 | + struct Check { | ||
| 504 | + chunks: BoxStream<'static, io::Result<Bytes>>, | ||
| 505 | + hasher: Sha256, | ||
| 506 | + expected: String, | ||
| 507 | + id: String, | ||
| 508 | + } | ||
| 509 | + stream::unfold( | ||
| 510 | + Some(Check { | ||
| 511 | + chunks, | ||
| 512 | + hasher: Sha256::new(), | ||
| 513 | + expected, | ||
| 514 | + id, | ||
| 515 | + }), | ||
| 516 | + |state| async move { | ||
| 517 | + let mut check = state?; | ||
| 518 | + match check.chunks.next().await { | ||
| 519 | + Some(Ok(chunk)) => { | ||
| 520 | + check.hasher.update(&chunk); | ||
| 521 | + Some((Ok(Frame::data(chunk)), Some(check))) | ||
| 522 | + } | ||
| 523 | + Some(Err(error)) => Some((Err(error), None)), | ||
| 524 | + None => { | ||
| 525 | + if hex::encode(check.hasher.finalize()) == check.expected { | ||
| 526 | + return None; | ||
| 527 | + } | ||
| 528 | + tracing::error!( | ||
| 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 | + } | ||
| 540 | + } | ||
| 541 | + }, | ||
| 542 | + ) | ||
| 460 | } | 543 | } |
| 461 | 544 | ||
| 462 | -/// Opens `path`, seeks to the span's start and streams its bytes. The open is the error that matters: a file | 545 | +/// Opens `path`, seeks to the span's start and yields the span's bytes in pieces of [`FRAME_BYTES`]. The open is |
| 463 | -/// that is not there is `NotFound`. | 546 | +/// the error that matters: a file that is not there is `NotFound`. |
| 464 | -async fn open_streamed(path: &Path, span: Span) -> io::Result<Body> { | 547 | +async fn open_streamed( |
| 548 | + path: &Path, | ||
| 549 | + span: Span, | ||
| 550 | +) -> io::Result<BoxStream<'static, io::Result<Bytes>>> { | ||
| 465 | let mut file = tokio::fs::File::open(path).await?; | 551 | let mut file = tokio::fs::File::open(path).await?; |
| 466 | if span.start > 0 { | 552 | if span.start > 0 { |
| 467 | file.seek(SeekFrom::Start(span.start)).await?; | 553 | file.seek(SeekFrom::Start(span.start)).await?; |
| 468 | } | 554 | } |
| 469 | - let frames = | 555 | + let chunks = stream::try_unfold((file, span.length), |(mut file, left)| async move { |
| 470 | - futures_util::stream::try_unfold((file, span.length), |(mut file, left)| async move { | 556 | + if left == 0 { |
| 471 | - if left == 0 { | 557 | + return Ok(None); |
| 472 | - return Ok(None); | 558 | + } |
| 473 | - } | 559 | + let want = left.min(FRAME_BYTES as u64) as usize; |
| 474 | - let want = left.min(FRAME_BYTES as u64) as usize; | 560 | + let mut buf = vec![0u8; want]; |
| 475 | - let mut buf = vec![0u8; want]; | 561 | + let read = file.read(&mut buf).await?; |
| 476 | - let read = file.read(&mut buf).await?; | 562 | + if read == 0 { |
| 477 | - if read == 0 { | 563 | + return Err(io::Error::new( |
| 478 | - return Err(io::Error::new( | 564 | + io::ErrorKind::UnexpectedEof, |
| 479 | - io::ErrorKind::UnexpectedEof, | 565 | + "the file is shorter than its record", |
| 480 | - "the file is shorter than its record", | 566 | + )); |
| 481 | - )); | 567 | + } |
| 482 | - } | 568 | + buf.truncate(read); |
| 483 | - buf.truncate(read); | 569 | + Ok(Some((Bytes::from(buf), (file, left - read as u64)))) |
| 484 | - Ok(Some(( | 570 | + }); |
| 485 | - Frame::data(Bytes::from(buf)), | 571 | + Ok(chunks.boxed()) |
| 486 | - (file, left - read as u64), | ||
| 487 | - ))) | ||
| 488 | - }); | ||
| 489 | - Ok(Body::new(StreamBody::new(frames))) | ||
| 490 | } | 572 | } |
| 491 | 573 | ||
| 492 | #[cfg(test)] | 574 | #[cfg(test)] |
| @@ -510,24 +592,26 @@ mod tests { | |||
| 510 | (" bytes=1 - 2 ", Part { start: 1, end: 2 }), | 592 | (" bytes=1 - 2 ", Part { start: 1, end: 2 }), |
| 511 | // Several ranges: the whole file. | 593 | // Several ranges: the whole file. |
| 512 | ("bytes=0-1,5-6", Full), | 594 | ("bytes=0-1,5-6", Full), |
| 513 | - // Unsatisfiable or malformed. | 595 | + // Valid syntax the file cannot satisfy: 416. |
| 514 | ("bytes=-0", Unsatisfiable), | 596 | ("bytes=-0", Unsatisfiable), |
| 515 | ("bytes=100-", Unsatisfiable), | 597 | ("bytes=100-", Unsatisfiable), |
| 516 | ("bytes=100-120", Unsatisfiable), | 598 | ("bytes=100-120", Unsatisfiable), |
| 517 | - ("bytes=20-10", Unsatisfiable), | 599 | + // Not valid syntax (or another unit): the header is ignored, so the whole file. |
| 518 | - ("bytes=5-4", Unsatisfiable), | 600 | + ("bytes=20-10", Full), |
| 519 | - ("bytes=-", Unsatisfiable), | 601 | + ("bytes=5-4", Full), |
| 520 | - ("bytes=", Unsatisfiable), | 602 | + ("bytes=-", Full), |
| 521 | - ("bytes=-x", Unsatisfiable), | 603 | + ("bytes=", Full), |
| 522 | - ("bytes=+1-2", Unsatisfiable), | 604 | + ("bytes=-x", Full), |
| 523 | - ("bytes=1e2-", Unsatisfiable), | 605 | + ("bytes=+1-2", Full), |
| 524 | - ("bytes=--1", Unsatisfiable), | 606 | + ("bytes=1e2-", Full), |
| 525 | - ("items=0-1", Unsatisfiable), | 607 | + ("bytes=--1", Full), |
| 526 | - ("0-1", Unsatisfiable), | 608 | + ("items=0-1", Full), |
| 527 | - // Overflow of u64 is refused, not wrapped. | 609 | + ("0-1", Full), |
| 610 | + // A number too large for u64 is valid syntax: far past the end, so 416 for a first byte, and | ||
| 611 | + // clamped for a last byte or a suffix. | ||
| 528 | ("bytes=18446744073709551616-", Unsatisfiable), | 612 | ("bytes=18446744073709551616-", Unsatisfiable), |
| 529 | - ("bytes=0-18446744073709551616", Unsatisfiable), | 613 | + ("bytes=0-18446744073709551616", Part { start: 0, end: 99 }), |
| 530 | - ("bytes=-18446744073709551616", Unsatisfiable), | 614 | + ("bytes=-18446744073709551616", Part { start: 0, end: 99 }), |
| 531 | ]; | 615 | ]; |
| 532 | for (header, want) in cases { | 616 | for (header, want) in cases { |
| 533 | assert_eq!(parse_range(header, 100), *want, "header {header:?}"); | 617 | assert_eq!(parse_range(header, 100), *want, "header {header:?}"); |
| @@ -626,12 +710,14 @@ mod tests { | |||
| 626 | .await; | 710 | .await; |
| 627 | let (_dir, mut state) = test_state().await; | 711 | let (_dir, mut state) = test_state().await; |
| 628 | state.in_store = Some(Arc::new(InStore::for_tests(&base))); | 712 | state.in_store = Some(Arc::new(InStore::for_tests(&base))); |
| 713 | + let digest = hex::encode(Sha256::digest(data)); | ||
| 629 | let source = ByteSource { | 714 | let source = ByteSource { |
| 630 | path: Path::new("/does/not/exist"), | 715 | path: Path::new("/does/not/exist"), |
| 631 | size: data.len() as u64, | 716 | size: data.len() as u64, |
| 632 | - sha256: "0000000000000000000000000000000000000000000000000000000000000000", | 717 | + sha256: &digest, |
| 633 | mime: "image/png", | 718 | mime: "image/png", |
| 634 | name: "a.png", | 719 | name: "a.png", |
| 720 | + id: "01HZ0000000000000000000000", | ||
| 635 | }; | 721 | }; |
| 636 | let store = state.in_store.as_deref().expect("client"); | 722 | let store = state.in_store.as_deref().expect("client"); |
| 637 | 723 | ||
| @@ -669,4 +755,47 @@ mod tests { | |||
| 669 | assert_eq!(status, StatusCode::OK); | 755 | assert_eq!(status, StatusCode::OK); |
| 670 | assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data); | 756 | assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data); |
| 671 | } | 757 | } |
| 758 | + | ||
| 759 | + /// A whole-file answer is verified: the right digest sends every byte, a wrong one fails the body at its end. | ||
| 760 | + #[tokio::test] | ||
| 761 | + 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"); | ||
| 765 | + let path = dir.path().join("blob"); | ||
| 766 | + std::fs::write(&path, b"hello world").expect("bytes"); | ||
| 767 | + let right = hex::encode(Sha256::digest(b"hello world")); | ||
| 768 | + let wrong = "0".repeat(64); | ||
| 769 | + let good = ByteSource { | ||
| 770 | + path: &path, | ||
| 771 | + size: 11, | ||
| 772 | + sha256: &right, | ||
| 773 | + mime: "image/png", | ||
| 774 | + name: "a.png", | ||
| 775 | + id: "01HZ0000000000000000000000", | ||
| 776 | + }; | ||
| 777 | + let (status, _, body) = serve_local(&HeaderMap::new(), &good, Disposition::Inline) | ||
| 778 | + .await | ||
| 779 | + .expect("io") | ||
| 780 | + .expect("answer"); | ||
| 781 | + assert_eq!(status, StatusCode::OK); | ||
| 782 | + assert_eq!( | ||
| 783 | + to_bytes(body, 1024).await.expect("body").as_ref(), | ||
| 784 | + b"hello world" | ||
| 785 | + ); | ||
| 786 | + | ||
| 787 | + let bad = ByteSource { | ||
| 788 | + sha256: &wrong, | ||
| 789 | + ..good | ||
| 790 | + }; | ||
| 791 | + let (status, _, body) = serve_local(&HeaderMap::new(), &bad, Disposition::Inline) | ||
| 792 | + .await | ||
| 793 | + .expect("io") | ||
| 794 | + .expect("answer"); | ||
| 795 | + assert_eq!(status, StatusCode::OK); | ||
| 796 | + assert!( | ||
| 797 | + to_bytes(body, 1024).await.is_err(), | ||
| 798 | + "a mismatch aborts the body" | ||
| 799 | + ); | ||
| 800 | + } | ||
| 672 | } | 801 | } |