1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum FrameOptions {
27 #[default]
29 Deny,
30 SameOrigin,
32 Disabled,
36}
37
38#[derive(Debug, Clone, Default)]
46pub struct SecurityHeadersConfig {
47 pub frame_options: FrameOptions,
49 pub hsts_max_age_secs: Option<u64>,
52 pub content_security_policy: Option<String>,
55}
56
57impl SecurityHeadersConfig {
58 pub fn new() -> Self {
59 Self::default()
60 }
61
62 pub fn with_frame_options(mut self, frame_options: FrameOptions) -> Self {
64 self.frame_options = frame_options;
65 self
66 }
67
68 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 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#[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 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 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 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#[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#[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#[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}