Skip to main content

churust_core/
security.rs

1//! Security response headers, applied to every response by default.
2//!
3//! Most frameworks leave these to the application, which means most
4//! applications ship without them. Churust sends a conservative set unless told
5//! otherwise, and always yields to a handler that set the header itself.
6//!
7//! "Every response" is meant literally, and that takes two mechanisms rather
8//! than one. Most responses come out of the pipeline, where
9//! `SecurityHeadersMiddleware` decorates them. A few do not: a body refused on
10//! its declared `Content-Length` before dispatch, the RFC 9112 §6.3 refusal, a
11//! request that outran `request_timeout_ms` so the pipeline never produced
12//! anything at all. Those are answered by the transport, and each transport
13//! applies the same set to whatever it is about to write — see
14//! `App::apply_security_headers`. Applying twice is deliberately harmless,
15//! because a header already present is left alone.
16//!
17//! What is genuinely out of reach is a response Churust never composed: hyper
18//! answering `431` for a header block over `max_headers`, or a malformed
19//! request line that never became a request. Nothing in this crate sees those.
20//!
21//! ```
22//! use churust_core::{Churust, SecurityHeaders};
23//!
24//! # fn build() {
25//! // Customise:
26//! Churust::server().security_headers(
27//!     SecurityHeaders::new().referrer_policy(Some("strict-origin-when-cross-origin")),
28//! );
29//!
30//! // Or opt out entirely:
31//! Churust::server().without_security_headers();
32//! # }
33//! ```
34
35use crate::call::Call;
36use crate::pipeline::{Middleware, Next};
37use crate::response::Response;
38use async_trait::async_trait;
39use http::header::{
40    HeaderName, CONTENT_SECURITY_POLICY, REFERRER_POLICY, STRICT_TRANSPORT_SECURITY,
41    X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
42};
43use http::HeaderValue;
44
45/// Which security headers to add, and with what values.
46///
47/// `None` for any field disables that header. Defaults:
48///
49/// | Header | Default |
50/// | --- | --- |
51/// | `X-Content-Type-Options` | `nosniff` |
52/// | `X-Frame-Options` | `DENY` |
53/// | `Referrer-Policy` | `no-referrer` |
54/// | `Strict-Transport-Security` | `max-age=31536000`, **only when TLS is configured** |
55/// | `Content-Security-Policy` | off |
56///
57/// There is no default Content-Security-Policy on purpose: a useful one is
58/// application-specific, and a generic one either breaks pages or is so
59/// permissive that it implies protection it does not give.
60#[derive(Debug, Clone)]
61pub struct SecurityHeaders {
62    content_type_options: Option<String>,
63    frame_options: Option<String>,
64    referrer_policy: Option<String>,
65    hsts: Option<String>,
66    csp: Option<String>,
67}
68
69impl Default for SecurityHeaders {
70    fn default() -> Self {
71        Self {
72            content_type_options: Some("nosniff".into()),
73            frame_options: Some("DENY".into()),
74            referrer_policy: Some("no-referrer".into()),
75            hsts: Some("max-age=31536000".into()),
76            csp: None,
77        }
78    }
79}
80
81impl SecurityHeaders {
82    /// The default set. Equivalent to [`SecurityHeaders::default`].
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// Set or disable `X-Content-Type-Options`.
88    pub fn content_type_options(mut self, v: Option<&str>) -> Self {
89        self.content_type_options = v.map(Into::into);
90        self
91    }
92
93    /// Set or disable `X-Frame-Options`.
94    pub fn frame_options(mut self, v: Option<&str>) -> Self {
95        self.frame_options = v.map(Into::into);
96        self
97    }
98
99    /// Set or disable `Referrer-Policy`.
100    pub fn referrer_policy(mut self, v: Option<&str>) -> Self {
101        self.referrer_policy = v.map(Into::into);
102        self
103    }
104
105    /// Set or disable `Strict-Transport-Security`.
106    ///
107    /// Only sent when the response is known to be going out over TLS.
108    /// Announcing HSTS over plaintext tells a client nothing it can trust, and
109    /// behind a terminating proxy it can pin a hostname to HTTPS the origin
110    /// does not actually serve.
111    ///
112    /// Two things establish that knowledge. Over TCP it is
113    /// [`AppBuilder::tls`](crate::AppBuilder::tls): this process holding the
114    /// certificate is what rules out a plaintext hop in front of it. Over
115    /// HTTP/3 nothing needs to be configured, because QUIC has no plaintext
116    /// mode — `server_config_from_pem` pins TLS 1.3 — so an h3 response is
117    /// encrypted whether or not the builder was ever told about a certificate.
118    pub fn hsts(mut self, v: Option<&str>) -> Self {
119        self.hsts = v.map(Into::into);
120        self
121    }
122
123    /// Set a `Content-Security-Policy`. Off by default.
124    pub fn content_security_policy(mut self, v: Option<&str>) -> Self {
125        self.csp = v.map(Into::into);
126        self
127    }
128
129    /// Fill in whichever of these headers a response does not already carry.
130    ///
131    /// Split out of the middleware so the transports can reuse it verbatim.
132    /// Responses that never reach the pipeline — a body refused on its declared
133    /// length, a request that outran its deadline — used to arrive bare because
134    /// the only implementation of this lived inside a `Middleware::handle` they
135    /// never passed through. One function, called from both places, is what
136    /// keeps the two sets from drifting apart.
137    ///
138    /// `over_tls` answers "is this response definitely encrypted on the way
139    /// out", which is the only question [`hsts`](Self::hsts) depends on.
140    ///
141    /// Idempotent by construction: every header is skipped when already
142    /// present, which is the same rule that lets a handler override a default,
143    /// so calling it twice on one response cannot change the result.
144    pub(crate) fn apply_to(&self, headers: &mut http::HeaderMap, over_tls: bool) {
145        let mut set = |name: HeaderName, value: &Option<String>| {
146            let Some(v) = value else { return };
147            // The application wins. A handler that set this header did so on
148            // purpose, and silently overwriting it would be a trap.
149            if headers.contains_key(&name) {
150                return;
151            }
152            if let Ok(hv) = HeaderValue::from_str(v) {
153                headers.insert(name, hv);
154            }
155        };
156
157        set(X_CONTENT_TYPE_OPTIONS, &self.content_type_options);
158        set(X_FRAME_OPTIONS, &self.frame_options);
159        set(REFERRER_POLICY, &self.referrer_policy);
160        set(CONTENT_SECURITY_POLICY, &self.csp);
161        if over_tls {
162            set(STRICT_TRANSPORT_SECURITY, &self.hsts);
163        }
164    }
165
166    pub(crate) fn into_middleware(self, tls_enabled: bool) -> SecurityHeadersMiddleware {
167        SecurityHeadersMiddleware {
168            cfg: self,
169            tls_enabled,
170        }
171    }
172}
173
174pub(crate) struct SecurityHeadersMiddleware {
175    cfg: SecurityHeaders,
176    tls_enabled: bool,
177}
178
179#[async_trait]
180impl Middleware for SecurityHeadersMiddleware {
181    async fn handle(&self, call: Call, next: Next) -> Response {
182        let mut res = next.run(call).await;
183        // `tls_enabled` is all the pipeline knows: it runs identically on every
184        // transport, so it cannot tell an h3 request from a plaintext one. The
185        // transport fills that in afterwards, which is why HSTS over h3 is
186        // added by `send_response` rather than here.
187        self.cfg.apply_to(&mut res.headers, self.tls_enabled);
188        res
189    }
190}