Skip to main content

compmd_host/
respond.rs

1//! The serving contract ([hosting], decision 8): a bundle's frames and the packs the bundle or the store holds, with
2//! the headers that sandbox them, and a refusal, saying why, for anything else.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use compmd_pack::{FilePath, Place};
7use http::header::{self, HeaderValue};
8use http::{Method, Request, Response, StatusCode};
9
10use crate::bundle::Bundle;
11use crate::content_type::content_type;
12use crate::store::Store;
13
14/// The headers every served file has.
15const HEADERS: [(&str, &str); 5] = [
16    // Sandboxed even when a frame document is opened outside a frame.
17    ("content-security-policy", "sandbox allow-scripts"),
18    // A frame's module scripts come from an opaque origin, so they are cross-origin requests.
19    (ALLOW_ORIGIN, "*"),
20    // A page that checks how its frames are served (a host's check) reads these headers.
21    ("access-control-expose-headers", "*"),
22    ("x-content-type-options", "nosniff"),
23    // A frame's path names its build, a pack's its version, so what it serves never changes.
24    ("cache-control", "max-age=31536000, immutable"),
25];
26
27/// Readable from any origin: a file, and a refusal, so a page reads why.
28const ALLOW_ORIGIN: &str = "access-control-allow-origin";
29
30/// Why a request that isn't for a file the host serves is refused.
31const NOT_SERVED: &str = "not a file of the frames or packs this host serves";
32
33/// Why a request with another method is refused.
34const ONLY_GET: &str = "the frames and packs are only read, with GET";
35
36/// The answer to `request`: the frames' file or pack file it names, from the bundle or, for a pack the bundle doesn't
37/// hold, from `store`; a `405` for another method than `GET`; a `404` for anything else. Each refusal says why.
38///
39/// The paths it answers are `/frames/<hash>/<path>`, with the bundle's hash, and `/packs/<place>`, where a path is a
40/// [`FilePath`], which can't leave its folder.
41pub fn respond<B>(bundle: &Bundle, store: &dyn Store, request: &Request<B>) -> Response<Vec<u8>> {
42    if request.method() != Method::GET {
43        return refused(StatusCode::METHOD_NOT_ALLOWED, ONLY_GET);
44    }
45    let path = request.uri().path();
46    file(bundle, store, path).map_or_else(
47        || refused(StatusCode::NOT_FOUND, NOT_SERVED),
48        |(body, path)| served(&path, body),
49    )
50}
51
52/// The bytes of the file `path` names, with the path its type comes from.
53fn file(bundle: &Bundle, store: &dyn Store, path: &str) -> Option<(Vec<u8>, FilePath)> {
54    let parts: Vec<&str> = path.strip_prefix('/')?.split('/').collect();
55    match parts.as_slice() {
56        ["frames", hash, file @ ..] if *hash == bundle.manifest().frames.hash.as_str() => {
57            let path = FilePath::new(file.join("/")).ok()?;
58            Some((bundle.frame_file(&path)?, path))
59        }
60        ["packs", place @ ..] => {
61            let place = Place::from_parts(place)?;
62            let body = bundle.pack_file(&place).or_else(|| store.file(&place))?;
63            Some((body, place.path))
64        }
65        _ => None,
66    }
67}
68
69/// `body`, the file at `path`, with its type and the headers.
70fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
71    let mut response = with_type(StatusCode::OK, content_type(path.as_str()), body);
72    let headers = response.headers_mut();
73    for (name, value) in HEADERS {
74        headers.insert(name, HeaderValue::from_static(value));
75    }
76    response
77}
78
79/// A refusal with `status`, saying `why` in plain text, to any origin.
80fn refused(status: StatusCode, why: &str) -> Response<Vec<u8>> {
81    let mut response = with_type(status, "text/plain; charset=utf-8", why.as_bytes().to_vec());
82    response
83        .headers_mut()
84        .insert(ALLOW_ORIGIN, HeaderValue::from_static("*"));
85    response
86}
87
88/// `body` with `status` and the content type `kind`.
89fn with_type(status: StatusCode, kind: &'static str, body: Vec<u8>) -> Response<Vec<u8>> {
90    let mut response = Response::new(body);
91    *response.status_mut() = status;
92    response
93        .headers_mut()
94        .insert(header::CONTENT_TYPE, HeaderValue::from_static(kind));
95    response
96}
97
98#[cfg(test)]
99mod tests;