diff --git a/crates/in-core/src/blob/mod.rs b/crates/in-core/src/blob/mod.rs index 054c7a2..8d1a8e3 100644 --- a/crates/in-core/src/blob/mod.rs +++ b/crates/in-core/src/blob/mod.rs @@ -97,20 +97,45 @@ pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result BlobStream { +pub fn check_digest(stream: BlobStream, key: &str, size: u64, sha256: &str) -> BlobStream { struct Checking { stream: BlobStream, hasher: Sha256, key: String, expected: String, + size: u64, + seen: u64, + /// Set once the hash of the full `size` bytes has matched. + verified: bool, + } + impl Checking { + fn digest_matches(&self) -> bool { + hex::encode(self.hasher.clone().finalize()) == self.expected + } + } + /// Logs the refusal with the key and returns the error the body ends with. + fn refuse(key: &str, reason: &str) -> Error { + tracing::error!( + blob_key = %key, + reason, + "blob bytes do not match their row; run `in fsck --hash`" + ); + Error::Io(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "blob does not match its row", + )) } Box::pin(stream::unfold( Some(Checking { @@ -118,30 +143,37 @@ pub fn check_digest(stream: BlobStream, key: &str, sha256: &str) -> BlobStream { hasher: Sha256::new(), key: key.to_string(), expected: sha256.to_string(), + size, + seen: 0, + verified: false, }), |state| async move { let mut state = state?; match state.stream.next().await { Some(Ok(frame)) => { + let total = state.seen + frame.len() as u64; + if total > state.size { + return Some((Err(refuse(&state.key, "longer than its row")), None)); + } state.hasher.update(&frame); + state.seen = total; + if total == state.size { + if !state.digest_matches() { + return Some((Err(refuse(&state.key, "sha256 differs")), None)); + } + state.verified = true; + } Some((Ok(frame), Some(state))) } Some(Err(e)) => Some((Err(e), None)), None => { - if hex::encode(state.hasher.finalize()) == state.expected { + if state.seen != state.size { + return Some((Err(refuse(&state.key, "shorter than its row")), None)); + } + if state.verified || state.digest_matches() { 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, - )) + Some((Err(refuse(&state.key, "sha256 differs")), None)) } } }, @@ -194,12 +226,43 @@ mod tests { 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); + let mut stream = check_digest(stream, "files/ab/abcd", 11, &sha); + // Read the way a Content-Length body does: stop once `size` bytes have been asked for, never poll + // for the end. The tampered frame must come back as the error, not as bytes. + let mut consumed = 0u64; + let mut items: Vec> = Vec::new(); + while consumed < 11 { + let item = stream + .next() + .await + .expect("the stream must end with the error or the last byte"); + let failed = item.is_err(); + if let Ok(frame) = &item { + consumed += frame.len() as u64; + } + items.push(item); + if failed { + break; + } + } + assert_eq!(items.len(), 1, "no byte may be delivered before the error"); + assert!(items[0].is_err(), "the body must end with an error"); + } + + #[tokio::test] + async fn a_blob_longer_than_its_row_ends_the_stream_with_an_error() { + let sha = hex::encode(Sha256::digest(b"hello world")); + let frames: Vec> = vec![ + Ok(Bytes::from_static(b"hello world")), + Ok(Bytes::from_static(b"!")), + ]; + let items: Vec> = + check_digest(Box::pin(stream::iter(frames)), "files/ab/abcd", 11, &sha) + .collect() + .await; + assert_eq!(items.len(), 2); + assert!(items[0].is_ok(), "the matching bytes are delivered"); + assert!(items[1].is_err(), "the extra byte is refused"); } #[test] diff --git a/crates/in-web/src/pages/shared.rs b/crates/in-web/src/pages/shared.rs index 97ce59e..196b454 100644 --- a/crates/in-web/src/pages/shared.rs +++ b/crates/in-web/src/pages/shared.rs @@ -127,7 +127,8 @@ async fn shared_page(cx: &Cx) -> Result { } /// `GET /live/shared`: a data-less `changed` event whenever the viewer's shared items change. It ends when -/// the session is gone. +/// the session is gone, and when a share the page showed when the stream opened is revoked (or its item is +/// trashed): the viewer no longer has that grant, so the page must not stay open on it. #[route(GET "/live/shared")] async fn shared_live(cx: &Cx) -> Result { let state = app_context::(cx); @@ -135,16 +136,30 @@ async fn shared_live(cx: &Cx) -> Result { let me = viewer.member.sub.clone(); let token_hash = viewer.session.token_hash.clone(); let store = state.store.clone(); + // The grants the page shows now. A grant that later leaves the list has been revoked. + let shown: Vec = store + .shared_with(&me) + .await? + .into_iter() + .map(|item| item.share.id) + .collect(); let topics = vec![Topic::Shared(me.clone())]; stream_changes(cx, &state.live, &topics, move || { let store = store.clone(); let me = me.clone(); let token_hash = token_hash.clone(); + let shown = shown.clone(); async move { if store.session_by_token_hash(&token_hash).await?.is_none() { return Err(not_found().into()); } let items = store.shared_with(&me).await?; + let revoked = shown + .iter() + .any(|id| !items.iter().any(|item| &item.share.id == id)); + if revoked { + return Err(not_found().into()); + } Ok(fingerprint(&items)) } }) diff --git a/crates/in-web/src/pages/trash.rs b/crates/in-web/src/pages/trash.rs index a1392f9..33bcc3e 100644 --- a/crates/in-web/src/pages/trash.rs +++ b/crates/in-web/src/pages/trash.rs @@ -7,14 +7,13 @@ //! request that names a foreign or missing item changes nothing. use in_core::authz::Action; -use in_core::error::Error as CoreError; use in_core::store::folders::Listing; use in_core::store::trash::ItemKind; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; -use topcoat::router::error::SeeOther; +use topcoat::router::error::{SeeOther, not_found}; use topcoat::router::{page, parse_query_params, route}; use topcoat::view::{View, component, view}; @@ -173,7 +172,7 @@ async fn restore(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let back = back_or(&form.back, "/trash"); let Some(kind) = kind_of(&form.kind) else { - return Err(CoreError::NotFound.into()); + return Err(not_found().into()); }; match kind { ItemKind::File => { @@ -211,7 +210,7 @@ async fn purge(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let back = back_or(&form.back, "/trash"); let Some(kind) = kind_of(&form.kind) else { - return Err(CoreError::NotFound.into()); + return Err(not_found().into()); }; match kind { ItemKind::File => { @@ -284,7 +283,7 @@ async fn trash_items(cx: &Cx, Form(pairs): Form>) -> Resul folder_for(state, &viewer, id, Action::Write).await?; folders.push(id.to_owned()); } - _ => return Err(CoreError::NotFound.into()), + _ => return Err(not_found().into()), } } let owner = viewer.member.sub.clone(); diff --git a/crates/in-web/src/serve_bytes.rs b/crates/in-web/src/serve_bytes.rs index 485649e..40eb5bb 100644 --- a/crates/in-web/src/serve_bytes.rs +++ b/crates/in-web/src/serve_bytes.rs @@ -13,10 +13,11 @@ //! 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 -//! file. +//! Range rules (RFC 7233 section 3.1): one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with +//! several ranges gets the whole file with `200`. A header that is syntactically invalid, reversed, or in +//! an unknown unit is ignored and gets the whole file with `200`. A valid range 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. use futures_util::TryStreamExt; use http::header::{ @@ -87,7 +88,7 @@ pub const SHARE_CACHE: &str = "private, no-cache"; /// 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, several ranges, or a header that is ignored (RFC 7233 3.1). Full, /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. Part { @@ -96,7 +97,7 @@ 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. Answer `416`. Unsatisfiable, } @@ -104,23 +105,28 @@ 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 is ignored, so it gives [`Ranged::Full`] too: a unit other than +/// `bytes`, a missing `-`, a non-digit, or a last byte before the first. A valid range the file cannot +/// satisfy is [`Ranged::Unsatisfiable`]: a first byte at or past the end, a suffix of `-0`, or any range +/// on an empty file. A number too large for `u64` is valid digits, so it saturates: as a first byte it is +/// past the end, as a last byte it is clamped. 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; @@ -132,14 +138,14 @@ 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, + _ => return Ranged::Full, } }; if start >= len { @@ -149,12 +155,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 value too large for `u64` +/// saturates to `u64::MAX`. 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 @@ -370,7 +377,7 @@ pub async fn serve_bytes_with( ); 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), + Some(sha256) => check_digest(stream, source.blob_key, source.size, sha256), None => stream, }; Ok((StatusCode::OK, answer_headers, streamed(stream))) @@ -420,24 +427,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. ("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. ("bytes=18446744073709551616-", Unsatisfiable), - ("bytes=0-18446744073709551616", Unsatisfiable), - ("bytes=-18446744073709551616", Unsatisfiable), + // Malformed, reversed or another unit: ignored, 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), + ("bytes=abc", Full), + ("items=0-1", Full), + ("0-1", Full), + // A last byte too large for u64 is clamped to the file, not refused. + ("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:?}"); diff --git a/docs/architecture.md b/docs/architecture.md index f19a262..1d37b05 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -187,14 +187,25 @@ and has no sessions. ## 7. Byte serving (one function for every byte route) -- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `""`; `If-None-Match` → 304. +- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `""`; `If-None-Match` → 304. Per RFC 7233 + 3.1 a `Range` that is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range + the file cannot satisfy gets 416 with `Content-Range: bytes */`. Several ranges get 200, whole file. - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf, text/plain, and only when the action allows `View` and `dl` is not set; otherwise `attachment`. Always both `filename=""` and `filename*=UTF-8''`. -- Every byte response: `X-Content-Type-Options: nosniff`, - `Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox`, - `Cross-Origin-Resource-Policy: same-origin`, `Cache-Control: private, max-age=31536000, immutable` for - content addressed by id and hash, `private, no-cache` for share-link bytes. +- Every byte response: `X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, + `Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox; frame-ancestors 'self'`, + `Cross-Origin-Resource-Policy: same-origin`. + - PDFs get the same policy without `sandbox`. Browser PDF viewers do not run inside a sandboxed document and + stop working, so a PDF is served inline without it. It stays safe: the type is fixed to `application/pdf` + with `nosniff`, so it is never read as HTML, and `default-src 'none'` still blocks everything else. +- `Cache-Control: private, no-cache` on every byte response, member bytes and share-link bytes alike. Not + `immutable`: the same URL can return different bytes after an overwrite or a restore, and a grant change must + be seen at once. The browser revalidates, and the `ETag` turns that into a cheap `304` while the bytes are the same. +- A full-body answer of a stored file is hashed against its row's SHA-256 while it streams. The check runs on the + frame that reaches the row's size, before that frame is sent: on a mismatch the body is cut short with no bad + bytes, and the key is logged for `in fsck --hash`. A longer stream is refused the same way. Range answers are + not checked (they are part of the file). - Streams from the blob store in 64 KiB frames; never buffers a whole file. - The download counter counts a forced download that starts at byte 0, once per request.