aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / crates / site-builder / src / components / csp.rs
| 1 | //! Page-level Content-Security-Policy. The site is served by SiteHub on |
| 2 | //! Drake's own hardware; every emitted HTML page carries the policy as the |
| 3 | //! first element of its head: a `<meta http-equiv>` governs only what follows it. |
| 4 | //! |
| 5 | //! Scripts run from first-party files only. The single outside script host is |
| 6 | //! no advertising-pixel exception; page requests go |
| 7 | //! to the analytics hosts in `img-src` and `connect-src`. `style-src` keeps |
| 8 | //! `'unsafe-inline'` because every page carries `style` attributes (the |
| 9 | //! shared layout sets them on `#root` and `main`) and hand-written pages |
| 10 | //! carry `<style>` blocks; inline styles cannot run code. Additions are |
| 11 | //! page-scoped by what the page actually loads: |
| 12 | //! - `WASM_SCRIPTS` compile WebAssembly in the page, so their pages get |
| 13 | //! `'wasm-unsafe-eval'` (WebAssembly compilation only, never JavaScript |
| 14 | //! `eval`). |
| 15 | //! - `BLOB_WORKER_SCRIPTS` start a worker from a `blob:` URL, so their pages |
| 16 | //! get `worker-src blob:`; a blob worker inherits the page policy. |
| 17 | //! - Pages that embed YouTube videos may frame `www.youtube.com`. |
| 18 | //! |
| 19 | //! `verify` checks both lists against the scripts themselves, in both |
| 20 | //! directions, so a grant cannot go missing or outlive its need. |
| 21 | //! |
| 22 | //! A frame showing `srcdoc` inherits its parent's policy, so programs Aien |
| 23 | //! writes, which carry inline scripts, cannot run in one. They run in |
| 24 | //! `RUNNER_PATH`, the one document whose policy allows inline scripts: its |
| 25 | //! only script, `RUNNER_SCRIPT`, writes what the parent posts, and only while |
| 26 | //! the frame is sandboxed to an opaque origin. The edge-rendered |
| 27 | //! `/hive/board/` is not built here and keeps its own stricter header policy. |
| 28 | |
| 29 | use regex::Regex; |
| 30 | use std::collections::BTreeSet; |
| 31 | use std::fs; |
| 32 | use std::path::Path; |
| 33 | use std::sync::LazyLock; |
| 34 | |
| 35 | const WASM_SCRIPTS: &[&str] = &["/js/hive.js", "/js/allen.js", "/js/allen-scene.js"]; |
| 36 | const BLOB_WORKER_SCRIPTS: &[&str] = &["/js/allen.js"]; |
| 37 | const YOUTUBE_EMBED: &str = "src=\"https://www.youtube.com/embed/"; |
| 38 | const META_OPEN: &str = "<meta http-equiv=\"Content-Security-Policy\" content=\""; |
| 39 | |
| 40 | /// The program runner, relative to dist, and its script. |
| 41 | pub const RUNNER_PATH: &str = "aien/run.html"; |
| 42 | pub const RUNNER_SCRIPT: &str = "/js/aien-run.js"; |
| 43 | /// The runner's policy. The program's own policy, which `sandboxed()` in the |
| 44 | /// Aien scripts writes into its head, narrows this further. |
| 45 | const RUNNER_POLICY: &str = "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; \ |
| 46 | img-src 'self' data:; form-action 'none'; base-uri 'none'"; |
| 47 | |
| 48 | fn loads(html: &str, script: &str) -> bool { |
| 49 | html.contains(&format!("src=\"{script}\"")) |
| 50 | } |
| 51 | |
| 52 | /// The policy for one page, derived from what the page loads. |
| 53 | pub fn policy_for(html: &str) -> String { |
| 54 | if loads(html, RUNNER_SCRIPT) { |
| 55 | return RUNNER_POLICY.into(); |
| 56 | } |
| 57 | let wasm = if WASM_SCRIPTS.iter().any(|s| loads(html, s)) { " 'wasm-unsafe-eval'" } else { "" }; |
| 58 | let mut p = format!( |
| 59 | "default-src 'self'; script-src 'self'{wasm}; style-src 'self' 'unsafe-inline'; \ |
| 60 | img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; \ |
| 61 | base-uri 'self'; form-action 'self'" |
| 62 | ); |
| 63 | if BLOB_WORKER_SCRIPTS.iter().any(|s| loads(html, s)) { |
| 64 | p.push_str("; worker-src blob:"); |
| 65 | } |
| 66 | if html.contains(YOUTUBE_EMBED) { |
| 67 | p.push_str("; frame-src https://www.youtube.com"); |
| 68 | } |
| 69 | p |
| 70 | } |
| 71 | |
| 72 | /// End of the opening `<head ...>` tag, or after a leading `<meta charset>` |
| 73 | /// so the charset declaration stays first. |
| 74 | fn insertion_point(html: &str) -> Option<usize> { |
| 75 | let lower = html.to_ascii_lowercase(); |
| 76 | let head = lower.find("<head")?; |
| 77 | let mut at = head + lower[head..].find('>')? + 1; |
| 78 | let rest = &lower[at..]; |
| 79 | let lead = rest.len() - rest.trim_start().len(); |
| 80 | if rest.trim_start().starts_with("<meta charset") { |
| 81 | at += lead + rest[lead..].find('>')? + 1; |
| 82 | } |
| 83 | Some(at) |
| 84 | } |
| 85 | |
| 86 | /// Adds the policy to a finished page. Idempotent. |
| 87 | pub fn enrich(mut page: String) -> String { |
| 88 | if page.contains(META_OPEN) { |
| 89 | return page; |
| 90 | } |
| 91 | let at = insertion_point(&page).expect("csp: page has a head"); |
| 92 | let meta = format!("{META_OPEN}{}\">", policy_for(&page)); |
| 93 | page.insert_str(at, &meta); |
| 94 | page |
| 95 | } |
| 96 | |
| 97 | static HANDLER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?i)<[a-z][a-z0-9-]*\b[^>]*?\son[a-z]+\s*="#).unwrap()); |
| 98 | static SCRIPT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?is)<script\b([^>]*)>(.*?)</script\s*>").unwrap()); |
| 99 | /// Comments, style blocks and script bodies: text a handler scan must skip. |
| 100 | static INERT: LazyLock<Regex> = |
| 101 | LazyLock::new(|| Regex::new(r"(?is)<!--.*?-->|<style\b.*?</style\s*>|<script\b[^>]*>.*?</script\s*>").unwrap()); |
| 102 | /// A `javascript:` URL where a URL starts: after `=` (attributes, and `url=` |
| 103 | /// in a refresh) or `(` (CSS `url(`), past optional quotes and the spaces |
| 104 | /// and controls a browser trims. Prose such as "needs JavaScript: it" is |
| 105 | /// not a URL. |
| 106 | static JS_URL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"[=(]["'\x00-\x20]*javascript:"#).unwrap()); |
| 107 | static PAGE_SCRIPT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"src="(/js/[A-Za-z0-9._-]+\.js)""#).unwrap()); |
| 108 | static COMPILES_WASM: LazyLock<Regex> = |
| 109 | LazyLock::new(|| Regex::new(r"WebAssembly\.(compile|compileStreaming|instantiate|instantiateStreaming|validate|Module)\b").unwrap()); |
| 110 | |
| 111 | /// Lowercased markup with character references decoded (`:`, `&tab;`, |
| 112 | /// `&newline;` and numeric ones, with or without `;`) and the tabs and line |
| 113 | /// breaks a URL parser drops removed, so `java	script:` reads as |
| 114 | /// `javascript:`. |
| 115 | fn url_text(markup: &str) -> String { |
| 116 | let lower = markup.to_ascii_lowercase(); |
| 117 | let mut out = String::with_capacity(lower.len()); |
| 118 | let mut rest = lower.as_str(); |
| 119 | while let Some(amp) = rest.find('&') { |
| 120 | out.push_str(&rest[..amp]); |
| 121 | rest = &rest[amp..]; |
| 122 | let (decoded, used) = reference(rest); |
| 123 | match decoded { |
| 124 | Some(c) => out.push(c), |
| 125 | None => out.push('&'), |
| 126 | } |
| 127 | rest = &rest[used..]; |
| 128 | } |
| 129 | out.push_str(rest); |
| 130 | out.retain(|c| !matches!(c, '\t' | '\n' | '\r')); |
| 131 | out |
| 132 | } |
| 133 | |
| 134 | /// One character reference at the start of `s` (which begins with `&`): |
| 135 | /// the character and the bytes consumed, or `None` and 1. |
| 136 | fn reference(s: &str) -> (Option<char>, usize) { |
| 137 | for (name, c) in [(":", ':'), ("&tab;", '\t'), ("&newline;", '\n'), ("(", '(')] { |
| 138 | if s.starts_with(name) { |
| 139 | return (Some(c), name.len()); |
| 140 | } |
| 141 | } |
| 142 | let Some(num) = s.strip_prefix("&#") else { return (None, 1) }; |
| 143 | let (hex, digits) = match num.strip_prefix('x') { |
| 144 | Some(h) => (true, h), |
| 145 | None => (false, num), |
| 146 | }; |
| 147 | let len = digits.bytes().take_while(|b| if hex { b.is_ascii_hexdigit() } else { b.is_ascii_digit() }).count(); |
| 148 | if len == 0 { |
| 149 | return (None, 1); |
| 150 | } |
| 151 | let value = u32::from_str_radix(&digits[..len], if hex { 16 } else { 10 }).ok().and_then(char::from_u32); |
| 152 | let mut used = 2 + usize::from(hex) + len; |
| 153 | if s[used..].starts_with(';') { |
| 154 | used += 1; |
| 155 | } |
| 156 | (Some(value.unwrap_or('\u{fffd}')), used) |
| 157 | } |
| 158 | |
| 159 | /// One page: exactly one policy, equal to `policy_for`, ahead of anything it |
| 160 | /// governs; no inline script other than JSON-LD data; no inline event |
| 161 | /// handler; no `javascript:` URL. The runner loads its script and nothing |
| 162 | /// else. |
| 163 | pub fn check_page(html: &str) -> Result<(), String> { |
| 164 | if html.matches(META_OPEN).count() != 1 { |
| 165 | return Err("needs exactly one Content-Security-Policy meta".into()); |
| 166 | } |
| 167 | let start = html.find(META_OPEN).unwrap(); |
| 168 | let body = &html[start + META_OPEN.len()..]; |
| 169 | let got = &body[..body.find('"').ok_or("unterminated policy")?]; |
| 170 | let want = policy_for(html); |
| 171 | if got != want { |
| 172 | return Err(format!("policy {got:?} differs from {want:?}")); |
| 173 | } |
| 174 | let lower = html.to_ascii_lowercase(); |
| 175 | let head = lower.find("<head").ok_or("no head")?; |
| 176 | if start < head || lower[..start].contains("<script") || lower[..start].contains("<link") || lower[..start].contains("<style") { |
| 177 | return Err("the policy must precede every script, link and style".into()); |
| 178 | } |
| 179 | for c in SCRIPT.captures_iter(html) { |
| 180 | let attrs = c[1].to_ascii_lowercase(); |
| 181 | let ld = attrs.contains("type=\"application/ld+json\""); |
| 182 | if !attrs.contains("src=") && !ld { |
| 183 | return Err(format!("inline script: {}", c[2].trim().chars().take(60).collect::<String>())); |
| 184 | } |
| 185 | if attrs.contains("src=") && !c[2].trim().is_empty() { |
| 186 | return Err("a script with src must have an empty body".into()); |
| 187 | } |
| 188 | } |
| 189 | if want == RUNNER_POLICY && (lower.matches("<script").count() != 1 || lower.contains("<iframe") || lower.contains("<object") || lower.contains("<embed")) { |
| 190 | return Err("the runner loads its own script and nothing else that runs".into()); |
| 191 | } |
| 192 | let markup = INERT.replace_all(html, ""); |
| 193 | if let Some(m) = HANDLER.find(&markup) { |
| 194 | return Err(format!("inline event handler: {}", m.as_str().chars().take(80).collect::<String>())); |
| 195 | } |
| 196 | if JS_URL.is_match(&url_text(&markup)) { |
| 197 | return Err("javascript: URL".into()); |
| 198 | } |
| 199 | Ok(()) |
| 200 | } |
| 201 | |
| 202 | /// What one first-party script needs beyond the base policy, read from the |
| 203 | /// script itself: (compiles WebAssembly, starts a blob: worker). |
| 204 | fn script_needs(js: &str) -> (bool, bool) { |
| 205 | (COMPILES_WASM.is_match(js), js.contains("new Worker(") && js.contains("URL.createObjectURL(")) |
| 206 | } |
| 207 | |
| 208 | /// Every HTML file in the build carries the policy and needs nothing it |
| 209 | /// forbids; only `RUNNER_PATH` loads the runner; the page-scoped grants match |
| 210 | /// what the scripts the pages load actually do. All failures are reported |
| 211 | /// together. |
| 212 | pub fn verify(dist: &Path) { |
| 213 | fn walk(dist: &Path, dir: &Path, n: &mut usize, bad: &mut Vec<String>, scripts: &mut BTreeSet<String>) { |
| 214 | for entry in fs::read_dir(dir).expect("read dist directory") { |
| 215 | let path = entry.expect("dist entry").path(); |
| 216 | if path.is_dir() { |
| 217 | walk(dist, &path, n, bad, scripts); |
| 218 | } else if path.extension().and_then(|e| e.to_str()) == Some("html") { |
| 219 | let html = fs::read_to_string(&path).expect("read page"); |
| 220 | if let Err(e) = check_page(&html) { |
| 221 | bad.push(format!("{}: {e}", path.display())); |
| 222 | } |
| 223 | let rel = path.strip_prefix(dist).expect("under dist").to_string_lossy().replace('\\', "/"); |
| 224 | if loads(&html, RUNNER_SCRIPT) != (rel == RUNNER_PATH) { |
| 225 | bad.push(format!("{}: only {RUNNER_PATH} loads {RUNNER_SCRIPT}, and it must", path.display())); |
| 226 | } |
| 227 | scripts.extend(PAGE_SCRIPT.captures_iter(&html).map(|c| c[1].to_string())); |
| 228 | *n += 1; |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | let (mut n, mut bad, mut scripts) = (0, Vec::new(), BTreeSet::new()); |
| 233 | walk(dist, dist, &mut n, &mut bad, &mut scripts); |
| 234 | assert!(n > 0, "csp: no HTML pages found under {}", dist.display()); |
| 235 | if !dist.join(RUNNER_PATH).is_file() { |
| 236 | bad.push(format!("{}: missing; Aien's programs run there", dist.join(RUNNER_PATH).display())); |
| 237 | } |
| 238 | for script in &scripts { |
| 239 | let file = dist.join(&script[1..]); |
| 240 | let Ok(js) = fs::read_to_string(&file) else { |
| 241 | bad.push(format!("{}: a page loads it, but it is not in the build", file.display())); |
| 242 | continue; |
| 243 | }; |
| 244 | let (wasm, blob_worker) = script_needs(&js); |
| 245 | if wasm != WASM_SCRIPTS.contains(&script.as_str()) { |
| 246 | bad.push(format!("{script}: compiles WebAssembly is {wasm}, but WASM_SCRIPTS says otherwise")); |
| 247 | } |
| 248 | if blob_worker != BLOB_WORKER_SCRIPTS.contains(&script.as_str()) { |
| 249 | bad.push(format!("{script}: starts a blob: worker is {blob_worker}, but BLOB_WORKER_SCRIPTS says otherwise")); |
| 250 | } |
| 251 | } |
| 252 | for listed in WASM_SCRIPTS.iter().chain(BLOB_WORKER_SCRIPTS) { |
| 253 | if !scripts.contains(*listed) { |
| 254 | bad.push(format!("{listed}: granted a policy addition, but no page loads it")); |
| 255 | } |
| 256 | } |
| 257 | bad.sort(); |
| 258 | bad.dedup(); |
| 259 | assert!(bad.is_empty(), "csp: {} problems in {n} pages:\n{}", bad.len(), bad.join("\n")); |
| 260 | println!(" Content-Security-Policy meta: {n} pages, {} first-party scripts checked", scripts.len()); |
| 261 | } |
| 262 | |
| 263 | #[cfg(test)] |
| 264 | mod tests { |
| 265 | use super::*; |
| 266 | |
| 267 | const PAGE: &str = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>t</title><link rel=\"stylesheet\" href=\"/a.css\"><script defer src=\"/js/allen-intro.js\"></script><script type=\"application/ld+json\">{\"a\":1}</script></head><body><p style=\"color:red\">x</p></body></html>"; |
| 268 | const RUNNER: &str = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>r</title><link rel=\"stylesheet\" href=\"/a.css\"><script src=\"/js/aien-run.js\"></script></head><body><p>x</p></body></html>"; |
| 269 | |
| 270 | #[test] |
| 271 | fn enriched_page_passes_and_keeps_charset_first() { |
| 272 | let page = enrich(PAGE.to_string()); |
| 273 | check_page(&page).unwrap(); |
| 274 | assert!(page.contains("<head><meta charset=\"utf-8\"><meta http-equiv=\"Content-Security-Policy\"")); |
| 275 | assert_eq!(enrich(page.clone()), page, "enrich is idempotent"); |
| 276 | let p = policy_for(&page); |
| 277 | for d in [ |
| 278 | "default-src 'self'", |
| 279 | "script-src 'self';", |
| 280 | "object-src 'none'", |
| 281 | "base-uri 'self'", |
| 282 | "form-action 'self'", |
| 283 | "img-src 'self' data:", |
| 284 | "connect-src 'self'", |
| 285 | ] { |
| 286 | assert!(p.contains(d), "policy lacks {d}"); |
| 287 | } |
| 288 | assert!(!p.contains("frame-src") && !p.contains("wasm") && !p.contains("worker-src"), "no page-scoped additions on a plain page"); |
| 289 | let script_src = p.split(';').find(|d| d.trim_start().starts_with("script-src")).unwrap(); |
| 290 | assert!(!script_src.contains("unsafe"), "scripts never get unsafe-inline or unsafe-eval"); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn additions_follow_what_the_page_loads() { |
| 295 | let hive = enrich(PAGE.replace("</head>", "<script defer src=\"/js/hive.js\"></script></head>")); |
| 296 | assert!(policy_for(&hive).contains("script-src 'self' 'wasm-unsafe-eval';")); |
| 297 | assert!(!policy_for(&hive).contains("worker-src")); |
| 298 | let aien = enrich(PAGE.replace("</head>", "<script defer src=\"/js/allen.js\"></script></head>")); |
| 299 | assert!(policy_for(&aien).contains("'wasm-unsafe-eval';")); |
| 300 | assert!(policy_for(&aien).ends_with("; worker-src blob:")); |
| 301 | let tube = enrich(PAGE.replace("</body>", "<iframe src=\"https://www.youtube.com/embed/x\"></iframe></body>")); |
| 302 | assert!(policy_for(&tube).ends_with("; frame-src https://www.youtube.com")); |
| 303 | for page in [&hive, &aien, &tube] { |
| 304 | check_page(page).unwrap(); |
| 305 | let script_src = policy_for(page); |
| 306 | let script_src = script_src.split(';').find(|d| d.trim_start().starts_with("script-src")).unwrap(); |
| 307 | assert!(script_src.split_whitespace().all(|t| t != "'unsafe-inline'" && t != "'unsafe-eval'"), "no page script gets inline or eval"); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn the_runner_alone_allows_inline_scripts() { |
| 313 | let runner = enrich(RUNNER.to_string()); |
| 314 | check_page(&runner).unwrap(); |
| 315 | assert_eq!(policy_for(&runner), RUNNER_POLICY); |
| 316 | for d in ["default-src 'none'", "form-action 'none'", "base-uri 'none'"] { |
| 317 | assert!(RUNNER_POLICY.contains(d), "runner policy lacks {d}"); |
| 318 | } |
| 319 | for bad in [ |
| 320 | runner.replace("</head>", "<script src=\"/js/allen-intro.js\"></script></head>"), |
| 321 | runner.replace("</body>", "<iframe src=\"/x/\"></iframe></body>"), |
| 322 | runner.replace("</body>", "<script>x()</script></body>"), |
| 323 | ] { |
| 324 | assert!(check_page(&bad).is_err(), "the runner must load nothing else: {bad}"); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn script_needs_read_the_script() { |
| 330 | assert_eq!(script_needs("WebAssembly.instantiate(bytes)"), (true, false)); |
| 331 | assert_eq!(script_needs("const w = new Worker(URL.createObjectURL(blob));"), (false, true)); |
| 332 | assert_eq!(script_needs("new Worker('/js/lab-worker.js')"), (false, false)); |
| 333 | assert_eq!(script_needs("WebAssembly.RuntimeError"), (false, false)); |
| 334 | } |
| 335 | |
| 336 | #[test] |
| 337 | fn negative_controls_are_refused() { |
| 338 | let good = enrich(PAGE.to_string()); |
| 339 | let bad = [ |
| 340 | ("no meta", PAGE.to_string()), |
| 341 | ("two metas", good.replacen("<title>", &format!("{META_OPEN}x\"><title>"), 1)), |
| 342 | ("wrong policy", good.replace("object-src 'none'", "object-src *")), |
| 343 | ("runner policy on a page", good.replace(&policy_for(&good), RUNNER_POLICY)), |
| 344 | ("inline script", good.replace("</body>", "<script>alert(1)</script></body>")), |
| 345 | ("inline module", good.replace("</body>", "<script type=\"module\">x()</script></body>")), |
| 346 | ("src with body", good.replace("allen-intro.js\"></script>", "allen-intro.js\">x()</script>")), |
| 347 | ("inline handler", good.replace("<p style", "<p onclick=\"x()\" style")), |
| 348 | ("upper handler", good.replace("<p style", "<P ONLOAD='x()' style")), |
| 349 | ("javascript url", good.replace("</body>", "<a href=\"javascript:x()\">a</a></body>")), |
| 350 | ("unquoted javascript url", good.replace("</body>", "<a href=JavaScript:x()>a</a></body>")), |
| 351 | ("spaced javascript url", good.replace("</body>", "<a href=\" \tjavascript:x()\">a</a></body>")), |
| 352 | ("tab in javascript url", good.replace("</body>", "<a href=\"java	script:x()\">a</a></body>")), |
| 353 | ("named colon", good.replace("</body>", "<a href=\"javascript:x()\">a</a></body>")), |
| 354 | ("decimal colon", good.replace("</body>", "<a href=\"javascript:x()\">a</a></body>")), |
| 355 | ("refresh to javascript", good.replace("</head>", "<meta http-equiv=\"refresh\" content=\"0; url=javascript:x()\"></head>")), |
| 356 | ("css javascript url", good.replace("<p style=\"color:red\"", "<p style=\"background:url(javascript:x())\"")), |
| 357 | ("meta after script", PAGE.replace("<title>", "<script src=\"/x.js\"></script><title>").replace("<title>", &format!("{META_OPEN}{}\"><title>", policy_for(PAGE)))), |
| 358 | ]; |
| 359 | for (what, page) in bad { |
| 360 | assert!(check_page(&page).is_err(), "must refuse: {what}"); |
| 361 | } |
| 362 | // JSON-LD and text that merely mentions handlers or JavaScript stay allowed. |
| 363 | let fine = good.replace( |
| 364 | "</body>", |
| 365 | "<p>use onclick= in text</p><noscript><p>Aien needs JavaScript: he lives in the page.</p></noscript><script type=\"application/ld+json\">{\"onload\":\"x\"}</script></body>", |
| 366 | ); |
| 367 | check_page(&fine).unwrap(); |
| 368 | } |
| 369 | } |