Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ 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"] }
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"
Expand Down
1 change: 1 addition & 0 deletions app/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@

pub mod api;
pub mod hosts;
pub mod security;
180 changes: 180 additions & 0 deletions app/src/http/security.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
//! 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 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;

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<HeaderValue> = OnceLock::new();

/// `'sha256-…'` for each inline `<script>` (one without `src`) in `html`.
#[must_use]
pub fn inline_script_hashes(html: &str) -> Vec<String> {
let mut hashes = Vec::new();
let mut rest = html;
while let Some(open) = rest.find("<script") {
let after = &rest[open..];
let Some(gt) = after.find('>') else { break };
let tag = &after[..gt];
let body_start = gt + 1;
let Some(close) = after[body_start..].find("</script>") 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 + "</script>".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::<Vec<_>>()
.join(" ");
let images = ["'self'", "data:", "blob:", "https:"]
.into_iter()
.map(str::to_string)
.chain(storage.map(str::to_string))
.collect::<Vec<_>>()
.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 storage's public endpoint, for the policy's images.
#[derive(Clone, laravel::config::Section)]
pub struct Frontend {
#[env("S3_PUBLIC_ENDPOINT")]
pub storage_endpoint: Option<String>,
}

/// An origin (`scheme://host[:port]`) from a URL.
fn origin(url: &str) -> Option<String> {
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()))
}

/// 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<String, String> {
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::<Frontend>().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(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().cloned().unwrap_or(HeaderValue::from_static("default-src 'self'"));
h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy);
response
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn hashes_only_inline_scripts() {
let html = r#"<head><script>var a = 1</script><script async src="https://pa.docspring.com/js/x.js"></script>
<script type="module" src="/assets/app.js"></script><script>
plausible.init()
</script></head>"#;
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"));
}

#[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, "<html><script src=\"/assets/app.js\"></script></html>").unwrap();
assert!(policy_for(&page, None).is_err(), "only external scripts");
std::fs::write(&page, "<html><script>theme()</script></html>").unwrap();
assert!(policy_for(&page, None).unwrap().contains("'sha256-"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
7 changes: 7 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,15 @@ pub fn configure() -> ApplicationBuilder {
.with_auth(|auth, _| {
auth.session::<models::Users>();
})
.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
middleware.prepend(http::security::security_headers);
})
.with_routing(|routing, _| {
routing.web(auth::routes).api(http::api::routes).health("/up");
Expand Down
17 changes: 17 additions & 0 deletions app/tests/hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}