From 7f30c16a753465538d4ad95439ed27dec191dba0 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:57:22 +1300 Subject: [PATCH 1/2] app/: security headers on every response (sc-8900), as today's: nosniff, the referrer policy, no framing (DENY, over Laravel's SAMEORIGIN) and the Content-Security-Policy allowing only VisualCI's scripts, the built page's inline script hashes (VISUALCI_FRONTEND_DIR) and the analytics; x-powered-by dropped; the gallery's /g/ paths CORS and CORP cross-origin; outermost, so the host check's 404s carry them too --- app/Cargo.lock | 1 + app/Cargo.toml | 1 + app/src/http/mod.rs | 1 + app/src/http/security.rs | 143 +++++++++++++++++++++++++++++++++++++++ app/src/lib.rs | 2 + app/tests/hosts.rs | 17 +++++ 6 files changed, 165 insertions(+) create mode 100644 app/src/http/security.rs diff --git a/app/Cargo.lock b/app/Cargo.lock index 6ed23918..8d3fe3ff 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4534,6 +4534,7 @@ name = "visualci-app" version = "0.0.0" dependencies = [ "axum", + "base64 0.22.1", "hex", "image", "laravel-rust", diff --git a/app/Cargo.toml b/app/Cargo.toml index 67d58e3d..49c8b64a 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -26,6 +26,7 @@ path = "src/main.rs" laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } # The same axum Laravel Rust runs on, for extractors (auth::Principal) axum = "0.8" +base64 = "0.22" hex = "0.4" oauth-provider-laravel = { version = "0.1", features = ["postgres"] } serde = { version = "1", features = ["derive"] } diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 44cc1f01..e19f4abb 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -2,3 +2,4 @@ pub mod api; pub mod hosts; +pub mod security; diff --git a/app/src/http/security.rs b/app/src/http/security.rs new file mode 100644 index 00000000..78611456 --- /dev/null +++ b/app/src/http/security.rs @@ -0,0 +1,143 @@ +//! Security headers on every response (sc-8900, ported from today's server): `nosniff`, a referrer policy, no framing, +//! and a Content-Security-Policy that lets the app's pages run only VisualCI's own scripts (and Plausible's and +//! Cloudflare's analytics), so script injected into a page or served from the app's origin by mistake doesn't run. A +//! route that sets its own headers (the gallery's sandbox) keeps them, and the gallery's images may be embedded +//! anywhere (`/g/`: CORS and CORP cross-origin). +//! +//! The app's `index.html` has inline scripts (the theme, before the page draws; Plausible's queue in production). +//! Their SHA-256 hashes are read from the built page (`VISUALCI_FRONTEND_DIR`, default `frontend/dist`) the first +//! time a response goes out, so the policy always matches the page it's served with. There's no `form-action`: +//! Chrome applies it to every redirect after a form posts, which would block an MCP client's OAuth callback. + +use std::sync::OnceLock; + +use axum::http::{HeaderValue, header}; +use base64::Engine; +use laravel::http::{Next, Request, Response, middleware}; +use sha2::{Digest, Sha256}; + +/// Plausible, DocSpring's self-hosted analytics. +const ANALYTICS: &str = "https://pa.docspring.com"; +/// Cloudflare's Web Analytics beacon, which Cloudflare adds to pages it serves, and where it reports. +const CLOUDFLARE_SCRIPT: &str = "https://static.cloudflareinsights.com"; +const CLOUDFLARE_REPORT: &str = "https://cloudflareinsights.com"; + +static POLICY: OnceLock = OnceLock::new(); + +/// `'sha256-…'` for each inline `") else { break }; + if !tag.contains("src=") { + let body = &after[body_start..body_start + close]; + let digest = Sha256::digest(body.as_bytes()); + hashes.push(format!("'sha256-{}'", base64::engine::general_purpose::STANDARD.encode(digest))); + } + rest = &after[body_start + close + "".len()..]; + } + hashes +} + +/// The policy for a page whose inline scripts hash to `hashes`, with images also from `storage` (the bucket's public +/// origin, for a development server; production's is HTTPS, which `https:` covers). +#[must_use] +pub fn policy(hashes: &[String], storage: Option<&str>) -> String { + let scripts = std::iter::once("'self'".to_string()) + .chain([ANALYTICS.to_string(), CLOUDFLARE_SCRIPT.to_string()]) + .chain(hashes.iter().cloned()) + .collect::>() + .join(" "); + let images = ["'self'", "data:", "blob:", "https:"] + .into_iter() + .map(str::to_string) + .chain(storage.map(str::to_string)) + .collect::>() + .join(" "); + format!( + "default-src 'self'; script-src {scripts}; style-src 'self' 'unsafe-inline'; img-src {images}; \ + font-src 'self' data:; connect-src 'self' {ANALYTICS} {CLOUDFLARE_REPORT}; frame-src 'self'; object-src 'none'; \ + base-uri 'self'; frame-ancestors 'none'" + ) +} + +/// The built app and the storage's public endpoint, for the policy. +#[derive(Clone, laravel::config::Section)] +pub struct Frontend { + #[env("VISUALCI_FRONTEND_DIR", default = "frontend/dist")] + pub dir: String, + #[env("S3_PUBLIC_ENDPOINT")] + pub storage_endpoint: Option, +} + +/// An origin (`scheme://host[:port]`) from a URL. +fn origin(url: &str) -> Option { + let (scheme, rest) = url.trim().split_once("://")?; + let authority = rest.split('/').next().filter(|a| !a.is_empty())?; + Some(format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase())) +} + +fn built_policy(frontend: &Frontend) -> HeaderValue { + let html = std::fs::read_to_string(std::path::Path::new(&frontend.dir).join("index.html")).unwrap_or_default(); + let storage = frontend.storage_endpoint.as_deref().and_then(origin); + HeaderValue::from_str(&policy(&inline_script_hashes(&html), storage.as_deref())) + .unwrap_or(HeaderValue::from_static("default-src 'self'")) +} + +/// Global middleware: adds the headers a response doesn't already have, and drops `x-powered-by`. +#[middleware] +pub async fn security_headers(frontend: laravel::config::Section, request: Request, next: Next) -> Response { + let gallery = request.path().starts_with("/g/"); + let mut response = next.run(request).await; + let h = response.headers_mut(); + h.remove("x-powered-by"); + if gallery { + h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); + h.insert("cross-origin-resource-policy", HeaderValue::from_static("cross-origin")); + } + h.entry(header::X_CONTENT_TYPE_OPTIONS).or_insert(HeaderValue::from_static("nosniff")); + h.entry(header::REFERRER_POLICY).or_insert(HeaderValue::from_static("strict-origin-when-cross-origin")); + // Laravel's own default is SAMEORIGIN; VisualCI's pages are never framed (the policy's `frame-ancestors 'none'`) + h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); + let policy = POLICY.get_or_init(|| built_policy(&frontend)); + h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy.clone()); + response +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hashes_only_inline_scripts() { + let html = r#" + "#; + let hashes = inline_script_hashes(html); + assert_eq!(hashes.len(), 2); + let expected = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(b"var a = 1")); + assert_eq!(hashes[0], format!("'sha256-{expected}'")); + } + + #[test] + fn the_policy_allows_the_app_and_nothing_else() { + let p = policy(&["'sha256-abc'".into()], Some("http://docspring-dev.hs:5190")); + assert!( + p.contains( + "script-src 'self' https://pa.docspring.com https://static.cloudflareinsights.com 'sha256-abc';" + ), + "{p}" + ); + assert!(p.contains("img-src 'self' data: blob: https: http://docspring-dev.hs:5190;"), "{p}"); + assert!(p.contains("frame-ancestors 'none'")); + assert!(!p.contains("unsafe-eval") && !p.contains("form-action")); + assert_eq!(origin("http://Docspring-Dev.hs:5190/bucket").as_deref(), Some("http://docspring-dev.hs:5190")); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index a9cd9a1f..1dc30244 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -22,6 +22,8 @@ pub fn configure() -> ApplicationBuilder { }) .with_middleware(|middleware, _| { middleware.prepend(http::hosts::route_by_host); + // Outermost, so every response gets the security headers, the host check's 404s included + middleware.prepend(http::security::security_headers); }) .with_routing(|routing, _| { routing.web(auth::routes).api(http::api::routes).health("/up"); diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index da6ad020..be2e3b55 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -25,3 +25,20 @@ async fn each_host_serves_only_its_own_paths(app: Application) { // Any other host (a pod's own address) gets every path app.get("/api/v1/version").header("host", "10.0.0.7").await.assert_ok(); } + +#[laravel::test(app = hosts)] +async fn every_response_carries_the_security_headers(app: Application) { + let response = app.get("/api/v1/version").header("host", "api.visualci.test").await; + response + .assert_ok() + .assert_header("x-content-type-options", "nosniff") + .assert_header("x-frame-options", "DENY") + .assert_header("referrer-policy", "strict-origin-when-cross-origin") + .assert_header_contains("content-security-policy", "frame-ancestors 'none'"); + // A 404 from the host check too + app.get("/mcp") + .header("host", "app.visualci.test") + .await + .assert_status(404) + .assert_header("x-frame-options", "DENY"); +} From 4b5e0044b0d645ef38c53ad506c3562dc103c8dd Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:10:03 +1300 Subject: [PATCH 2/2] Security headers, review fixes: the policy's hashes come from the page the server serves (public/index.html under the application's base path, the frontend in the same image), read once at boot; in production a missing page or one with no inline scripts stops the boot (the theme script would be blocked), elsewhere it's logged --- app/Cargo.lock | 1 + app/Cargo.toml | 1 + app/src/http/security.rs | 63 +++++++++++++++++++++++++++++++--------- app/src/lib.rs | 5 ++++ 4 files changed, 57 insertions(+), 13 deletions(-) diff --git a/app/Cargo.lock b/app/Cargo.lock index 8d3fe3ff..b052fba4 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4546,6 +4546,7 @@ dependencies = [ "sha2 0.10.9", "snapshot-diff", "tokio", + "tracing", "visualci-core", ] diff --git a/app/Cargo.toml b/app/Cargo.toml index 49c8b64a..22aa995d 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -33,6 +33,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +tracing = "0.1" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" diff --git a/app/src/http/security.rs b/app/src/http/security.rs index 78611456..fc2d11c6 100644 --- a/app/src/http/security.rs +++ b/app/src/http/security.rs @@ -5,8 +5,10 @@ //! anywhere (`/g/`: CORS and CORP cross-origin). //! //! The app's `index.html` has inline scripts (the theme, before the page draws; Plausible's queue in production). -//! Their SHA-256 hashes are read from the built page (`VISUALCI_FRONTEND_DIR`, default `frontend/dist`) the first -//! time a response goes out, so the policy always matches the page it's served with. There's no `form-action`: +//! Their SHA-256 hashes are read at boot from the built page the server serves, `public/index.html` under the +//! application's base path (the frontend in the same image), so the policy always matches the page it's served with. +//! In production a page with no inline scripts (or none at all) stops the boot ([`check`]): the theme script would be +//! blocked. There's no `form-action`: //! Chrome applies it to every redirect after a form posts, which would block an MCP client's OAuth callback. use std::sync::OnceLock; @@ -67,11 +69,9 @@ pub fn policy(hashes: &[String], storage: Option<&str>) -> String { ) } -/// The built app and the storage's public endpoint, for the policy. +/// The storage's public endpoint, for the policy's images. #[derive(Clone, laravel::config::Section)] pub struct Frontend { - #[env("VISUALCI_FRONTEND_DIR", default = "frontend/dist")] - pub dir: String, #[env("S3_PUBLIC_ENDPOINT")] pub storage_endpoint: Option, } @@ -83,16 +83,40 @@ fn origin(url: &str) -> Option { Some(format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase())) } -fn built_policy(frontend: &Frontend) -> HeaderValue { - let html = std::fs::read_to_string(std::path::Path::new(&frontend.dir).join("index.html")).unwrap_or_default(); - let storage = frontend.storage_endpoint.as_deref().and_then(origin); - HeaderValue::from_str(&policy(&inline_script_hashes(&html), storage.as_deref())) - .unwrap_or(HeaderValue::from_static("default-src 'self'")) +/// The policy for the page at `page`, or a message when it's missing or has no inline scripts to allow. +/// +/// # Errors +/// That message. +pub fn policy_for(page: &std::path::Path, storage: Option<&str>) -> Result { + let html = std::fs::read_to_string(page).unwrap_or_default(); + let hashes = inline_script_hashes(&html); + if hashes.is_empty() { + return Err(format!("{} has no inline scripts: the policy would block the theme script", page.display())); + } + Ok(policy(&hashes, storage)) +} + +/// Build the policy from the served page (`public/index.html` under the base path), once, at boot. +/// +/// # Errors +/// In production, when the page is missing or has no inline scripts to allow; elsewhere that's only logged. +pub fn check(config: &laravel::config::Config, production: bool) -> laravel::Result<()> { + let storage = config.section::().storage_endpoint.as_deref().and_then(origin); + let value = match policy_for(&config.app.public_path("index.html"), storage.as_deref()) { + Ok(p) => p, + Err(message) if production => return Err(laravel::Error::msg(message)), + Err(message) => { + tracing::warn!("{message}"); + policy(&[], storage.as_deref()) + } + }; + let _ = POLICY.set(HeaderValue::from_str(&value).unwrap_or(HeaderValue::from_static("default-src 'self'"))); + Ok(()) } /// Global middleware: adds the headers a response doesn't already have, and drops `x-powered-by`. #[middleware] -pub async fn security_headers(frontend: laravel::config::Section, request: Request, next: Next) -> Response { +pub async fn security_headers(request: Request, next: Next) -> Response { let gallery = request.path().starts_with("/g/"); let mut response = next.run(request).await; let h = response.headers_mut(); @@ -105,8 +129,8 @@ pub async fn security_headers(frontend: laravel::config::Section, requ h.entry(header::REFERRER_POLICY).or_insert(HeaderValue::from_static("strict-origin-when-cross-origin")); // Laravel's own default is SAMEORIGIN; VisualCI's pages are never framed (the policy's `frame-ancestors 'none'`) h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); - let policy = POLICY.get_or_init(|| built_policy(&frontend)); - h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy.clone()); + let policy = POLICY.get().cloned().unwrap_or(HeaderValue::from_static("default-src 'self'")); + h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy); response } @@ -140,4 +164,17 @@ mod tests { assert!(!p.contains("unsafe-eval") && !p.contains("form-action")); assert_eq!(origin("http://Docspring-Dev.hs:5190/bucket").as_deref(), Some("http://docspring-dev.hs:5190")); } + + #[test] + fn a_page_without_inline_scripts_has_no_policy() { + assert!(policy_for(std::path::Path::new("/nonexistent/index.html"), None).is_err()); + let dir = std::env::temp_dir().join(format!("visualci-csp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let page = dir.join("index.html"); + std::fs::write(&page, "").unwrap(); + assert!(policy_for(&page, None).is_err(), "only external scripts"); + std::fs::write(&page, "").unwrap(); + assert!(policy_for(&page, None).unwrap().contains("'sha256-")); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/app/src/lib.rs b/app/src/lib.rs index 1dc30244..b801ef35 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -20,6 +20,11 @@ pub fn configure() -> ApplicationBuilder { .with_auth(|auth, _| { auth.session::(); }) + .booted(async |app| { + let config = app.config(); + http::security::check(config, config.app.env.is_production())?; + Ok(()) + }) .with_middleware(|middleware, _| { middleware.prepend(http::hosts::route_by_host); // Outermost, so every response gets the security headers, the host check's 404s included