use axum::Router;
use axum::extract::Request;
use axum::http::header::{CONTENT_SECURITY_POLICY, CONTENT_TYPE, LOCATION};
use axum::http::{HeaderName, HeaderValue, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{MethodRouter, any, get, post};
pub type File = (&'static str, &'static [u8], &'static str);
pub const FILES: [File; 6] = [
(
"index.html",
include_bytes!("../console/index.html"),
"text/html; charset=utf-8",
),
(
"console.js",
include_bytes!("../console/console.js"),
"text/javascript; charset=utf-8",
),
(
"format.js",
include_bytes!("../console/format.js"),
"text/javascript; charset=utf-8",
),
(
"console.css",
include_bytes!("../console/console.css"),
"text/css; charset=utf-8",
),
(
"player.html",
include_bytes!("../console/player.html"),
"text/html; charset=utf-8",
),
(
"player.js",
include_bytes!("../console/player.js"),
"text/javascript; charset=utf-8",
),
];
const PAGE: &str = "index.html";
#[must_use]
pub fn path_of(name: &str) -> String {
if name == PAGE {
"/console/".to_owned()
} else {
format!("/console/{name}")
}
}
pub const HEADERS: [(&str, &str); 7] = [
(
"content-security-policy",
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
require-trusted-types-for 'script'; trusted-types 'none'; \
report-uri /console/csp-report",
),
("x-frame-options", "DENY"),
("x-content-type-options", "nosniff"),
("referrer-policy", "no-referrer"),
("cache-control", "no-store"),
("cross-origin-opener-policy", "same-origin"),
("cross-origin-resource-policy", "same-origin"),
];
pub const PLAYER_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
connect-src 'none'; media-src blob:; base-uri 'none'; form-action 'none'; \
frame-ancestors 'none'; require-trusted-types-for 'script'; trusted-types 'none'; \
report-uri /console/csp-report";
pub const PLAYER_PATH: &str = "/console/player.html";
#[must_use]
pub fn policy_for(path: &str) -> &'static str {
if path == PLAYER_PATH {
PLAYER_POLICY
} else {
HEADERS[0].1
}
}
pub fn router<S: Clone + Send + Sync + 'static>() -> Router<S> {
router_with(post(dropped))
}
async fn dropped() -> StatusCode {
StatusCode::NO_CONTENT
}
pub const REPORT_PATH: &str = "/console/csp-report";
pub(crate) fn router_with<S: Clone + Send + Sync + 'static>(report: MethodRouter<S>) -> Router<S> {
let mut router = Router::new().route(
"/console",
get(|| async { (StatusCode::PERMANENT_REDIRECT, [(LOCATION, "/console/")]) }),
);
for (name, body, media_type) in FILES {
router = router.route(&path_of(name), get(move || file(body, media_type)));
}
router
.route(REPORT_PATH, report)
.route("/console/{*other}", any(|| async { StatusCode::NOT_FOUND }))
.route_layer(middleware::from_fn(with_headers))
}
async fn file(body: &'static [u8], media_type: &'static str) -> Response {
([(CONTENT_TYPE, media_type)], body).into_response()
}
async fn with_headers(request: Request, next: Next) -> Response {
let policy = policy_for(request.uri().path());
let mut answer = next.run(request).await;
for (name, value) in HEADERS {
answer.headers_mut().insert(
HeaderName::from_static(name),
HeaderValue::from_static(value),
);
}
if answer.status() == StatusCode::OK {
answer
.headers_mut()
.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(policy));
}
answer
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
fn source(name: &str) -> String {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("console")
.join(name);
std::fs::read_to_string(path).expect("the source file")
}
fn scripts() -> Vec<(&'static str, String)> {
super::FILES
.into_iter()
.filter(|(name, _, _)| name.ends_with(".js"))
.map(|(name, _, _)| (name, source(name)))
.collect()
}
#[test]
fn the_directory_the_served_files_and_the_package_agree() {
let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("console");
let mut on_disk: Vec<String> = std::fs::read_dir(directory)
.expect("the console directory")
.map(|entry| {
entry
.expect("an entry")
.file_name()
.into_string()
.expect("a UTF-8 name")
})
.collect();
on_disk.sort();
let mut served: Vec<String> = super::FILES
.into_iter()
.map(|(name, _, _)| name.to_owned())
.collect();
served.sort();
assert_eq!(served, on_disk, "served files against the directory");
let manifest =
std::fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
.expect("the manifest");
for name in &on_disk {
assert!(
manifest.contains(&format!("\"/console/{name}\",")),
"the package includes {name}"
);
}
}
#[test]
fn each_file_has_the_media_type_of_its_extension() {
for (name, body, media_type) in super::FILES {
let expected = match name.rsplit('.').next() {
Some("html") => "text/html; charset=utf-8",
Some("js") => "text/javascript; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
other => panic!("{name}: no media type for {other:?}"),
};
assert_eq!(media_type, expected, "{name}");
assert!(!body.is_empty(), "{name} is not empty");
assert!(std::str::from_utf8(body).is_ok(), "{name} is UTF-8");
}
}
#[test]
fn the_page_is_served_at_the_directory_path_and_the_rest_by_name() {
assert_eq!(super::path_of("index.html"), "/console/", "index.html");
assert_eq!(
super::path_of("console.js"),
"/console/console.js",
"console.js"
);
assert_eq!(
super::path_of("console.css"),
"/console/console.css",
"console.css"
);
assert_eq!(
super::path_of("format.js"),
"/console/format.js",
"format.js"
);
}
#[test]
fn the_headers_are_the_designed_ones() {
let headers: std::collections::BTreeMap<&str, &str> = super::HEADERS.into_iter().collect();
assert_eq!(headers.len(), super::HEADERS.len(), "each header once");
let csp: std::collections::BTreeMap<&str, Vec<&str>> = headers["content-security-policy"]
.split(';')
.map(|d| {
let mut words = d.split_whitespace();
(words.next().expect("a directive"), words.collect())
})
.collect();
for (directive, sources) in [
("default-src", ["'none'"]),
("script-src", ["'self'"]),
("frame-ancestors", ["'none'"]),
("base-uri", ["'none'"]),
("form-action", ["'none'"]),
("require-trusted-types-for", ["'script'"]),
("trusted-types", ["'none'"]),
] {
assert_eq!(csp.get(directive), Some(&sources.to_vec()), "{directive}");
}
let mut csp = csp;
assert_eq!(
csp.remove("report-uri"),
Some(vec!["/console/csp-report"]),
"report-uri names a path, so the console's own origin"
);
for (directive, sources) in &csp {
assert!(
sources
.iter()
.all(|s| ["'none'", "'self'", "'script'"].contains(s)),
"{directive} allows only the console's own origin: {sources:?}"
);
}
for (name, value) in [
("x-frame-options", "DENY"),
("x-content-type-options", "nosniff"),
("referrer-policy", "no-referrer"),
("cache-control", "no-store"),
("cross-origin-opener-policy", "same-origin"),
("cross-origin-resource-policy", "same-origin"),
] {
assert_eq!(headers.get(name), Some(&value), "{name}");
}
}
#[test]
fn the_page_holds_no_inline_code() {
let page = source("index.html");
assert!(
page.contains(r#"<script type="module" src="console.js"></script>"#),
"the page loads its script"
);
assert!(
page.contains(r#"<link rel="stylesheet" href="console.css">"#),
"the page loads its styles"
);
let lower = page.to_lowercase();
assert_eq!(lower.matches("<script").count(), 1, "one script element");
assert!(!lower.contains("<style"), "no style element");
assert!(!lower.contains(" style="), "no style attribute");
assert!(!has_event_handler(&page), "no event-handler attribute");
}
fn has_event_handler(html: &str) -> bool {
let lower = html.to_lowercase();
lower
.match_indices("on")
.filter(|(at, _)| lower[..*at].ends_with(char::is_whitespace))
.any(|(at, _)| {
let rest = &lower[at + 2..];
let name = rest.chars().take_while(char::is_ascii_lowercase).count();
name > 0 && rest[name..].trim_start().starts_with('=')
})
}
#[test]
fn an_event_handler_is_found_wherever_it_is() {
for found in [
"<b onclick=\"x\">",
"<b\nonload = x>",
"<img src=a ONERROR=x>",
] {
assert!(has_event_handler(found), "{found}");
}
for clean in [
"<b class=on>",
"<b>on=</b>",
"<a href=\"x\">done</a>",
"<b on=x>",
] {
assert!(!has_event_handler(clean), "{clean}");
}
}
#[test]
fn no_script_uses_an_html_sink_or_storage() {
for (name, script) in scripts() {
for refused in [
"innerHTML",
"outerHTML",
"insertAdjacentHTML",
"document.write",
"eval(",
"Function(",
"setTimeout(\"",
"setInterval(\"",
"localStorage",
"sessionStorage",
"indexedDB",
"document.cookie",
"caches.",
] {
assert!(!script.contains(refused), "{name} uses {refused}");
}
}
assert!(
source("console.js").contains("textContent"),
"values are set as text"
);
}
#[test]
fn every_request_goes_through_one_fetch() {
let calls: usize = scripts()
.iter()
.map(|(_, script)| script.matches("fetch(").count())
.sum();
assert_eq!(calls, 1, "one fetch call in all the scripts");
let script = source("console.js");
for option in [
r#"cache: "no-store""#,
r#"credentials: "omit""#,
r#"redirect: "error""#,
] {
assert!(script.contains(option), "fetch is made with {option}");
}
}
fn directives(policy: &str) -> std::collections::BTreeMap<&str, Vec<&str>> {
policy
.split(';')
.map(|d| {
let mut words = d.split_whitespace();
(words.next().expect("a directive"), words.collect())
})
.collect()
}
const STRICT: &str = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
require-trusted-types-for 'script'; trusted-types 'none'; \
report-uri /console/csp-report";
#[test]
fn the_player_page_has_the_strict_policy_but_plays_a_blob_and_connects_nowhere() {
let mut expected = directives(STRICT);
expected.insert("connect-src", vec!["'none'"]);
expected.insert("media-src", vec!["blob:"]);
assert_eq!(
directives(super::policy_for("/console/player.html")),
expected,
"the player's policy"
);
}
#[test]
fn the_strict_policy_is_the_one_written_out() {
assert_eq!(
super::HEADERS[0].0,
"content-security-policy",
"the first header"
);
assert_eq!(super::HEADERS[0].1, STRICT, "the console's policy");
}
#[test]
fn both_policies_report_violations_to_the_report_path() {
for path in ["/console/", super::PLAYER_PATH] {
let policy = directives(super::policy_for(path));
assert_eq!(policy["report-uri"], [super::REPORT_PATH], "{path}");
}
}
#[test]
fn the_reporting_directive_ends_both_policies() {
for path in ["/console/", super::PLAYER_PATH] {
let policy = super::policy_for(path);
assert!(
policy.ends_with("'none'; report-uri /console/csp-report"),
"{path}: {policy}"
);
}
}
#[test]
fn no_policy_names_a_reporting_api_endpoint() {
for path in ["/console/", super::PLAYER_PATH] {
let policy = directives(super::policy_for(path));
assert_eq!(policy.get("report-to"), None, "{path}");
}
for (name, _) in super::HEADERS {
assert_ne!(name, "reporting-endpoints", "no endpoint is named");
assert_ne!(name, "report-to", "nor in the header's older form");
}
}
#[test]
fn the_report_path_is_the_consoles_and_no_files() {
assert_eq!(super::REPORT_PATH, "/console/csp-report", "the path");
for (name, _, _) in super::FILES {
assert_ne!(super::path_of(name), super::REPORT_PATH, "{name}");
}
assert_eq!(super::policy_for(super::REPORT_PATH), STRICT, "its policy");
}
#[test]
fn but_for_reporting_the_policies_are_as_they_were() {
let before = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; \
connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; \
require-trusted-types-for 'script'; trusted-types 'none'";
let mut expected = directives(before);
let mut now = directives(super::HEADERS[0].1);
assert_eq!(
now.remove("report-uri"),
Some(vec![super::REPORT_PATH]),
"report-uri"
);
assert_eq!(now, expected, "the console's policy");
expected.insert("connect-src", vec!["'none'"]);
expected.insert("media-src", vec!["blob:"]);
let mut now = directives(super::PLAYER_POLICY);
assert_eq!(
now.remove("report-uri"),
Some(vec![super::REPORT_PATH]),
"report-uri"
);
assert_eq!(now, expected, "the player's policy");
}
#[tokio::test]
async fn the_public_routers_answer_to_a_report_is_204() {
assert_eq!(
super::dropped().await,
super::StatusCode::NO_CONTENT,
"the status"
);
let _: super::Router<()> = super::router();
}
#[test]
fn a_path_that_is_not_exactly_the_players_has_the_strict_policy() {
for path in [
"/console/csp-report",
"/console/",
"/console/console.js",
"/console/player.js",
"/console/player.html/",
"/console/player.html/x",
"/console/PLAYER.HTML",
"/console/player.htm",
"/console/x/player.html",
"/console//player.html",
"/console/player.html%2f",
"/player.html",
"/console/aplayer.html",
"",
] {
assert_eq!(super::policy_for(path), STRICT, "{path}");
}
}
#[test]
fn the_players_page_holds_no_inline_code_and_nothing_to_play() {
let page = source("player.html");
assert!(
page.contains(r#"<script type="module" src="player.js"></script>"#),
"the page loads its script"
);
assert!(
page.contains(r#"<link rel="stylesheet" href="console.css">"#),
"the page loads the console's styles"
);
let lower = page.to_lowercase();
assert_eq!(lower.matches("<script").count(), 1, "one script element");
assert!(!lower.contains("<style"), "no style element");
assert!(!lower.contains(" style="), "no style attribute");
assert!(!has_event_handler(&page), "no event-handler attribute");
assert_eq!(lower.matches("<audio").count(), 1, "one audio element");
let audio = &lower[lower.find("<audio").expect("the audio element")..];
let audio = &audio[..audio.find('>').expect("its end")];
assert!(audio.contains(" controls"), "the browser's own controls");
for refused in [" src", " autoplay", " loop", " crossorigin"] {
assert!(
!audio.contains(refused),
"the audio element has no{refused}"
);
}
for refused in [
"<source", "<track", "<iframe", "<img", "<object", "<embed", "<a ",
] {
assert!(!lower.contains(refused), "the page has no {refused}");
}
}
#[test]
fn the_players_script_makes_no_request_and_names_its_own_origin() {
let script = source("player.js");
for refused in [
"fetch(",
"XMLHttpRequest",
"WebSocket",
"EventSource",
"sendBeacon",
"import(",
"serviceWorker",
"Worker(",
"\"*\"",
"'*'",
"http:",
"https:",
] {
assert!(!script.contains(refused), "player.js uses {refused}");
}
assert!(
script.contains("location.origin"),
"messages name the page's own origin"
);
let imports: Vec<&str> = script
.lines()
.filter(|line| line.starts_with("import "))
.collect();
assert_eq!(imports.len(), 1, "one import: {imports:?}");
assert!(
imports[0].ends_with(r#" from "./format.js";"#),
"the console's own rules, from its own file: {imports:?}"
);
}
#[test]
fn no_script_posts_a_message_to_every_origin() {
let names: Vec<&str> = scripts().iter().map(|(name, _)| *name).collect();
assert!(
names.contains(&"player.js"),
"the player's script is served"
);
for (name, script) in scripts() {
for refused in ["\"*\"", "'*'"] {
assert!(!script.contains(refused), "{name} names every origin");
}
}
}
}