Download digest compared on the last byte, malformed Range ignored, bad item ids answer 404, shared stream ends when a share is revoked
Browse files at this commit7a822e74cecf3e77ee6c1326e2ffcdea83f9c6a2Parent: 57f59ff- fix
- download digest compared on the last byte, malformed Range ignored, bad item ids answer 404, shared stream ends when a share is revoked
- serving docs match the code
5 changed files +162 -65
- crates/in-core/src/blob/mod.rs +87 -24
- crates/in-web/src/pages/shared.rs +16 -1
- crates/in-web/src/pages/trash.rs +4 -5
- crates/in-web/src/serve_bytes.rs +39 -30
- docs/architecture.md +16 -5
crates/in-core/src/blob/mod.rsmodified+87 -24
| @@ -97,20 +97,45 @@ pub async fn digest(blobs: &dyn BlobStore, key: &str) -> Result<Option<(u64, Str | |||
| 97 | Ok(Some((size, hex::encode(hasher.finalize())))) | 97 | Ok(Some((size, hex::encode(hasher.finalize())))) |
| 98 | } | 98 | } |
| 99 | 99 | ||
| 100 | -/// Checks a whole-blob stream against the lowercase hex SHA-256 its row names. Every frame passes through | 100 | +/// Checks a whole-blob stream against the lowercase hex SHA-256 its row names, given the row's `size`. |
| 101 | -/// unchanged and is hashed on the way, so no extra buffer is kept. When the stream ends with the hash equal | 101 | +/// Every frame passes through unchanged and is hashed on the way, so no extra buffer is kept. |
| 102 | -/// to `sha256`, it ends cleanly. When the hash differs, the stream yields one `InvalidData` error and then | 102 | +/// |
| 103 | -/// ends, so the HTTP body is aborted and the client does not take the bad bytes for a complete file. The | 103 | +/// The HTTP layer stops polling once it has sent `Content-Length` bytes, so the check cannot wait for the |
| 104 | -/// mismatch is logged with the blob key, which is what `in fsck --hash` needs to find the blob. | 104 | +/// end of the stream. It runs on the frame that brings the count to `size`: the hash is finished and |
| 105 | +/// compared before that frame is yielded. On a match the frame goes out. On a mismatch the frame is | ||
| 106 | +/// replaced by one `InvalidData` error and the stream ends, so the body is cut short and the client does | ||
| 107 | +/// not take the bad bytes for a complete file. A stream that yields more than `size` bytes gets the same | ||
| 108 | +/// error. The refusal is logged with the blob key, which is what `in fsck --hash` needs to find the blob. | ||
| 105 | /// | 109 | /// |
| 106 | /// Only whole-blob streams can be checked: a range is a part of the file and has no hash to compare with. | 110 | /// 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. | 111 | /// 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 { | 112 | +pub fn check_digest(stream: BlobStream, key: &str, size: u64, sha256: &str) -> BlobStream { |
| 109 | struct Checking { | 113 | struct Checking { |
| 110 | stream: BlobStream, | 114 | stream: BlobStream, |
| 111 | hasher: Sha256, | 115 | hasher: Sha256, |
| 112 | key: String, | 116 | key: String, |
| 113 | expected: String, | 117 | expected: String, |
| 118 | + size: u64, | ||
| 119 | + seen: u64, | ||
| 120 | + /// Set once the hash of the full `size` bytes has matched. | ||
| 121 | + verified: bool, | ||
| 122 | + } | ||
| 123 | + impl Checking { | ||
| 124 | + fn digest_matches(&self) -> bool { | ||
| 125 | + hex::encode(self.hasher.clone().finalize()) == self.expected | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + /// Logs the refusal with the key and returns the error the body ends with. | ||
| 129 | + fn refuse(key: &str, reason: &str) -> Error { | ||
| 130 | + tracing::error!( | ||
| 131 | + blob_key = %key, | ||
| 132 | + reason, | ||
| 133 | + "blob bytes do not match their row; run `in fsck --hash`" | ||
| 134 | + ); | ||
| 135 | + Error::Io(std::io::Error::new( | ||
| 136 | + std::io::ErrorKind::InvalidData, | ||
| 137 | + "blob does not match its row", | ||
| 138 | + )) | ||
| 114 | } | 139 | } |
| 115 | Box::pin(stream::unfold( | 140 | Box::pin(stream::unfold( |
| 116 | Some(Checking { | 141 | Some(Checking { |
| @@ -118,30 +143,37 @@ pub fn check_digest(stream: BlobStream, key: &str, sha256: &str) -> BlobStream { | |||
| 118 | hasher: Sha256::new(), | 143 | hasher: Sha256::new(), |
| 119 | key: key.to_string(), | 144 | key: key.to_string(), |
| 120 | expected: sha256.to_string(), | 145 | expected: sha256.to_string(), |
| 146 | + size, | ||
| 147 | + seen: 0, | ||
| 148 | + verified: false, | ||
| 121 | }), | 149 | }), |
| 122 | |state| async move { | 150 | |state| async move { |
| 123 | let mut state = state?; | 151 | let mut state = state?; |
| 124 | match state.stream.next().await { | 152 | match state.stream.next().await { |
| 125 | Some(Ok(frame)) => { | 153 | Some(Ok(frame)) => { |
| 154 | + let total = state.seen + frame.len() as u64; | ||
| 155 | + if total > state.size { | ||
| 156 | + return Some((Err(refuse(&state.key, "longer than its row")), None)); | ||
| 157 | + } | ||
| 126 | state.hasher.update(&frame); | 158 | state.hasher.update(&frame); |
| 159 | + state.seen = total; | ||
| 160 | + if total == state.size { | ||
| 161 | + if !state.digest_matches() { | ||
| 162 | + return Some((Err(refuse(&state.key, "sha256 differs")), None)); | ||
| 163 | + } | ||
| 164 | + state.verified = true; | ||
| 165 | + } | ||
| 127 | Some((Ok(frame), Some(state))) | 166 | Some((Ok(frame), Some(state))) |
| 128 | } | 167 | } |
| 129 | Some(Err(e)) => Some((Err(e), None)), | 168 | Some(Err(e)) => Some((Err(e), None)), |
| 130 | None => { | 169 | None => { |
| 131 | - if hex::encode(state.hasher.finalize()) == state.expected { | 170 | + if state.seen != state.size { |
| 171 | + return Some((Err(refuse(&state.key, "shorter than its row")), None)); | ||
| 172 | + } | ||
| 173 | + if state.verified || state.digest_matches() { | ||
| 132 | return None; | 174 | return None; |
| 133 | } | 175 | } |
| 134 | - tracing::error!( | 176 | + Some((Err(refuse(&state.key, "sha256 differs")), None)) |
| 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 | } | 177 | } |
| 146 | } | 178 | } |
| 147 | }, | 179 | }, |
| @@ -194,12 +226,43 @@ mod tests { | |||
| 194 | std::fs::write(dir.path().join("blobs/files/ab/abcd"), b"hello_world").unwrap(); | 226 | std::fs::write(dir.path().join("blobs/files/ab/abcd"), b"hello_world").unwrap(); |
| 195 | 227 | ||
| 196 | let stream = blobs.open_range("files/ab/abcd", 0, 11).await.unwrap(); | 228 | 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; | 229 | + let mut stream = check_digest(stream, "files/ab/abcd", 11, &sha); |
| 198 | - assert!( | 230 | + // Read the way a Content-Length body does: stop once `size` bytes have been asked for, never poll |
| 199 | - matches!(items.last(), Some(Err(_))), | 231 | + // for the end. The tampered frame must come back as the error, not as bytes. |
| 200 | - "the body must end with an error" | 232 | + let mut consumed = 0u64; |
| 201 | - ); | 233 | + let mut items: Vec<Result<Bytes>> = Vec::new(); |
| 202 | - assert_eq!(items.iter().filter(|item| item.is_err()).count(), 1); | 234 | + while consumed < 11 { |
| 235 | + let item = stream | ||
| 236 | + .next() | ||
| 237 | + .await | ||
| 238 | + .expect("the stream must end with the error or the last byte"); | ||
| 239 | + let failed = item.is_err(); | ||
| 240 | + if let Ok(frame) = &item { | ||
| 241 | + consumed += frame.len() as u64; | ||
| 242 | + } | ||
| 243 | + items.push(item); | ||
| 244 | + if failed { | ||
| 245 | + break; | ||
| 246 | + } | ||
| 247 | + } | ||
| 248 | + assert_eq!(items.len(), 1, "no byte may be delivered before the error"); | ||
| 249 | + assert!(items[0].is_err(), "the body must end with an error"); | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + #[tokio::test] | ||
| 253 | + async fn a_blob_longer_than_its_row_ends_the_stream_with_an_error() { | ||
| 254 | + let sha = hex::encode(Sha256::digest(b"hello world")); | ||
| 255 | + let frames: Vec<Result<Bytes>> = vec![ | ||
| 256 | + Ok(Bytes::from_static(b"hello world")), | ||
| 257 | + Ok(Bytes::from_static(b"!")), | ||
| 258 | + ]; | ||
| 259 | + let items: Vec<Result<Bytes>> = | ||
| 260 | + check_digest(Box::pin(stream::iter(frames)), "files/ab/abcd", 11, &sha) | ||
| 261 | + .collect() | ||
| 262 | + .await; | ||
| 263 | + assert_eq!(items.len(), 2); | ||
| 264 | + assert!(items[0].is_ok(), "the matching bytes are delivered"); | ||
| 265 | + assert!(items[1].is_err(), "the extra byte is refused"); | ||
| 203 | } | 266 | } |
| 204 | 267 | ||
| 205 | #[test] | 268 | #[test] |
crates/in-web/src/pages/shared.rsmodified+16 -1
| @@ -127,7 +127,8 @@ async fn shared_page(cx: &Cx) -> Result<impl View> { | |||
| 127 | } | 127 | } |
| 128 | 128 | ||
| 129 | /// `GET /live/shared`: a data-less `changed` event whenever the viewer's shared items change. It ends when | 129 | /// `GET /live/shared`: a data-less `changed` event whenever the viewer's shared items change. It ends when |
| 130 | -/// the session is gone. | 130 | +/// the session is gone, and when a share the page showed when the stream opened is revoked (or its item is |
| 131 | +/// trashed): the viewer no longer has that grant, so the page must not stay open on it. | ||
| 131 | #[route(GET "/live/shared")] | 132 | #[route(GET "/live/shared")] |
| 132 | async fn shared_live(cx: &Cx) -> Result<Response> { | 133 | async fn shared_live(cx: &Cx) -> Result<Response> { |
| 133 | let state = app_context::<AppState>(cx); | 134 | let state = app_context::<AppState>(cx); |
| @@ -135,16 +136,30 @@ async fn shared_live(cx: &Cx) -> Result<Response> { | |||
| 135 | let me = viewer.member.sub.clone(); | 136 | let me = viewer.member.sub.clone(); |
| 136 | let token_hash = viewer.session.token_hash.clone(); | 137 | let token_hash = viewer.session.token_hash.clone(); |
| 137 | let store = state.store.clone(); | 138 | let store = state.store.clone(); |
| 139 | + // The grants the page shows now. A grant that later leaves the list has been revoked. | ||
| 140 | + let shown: Vec<String> = store | ||
| 141 | + .shared_with(&me) | ||
| 142 | + .await? | ||
| 143 | + .into_iter() | ||
| 144 | + .map(|item| item.share.id) | ||
| 145 | + .collect(); | ||
| 138 | let topics = vec![Topic::Shared(me.clone())]; | 146 | let topics = vec![Topic::Shared(me.clone())]; |
| 139 | stream_changes(cx, &state.live, &topics, move || { | 147 | stream_changes(cx, &state.live, &topics, move || { |
| 140 | let store = store.clone(); | 148 | let store = store.clone(); |
| 141 | let me = me.clone(); | 149 | let me = me.clone(); |
| 142 | let token_hash = token_hash.clone(); | 150 | let token_hash = token_hash.clone(); |
| 151 | + let shown = shown.clone(); | ||
| 143 | async move { | 152 | async move { |
| 144 | if store.session_by_token_hash(&token_hash).await?.is_none() { | 153 | if store.session_by_token_hash(&token_hash).await?.is_none() { |
| 145 | return Err(not_found().into()); | 154 | return Err(not_found().into()); |
| 146 | } | 155 | } |
| 147 | let items = store.shared_with(&me).await?; | 156 | let items = store.shared_with(&me).await?; |
| 157 | + let revoked = shown | ||
| 158 | + .iter() | ||
| 159 | + .any(|id| !items.iter().any(|item| &item.share.id == id)); | ||
| 160 | + if revoked { | ||
| 161 | + return Err(not_found().into()); | ||
| 162 | + } | ||
| 148 | Ok(fingerprint(&items)) | 163 | Ok(fingerprint(&items)) |
| 149 | } | 164 | } |
| 150 | }) | 165 | }) |
crates/in-web/src/pages/trash.rsmodified+4 -5
| @@ -7,14 +7,13 @@ | |||
| 7 | //! request that names a foreign or missing item changes nothing. | 7 | //! request that names a foreign or missing item changes nothing. |
| 8 | 8 | ||
| 9 | use in_core::authz::Action; | 9 | use in_core::authz::Action; |
| 10 | -use in_core::error::Error as CoreError; | ||
| 11 | use in_core::store::folders::Listing; | 10 | use in_core::store::folders::Listing; |
| 12 | use in_core::store::trash::ItemKind; | 11 | use in_core::store::trash::ItemKind; |
| 13 | use serde::Deserialize; | 12 | use serde::Deserialize; |
| 14 | use topcoat::Result; | 13 | use topcoat::Result; |
| 15 | use topcoat::context::{Cx, app_context}; | 14 | use topcoat::context::{Cx, app_context}; |
| 16 | use topcoat::router::content::Form; | 15 | use topcoat::router::content::Form; |
| 17 | -use topcoat::router::error::SeeOther; | 16 | +use topcoat::router::error::{SeeOther, not_found}; |
| 18 | use topcoat::router::{page, parse_query_params, route}; | 17 | use topcoat::router::{page, parse_query_params, route}; |
| 19 | use topcoat::view::{View, component, view}; | 18 | use topcoat::view::{View, component, view}; |
| 20 | 19 | ||
| @@ -173,7 +172,7 @@ async fn restore(cx: &Cx, Form(form): Form<TrashForm>) -> Result<SeeOther> { | |||
| 173 | let viewer = require_csrf(cx, &form.csrf).await?; | 172 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 174 | let back = back_or(&form.back, "/trash"); | 173 | let back = back_or(&form.back, "/trash"); |
| 175 | let Some(kind) = kind_of(&form.kind) else { | 174 | let Some(kind) = kind_of(&form.kind) else { |
| 176 | - return Err(CoreError::NotFound.into()); | 175 | + return Err(not_found().into()); |
| 177 | }; | 176 | }; |
| 178 | match kind { | 177 | match kind { |
| 179 | ItemKind::File => { | 178 | ItemKind::File => { |
| @@ -211,7 +210,7 @@ async fn purge(cx: &Cx, Form(form): Form<TrashForm>) -> Result<SeeOther> { | |||
| 211 | let viewer = require_csrf(cx, &form.csrf).await?; | 210 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 212 | let back = back_or(&form.back, "/trash"); | 211 | let back = back_or(&form.back, "/trash"); |
| 213 | let Some(kind) = kind_of(&form.kind) else { | 212 | let Some(kind) = kind_of(&form.kind) else { |
| 214 | - return Err(CoreError::NotFound.into()); | 213 | + return Err(not_found().into()); |
| 215 | }; | 214 | }; |
| 216 | match kind { | 215 | match kind { |
| 217 | ItemKind::File => { | 216 | ItemKind::File => { |
| @@ -284,7 +283,7 @@ async fn trash_items(cx: &Cx, Form(pairs): Form<Vec<(String, String)>>) -> Resul | |||
| 284 | folder_for(state, &viewer, id, Action::Write).await?; | 283 | folder_for(state, &viewer, id, Action::Write).await?; |
| 285 | folders.push(id.to_owned()); | 284 | folders.push(id.to_owned()); |
| 286 | } | 285 | } |
| 287 | - _ => return Err(CoreError::NotFound.into()), | 286 | + _ => return Err(not_found().into()), |
| 288 | } | 287 | } |
| 289 | } | 288 | } |
| 290 | let owner = viewer.member.sub.clone(); | 289 | let owner = viewer.member.sub.clone(); |
crates/in-web/src/serve_bytes.rsmodified+39 -30
| @@ -13,10 +13,11 @@ | |||
| 13 | //! part of the file, and a partial read cannot be compared with the whole-file hash. `in fsck --hash` | 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. | 14 | //! checks every blob in full. |
| 15 | //! | 15 | //! |
| 16 | -//! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the | 16 | +//! Range rules (RFC 7233 section 3.1): one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with |
| 17 | -//! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with | 17 | +//! several ranges gets the whole file with `200`. A header that is syntactically invalid, reversed, or in |
| 18 | -//! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole | 18 | +//! an unknown unit is ignored and gets the whole file with `200`. A valid range the file cannot satisfy |
| 19 | -//! file. | 19 | +//! gets `416` with `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one |
| 20 | +//! gets the whole file. | ||
| 20 | 21 | ||
| 21 | use futures_util::TryStreamExt; | 22 | use futures_util::TryStreamExt; |
| 22 | use http::header::{ | 23 | use http::header::{ |
| @@ -87,7 +88,7 @@ pub const SHARE_CACHE: &str = "private, no-cache"; | |||
| 87 | /// The outcome of reading a `Range` header against a length. | 88 | /// The outcome of reading a `Range` header against a length. |
| 88 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 89 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 89 | pub enum Ranged { | 90 | pub enum Ranged { |
| 90 | - /// Send the whole file (no range, or several ranges). | 91 | + /// Send the whole file: no range, several ranges, or a header that is ignored (RFC 7233 3.1). |
| 91 | Full, | 92 | Full, |
| 92 | /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. | 93 | /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. |
| 93 | Part { | 94 | Part { |
| @@ -96,7 +97,7 @@ pub enum Ranged { | |||
| 96 | /// Last byte, inclusive. | 97 | /// Last byte, inclusive. |
| 97 | end: u64, | 98 | end: u64, |
| 98 | }, | 99 | }, |
| 99 | - /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`. | 100 | + /// The header is valid but asks for nothing the file has. Answer `416`. |
| 100 | Unsatisfiable, | 101 | Unsatisfiable, |
| 101 | } | 102 | } |
| 102 | 103 | ||
| @@ -104,23 +105,28 @@ pub enum Ranged { | |||
| 104 | /// | 105 | /// |
| 105 | /// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last | 106 | /// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last |
| 106 | /// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give | 107 | /// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give |
| 107 | -/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value | 108 | +/// [`Ranged::Full`]. |
| 108 | -/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end. | 109 | +/// |
| 110 | +/// A header that is not valid syntax is ignored, so it gives [`Ranged::Full`] too: a unit other than | ||
| 111 | +/// `bytes`, a missing `-`, a non-digit, or a last byte before the first. A valid range the file cannot | ||
| 112 | +/// satisfy is [`Ranged::Unsatisfiable`]: a first byte at or past the end, a suffix of `-0`, or any range | ||
| 113 | +/// on an empty file. A number too large for `u64` is valid digits, so it saturates: as a first byte it is | ||
| 114 | +/// past the end, as a last byte it is clamped. | ||
| 109 | pub fn parse_range(value: &str, len: u64) -> Ranged { | 115 | pub fn parse_range(value: &str, len: u64) -> Ranged { |
| 110 | let Some(spec) = value.trim().strip_prefix("bytes=") else { | 116 | let Some(spec) = value.trim().strip_prefix("bytes=") else { |
| 111 | - return Ranged::Unsatisfiable; | 117 | + return Ranged::Full; |
| 112 | }; | 118 | }; |
| 113 | if spec.contains(',') { | 119 | if spec.contains(',') { |
| 114 | return Ranged::Full; | 120 | return Ranged::Full; |
| 115 | } | 121 | } |
| 116 | let Some((first, last)) = spec.trim().split_once('-') else { | 122 | let Some((first, last)) = spec.trim().split_once('-') else { |
| 117 | - return Ranged::Unsatisfiable; | 123 | + return Ranged::Full; |
| 118 | }; | 124 | }; |
| 119 | let (first, last) = (first.trim(), last.trim()); | 125 | let (first, last) = (first.trim(), last.trim()); |
| 120 | if first.is_empty() { | 126 | if first.is_empty() { |
| 121 | // A suffix range: the last `n` bytes. | 127 | // A suffix range: the last `n` bytes. |
| 122 | let Some(n) = digits(last) else { | 128 | let Some(n) = digits(last) else { |
| 123 | - return Ranged::Unsatisfiable; | 129 | + return Ranged::Full; |
| 124 | }; | 130 | }; |
| 125 | if n == 0 || len == 0 { | 131 | if n == 0 || len == 0 { |
| 126 | return Ranged::Unsatisfiable; | 132 | return Ranged::Unsatisfiable; |
| @@ -132,14 +138,14 @@ pub fn parse_range(value: &str, len: u64) -> Ranged { | |||
| 132 | }; | 138 | }; |
| 133 | } | 139 | } |
| 134 | let Some(start) = digits(first) else { | 140 | let Some(start) = digits(first) else { |
| 135 | - return Ranged::Unsatisfiable; | 141 | + return Ranged::Full; |
| 136 | }; | 142 | }; |
| 137 | let end = if last.is_empty() { | 143 | let end = if last.is_empty() { |
| 138 | None | 144 | None |
| 139 | } else { | 145 | } else { |
| 140 | match digits(last) { | 146 | match digits(last) { |
| 141 | Some(end) if end >= start => Some(end), | 147 | Some(end) if end >= start => Some(end), |
| 142 | - _ => return Ranged::Unsatisfiable, | 148 | + _ => return Ranged::Full, |
| 143 | } | 149 | } |
| 144 | }; | 150 | }; |
| 145 | if start >= len { | 151 | if start >= len { |
| @@ -149,12 +155,13 @@ pub fn parse_range(value: &str, len: u64) -> Ranged { | |||
| 149 | Ranged::Part { start, end } | 155 | Ranged::Part { start, end } |
| 150 | } | 156 | } |
| 151 | 157 | ||
| 152 | -/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`. | 158 | +/// A non-empty run of ASCII digits as a number. Anything else is `None`; a value too large for `u64` |
| 159 | +/// saturates to `u64::MAX`. | ||
| 153 | fn digits(text: &str) -> Option<u64> { | 160 | fn digits(text: &str) -> Option<u64> { |
| 154 | if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { | 161 | if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { |
| 155 | return None; | 162 | return None; |
| 156 | } | 163 | } |
| 157 | - text.parse().ok() | 164 | + Some(text.parse().unwrap_or(u64::MAX)) |
| 158 | } | 165 | } |
| 159 | 166 | ||
| 160 | /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong | 167 | /// 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( | |||
| 370 | ); | 377 | ); |
| 371 | let stream = blobs.open_range(source.blob_key, 0, source.size).await?; | 378 | let stream = blobs.open_range(source.blob_key, 0, source.size).await?; |
| 372 | let stream = match source.content_sha256 { | 379 | let stream = match source.content_sha256 { |
| 373 | - Some(sha256) => check_digest(stream, source.blob_key, sha256), | 380 | + Some(sha256) => check_digest(stream, source.blob_key, source.size, sha256), |
| 374 | None => stream, | 381 | None => stream, |
| 375 | }; | 382 | }; |
| 376 | Ok((StatusCode::OK, answer_headers, streamed(stream))) | 383 | Ok((StatusCode::OK, answer_headers, streamed(stream))) |
| @@ -420,24 +427,26 @@ mod tests { | |||
| 420 | (" bytes=1 - 2 ", Part { start: 1, end: 2 }), | 427 | (" bytes=1 - 2 ", Part { start: 1, end: 2 }), |
| 421 | // Several ranges: the whole file. | 428 | // Several ranges: the whole file. |
| 422 | ("bytes=0-1,5-6", Full), | 429 | ("bytes=0-1,5-6", Full), |
| 423 | - // Unsatisfiable or malformed. | 430 | + // Valid syntax the file cannot satisfy. |
| 424 | ("bytes=-0", Unsatisfiable), | 431 | ("bytes=-0", Unsatisfiable), |
| 425 | ("bytes=100-", Unsatisfiable), | 432 | ("bytes=100-", Unsatisfiable), |
| 426 | ("bytes=100-120", Unsatisfiable), | 433 | ("bytes=100-120", Unsatisfiable), |
| 427 | - ("bytes=20-10", Unsatisfiable), | ||
| 428 | - ("bytes=5-4", Unsatisfiable), | ||
| 429 | - ("bytes=-", Unsatisfiable), | ||
| 430 | - ("bytes=", Unsatisfiable), | ||
| 431 | - ("bytes=-x", Unsatisfiable), | ||
| 432 | - ("bytes=+1-2", Unsatisfiable), | ||
| 433 | - ("bytes=1e2-", Unsatisfiable), | ||
| 434 | - ("bytes=--1", Unsatisfiable), | ||
| 435 | - ("items=0-1", Unsatisfiable), | ||
| 436 | - ("0-1", Unsatisfiable), | ||
| 437 | - // Overflow of u64 is refused, not wrapped. | ||
| 438 | ("bytes=18446744073709551616-", Unsatisfiable), | 434 | ("bytes=18446744073709551616-", Unsatisfiable), |
| 439 | - ("bytes=0-18446744073709551616", Unsatisfiable), | 435 | + // Malformed, reversed or another unit: ignored, the whole file. |
| 440 | - ("bytes=-18446744073709551616", Unsatisfiable), | 436 | + ("bytes=20-10", Full), |
| 437 | + ("bytes=5-4", Full), | ||
| 438 | + ("bytes=-", Full), | ||
| 439 | + ("bytes=", Full), | ||
| 440 | + ("bytes=-x", Full), | ||
| 441 | + ("bytes=+1-2", Full), | ||
| 442 | + ("bytes=1e2-", Full), | ||
| 443 | + ("bytes=--1", Full), | ||
| 444 | + ("bytes=abc", Full), | ||
| 445 | + ("items=0-1", Full), | ||
| 446 | + ("0-1", Full), | ||
| 447 | + // A last byte too large for u64 is clamped to the file, not refused. | ||
| 448 | + ("bytes=0-18446744073709551616", Part { start: 0, end: 99 }), | ||
| 449 | + ("bytes=-18446744073709551616", Part { start: 0, end: 99 }), | ||
| 441 | ]; | 450 | ]; |
| 442 | for (header, want) in cases { | 451 | for (header, want) in cases { |
| 443 | assert_eq!(parse_range(header, 100), *want, "header {header:?}"); | 452 | assert_eq!(parse_range(header, 100), *want, "header {header:?}"); |
docs/architecture.mdmodified+16 -5
| @@ -187,14 +187,25 @@ and has no sessions. | |||
| 187 | 187 | ||
| 188 | ## 7. Byte serving (one function for every byte route) | 188 | ## 7. Byte serving (one function for every byte route) |
| 189 | 189 | ||
| 190 | -- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `"<sha256>"`; `If-None-Match` → 304. | 190 | +- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `"<sha256>"`; `If-None-Match` → 304. Per RFC 7233 |
| 191 | + 3.1 a `Range` that is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range | ||
| 192 | + the file cannot satisfy gets 416 with `Content-Range: bytes */<len>`. Several ranges get 200, whole file. | ||
| 191 | - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf, | 193 | - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf, |
| 192 | text/plain, and only when the action allows `View` and `dl` is not set; otherwise `attachment`. Always both | 194 | text/plain, and only when the action allows `View` and `dl` is not set; otherwise `attachment`. Always both |
| 193 | `filename="<ascii fallback>"` and `filename*=UTF-8''<percent-encoded>`. | 195 | `filename="<ascii fallback>"` and `filename*=UTF-8''<percent-encoded>`. |
| 194 | -- Every byte response: `X-Content-Type-Options: nosniff`, | 196 | +- Every byte response: `X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, |
| 195 | - `Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox`, | 197 | + `Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox; frame-ancestors 'self'`, |
| 196 | - `Cross-Origin-Resource-Policy: same-origin`, `Cache-Control: private, max-age=31536000, immutable` for | 198 | + `Cross-Origin-Resource-Policy: same-origin`. |
| 197 | - content addressed by id and hash, `private, no-cache` for share-link bytes. | 199 | + - PDFs get the same policy without `sandbox`. Browser PDF viewers do not run inside a sandboxed document and |
| 200 | + stop working, so a PDF is served inline without it. It stays safe: the type is fixed to `application/pdf` | ||
| 201 | + with `nosniff`, so it is never read as HTML, and `default-src 'none'` still blocks everything else. | ||
| 202 | +- `Cache-Control: private, no-cache` on every byte response, member bytes and share-link bytes alike. Not | ||
| 203 | + `immutable`: the same URL can return different bytes after an overwrite or a restore, and a grant change must | ||
| 204 | + be seen at once. The browser revalidates, and the `ETag` turns that into a cheap `304` while the bytes are the same. | ||
| 205 | +- A full-body answer of a stored file is hashed against its row's SHA-256 while it streams. The check runs on the | ||
| 206 | + frame that reaches the row's size, before that frame is sent: on a mismatch the body is cut short with no bad | ||
| 207 | + bytes, and the key is logged for `in fsck --hash`. A longer stream is refused the same way. Range answers are | ||
| 208 | + not checked (they are part of the file). | ||
| 198 | - Streams from the blob store in 64 KiB frames; never buffers a whole file. | 209 | - Streams from the blob store in 64 KiB frames; never buffers a whole file. |
| 199 | - The download counter counts a forced download that starts at byte 0, once per request. | 210 | - The download counter counts a forced download that starts at byte 0, once per request. |
| 200 | 211 | ||