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_SECURITY_POLICY, CONTENT_TYPE, LOCATION};
10use axum::http::{HeaderName, HeaderValue, StatusCode};
11use axum::middleware::{self, Next};
12use axum::response::{IntoResponse, Response};
13use axum::routing::{MethodRouter, any, get, post};
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; 6] = [
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        "player.html",
45        include_bytes!("../console/player.html"),
46        "text/html; charset=utf-8",
47    ),
48    (
49        "player.js",
50        include_bytes!("../console/player.js"),
51        "text/javascript; charset=utf-8",
52    ),
53];
54
55/// The file the bare `/console/` path answers with.
56const PAGE: &str = "index.html";
57
58/// The path a console file is served at.
59#[must_use]
60pub fn path_of(name: &str) -> String {
61    if name == PAGE {
62        "/console/".to_owned()
63    } else {
64        format!("/console/{name}")
65    }
66}
67
68/// The headers on every console answer: no inline code, nothing from
69/// another origin, no framing, no sniffing, no referrer, no caching. The
70/// player's page alone carries [`PLAYER_POLICY`] in place of the first.
71pub const HEADERS: [(&str, &str); 7] = [
72    (
73        "content-security-policy",
74        "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
75         connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
76         require-trusted-types-for 'script'; trusted-types 'none'; \
77         report-uri /console/csp-report",
78    ),
79    ("x-frame-options", "DENY"),
80    ("x-content-type-options", "nosniff"),
81    ("referrer-policy", "no-referrer"),
82    ("cache-control", "no-store"),
83    ("cross-origin-opener-policy", "same-origin"),
84    ("cross-origin-resource-policy", "same-origin"),
85];
86
87/// The policy of the player's page: the console's, but a recording may
88/// play from a blob made in the page (`media-src blob:`) and the page may
89/// make no request at all (`connect-src 'none'`). The console hands the
90/// player the bytes; the player fetches nothing.
91pub const PLAYER_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
92     connect-src 'none'; media-src blob:; base-uri 'none'; form-action 'none'; \
93     frame-ancestors 'none'; require-trusted-types-for 'script'; trusted-types 'none'; \
94     report-uri /console/csp-report";
95
96/// The path of the player's page, the one console answer with a policy
97/// of its own.
98pub const PLAYER_PATH: &str = "/console/player.html";
99
100/// The content-security policy of the answer at `path`: the player's for
101/// the player's page and the console's for everything else.
102#[must_use]
103pub fn policy_for(path: &str) -> &'static str {
104    if path == PLAYER_PATH {
105        PLAYER_POLICY
106    } else {
107        HEADERS[0].1
108    }
109}
110
111/// The console's routes, merged into the API's router: its files,
112/// `/console` sent on to `/console/`, and 404 for any other path under
113/// it, each answer with the headers. A report sent to [`REPORT_PATH`] is
114/// answered 204 and dropped; the server's own router counts each one
115/// (`api::router`).
116pub fn router<S: Clone + Send + Sync + 'static>() -> Router<S> {
117    router_with(post(dropped))
118}
119
120/// The public router's answer to a report: taken, and dropped.
121async fn dropped() -> StatusCode {
122    StatusCode::NO_CONTENT
123}
124
125/// The path the policies tell a browser to send its reports of a
126/// violation to.
127pub const REPORT_PATH: &str = "/console/csp-report";
128
129/// [`router`], with `report` serving [`REPORT_PATH`].
130pub(crate) fn router_with<S: Clone + Send + Sync + 'static>(report: MethodRouter<S>) -> Router<S> {
131    let mut router = Router::new().route(
132        "/console",
133        get(|| async { (StatusCode::PERMANENT_REDIRECT, [(LOCATION, "/console/")]) }),
134    );
135    for (name, body, media_type) in FILES {
136        router = router.route(&path_of(name), get(move || file(body, media_type)));
137    }
138    router
139        .route(REPORT_PATH, report)
140        .route("/console/{*other}", any(|| async { StatusCode::NOT_FOUND }))
141        // On the console's own routes only, so the API's answers and its
142        // fallback are left as they are.
143        .route_layer(middleware::from_fn(with_headers))
144}
145
146async fn file(body: &'static [u8], media_type: &'static str) -> Response {
147    ([(CONTENT_TYPE, media_type)], body).into_response()
148}
149
150/// Puts every header in `HEADERS` on a console answer. The player's
151/// page, when it is served, carries its own policy in place of the
152/// console's; a refusal at its path is not the page and does not.
153async fn with_headers(request: Request, next: Next) -> Response {
154    let policy = policy_for(request.uri().path());
155    let mut answer = next.run(request).await;
156    for (name, value) in HEADERS {
157        answer.headers_mut().insert(
158            HeaderName::from_static(name),
159            HeaderValue::from_static(value),
160        );
161    }
162    if answer.status() == StatusCode::OK {
163        answer
164            .headers_mut()
165            .insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(policy));
166    }
167    answer
168}
169
170#[cfg(test)]
171mod tests {
172    use std::path::PathBuf;
173
174    fn source(name: &str) -> String {
175        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
176            .join("console")
177            .join(name);
178        std::fs::read_to_string(path).expect("the source file")
179    }
180
181    /// Every script of the console, by name.
182    fn scripts() -> Vec<(&'static str, String)> {
183        super::FILES
184            .into_iter()
185            .filter(|(name, _, _)| name.ends_with(".js"))
186            .map(|(name, _, _)| (name, source(name)))
187            .collect()
188    }
189
190    /// The directory, the served list and the package's include list name
191    /// the same files, so a file added to one and not the others fails
192    /// here and not as a 404 in a browser or a broken published crate.
193    #[test]
194    fn the_directory_the_served_files_and_the_package_agree() {
195        let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("console");
196        let mut on_disk: Vec<String> = std::fs::read_dir(directory)
197            .expect("the console directory")
198            .map(|entry| {
199                entry
200                    .expect("an entry")
201                    .file_name()
202                    .into_string()
203                    .expect("a UTF-8 name")
204            })
205            .collect();
206        on_disk.sort();
207        let mut served: Vec<String> = super::FILES
208            .into_iter()
209            .map(|(name, _, _)| name.to_owned())
210            .collect();
211        served.sort();
212        assert_eq!(served, on_disk, "served files against the directory");
213        let manifest =
214            std::fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
215                .expect("the manifest");
216        for name in &on_disk {
217            assert!(
218                manifest.contains(&format!("\"/console/{name}\",")),
219                "the package includes {name}"
220            );
221        }
222    }
223
224    /// Each file is served with the media type its extension needs: a
225    /// module script under another type is refused by the browser.
226    #[test]
227    fn each_file_has_the_media_type_of_its_extension() {
228        for (name, body, media_type) in super::FILES {
229            let expected = match name.rsplit('.').next() {
230                Some("html") => "text/html; charset=utf-8",
231                Some("js") => "text/javascript; charset=utf-8",
232                Some("css") => "text/css; charset=utf-8",
233                other => panic!("{name}: no media type for {other:?}"),
234            };
235            assert_eq!(media_type, expected, "{name}");
236            assert!(!body.is_empty(), "{name} is not empty");
237            assert!(std::str::from_utf8(body).is_ok(), "{name} is UTF-8");
238        }
239    }
240
241    #[test]
242    fn the_page_is_served_at_the_directory_path_and_the_rest_by_name() {
243        assert_eq!(super::path_of("index.html"), "/console/", "index.html");
244        assert_eq!(
245            super::path_of("console.js"),
246            "/console/console.js",
247            "console.js"
248        );
249        assert_eq!(
250            super::path_of("console.css"),
251            "/console/console.css",
252            "console.css"
253        );
254        assert_eq!(
255            super::path_of("format.js"),
256            "/console/format.js",
257            "format.js"
258        );
259    }
260
261    /// The headers hold the rules the design sets, so a weaker policy
262    /// fails here, not only in a browser: the CSP allows nothing by
263    /// default, each source is the console's own origin or none, and no
264    /// script may run but the console's file; the page is never framed,
265    /// cached, sniffed or sent a referrer.
266    #[test]
267    fn the_headers_are_the_designed_ones() {
268        let headers: std::collections::BTreeMap<&str, &str> = super::HEADERS.into_iter().collect();
269        assert_eq!(headers.len(), super::HEADERS.len(), "each header once");
270        let csp: std::collections::BTreeMap<&str, Vec<&str>> = headers["content-security-policy"]
271            .split(';')
272            .map(|d| {
273                let mut words = d.split_whitespace();
274                (words.next().expect("a directive"), words.collect())
275            })
276            .collect();
277        for (directive, sources) in [
278            ("default-src", ["'none'"]),
279            ("script-src", ["'self'"]),
280            ("frame-ancestors", ["'none'"]),
281            ("base-uri", ["'none'"]),
282            ("form-action", ["'none'"]),
283            ("require-trusted-types-for", ["'script'"]),
284            ("trusted-types", ["'none'"]),
285        ] {
286            assert_eq!(csp.get(directive), Some(&sources.to_vec()), "{directive}");
287        }
288        // Where violations are reported is a path on the console's own
289        // origin; it lets a page load or do nothing.
290        let mut csp = csp;
291        assert_eq!(
292            csp.remove("report-uri"),
293            Some(vec!["/console/csp-report"]),
294            "report-uri names a path, so the console's own origin"
295        );
296        for (directive, sources) in &csp {
297            assert!(
298                sources
299                    .iter()
300                    .all(|s| ["'none'", "'self'", "'script'"].contains(s)),
301                "{directive} allows only the console's own origin: {sources:?}"
302            );
303        }
304        for (name, value) in [
305            ("x-frame-options", "DENY"),
306            ("x-content-type-options", "nosniff"),
307            ("referrer-policy", "no-referrer"),
308            ("cache-control", "no-store"),
309            ("cross-origin-opener-policy", "same-origin"),
310            ("cross-origin-resource-policy", "same-origin"),
311        ] {
312            assert_eq!(headers.get(name), Some(&value), "{name}");
313        }
314    }
315
316    /// The page loads its one script and one stylesheet and holds no
317    /// inline script, style or event handler, which the CSP would refuse.
318    #[test]
319    fn the_page_holds_no_inline_code() {
320        let page = source("index.html");
321        assert!(
322            page.contains(r#"<script type="module" src="console.js"></script>"#),
323            "the page loads its script"
324        );
325        assert!(
326            page.contains(r#"<link rel="stylesheet" href="console.css">"#),
327            "the page loads its styles"
328        );
329        let lower = page.to_lowercase();
330        assert_eq!(lower.matches("<script").count(), 1, "one script element");
331        assert!(!lower.contains("<style"), "no style element");
332        assert!(!lower.contains(" style="), "no style attribute");
333        assert!(!has_event_handler(&page), "no event-handler attribute");
334    }
335
336    /// Whether markup holds an attribute such as `onclick=`: whitespace,
337    /// `on`, a name of letters, then `=` after any spaces.
338    fn has_event_handler(html: &str) -> bool {
339        let lower = html.to_lowercase();
340        lower
341            .match_indices("on")
342            .filter(|(at, _)| lower[..*at].ends_with(char::is_whitespace))
343            .any(|(at, _)| {
344                let rest = &lower[at + 2..];
345                let name = rest.chars().take_while(char::is_ascii_lowercase).count();
346                name > 0 && rest[name..].trim_start().starts_with('=')
347            })
348    }
349
350    #[test]
351    fn an_event_handler_is_found_wherever_it_is() {
352        for found in [
353            "<b onclick=\"x\">",
354            "<b\nonload = x>",
355            "<img src=a ONERROR=x>",
356        ] {
357            assert!(has_event_handler(found), "{found}");
358        }
359        for clean in [
360            "<b class=on>",
361            "<b>on=</b>",
362            "<a href=\"x\">done</a>",
363            "<b on=x>",
364        ] {
365            assert!(!has_event_handler(clean), "{clean}");
366        }
367    }
368
369    /// No script reaches the page through markup, runs code from strings
370    /// or keeps anything in browser storage; values are set as text.
371    #[test]
372    fn no_script_uses_an_html_sink_or_storage() {
373        for (name, script) in scripts() {
374            for refused in [
375                "innerHTML",
376                "outerHTML",
377                "insertAdjacentHTML",
378                "document.write",
379                "eval(",
380                "Function(",
381                "setTimeout(\"",
382                "setInterval(\"",
383                "localStorage",
384                "sessionStorage",
385                "indexedDB",
386                "document.cookie",
387                "caches.",
388            ] {
389                assert!(!script.contains(refused), "{name} uses {refused}");
390            }
391        }
392        assert!(
393            source("console.js").contains("textContent"),
394            "values are set as text"
395        );
396    }
397
398    /// Every request goes through one call of `fetch`, which never lets
399    /// the browser keep the answer, send a cookie or follow a redirect.
400    #[test]
401    fn every_request_goes_through_one_fetch() {
402        let calls: usize = scripts()
403            .iter()
404            .map(|(_, script)| script.matches("fetch(").count())
405            .sum();
406        assert_eq!(calls, 1, "one fetch call in all the scripts");
407        let script = source("console.js");
408        for option in [
409            r#"cache: "no-store""#,
410            r#"credentials: "omit""#,
411            r#"redirect: "error""#,
412        ] {
413            assert!(script.contains(option), "fetch is made with {option}");
414        }
415    }
416
417    /// A policy as its directives and their sources.
418    fn directives(policy: &str) -> std::collections::BTreeMap<&str, Vec<&str>> {
419        policy
420            .split(';')
421            .map(|d| {
422                let mut words = d.split_whitespace();
423                (words.next().expect("a directive"), words.collect())
424            })
425            .collect()
426    }
427
428    /// The policy every console answer has carried since the console
429    /// shipped, written out here so a change to it fails a test.
430    const STRICT: &str = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
431         connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
432         require-trusted-types-for 'script'; trusted-types 'none'; \
433         report-uri /console/csp-report";
434
435    /// The player's page may play a recording the console hands it, from
436    /// a blob made in the page, and may make no request of its own. Every
437    /// other rule is the console's.
438    #[test]
439    fn the_player_page_has_the_strict_policy_but_plays_a_blob_and_connects_nowhere() {
440        let mut expected = directives(STRICT);
441        expected.insert("connect-src", vec!["'none'"]);
442        expected.insert("media-src", vec!["blob:"]);
443        assert_eq!(
444            directives(super::policy_for("/console/player.html")),
445            expected,
446            "the player's policy"
447        );
448    }
449
450    /// The console's policy, byte for byte: what a browser is sent.
451    #[test]
452    fn the_strict_policy_is_the_one_written_out() {
453        assert_eq!(
454            super::HEADERS[0].0,
455            "content-security-policy",
456            "the first header"
457        );
458        assert_eq!(super::HEADERS[0].1, STRICT, "the console's policy");
459    }
460
461    /// Both policies tell a browser where to report a violation, with
462    /// `report-uri` and the path.
463    #[test]
464    fn both_policies_report_violations_to_the_report_path() {
465        for path in ["/console/", super::PLAYER_PATH] {
466            let policy = directives(super::policy_for(path));
467            assert_eq!(policy["report-uri"], [super::REPORT_PATH], "{path}");
468        }
469    }
470
471    /// The reporting directive comes last, so the rules a reader looks
472    /// for first are where they were.
473    #[test]
474    fn the_reporting_directive_ends_both_policies() {
475        for path in ["/console/", super::PLAYER_PATH] {
476            let policy = super::policy_for(path);
477            assert!(
478                policy.ends_with("'none'; report-uri /console/csp-report"),
479                "{path}: {policy}"
480            );
481        }
482    }
483
484    /// Neither policy has `report-to`, and no answer has the
485    /// `Reporting-Endpoints` header it would need. A browser that knows
486    /// `report-to` does not act on `report-uri` beside it, and in the
487    /// browser tests Chromium, given `report-to`, sent no report to the
488    /// test server in 100 seconds, where with `report-uri` alone it sent
489    /// one in a second (console-tests/tests/csp-report.spec.js).
490    #[test]
491    fn no_policy_names_a_reporting_api_endpoint() {
492        for path in ["/console/", super::PLAYER_PATH] {
493            let policy = directives(super::policy_for(path));
494            assert_eq!(policy.get("report-to"), None, "{path}");
495        }
496        for (name, _) in super::HEADERS {
497            assert_ne!(name, "reporting-endpoints", "no endpoint is named");
498            assert_ne!(name, "report-to", "nor in the header's older form");
499        }
500    }
501
502    /// The report path is under the console's, is no file's path, and is
503    /// answered with the console's policy, not the player's.
504    #[test]
505    fn the_report_path_is_the_consoles_and_no_files() {
506        assert_eq!(super::REPORT_PATH, "/console/csp-report", "the path");
507        for (name, _, _) in super::FILES {
508            assert_ne!(super::path_of(name), super::REPORT_PATH, "{name}");
509        }
510        assert_eq!(super::policy_for(super::REPORT_PATH), STRICT, "its policy");
511    }
512
513    /// Reporting adds nothing a page may do: but for the reporting
514    /// directive, the policies are the ones the console shipped with.
515    #[test]
516    fn but_for_reporting_the_policies_are_as_they_were() {
517        let before = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
518             connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
519             require-trusted-types-for 'script'; trusted-types 'none'";
520        let mut expected = directives(before);
521        let mut now = directives(super::HEADERS[0].1);
522        assert_eq!(
523            now.remove("report-uri"),
524            Some(vec![super::REPORT_PATH]),
525            "report-uri"
526        );
527        assert_eq!(now, expected, "the console's policy");
528        expected.insert("connect-src", vec!["'none'"]);
529        expected.insert("media-src", vec!["blob:"]);
530        let mut now = directives(super::PLAYER_POLICY);
531        assert_eq!(
532            now.remove("report-uri"),
533            Some(vec![super::REPORT_PATH]),
534            "report-uri"
535        );
536        assert_eq!(now, expected, "the player's policy");
537    }
538
539    /// The public router, which has no log to count in, still takes a
540    /// report at the path its policies name.
541    #[tokio::test]
542    async fn the_public_routers_answer_to_a_report_is_204() {
543        // Its place in the router, and the headers on it, are the same
544        // route's that api::csp_report tests over HTTPS.
545        assert_eq!(
546            super::dropped().await,
547            super::StatusCode::NO_CONTENT,
548            "the status"
549        );
550        let _: super::Router<()> = super::router();
551    }
552
553    /// Only the player's page, by its exact path, has the player's policy:
554    /// a path that is nearly it, holds it or adds to it has the console's.
555    #[test]
556    fn a_path_that_is_not_exactly_the_players_has_the_strict_policy() {
557        for path in [
558            "/console/csp-report",
559            "/console/",
560            "/console/console.js",
561            "/console/player.js",
562            "/console/player.html/",
563            "/console/player.html/x",
564            "/console/PLAYER.HTML",
565            "/console/player.htm",
566            "/console/x/player.html",
567            "/console//player.html",
568            "/console/player.html%2f",
569            "/player.html",
570            "/console/aplayer.html",
571            "",
572        ] {
573            assert_eq!(super::policy_for(path), STRICT, "{path}");
574        }
575    }
576
577    /// The player's page loads its one script and the console's
578    /// stylesheet, holds no inline code, and its audio element has the
579    /// browser's own controls and nothing to play until the script is
580    /// handed a recording: no source, and it never starts by itself.
581    #[test]
582    fn the_players_page_holds_no_inline_code_and_nothing_to_play() {
583        let page = source("player.html");
584        assert!(
585            page.contains(r#"<script type="module" src="player.js"></script>"#),
586            "the page loads its script"
587        );
588        assert!(
589            page.contains(r#"<link rel="stylesheet" href="console.css">"#),
590            "the page loads the console's styles"
591        );
592        let lower = page.to_lowercase();
593        assert_eq!(lower.matches("<script").count(), 1, "one script element");
594        assert!(!lower.contains("<style"), "no style element");
595        assert!(!lower.contains(" style="), "no style attribute");
596        assert!(!has_event_handler(&page), "no event-handler attribute");
597        assert_eq!(lower.matches("<audio").count(), 1, "one audio element");
598        let audio = &lower[lower.find("<audio").expect("the audio element")..];
599        let audio = &audio[..audio.find('>').expect("its end")];
600        assert!(audio.contains(" controls"), "the browser's own controls");
601        for refused in [" src", " autoplay", " loop", " crossorigin"] {
602            assert!(
603                !audio.contains(refused),
604                "the audio element has no{refused}"
605            );
606        }
607        for refused in [
608            "<source", "<track", "<iframe", "<img", "<object", "<embed", "<a ",
609        ] {
610            assert!(!lower.contains(refused), "the page has no {refused}");
611        }
612    }
613
614    /// The player is handed its recording: its script makes no request of
615    /// any kind, loads no other code, and posts a message to no origin
616    /// but its own.
617    #[test]
618    fn the_players_script_makes_no_request_and_names_its_own_origin() {
619        let script = source("player.js");
620        for refused in [
621            "fetch(",
622            "XMLHttpRequest",
623            "WebSocket",
624            "EventSource",
625            "sendBeacon",
626            "import(",
627            "serviceWorker",
628            "Worker(",
629            "\"*\"",
630            "'*'",
631            "http:",
632            "https:",
633        ] {
634            assert!(!script.contains(refused), "player.js uses {refused}");
635        }
636        assert!(
637            script.contains("location.origin"),
638            "messages name the page's own origin"
639        );
640        let imports: Vec<&str> = script
641            .lines()
642            .filter(|line| line.starts_with("import "))
643            .collect();
644        assert_eq!(imports.len(), 1, "one import: {imports:?}");
645        assert!(
646            imports[0].ends_with(r#" from "./format.js";"#),
647            "the console's own rules, from its own file: {imports:?}"
648        );
649    }
650
651    /// The console hands a recording to the player's window alone: no
652    /// script posts a message to every origin.
653    #[test]
654    fn no_script_posts_a_message_to_every_origin() {
655        let names: Vec<&str> = scripts().iter().map(|(name, _)| *name).collect();
656        assert!(
657            names.contains(&"player.js"),
658            "the player's script is served"
659        );
660        for (name, script) in scripts() {
661            for refused in ["\"*\"", "'*'"] {
662                assert!(!script.contains(refused), "{name} names every origin");
663            }
664        }
665    }
666}