Skip to main content

proa_framework_axum/
security_headers.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Default security response headers applied by the framework builder.
5//!
6//! `proa_framework_core` already stamps `X-Content-Type-Options`,
7//! `X-Frame-Options`, and `Referrer-Policy` onto SSR responses at
8//! construction time. This layer is the HTTP-level counterpart: it covers
9//! every response that leaves the built router (static files, proxied
10//! apps, plain axum handlers, error responses from other middleware) and
11//! carries the opt-in headers that need deployment knowledge
12//! (`Strict-Transport-Security`, `Content-Security-Policy`) plus the
13//! ability to relax or remove `X-Frame-Options` for embeddable apps.
14
15use std::future::Future;
16use std::pin::Pin;
17use std::sync::Arc;
18use std::task::{ready, Context, Poll};
19
20use axum::http::{header, HeaderValue, Request, Response};
21use pin_project::pin_project;
22use tower::{Layer, Service};
23
24/// `X-Frame-Options` policy applied by [`SecurityHeadersConfig`].
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum FrameOptions {
27    /// `X-Frame-Options: DENY` (the default): pages may never be framed.
28    #[default]
29    Deny,
30    /// `X-Frame-Options: SAMEORIGIN`: same-origin pages may frame the app.
31    SameOrigin,
32    /// Remove the header entirely, for apps that are embedded by other
33    /// origins. Prefer pairing this with a `Content-Security-Policy`
34    /// `frame-ancestors` directive that names the allowed embedders.
35    Disabled,
36}
37
38/// Security header policy for the built router.
39///
40/// Defaults: `X-Frame-Options: DENY`, `Referrer-Policy:
41/// strict-origin-when-cross-origin`, and `X-Content-Type-Options:
42/// nosniff` on every response that does not already carry them. HSTS and
43/// CSP are off by default: HSTS is only correct when the deployment
44/// terminates TLS, and a CSP must be authored per app.
45#[derive(Debug, Clone, Default)]
46pub struct SecurityHeadersConfig {
47    /// Clickjacking defense. See [`FrameOptions`].
48    pub frame_options: FrameOptions,
49    /// When set, emit `Strict-Transport-Security: max-age=<secs>`.
50    /// Off by default because it requires TLS awareness.
51    pub hsts_max_age_secs: Option<u64>,
52    /// When set, emit this exact string as the `Content-Security-Policy`
53    /// value. Off by default.
54    pub content_security_policy: Option<String>,
55}
56
57impl SecurityHeadersConfig {
58    pub fn new() -> Self {
59        Self::default()
60    }
61
62    /// Set the `X-Frame-Options` policy.
63    pub fn with_frame_options(mut self, frame_options: FrameOptions) -> Self {
64        self.frame_options = frame_options;
65        self
66    }
67
68    /// Enable `Strict-Transport-Security` with the given `max-age` in
69    /// seconds. Only do this when the deployment serves over TLS.
70    pub fn with_hsts_max_age_secs(mut self, max_age_secs: u64) -> Self {
71        self.hsts_max_age_secs = Some(max_age_secs);
72        self
73    }
74
75    /// Enable `Content-Security-Policy` with the given full policy
76    /// string, e.g. `"default-src 'self'"`.
77    pub fn with_content_security_policy(mut self, policy: impl Into<String>) -> Self {
78        self.content_security_policy = Some(policy.into());
79        self
80    }
81}
82
83/// Header values resolved once at layer construction so the per-response
84/// work is a handful of header-map probes with zero allocation.
85#[derive(Debug)]
86struct ResolvedSecurityHeaders {
87    frame_options: FrameOptions,
88    hsts: Option<HeaderValue>,
89    csp: Option<HeaderValue>,
90}
91
92impl ResolvedSecurityHeaders {
93    fn from_config(config: SecurityHeadersConfig) -> Self {
94        let hsts = config.hsts_max_age_secs.and_then(|secs| {
95            // proa-perf-ok: one-time layer construction, not a render path.
96            HeaderValue::from_str(&format!("max-age={secs}")).ok()
97        });
98        let csp = config.content_security_policy.and_then(|policy| {
99            match HeaderValue::from_str(&policy) {
100                Ok(value) => Some(value),
101                Err(_) => {
102                    tracing::warn!(
103                        "configured Content-Security-Policy contains invalid header \
104                         characters; the header will not be sent"
105                    );
106                    None
107                }
108            }
109        });
110        Self {
111            frame_options: config.frame_options,
112            hsts,
113            csp,
114        }
115    }
116
117    fn apply<B>(&self, response: &mut Response<B>) {
118        let headers = response.headers_mut();
119        if !headers.contains_key(header::X_CONTENT_TYPE_OPTIONS) {
120            headers.insert(
121                header::X_CONTENT_TYPE_OPTIONS,
122                HeaderValue::from_static("nosniff"),
123            );
124        }
125        match self.frame_options {
126            // The SSR response constructors already default to DENY; only
127            // fill the gap for responses that did not pass through them.
128            FrameOptions::Deny => {
129                if !headers.contains_key(header::X_FRAME_OPTIONS) {
130                    headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
131                }
132            }
133            // Overrides the core default of DENY, so insert unconditionally.
134            FrameOptions::SameOrigin => {
135                headers.insert(
136                    header::X_FRAME_OPTIONS,
137                    HeaderValue::from_static("SAMEORIGIN"),
138                );
139            }
140            FrameOptions::Disabled => {
141                headers.remove(header::X_FRAME_OPTIONS);
142            }
143        }
144        if !headers.contains_key(header::REFERRER_POLICY) {
145            headers.insert(
146                header::REFERRER_POLICY,
147                HeaderValue::from_static("strict-origin-when-cross-origin"),
148            );
149        }
150        if let Some(hsts) = &self.hsts {
151            if !headers.contains_key(header::STRICT_TRANSPORT_SECURITY) {
152                headers.insert(header::STRICT_TRANSPORT_SECURITY, hsts.clone());
153            }
154        }
155        if let Some(csp) = &self.csp {
156            if !headers.contains_key(header::CONTENT_SECURITY_POLICY) {
157                headers.insert(header::CONTENT_SECURITY_POLICY, csp.clone());
158            }
159        }
160    }
161}
162
163/// Tower layer that applies a [`SecurityHeadersConfig`] to every response.
164#[derive(Debug, Clone)]
165pub struct SecurityHeadersLayer {
166    resolved: Arc<ResolvedSecurityHeaders>,
167}
168
169impl SecurityHeadersLayer {
170    pub fn new(config: SecurityHeadersConfig) -> Self {
171        Self {
172            resolved: Arc::new(ResolvedSecurityHeaders::from_config(config)),
173        }
174    }
175}
176
177impl Default for SecurityHeadersLayer {
178    fn default() -> Self {
179        Self::new(SecurityHeadersConfig::default())
180    }
181}
182
183impl<S> Layer<S> for SecurityHeadersLayer {
184    type Service = SecurityHeaders<S>;
185
186    fn layer(&self, inner: S) -> Self::Service {
187        SecurityHeaders {
188            inner,
189            resolved: Arc::clone(&self.resolved),
190        }
191    }
192}
193
194/// Tower service produced by [`SecurityHeadersLayer`].
195#[derive(Debug, Clone)]
196pub struct SecurityHeaders<S> {
197    inner: S,
198    resolved: Arc<ResolvedSecurityHeaders>,
199}
200
201impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for SecurityHeaders<S>
202where
203    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
204{
205    type Response = Response<ResBody>;
206    type Error = S::Error;
207    type Future = SecurityHeadersFuture<S::Future>;
208
209    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
210        self.inner.poll_ready(cx)
211    }
212
213    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
214        SecurityHeadersFuture {
215            inner: self.inner.call(req),
216            resolved: Arc::clone(&self.resolved),
217        }
218    }
219}
220
221/// Future returned by [`SecurityHeaders`].
222#[pin_project]
223pub struct SecurityHeadersFuture<F> {
224    #[pin]
225    inner: F,
226    resolved: Arc<ResolvedSecurityHeaders>,
227}
228
229impl<F, ResBody, E> Future for SecurityHeadersFuture<F>
230where
231    F: Future<Output = Result<Response<ResBody>, E>>,
232{
233    type Output = Result<Response<ResBody>, E>;
234
235    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
236        let this = self.project();
237        let mut result = ready!(this.inner.poll(cx));
238        if let Ok(response) = &mut result {
239            this.resolved.apply(response);
240        }
241        Poll::Ready(result)
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use axum::body::Body;
249
250    fn apply(config: SecurityHeadersConfig, response: &mut Response<Body>) {
251        ResolvedSecurityHeaders::from_config(config).apply(response);
252    }
253
254    #[test]
255    fn defaults_add_frame_options_referrer_policy_and_nosniff() {
256        let mut response = Response::new(Body::empty());
257        apply(SecurityHeadersConfig::default(), &mut response);
258
259        let headers = response.headers();
260        assert_eq!(headers.get(header::X_FRAME_OPTIONS).unwrap(), "DENY");
261        assert_eq!(
262            headers.get(header::REFERRER_POLICY).unwrap(),
263            "strict-origin-when-cross-origin"
264        );
265        assert_eq!(
266            headers.get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
267            "nosniff"
268        );
269        assert!(headers.get(header::STRICT_TRANSPORT_SECURITY).is_none());
270        assert!(headers.get(header::CONTENT_SECURITY_POLICY).is_none());
271    }
272
273    #[test]
274    fn existing_headers_are_not_clobbered() {
275        let mut response = Response::new(Body::empty());
276        response.headers_mut().insert(
277            header::REFERRER_POLICY,
278            HeaderValue::from_static("no-referrer"),
279        );
280        apply(SecurityHeadersConfig::default(), &mut response);
281
282        assert_eq!(
283            response.headers().get(header::REFERRER_POLICY).unwrap(),
284            "no-referrer"
285        );
286    }
287
288    #[test]
289    fn same_origin_overrides_an_existing_deny() {
290        let mut response = Response::new(Body::empty());
291        response
292            .headers_mut()
293            .insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
294        apply(
295            SecurityHeadersConfig::default().with_frame_options(FrameOptions::SameOrigin),
296            &mut response,
297        );
298
299        assert_eq!(
300            response.headers().get(header::X_FRAME_OPTIONS).unwrap(),
301            "SAMEORIGIN"
302        );
303    }
304
305    #[test]
306    fn disabled_frame_options_removes_the_header() {
307        let mut response = Response::new(Body::empty());
308        response
309            .headers_mut()
310            .insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
311        apply(
312            SecurityHeadersConfig::default().with_frame_options(FrameOptions::Disabled),
313            &mut response,
314        );
315
316        assert!(response.headers().get(header::X_FRAME_OPTIONS).is_none());
317    }
318
319    #[test]
320    fn hsts_and_csp_are_emitted_when_configured() {
321        let mut response = Response::new(Body::empty());
322        apply(
323            SecurityHeadersConfig::default()
324                .with_hsts_max_age_secs(63072000)
325                .with_content_security_policy("default-src 'self'"),
326            &mut response,
327        );
328
329        let headers = response.headers();
330        assert_eq!(
331            headers.get(header::STRICT_TRANSPORT_SECURITY).unwrap(),
332            "max-age=63072000"
333        );
334        assert_eq!(
335            headers.get(header::CONTENT_SECURITY_POLICY).unwrap(),
336            "default-src 'self'"
337        );
338    }
339
340    #[test]
341    fn invalid_csp_is_dropped_instead_of_panicking() {
342        let mut response = Response::new(Body::empty());
343        apply(
344            SecurityHeadersConfig::default().with_content_security_policy("bad\npolicy"),
345            &mut response,
346        );
347
348        assert!(response
349            .headers()
350            .get(header::CONTENT_SECURITY_POLICY)
351            .is_none());
352    }
353}