forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

serve_bytes.rs522 lines, 21.3 KiBHistoryRawDownload
1//! The one function that sends a stored blob to a browser. Every byte route (download, raw, and the
2//! shared and public ones that come later) calls [`serve_bytes`], so the headers and the range rules
3//! exist in exactly one place (architecture section 7).
4//!
5//! The caller has already decided that the viewer may see the bytes (`authz`). This module decides how
6//! they are sent: a single byte range, a validator (`ETag`) and its conditional requests, a disposition
7//! that is `inline` only for types a browser can show without running them, and the response headers
8//! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of
9//! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole.
10//!
11//! Integrity rules: a full-body answer is hashed while it streams and aborted when the hash does not match
12//! the row (a changed blob, which the `ETag` would otherwise hide). A range answer is not checked: it is a
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.
15//!
16//! Range rules (RFC 7233 section 3.1): one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with
17//! several ranges gets the whole file with `200`. A header that is syntactically invalid, reversed, or in
18//! an unknown unit is ignored and gets the whole file with `200`. A valid range the file cannot satisfy
19//! gets `416` with `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one
20//! gets the whole file.
21
22use futures_util::TryStreamExt;
23use http::header::{
24 ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE,
25 CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE,
26 X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
27};
28use http_body::Frame;
29use http_body_util::StreamBody;
30use in_core::blob::{BlobStore, check_digest};
31use topcoat::Result;
32use topcoat::context::Cx;
33use topcoat::router::request::headers;
34use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode};
35
36/// What a browser may do with a byte response: show it in the page, or save it.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Disposition {
39 /// Show the bytes in the page. Granted only to the types in [`inline_safe`].
40 Inline,
41 /// Save the bytes as a file.
42 Attachment,
43}
44
45/// Everything about a stored file that a byte response needs. The caller fills it from the row.
46#[derive(Clone, Copy, Debug)]
47pub struct ByteSource<'a> {
48 /// Key of the bytes in the blob store.
49 pub blob_key: &'a str,
50 /// Length of the bytes in bytes.
51 pub size: u64,
52 /// The validator of the bytes, unquoted; the `ETag` is its quoted form. Equal validators mean equal bytes.
53 /// For a stored file it is [`file_validator`], which does not reveal the file's hash.
54 pub validator: &'a str,
55 /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer
56 /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as
57 /// thumbnails, whose validator is not the hash of what is stored.
58 pub content_sha256: Option<&'a str>,
59 /// The MIME type, as stored. For a file uploaded through the drive it is the sniffed type, never the
60 /// uploader's claim. For the objects API it is the calling service's claim, which is not sniffed.
61 pub mime: &'a str,
62 /// The display name, used for the `Content-Disposition` file name.
63 pub name: &'a str,
64}
65
66/// The status, headers and body of a byte response. Handlers return it as they are.
67pub type ByteAnswer = (StatusCode, HeaderMap, Body);
68
69/// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and
70/// `default-src 'none'` stops it from loading anything but its own image, media or style.
71/// Only the viewer page of this origin may frame the bytes.
72pub const BYTES_CSP: &str = "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; \
73 style-src 'unsafe-inline'; frame-ancestors 'self'";
74
75/// The same policy without `sandbox`, for PDFs only: browsers refuse to run their PDF viewer in a
76/// sandboxed document. A PDF is never interpreted as HTML (`nosniff`, fixed type), and the viewers
77/// keep PDF scripts away from the origin.
78pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; \
79 style-src 'unsafe-inline'; frame-ancestors 'self'";
80
81/// Cache policy of the member's own bytes (`/file` and `/thumb`). Access is revoked by a grant change, not by
82/// the URL, so a cached copy must not outlive the check: the browser revalidates, and the `ETag` turns that
83/// into a cheap `304` while the bytes are unchanged.
84const BYTES_CACHE: &str = "private, no-cache";
85
86/// Cache policy of bytes behind a public share link. The link can be revoked or its password changed, so
87/// a cached copy must not outlive the check: the browser asks again every time.
88pub const SHARE_CACHE: &str = "private, no-cache";
89
90/// The outcome of reading a `Range` header against a length.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum Ranged {
93 /// Send the whole file: no range, several ranges, or a header that is ignored (RFC 7233 3.1).
94 Full,
95 /// Send the bytes from `start` to `end`, both inclusive, and both inside the file.
96 Part {
97 /// First byte, inclusive.
98 start: u64,
99 /// Last byte, inclusive.
100 end: u64,
101 },
102 /// The header is valid but asks for nothing the file has. Answer `416`.
103 Unsatisfiable,
104}
105
106/// Parses the value of a `Range` header for a file of `len` bytes.
107///
108/// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last
109/// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give
110/// [`Ranged::Full`].
111///
112/// A header that is not valid syntax is ignored, so it gives [`Ranged::Full`] too: a unit other than
113/// `bytes`, a missing `-`, a non-digit, or a last byte before the first. A valid range the file cannot
114/// satisfy is [`Ranged::Unsatisfiable`]: a first byte at or past the end, a suffix of `-0`, or any range
115/// on an empty file. A number too large for `u64` is valid digits, so it saturates: as a first byte it is
116/// past the end, as a last byte it is clamped.
117pub fn parse_range(value: &str, len: u64) -> Ranged {
118 let Some(spec) = value.trim().strip_prefix("bytes=") else {
119 return Ranged::Full;
120 };
121 if spec.contains(',') {
122 return Ranged::Full;
123 }
124 let Some((first, last)) = spec.trim().split_once('-') else {
125 return Ranged::Full;
126 };
127 let (first, last) = (first.trim(), last.trim());
128 if first.is_empty() {
129 // A suffix range: the last `n` bytes.
130 let Some(n) = digits(last) else {
131 return Ranged::Full;
132 };
133 if n == 0 || len == 0 {
134 return Ranged::Unsatisfiable;
135 }
136 let n = n.min(len);
137 return Ranged::Part {
138 start: len - n,
139 end: len - 1,
140 };
141 }
142 let Some(start) = digits(first) else {
143 return Ranged::Full;
144 };
145 let end = if last.is_empty() {
146 None
147 } else {
148 match digits(last) {
149 Some(end) if end >= start => Some(end),
150 _ => return Ranged::Full,
151 }
152 };
153 if start >= len {
154 return Ranged::Unsatisfiable;
155 }
156 let end = end.map_or(len - 1, |end| end.min(len - 1));
157 Ranged::Part { start, end }
158}
159
160/// A non-empty run of ASCII digits as a number. Anything else is `None`; a value too large for `u64`
161/// saturates to `u64::MAX`.
162fn digits(text: &str) -> Option<u64> {
163 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
164 return None;
165 }
166 Some(text.parse().unwrap_or(u64::MAX))
167}
168
169/// The validator of a stored file's bytes. It is keyed (see [`in_core::secret::validator`]), so a viewer of
170/// the bytes learns nothing about the file's SHA-256 from the `ETag`, and cannot tell whether a file they know
171/// is stored in the drive.
172pub fn file_validator(key: &[u8; 32], sha256: &str) -> String {
173 in_core::secret::validator(key, "file", sha256)
174}
175
176/// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong
177/// form here, which is the rule for `GET` validators (RFC 9110).
178fn none_match_hits(request: &HeaderMap, etag: &str) -> bool {
179 request
180 .get(IF_NONE_MATCH)
181 .and_then(|value| value.to_str().ok())
182 .is_some_and(|value| {
183 value.split(',').map(str::trim).any(|candidate| {
184 candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
185 })
186 })
187}
188
189/// Whether a range may be honoured under `If-Range`. Without the header it always may. With it, only a
190/// strong validator equal to `etag` allows the range; a date or a weak tag never does.
191fn if_range_allows(request: &HeaderMap, etag: &str) -> bool {
192 match request.get(IF_RANGE).and_then(|value| value.to_str().ok()) {
193 None => true,
194 Some(value) => value.trim() == etag,
195 }
196}
197
198/// The range that applies to this request, after `If-Range` has had its say.
199fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged {
200 let Some(value) = request.get(RANGE).and_then(|value| value.to_str().ok()) else {
201 return Ranged::Full;
202 };
203 if !if_range_allows(request, etag) {
204 return Ranged::Full;
205 }
206 parse_range(value, len)
207}
208
209/// Whether serving this request counts as a download that started at byte 0. A `304`, a range that
210/// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does.
211/// The download counter is bumped by the caller before it serves the body. `validator` is the bytes'
212/// validator, as sent in [`ByteSource::validator`].
213pub fn counts_as_download(request: &HeaderMap, validator: &str, size: u64) -> bool {
214 let etag = format!("\"{validator}\"");
215 if none_match_hits(request, &etag) {
216 return false;
217 }
218 match requested_range(request, &etag, size) {
219 Ranged::Full => true,
220 Ranged::Part { start, .. } => start == 0,
221 Ranged::Unsatisfiable => false,
222 }
223}
224
225/// Whether a type may be shown inline. SVG is never inline: it can carry script. HTML is never inline.
226/// Images (except SVG and HEIC/HEIF, which browsers do not show everywhere), audio, video, PDF and plain
227/// text are.
228pub fn inline_safe(mime: &str) -> bool {
229 let essence = mime
230 .split(';')
231 .next()
232 .unwrap_or_default()
233 .trim()
234 .to_ascii_lowercase();
235 match essence.as_str() {
236 "image/svg+xml" | "image/heic" | "image/heif" => false,
237 "application/pdf" | "text/plain" => true,
238 other => {
239 other.starts_with("image/")
240 || other.starts_with("audio/")
241 || other.starts_with("video/")
242 }
243 }
244}
245
246/// The `Content-Type` value for a stored type. Plain text is always sent as UTF-8.
247fn content_type_value(mime: &str) -> String {
248 if mime.trim().eq_ignore_ascii_case("text/plain") {
249 "text/plain; charset=utf-8".into()
250 } else {
251 mime.to_string()
252 }
253}
254
255/// Characters that may appear unescaped in an RFC 5987 `filename*` value (`attr-char`).
256fn is_attr_char(b: u8) -> bool {
257 b.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&b)
258}
259
260/// The `Content-Disposition` header for a file name: `inline` or `attachment`, a quoted ASCII fallback
261/// and the UTF-8 name percent-encoded per RFC 5987.
262///
263/// The fallback keeps printable ASCII except the quote and the backslash, and turns everything else
264/// (control characters, including CR and LF, non-ASCII letters) into `_`. So no name can close the
265/// quoted string or start a new header line. The `filename*` value encodes every byte that is not an
266/// `attr-char`, which covers the same characters.
267pub fn content_disposition(kind: Disposition, name: &str) -> String {
268 let fallback: String = name
269 .chars()
270 .map(|c| {
271 if c.is_ascii() && (c.is_ascii_graphic() || c == ' ') && c != '"' && c != '\\' {
272 c
273 } else {
274 '_'
275 }
276 })
277 .collect();
278 let fallback = if fallback.trim().is_empty() {
279 "download".to_string()
280 } else {
281 fallback
282 };
283 let mut encoded = String::with_capacity(name.len());
284 for b in name.bytes() {
285 if is_attr_char(b) {
286 encoded.push(char::from(b));
287 } else {
288 encoded.push_str(&format!("%{b:02X}"));
289 }
290 }
291 let kind = match kind {
292 Disposition::Inline => "inline",
293 Disposition::Attachment => "attachment",
294 };
295 format!("{kind}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}")
296}
297
298/// The headers every byte response carries, whatever its status.
299fn common_headers(etag: &str, mime: &str, cache: &str) -> HeaderMap {
300 let mut headers = HeaderMap::new();
301 insert(&mut headers, ETAG, etag);
302 headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes"));
303 headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
304 let csp = if mime == "application/pdf" {
305 PDF_CSP
306 } else {
307 BYTES_CSP
308 };
309 headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(csp));
310 headers.insert(X_FRAME_OPTIONS, HeaderValue::from_static("SAMEORIGIN"));
311 headers.insert(
312 HeaderName::from_static("cross-origin-resource-policy"),
313 HeaderValue::from_static("same-origin"),
314 );
315 insert(&mut headers, CACHE_CONTROL, cache);
316 headers
317}
318
319/// Inserts a header whose value is text the code controls. A value that is not a valid header value is
320/// dropped, never sent half-formed; every caller passes ASCII that the code made.
321fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) {
322 if let Ok(value) = HeaderValue::from_str(value) {
323 headers.insert(name, value);
324 }
325}
326
327/// The `416` answer: no body, and the length the client may ask again within.
328fn unsatisfiable(etag: &str, len: u64, cache: &str) -> ByteAnswer {
329 let mut headers = common_headers(etag, "", cache);
330 insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}"));
331 (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty())
332}
333
334/// Sends the bytes of `source` for the request in `cx`.
335///
336/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in
337/// [`inline_safe`]. The body streams from the blob store from the first byte the answer needs. A
338/// missing blob is an error (the row names bytes that are not there), which the router answers as a
339/// `500`.
340pub async fn serve_bytes(
341 cx: &Cx,
342 blobs: &dyn BlobStore,
343 source: &ByteSource<'_>,
344 disposition: Disposition,
345) -> Result<ByteAnswer> {
346 serve_bytes_with(cx, blobs, source, disposition, BYTES_CACHE).await
347}
348
349/// [`serve_bytes`] with the cache policy given: the owner's bytes use [`BYTES_CACHE`], share-link bytes
350/// use [`SHARE_CACHE`]. Everything else is the same.
351pub async fn serve_bytes_with(
352 cx: &Cx,
353 blobs: &dyn BlobStore,
354 source: &ByteSource<'_>,
355 disposition: Disposition,
356 cache: &str,
357) -> Result<ByteAnswer> {
358 let request = headers(cx);
359 let etag = format!("\"{}\"", source.validator);
360 let disposition = match disposition {
361 Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,
362 _ => Disposition::Attachment,
363 };
364 let mut answer_headers = common_headers(&etag, source.mime, cache);
365 insert(
366 &mut answer_headers,
367 CONTENT_DISPOSITION,
368 &content_disposition(disposition, source.name),
369 );
370 insert(
371 &mut answer_headers,
372 CONTENT_TYPE,
373 &content_type_value(source.mime),
374 );
375
376 if none_match_hits(request, &etag) {
377 return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty()));
378 }
379
380 match requested_range(request, &etag, source.size) {
381 Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, cache)),
382 Ranged::Full => {
383 insert(
384 &mut answer_headers,
385 CONTENT_LENGTH,
386 &source.size.to_string(),
387 );
388 let stream = blobs.open_range(source.blob_key, 0, source.size).await?;
389 let stream = match source.content_sha256 {
390 Some(sha256) => check_digest(stream, source.blob_key, source.size, sha256),
391 None => stream,
392 };
393 Ok((StatusCode::OK, answer_headers, streamed(stream)))
394 }
395 Ranged::Part { start, end } => {
396 let length = end - start + 1;
397 insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string());
398 insert(
399 &mut answer_headers,
400 CONTENT_RANGE,
401 &format!("bytes {start}-{end}/{}", source.size),
402 );
403 // Not checked: this is a part of the file, so its bytes have no hash to compare with here.
404 let stream = blobs.open_range(source.blob_key, start, length).await?;
405 Ok((
406 StatusCode::PARTIAL_CONTENT,
407 answer_headers,
408 streamed(stream),
409 ))
410 }
411 }
412}
413
414/// Turns a blob stream into a response body. Frames are passed through as they come.
415fn streamed(stream: in_core::blob::BlobStream) -> Body {
416 Body::new(StreamBody::new(stream.map_ok(Frame::data)))
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422
423 /// A table of `Range` values for a 100-byte file, with the answer for each.
424 #[test]
425 fn range_table() {
426 use Ranged::*;
427 let cases: &[(&str, Ranged)] = &[
428 ("bytes=0-0", Part { start: 0, end: 0 }),
429 ("bytes=0-99", Part { start: 0, end: 99 }),
430 ("bytes=10-19", Part { start: 10, end: 19 }),
431 // Past the end is clamped, not refused.
432 ("bytes=50-500", Part { start: 50, end: 99 }),
433 ("bytes=90-", Part { start: 90, end: 99 }),
434 ("bytes=-10", Part { start: 90, end: 99 }),
435 // A suffix longer than the file is the whole file.
436 ("bytes=-1000", Part { start: 0, end: 99 }),
437 (" bytes=1 - 2 ", Part { start: 1, end: 2 }),
438 // Several ranges: the whole file.
439 ("bytes=0-1,5-6", Full),
440 // Valid syntax the file cannot satisfy.
441 ("bytes=-0", Unsatisfiable),
442 ("bytes=100-", Unsatisfiable),
443 ("bytes=100-120", Unsatisfiable),
444 ("bytes=18446744073709551616-", Unsatisfiable),
445 // Malformed, reversed or another unit: ignored, the whole file.
446 ("bytes=20-10", Full),
447 ("bytes=5-4", Full),
448 ("bytes=-", Full),
449 ("bytes=", Full),
450 ("bytes=-x", Full),
451 ("bytes=+1-2", Full),
452 ("bytes=1e2-", Full),
453 ("bytes=--1", Full),
454 ("bytes=abc", Full),
455 ("items=0-1", Full),
456 ("0-1", Full),
457 // A last byte too large for u64 is clamped to the file, not refused.
458 ("bytes=0-18446744073709551616", Part { start: 0, end: 99 }),
459 ("bytes=-18446744073709551616", Part { start: 0, end: 99 }),
460 ];
461 for (header, want) in cases {
462 assert_eq!(parse_range(header, 100), *want, "header {header:?}");
463 }
464 }
465
466 #[test]
467 fn an_empty_file_has_no_satisfiable_range() {
468 assert_eq!(parse_range("bytes=0-", 0), Ranged::Unsatisfiable);
469 assert_eq!(parse_range("bytes=-5", 0), Ranged::Unsatisfiable);
470 }
471
472 #[test]
473 fn disposition_is_inline_only_for_safe_types() {
474 assert!(inline_safe("image/png"));
475 assert!(inline_safe("application/pdf"));
476 assert!(inline_safe("text/plain; charset=utf-8"));
477 assert!(inline_safe("video/mp4"));
478 assert!(!inline_safe("image/svg+xml"));
479 assert!(!inline_safe("image/heic"));
480 assert!(!inline_safe("text/html"));
481 assert!(!inline_safe("application/octet-stream"));
482 assert_eq!(
483 content_type_value("text/plain"),
484 "text/plain; charset=utf-8"
485 );
486 }
487
488 /// Quotes, CR and LF, and a non-ASCII name cannot close the quoted string or add a header line.
489 #[test]
490 fn content_disposition_neutralises_quotes_crlf_and_unicode() {
491 let value = content_disposition(Disposition::Attachment, "a\"b\r\nc é.pdf");
492 assert!(!value.contains('\r') && !value.contains('\n'));
493 assert_eq!(
494 value.matches('"').count(),
495 2,
496 "only the two quotes: {value}"
497 );
498 assert_eq!(
499 value,
500 "attachment; filename=\"a_b__c _.pdf\"; filename*=UTF-8''a%22b%0D%0Ac%20%C3%A9.pdf"
501 );
502 let inline = content_disposition(Disposition::Inline, "plain.txt");
503 assert_eq!(
504 inline,
505 "inline; filename=\"plain.txt\"; filename*=UTF-8''plain.txt"
506 );
507 assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\""));
508 }
509
510 #[test]
511 fn a_download_counts_only_when_it_starts_at_byte_zero() {
512 let mut request = HeaderMap::new();
513 assert!(counts_as_download(&request, "ab", 10));
514 request.insert(RANGE, HeaderValue::from_static("bytes=0-3"));
515 assert!(counts_as_download(&request, "ab", 10));
516 request.insert(RANGE, HeaderValue::from_static("bytes=4-"));
517 assert!(!counts_as_download(&request, "ab", 10));
518 request.insert(RANGE, HeaderValue::from_static("bytes=0-3"));
519 request.insert(IF_NONE_MATCH, HeaderValue::from_static("\"ab\""));
520 assert!(!counts_as_download(&request, "ab", 10));
521 }
522}