//! The one function that sends a stored blob to a browser. Every byte route (download, raw, and the //! shared and public ones that come later) calls [`serve_bytes`], so the headers and the range rules //! exist in exactly one place (architecture section 7). //! //! The caller has already decided that the viewer may see the bytes (`authz`). This module decides how //! they are sent: a single byte range, a validator (`ETag`) and its conditional requests, a disposition //! that is `inline` only for types a browser can show without running them, and the response headers //! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of //! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole. //! //! Integrity rules: a full-body answer is hashed while it streams and aborted when the hash does not match //! the row (a changed blob, which the `ETag` would otherwise hide). A range answer is not checked: it is a //! part of the file, and a partial read cannot be compared with the whole-file hash. `in fsck --hash` //! checks every blob in full. //! //! Range rules (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::{ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS, }; use http_body::Frame; use http_body_util::StreamBody; use in_core::blob::{BlobStore, check_digest}; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::request::headers; use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; /// What a browser may do with a byte response: show it in the page, or save it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Disposition { /// Show the bytes in the page. Granted only to the types in [`inline_safe`]. Inline, /// Save the bytes as a file. Attachment, } /// Everything about a stored file that a byte response needs. The caller fills it from the row. #[derive(Clone, Copy, Debug)] pub struct ByteSource<'a> { /// Key of the bytes in the blob store. pub blob_key: &'a str, /// Length of the bytes in bytes. pub size: u64, /// The validator of the bytes, unquoted; the `ETag` is its quoted form. Equal validators mean equal bytes. /// For a stored file it is [`file_validator`], which does not reveal the file's hash. pub validator: &'a str, /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as /// thumbnails, whose validator is not the hash of what is stored. pub content_sha256: Option<&'a str>, /// The MIME type, as stored. For a file uploaded through the drive it is the sniffed type, never the /// uploader's claim. For the objects API it is the calling service's claim, which is not sniffed. pub mime: &'a str, /// The display name, used for the `Content-Disposition` file name. pub name: &'a str, } /// The status, headers and body of a byte response. Handlers return it as they are. pub type ByteAnswer = (StatusCode, HeaderMap, Body); /// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and /// `default-src 'none'` stops it from loading anything but its own image, media or style. /// Only the viewer page of this origin may frame the bytes. pub const BYTES_CSP: &str = "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; \ style-src 'unsafe-inline'; frame-ancestors 'self'"; /// The same policy without `sandbox`, for PDFs only: browsers refuse to run their PDF viewer in a /// sandboxed document. A PDF is never interpreted as HTML (`nosniff`, fixed type), and the viewers /// keep PDF scripts away from the origin. pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; \ style-src 'unsafe-inline'; frame-ancestors 'self'"; /// Cache policy of the member's own bytes (`/file` and `/thumb`). Access is revoked by a grant change, not by /// the URL, so a cached copy must not outlive the check: the browser revalidates, and the `ETag` turns that /// into a cheap `304` while the bytes are unchanged. const BYTES_CACHE: &str = "private, no-cache"; /// Cache policy of bytes behind a public share link. The link can be revoked or its password changed, so /// a cached copy must not outlive the check: the browser asks again every time. 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, 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 { /// First byte, inclusive. start: u64, /// Last byte, inclusive. end: u64, }, /// The header is valid but asks for nothing the file has. Answer `416`. Unsatisfiable, } /// Parses the value of a `Range` header for a file of `len` bytes. /// /// 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`]. /// /// 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::Full; }; if spec.contains(',') { return Ranged::Full; } let Some((first, last)) = spec.trim().split_once('-') else { 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::Full; }; if n == 0 || len == 0 { return Ranged::Unsatisfiable; } let n = n.min(len); return Ranged::Part { start: len - n, end: len - 1, }; } let Some(start) = digits(first) else { return Ranged::Full; }; let end = if last.is_empty() { None } else { match digits(last) { Some(end) if end >= start => Some(end), _ => return Ranged::Full, } }; if start >= len { return Ranged::Unsatisfiable; } let end = end.map_or(len - 1, |end| end.min(len - 1)); Ranged::Part { start, end } } /// 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; } Some(text.parse().unwrap_or(u64::MAX)) } /// The validator of a stored file's bytes. It is keyed (see [`in_core::secret::validator`]), so a viewer of /// the bytes learns nothing about the file's SHA-256 from the `ETag`, and cannot tell whether a file they know /// is stored in the drive. pub fn file_validator(key: &[u8; 32], sha256: &str) -> String { in_core::secret::validator(key, "file", sha256) } /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong /// form here, which is the rule for `GET` validators (RFC 9110). fn none_match_hits(request: &HeaderMap, etag: &str) -> bool { request .get(IF_NONE_MATCH) .and_then(|value| value.to_str().ok()) .is_some_and(|value| { value.split(',').map(str::trim).any(|candidate| { candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag }) }) } /// Whether a range may be honoured under `If-Range`. Without the header it always may. With it, only a /// strong validator equal to `etag` allows the range; a date or a weak tag never does. fn if_range_allows(request: &HeaderMap, etag: &str) -> bool { match request.get(IF_RANGE).and_then(|value| value.to_str().ok()) { None => true, Some(value) => value.trim() == etag, } } /// The range that applies to this request, after `If-Range` has had its say. fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged { let Some(value) = request.get(RANGE).and_then(|value| value.to_str().ok()) else { return Ranged::Full; }; if !if_range_allows(request, etag) { return Ranged::Full; } parse_range(value, len) } /// Whether serving this request counts as a download that started at byte 0. A `304`, a range that /// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does. /// The download counter is bumped by the caller before it serves the body. `validator` is the bytes' /// validator, as sent in [`ByteSource::validator`]. pub fn counts_as_download(request: &HeaderMap, validator: &str, size: u64) -> bool { let etag = format!("\"{validator}\""); if none_match_hits(request, &etag) { return false; } match requested_range(request, &etag, size) { Ranged::Full => true, Ranged::Part { start, .. } => start == 0, Ranged::Unsatisfiable => false, } } /// Whether a type may be shown inline. SVG is never inline: it can carry script. HTML is never inline. /// Images (except SVG and HEIC/HEIF, which browsers do not show everywhere), audio, video, PDF and plain /// text are. pub fn inline_safe(mime: &str) -> bool { let essence = mime .split(';') .next() .unwrap_or_default() .trim() .to_ascii_lowercase(); match essence.as_str() { "image/svg+xml" | "image/heic" | "image/heif" => false, "application/pdf" | "text/plain" => true, other => { other.starts_with("image/") || other.starts_with("audio/") || other.starts_with("video/") } } } /// The `Content-Type` value for a stored type. Plain text is always sent as UTF-8. fn content_type_value(mime: &str) -> String { if mime.trim().eq_ignore_ascii_case("text/plain") { "text/plain; charset=utf-8".into() } else { mime.to_string() } } /// Characters that may appear unescaped in an RFC 5987 `filename*` value (`attr-char`). fn is_attr_char(b: u8) -> bool { b.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&b) } /// The `Content-Disposition` header for a file name: `inline` or `attachment`, a quoted ASCII fallback /// and the UTF-8 name percent-encoded per RFC 5987. /// /// The fallback keeps printable ASCII except the quote and the backslash, and turns everything else /// (control characters, including CR and LF, non-ASCII letters) into `_`. So no name can close the /// quoted string or start a new header line. The `filename*` value encodes every byte that is not an /// `attr-char`, which covers the same characters. pub fn content_disposition(kind: Disposition, name: &str) -> String { let fallback: String = name .chars() .map(|c| { if c.is_ascii() && (c.is_ascii_graphic() || c == ' ') && c != '"' && c != '\\' { c } else { '_' } }) .collect(); let fallback = if fallback.trim().is_empty() { "download".to_string() } else { fallback }; let mut encoded = String::with_capacity(name.len()); for b in name.bytes() { if is_attr_char(b) { encoded.push(char::from(b)); } else { encoded.push_str(&format!("%{b:02X}")); } } let kind = match kind { Disposition::Inline => "inline", Disposition::Attachment => "attachment", }; format!("{kind}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}") } /// The headers every byte response carries, whatever its status. fn common_headers(etag: &str, mime: &str, cache: &str) -> HeaderMap { let mut headers = HeaderMap::new(); insert(&mut headers, ETAG, etag); headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); let csp = if mime == "application/pdf" { PDF_CSP } else { BYTES_CSP }; headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(csp)); headers.insert(X_FRAME_OPTIONS, HeaderValue::from_static("SAMEORIGIN")); headers.insert( HeaderName::from_static("cross-origin-resource-policy"), HeaderValue::from_static("same-origin"), ); insert(&mut headers, CACHE_CONTROL, cache); headers } /// Inserts a header whose value is text the code controls. A value that is not a valid header value is /// dropped, never sent half-formed; every caller passes ASCII that the code made. fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { if let Ok(value) = HeaderValue::from_str(value) { headers.insert(name, value); } } /// The `416` answer: no body, and the length the client may ask again within. fn unsatisfiable(etag: &str, len: u64, cache: &str) -> ByteAnswer { let mut headers = common_headers(etag, "", cache); insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) } /// Sends the bytes of `source` for the request in `cx`. /// /// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in /// [`inline_safe`]. The body streams from the blob store from the first byte the answer needs. A /// missing blob is an error (the row names bytes that are not there), which the router answers as a /// `500`. pub async fn serve_bytes( cx: &Cx, blobs: &dyn BlobStore, source: &ByteSource<'_>, disposition: Disposition, ) -> Result { serve_bytes_with(cx, blobs, source, disposition, BYTES_CACHE).await } /// [`serve_bytes`] with the cache policy given: the owner's bytes use [`BYTES_CACHE`], share-link bytes /// use [`SHARE_CACHE`]. Everything else is the same. pub async fn serve_bytes_with( cx: &Cx, blobs: &dyn BlobStore, source: &ByteSource<'_>, disposition: Disposition, cache: &str, ) -> Result { let request = headers(cx); let etag = format!("\"{}\"", source.validator); let disposition = match disposition { Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, _ => Disposition::Attachment, }; let mut answer_headers = common_headers(&etag, source.mime, cache); insert( &mut answer_headers, CONTENT_DISPOSITION, &content_disposition(disposition, source.name), ); insert( &mut answer_headers, CONTENT_TYPE, &content_type_value(source.mime), ); if none_match_hits(request, &etag) { return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty())); } match requested_range(request, &etag, source.size) { Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, cache)), Ranged::Full => { insert( &mut answer_headers, CONTENT_LENGTH, &source.size.to_string(), ); let stream = blobs.open_range(source.blob_key, 0, source.size).await?; let stream = match source.content_sha256 { Some(sha256) => check_digest(stream, source.blob_key, source.size, sha256), None => stream, }; Ok((StatusCode::OK, answer_headers, streamed(stream))) } Ranged::Part { start, end } => { let length = end - start + 1; insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string()); insert( &mut answer_headers, CONTENT_RANGE, &format!("bytes {start}-{end}/{}", source.size), ); // Not checked: this is a part of the file, so its bytes have no hash to compare with here. let stream = blobs.open_range(source.blob_key, start, length).await?; Ok(( StatusCode::PARTIAL_CONTENT, answer_headers, streamed(stream), )) } } } /// Turns a blob stream into a response body. Frames are passed through as they come. fn streamed(stream: in_core::blob::BlobStream) -> Body { Body::new(StreamBody::new(stream.map_ok(Frame::data))) } #[cfg(test)] mod tests { use super::*; /// A table of `Range` values for a 100-byte file, with the answer for each. #[test] fn range_table() { use Ranged::*; let cases: &[(&str, Ranged)] = &[ ("bytes=0-0", Part { start: 0, end: 0 }), ("bytes=0-99", Part { start: 0, end: 99 }), ("bytes=10-19", Part { start: 10, end: 19 }), // Past the end is clamped, not refused. ("bytes=50-500", Part { start: 50, end: 99 }), ("bytes=90-", Part { start: 90, end: 99 }), ("bytes=-10", Part { start: 90, end: 99 }), // A suffix longer than the file is the whole file. ("bytes=-1000", Part { start: 0, end: 99 }), (" bytes=1 - 2 ", Part { start: 1, end: 2 }), // Several ranges: the whole file. ("bytes=0-1,5-6", Full), // Valid syntax the file cannot satisfy. ("bytes=-0", Unsatisfiable), ("bytes=100-", Unsatisfiable), ("bytes=100-120", 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:?}"); } } #[test] fn an_empty_file_has_no_satisfiable_range() { assert_eq!(parse_range("bytes=0-", 0), Ranged::Unsatisfiable); assert_eq!(parse_range("bytes=-5", 0), Ranged::Unsatisfiable); } #[test] fn disposition_is_inline_only_for_safe_types() { assert!(inline_safe("image/png")); assert!(inline_safe("application/pdf")); assert!(inline_safe("text/plain; charset=utf-8")); assert!(inline_safe("video/mp4")); assert!(!inline_safe("image/svg+xml")); assert!(!inline_safe("image/heic")); assert!(!inline_safe("text/html")); assert!(!inline_safe("application/octet-stream")); assert_eq!( content_type_value("text/plain"), "text/plain; charset=utf-8" ); } /// Quotes, CR and LF, and a non-ASCII name cannot close the quoted string or add a header line. #[test] fn content_disposition_neutralises_quotes_crlf_and_unicode() { let value = content_disposition(Disposition::Attachment, "a\"b\r\nc é.pdf"); assert!(!value.contains('\r') && !value.contains('\n')); assert_eq!( value.matches('"').count(), 2, "only the two quotes: {value}" ); assert_eq!( value, "attachment; filename=\"a_b__c _.pdf\"; filename*=UTF-8''a%22b%0D%0Ac%20%C3%A9.pdf" ); let inline = content_disposition(Disposition::Inline, "plain.txt"); assert_eq!( inline, "inline; filename=\"plain.txt\"; filename*=UTF-8''plain.txt" ); assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\"")); } #[test] fn a_download_counts_only_when_it_starts_at_byte_zero() { let mut request = HeaderMap::new(); assert!(counts_as_download(&request, "ab", 10)); request.insert(RANGE, HeaderValue::from_static("bytes=0-3")); assert!(counts_as_download(&request, "ab", 10)); request.insert(RANGE, HeaderValue::from_static("bytes=4-")); assert!(!counts_as_download(&request, "ab", 10)); request.insert(RANGE, HeaderValue::from_static("bytes=0-3")); request.insert(IF_NONE_MATCH, HeaderValue::from_static("\"ab\"")); assert!(!counts_as_download(&request, "ab", 10)); } }