1use 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
15pub type File = (&'static str, &'static [u8], &'static str);
18
19pub 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
55const PAGE: &str = "index.html";
57
58#[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
68pub 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
87pub 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
96pub const PLAYER_PATH: &str = "/console/player.html";
99
100#[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
111pub fn router<S: Clone + Send + Sync + 'static>() -> Router<S> {
117 router_with(post(dropped))
118}
119
120async fn dropped() -> StatusCode {
122 StatusCode::NO_CONTENT
123}
124
125pub const REPORT_PATH: &str = "/console/csp-report";
128
129pub(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 .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
150async 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 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 #[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 #[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 #[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 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 #[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 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 #[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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[tokio::test]
542 async fn the_public_routers_answer_to_a_report_is_204() {
543 assert_eq!(
546 super::dropped().await,
547 super::StatusCode::NO_CONTENT,
548 "the status"
549 );
550 let _: super::Router<()> = super::router();
551 }
552
553 #[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 #[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 #[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 #[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}