//! The security headers of every response, 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/iz-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with //! `docs/conventions.md` section 5. use topcoat::context::Cx; 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 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 } /// Adds a fixed set of headers to every response of the router. /// /// A header that the route already set is kept: a byte response carries its own policy. Errors take the /// per-request response headers, which the router applies after the layers have run. 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 { match next.run(cx, body).await { // A header the route set itself wins: byte responses carry their own sandboxed // policy, and two policies would apply both (the page one forbids framing). Ok(mut response) => { let headers = response.headers_mut(); for (name, value) in &self.headers { if !headers.contains_key(name) { headers.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(self.headers.clone()); Err(error) } } }) } }