Skip to main content

vcon_server/
console.rs

1//! The console: a web page served on the TLS listener at `/console/`. It
2//! is a client of the HTTP API and nothing more. Its files are built
3//! into the binary and need no key: they are the same for every caller,
4//! hold no data and change nothing. Every request the page makes is an API
5//! request that carries the key the user signed in with.
6
7use axum::Router;
8use axum::extract::Request;
9use axum::http::header::{CONTENT_TYPE, LOCATION};
10use axum::http::{HeaderName, HeaderValue, StatusCode};
11use axum::middleware::{self, Next};
12use axum::response::{IntoResponse, Response};
13use axum::routing::{any, get};
14
15/// One console file: its name under `/console/` (empty for the page),
16/// its bytes as built into the binary, and its media type.
17pub type File = (&'static str, &'static [u8], &'static str);
18
19/// Every file the console is made of. The router serves exactly these, and
20/// a test holds this list, the `console` directory and the package's
21/// `include` list to one another.
22pub const FILES: [File; 4] = [
23    (
24        "index.html",
25        include_bytes!("../console/index.html"),
26        "text/html; charset=utf-8",
27    ),
28    (
29        "console.js",
30        include_bytes!("../console/console.js"),
31        "text/javascript; charset=utf-8",
32    ),
33    (
34        "format.js",
35        include_bytes!("../console/format.js"),
36        "text/javascript; charset=utf-8",
37    ),
38    (
39        "console.css",
40        include_bytes!("../console/console.css"),
41        "text/css; charset=utf-8",
42    ),
43];
44
45/// The file the bare `/console/` path answers with.
46const PAGE: &str = "index.html";
47
48/// The path a console file is served at.
49#[must_use]
50pub fn path_of(name: &str) -> String {
51    if name == PAGE {
52        "/console/".to_owned()
53    } else {
54        format!("/console/{name}")
55    }
56}
57
58/// The headers on every console answer: no inline code, nothing from
59/// another origin, no framing, no sniffing, no referrer, no caching.
60pub const HEADERS: [(&str, &str); 7] = [
61    (
62        "content-security-policy",
63        "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
64         connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
65         require-trusted-types-for 'script'; trusted-types 'none'",
66    ),
67    ("x-frame-options", "DENY"),
68    ("x-content-type-options", "nosniff"),
69    ("referrer-policy", "no-referrer"),
70    ("cache-control", "no-store"),
71    ("cross-origin-opener-policy", "same-origin"),
72    ("cross-origin-resource-policy", "same-origin"),
73];
74
75/// The console's routes, merged into the API's router: its files,
76/// `/console` sent on to `/console/`, and 404 for any other path under
77/// it, each answer with the headers.
78pub fn router<S: Clone + Send + Sync + 'static>() -> Router<S> {
79    let mut router = Router::new().route(
80        "/console",
81        get(|| async { (StatusCode::PERMANENT_REDIRECT, [(LOCATION, "/console/")]) }),
82    );
83    for (name, body, media_type) in FILES {
84        router = router.route(&path_of(name), get(move || file(body, media_type)));
85    }
86    router
87        .route("/console/{*other}", any(|| async { StatusCode::NOT_FOUND }))
88        // On the console's own routes only, so the API's answers and its
89        // fallback are left as they are.
90        .route_layer(middleware::from_fn(with_headers))
91}
92
93async fn file(body: &'static [u8], media_type: &'static str) -> Response {
94    ([(CONTENT_TYPE, media_type)], body).into_response()
95}
96
97/// Puts every header in `HEADERS` on a console answer.
98async fn with_headers(request: Request, next: Next) -> Response {
99    let mut answer = next.run(request).await;
100    for (name, value) in HEADERS {
101        answer.headers_mut().insert(
102            HeaderName::from_static(name),
103            HeaderValue::from_static(value),
104        );
105    }
106    answer
107}
108
109#[cfg(test)]
110mod tests {
111    use std::path::PathBuf;
112
113    fn source(name: &str) -> String {
114        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
115            .join("console")
116            .join(name);
117        std::fs::read_to_string(path).expect("the source file")
118    }
119
120    /// Every script of the console, by name.
121    fn scripts() -> Vec<(&'static str, String)> {
122        super::FILES
123            .into_iter()
124            .filter(|(name, _, _)| name.ends_with(".js"))
125            .map(|(name, _, _)| (name, source(name)))
126            .collect()
127    }
128
129    /// The directory, the served list and the package's include list name
130    /// the same files, so a file added to one and not the others fails
131    /// here and not as a 404 in a browser or a broken published crate.
132    #[test]
133    fn the_directory_the_served_files_and_the_package_agree() {
134        let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("console");
135        let mut on_disk: Vec<String> = std::fs::read_dir(directory)
136            .expect("the console directory")
137            .map(|entry| {
138                entry
139                    .expect("an entry")
140                    .file_name()
141                    .into_string()
142                    .expect("a UTF-8 name")
143            })
144            .collect();
145        on_disk.sort();
146        let mut served: Vec<String> = super::FILES
147            .into_iter()
148            .map(|(name, _, _)| name.to_owned())
149            .collect();
150        served.sort();
151        assert_eq!(served, on_disk, "served files against the directory");
152        let manifest =
153            std::fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
154                .expect("the manifest");
155        for name in &on_disk {
156            assert!(
157                manifest.contains(&format!("\"/console/{name}\",")),
158                "the package includes {name}"
159            );
160        }
161    }
162
163    /// Each file is served with the media type its extension needs: a
164    /// module script under another type is refused by the browser.
165    #[test]
166    fn each_file_has_the_media_type_of_its_extension() {
167        for (name, body, media_type) in super::FILES {
168            let expected = match name.rsplit('.').next() {
169                Some("html") => "text/html; charset=utf-8",
170                Some("js") => "text/javascript; charset=utf-8",
171                Some("css") => "text/css; charset=utf-8",
172                other => panic!("{name}: no media type for {other:?}"),
173            };
174            assert_eq!(media_type, expected, "{name}");
175            assert!(!body.is_empty(), "{name} is not empty");
176            assert!(std::str::from_utf8(body).is_ok(), "{name} is UTF-8");
177        }
178    }
179
180    #[test]
181    fn the_page_is_served_at_the_directory_path_and_the_rest_by_name() {
182        assert_eq!(super::path_of("index.html"), "/console/", "index.html");
183        assert_eq!(
184            super::path_of("console.js"),
185            "/console/console.js",
186            "console.js"
187        );
188        assert_eq!(
189            super::path_of("console.css"),
190            "/console/console.css",
191            "console.css"
192        );
193        assert_eq!(
194            super::path_of("format.js"),
195            "/console/format.js",
196            "format.js"
197        );
198    }
199
200    /// The headers hold the rules the design sets, so a weaker policy
201    /// fails here, not only in a browser: the CSP allows nothing by
202    /// default, each source is the console's own origin or none, and no
203    /// script may run but the console's file; the page is never framed,
204    /// cached, sniffed or sent a referrer.
205    #[test]
206    fn the_headers_are_the_designed_ones() {
207        let headers: std::collections::BTreeMap<&str, &str> = super::HEADERS.into_iter().collect();
208        assert_eq!(headers.len(), super::HEADERS.len(), "each header once");
209        let csp: std::collections::BTreeMap<&str, Vec<&str>> = headers["content-security-policy"]
210            .split(';')
211            .map(|d| {
212                let mut words = d.split_whitespace();
213                (words.next().expect("a directive"), words.collect())
214            })
215            .collect();
216        for (directive, sources) in [
217            ("default-src", ["'none'"]),
218            ("script-src", ["'self'"]),
219            ("frame-ancestors", ["'none'"]),
220            ("base-uri", ["'none'"]),
221            ("form-action", ["'none'"]),
222            ("require-trusted-types-for", ["'script'"]),
223            ("trusted-types", ["'none'"]),
224        ] {
225            assert_eq!(csp.get(directive), Some(&sources.to_vec()), "{directive}");
226        }
227        for (directive, sources) in &csp {
228            assert!(
229                sources
230                    .iter()
231                    .all(|s| ["'none'", "'self'", "'script'"].contains(s)),
232                "{directive} allows only the console's own origin: {sources:?}"
233            );
234        }
235        for (name, value) in [
236            ("x-frame-options", "DENY"),
237            ("x-content-type-options", "nosniff"),
238            ("referrer-policy", "no-referrer"),
239            ("cache-control", "no-store"),
240            ("cross-origin-opener-policy", "same-origin"),
241            ("cross-origin-resource-policy", "same-origin"),
242        ] {
243            assert_eq!(headers.get(name), Some(&value), "{name}");
244        }
245    }
246
247    /// The page loads its one script and one stylesheet and holds no
248    /// inline script, style or event handler, which the CSP would refuse.
249    #[test]
250    fn the_page_holds_no_inline_code() {
251        let page = source("index.html");
252        assert!(
253            page.contains(r#"<script type="module" src="console.js"></script>"#),
254            "the page loads its script"
255        );
256        assert!(
257            page.contains(r#"<link rel="stylesheet" href="console.css">"#),
258            "the page loads its styles"
259        );
260        let lower = page.to_lowercase();
261        assert_eq!(lower.matches("<script").count(), 1, "one script element");
262        assert!(!lower.contains("<style"), "no style element");
263        assert!(!lower.contains(" style="), "no style attribute");
264        assert!(!has_event_handler(&page), "no event-handler attribute");
265    }
266
267    /// Whether markup holds an attribute such as `onclick=`: whitespace,
268    /// `on`, a name of letters, then `=` after any spaces.
269    fn has_event_handler(html: &str) -> bool {
270        let lower = html.to_lowercase();
271        lower
272            .match_indices("on")
273            .filter(|(at, _)| lower[..*at].ends_with(char::is_whitespace))
274            .any(|(at, _)| {
275                let rest = &lower[at + 2..];
276                let name = rest.chars().take_while(char::is_ascii_lowercase).count();
277                name > 0 && rest[name..].trim_start().starts_with('=')
278            })
279    }
280
281    #[test]
282    fn an_event_handler_is_found_wherever_it_is() {
283        for found in [
284            "<b onclick=\"x\">",
285            "<b\nonload = x>",
286            "<img src=a ONERROR=x>",
287        ] {
288            assert!(has_event_handler(found), "{found}");
289        }
290        for clean in [
291            "<b class=on>",
292            "<b>on=</b>",
293            "<a href=\"x\">done</a>",
294            "<b on=x>",
295        ] {
296            assert!(!has_event_handler(clean), "{clean}");
297        }
298    }
299
300    /// No script reaches the page through markup, runs code from strings
301    /// or keeps anything in browser storage; values are set as text.
302    #[test]
303    fn no_script_uses_an_html_sink_or_storage() {
304        for (name, script) in scripts() {
305            for refused in [
306                "innerHTML",
307                "outerHTML",
308                "insertAdjacentHTML",
309                "document.write",
310                "eval(",
311                "Function(",
312                "setTimeout(\"",
313                "setInterval(\"",
314                "localStorage",
315                "sessionStorage",
316                "indexedDB",
317                "document.cookie",
318                "caches.",
319            ] {
320                assert!(!script.contains(refused), "{name} uses {refused}");
321            }
322        }
323        assert!(
324            source("console.js").contains("textContent"),
325            "values are set as text"
326        );
327    }
328
329    /// Every request goes through one call of `fetch`, which never lets
330    /// the browser keep the answer, send a cookie or follow a redirect.
331    #[test]
332    fn every_request_goes_through_one_fetch() {
333        let calls: usize = scripts()
334            .iter()
335            .map(|(_, script)| script.matches("fetch(").count())
336            .sum();
337        assert_eq!(calls, 1, "one fetch call in all the scripts");
338        let script = source("console.js");
339        for option in [
340            r#"cache: "no-store""#,
341            r#"credentials: "omit""#,
342            r#"redirect: "error""#,
343        ] {
344            assert!(script.contains(option), "fetch is made with {option}");
345        }
346    }
347}