//! The security headers of every response, the cache policy that goes with them, and the //! Content-Security-Policy they carry. //! //! The policy allows scripts and styles from the origin itself and nothing else. No page may use an //! inline script, an inline style or an inline event handler: all behaviour lives in //! `crates/im-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with //! `docs/conventions.md` section 5. //! //! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`, //! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy. //! Assets set their own long-lived policy. A photo that has its bytes sets its own `private` policy //! and its own CSP (see `pages/photo.rs`), and this layer leaves both alone. A photo's redirect or //! error (sign-in, 404) is a page to the browser, so it gets the page headers. use topcoat::context::Cx; use topcoat::router::request::uri; use topcoat::router::response::response_headers; use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; /// The Content-Security-Policy of every response. pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \ form-action 'self'; frame-ancestors 'none'; base-uri 'none'"; /// One year, in seconds. Sent only when the public origin is https. const HSTS: &str = "max-age=31536000"; /// The cache policy of every page: nothing is stored, not even for going back in the history. const NO_STORE: &str = "no-store"; /// The referrer policy of the pages that carry a single-use token in their path. The token must never leave /// the site in a `Referer` header, so these pages send none at all. const NO_REFERRER: &str = "no-referrer"; /// True for the pages whose path holds a token or starts an account link: the reset request and every /// `/reset/`, `/invite/` and `/email/` page. pub fn token_path(path: &str) -> bool { path == "/forgot" || path.starts_with("/reset/") || path.starts_with("/invite/") || path.starts_with("/email/") } /// The headers that every response carries, for an instance at `base_url`. pub fn headers_for(base_url: &str) -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert( header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"), ); headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); headers.insert( header::REFERRER_POLICY, HeaderValue::from_static("same-origin"), ); headers.insert( header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(CSP), ); if base_url.starts_with("https://") { headers.insert( header::STRICT_TRANSPORT_SECURITY, HeaderValue::from_static(HSTS), ); } headers } /// What kind of answer a path gets, which decides its headers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Answer { /// A static file under `/assets/`, with its own cache policy. Asset, /// A profile photo under `/photo/`. An answer with bytes has its own cache policy and CSP; a redirect or /// error has the page headers. Photo, /// Public OpenID metadata (discovery and the key set). Not secret, so it may be cached; the handler /// sets the short cache policy. Public, /// Everything else: pages, forms, streams. Never stored. Page, } /// The kind of answer for a request path. pub fn answer_for(path: &str) -> Answer { if path.starts_with("/assets/") { Answer::Asset } else if path.starts_with("/photo/") { Answer::Photo } else if path == "/.well-known/openid-configuration" || path == "/jwks.json" { Answer::Public } else { Answer::Page } } /// Adds the security headers to every response, and `Cache-Control: no-store` to every page and every /// photo answer that is not a photo's bytes. /// /// It uses the per-request response headers, which the router applies after the layers have run, /// so error responses (404, 500, the sign-in redirect) carry them as well. A header the route set /// itself is never replaced, so a photo with bytes keeps its own CSP and cache policy. pub struct SecurityHeaders { headers: HeaderMap, } impl SecurityHeaders { /// A layer that adds `headers` to every response. pub fn new(headers: HeaderMap) -> Self { Self { headers } } } impl Layer for SecurityHeaders { fn path(&self) -> Option<&Path> { None } fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { Box::pin(async move { let path = uri(cx).path(); let answer = answer_for(path); let mut headers = self.headers.clone(); if matches!(answer, Answer::Page | Answer::Photo) { headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); } if answer == Answer::Page && token_path(path) { headers.insert( header::REFERRER_POLICY, HeaderValue::from_static(NO_REFERRER), ); } match next.run(cx, body).await { // A header the route set itself wins: a token answer that is already `no-store`, or a // photo with its own stricter policy, must not get a second copy of the same header. Ok(mut response) => { let response_map = response.headers_mut(); for (name, value) in &headers { if !response_map.contains_key(name) { response_map.insert(name.clone(), value.clone()); } } Ok(response) } // Errors become responses after the layers have run; the per-request slot gives // them the headers too. Err(error) => { response_headers(cx).extend(headers); Err(error) } } }) } } #[cfg(test)] mod tests { use super::*; #[test] fn only_pages_are_marked_no_store() { assert_eq!(answer_for("/login"), Answer::Page); assert_eq!(answer_for("/account/profile"), Answer::Page); assert_eq!(answer_for("/setup"), Answer::Page); assert_eq!(answer_for("/photo/01HZ"), Answer::Photo); assert_eq!(answer_for("/assets/main.css"), Answer::Asset); assert_eq!(answer_for("/jwks.json"), Answer::Public); // A prefix match on the segment only: a page whose name starts the same is still a page. assert_eq!(answer_for("/photographs"), Answer::Page); } #[tokio::test] async fn a_route_header_is_not_repeated_by_the_layer() { let (_dir, state) = crate::boot::test_state().await; for (method, path) in [("POST", "/token"), ("GET", "/photo/01HZ")] { let request = http::Request::builder() .method(method) .uri(path) .body(topcoat::router::Body::empty()) .expect("request"); let response = crate::boot::router(state.clone()).handle(request).await; let headers = response.headers(); // A repeat is the bug under test. A photo redirect (to sign-in) is an error answer, so it // carries the layer's Cache-Control and CSP once each. let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count(); assert!(cache_control <= 1, "Cache-Control repeated on {path}"); if path == "/token" || path == "/photo/01HZ" { assert_eq!(cache_control, 1, "Cache-Control on {path}"); } let csp = headers .get_all(header::CONTENT_SECURITY_POLICY) .iter() .count(); assert!(csp <= 1, "CSP repeated on {path}"); if path == "/token" || path == "/photo/01HZ" { assert_eq!(csp, 1, "CSP on {path}"); } } } #[test] fn token_pages_are_recognised() { assert!(token_path("/reset/abc")); assert!(token_path("/invite/abc")); assert!(token_path("/email/abc")); assert!(token_path("/forgot")); assert!(!token_path("/login")); assert!(!token_path("/resetting")); } #[test] fn hsts_only_for_https_origins() { assert!( headers_for("https://im.example.com").contains_key(header::STRICT_TRANSPORT_SECURITY) ); assert!( !headers_for("http://127.0.0.1:7650").contains_key(header::STRICT_TRANSPORT_SECURITY) ); } }