webserver_base/webserver/
security.rs1use std::sync::Arc;
12
13use axum::extract::{Request, State};
14use axum::http::header::{self, HeaderName, HeaderValue};
15use axum::middleware::Next;
16use axum::response::Response;
17use uuid::Uuid;
18
19tokio::task_local! {
20 static NONCE: Arc<str>;
22}
23
24#[must_use]
27pub fn current_nonce() -> String {
28 NONCE
29 .try_with(|nonce: &Arc<str>| nonce.to_string())
30 .unwrap_or_default()
31}
32
33pub const NONCE_PLACEHOLDER: &str = "{nonce}";
35
36const DEFAULT_REFERRER_POLICY: &str = "strict-origin-when-cross-origin";
37const DEFAULT_PERMISSIONS_POLICY: &str =
38 "camera=(), microphone=(), geolocation=(), payment=(), usb=()";
39const DEFAULT_FRAME_ANCESTORS: &str = "'none'";
40
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum CspMode {
44 ReportOnly,
46 Enforce,
48}
49
50#[derive(Clone, Debug)]
57pub struct ContentSecurityPolicy {
58 mode: CspMode,
59 directives: Vec<(String, String)>,
60 report_uri: Option<String>,
61}
62
63impl ContentSecurityPolicy {
64 #[must_use]
66 pub const fn new(mode: CspMode) -> Self {
67 Self {
68 mode,
69 directives: Vec::new(),
70 report_uri: None,
71 }
72 }
73
74 #[must_use]
76 pub fn directive(mut self, name: &str, value: &str) -> Self {
77 self.directives.push((name.to_owned(), value.to_owned()));
78 self
79 }
80
81 #[must_use]
83 pub fn report_uri(mut self, uri: &str) -> Self {
84 self.report_uri = Some(uri.to_owned());
85 self
86 }
87
88 fn uses_nonce(&self) -> bool {
89 self.directives
90 .iter()
91 .any(|(_, value): &(String, String)| value.contains(NONCE_PLACEHOLDER))
92 }
93
94 fn template(&self) -> String {
95 let mut parts: Vec<String> = self
96 .directives
97 .iter()
98 .map(|(name, value): &(String, String)| format!("{name} {value}"))
99 .collect();
100 if let Some(uri) = &self.report_uri {
101 parts.push(format!("report-uri {uri}"));
102 }
103 parts.join("; ")
104 }
105
106 const fn header_name(&self) -> HeaderName {
107 match self.mode {
108 CspMode::ReportOnly => header::CONTENT_SECURITY_POLICY_REPORT_ONLY,
109 CspMode::Enforce => header::CONTENT_SECURITY_POLICY,
110 }
111 }
112}
113
114#[derive(Clone, Debug)]
116pub struct SecurityHeaders {
117 referrer_policy: String,
118 permissions_policy: String,
119 frame_ancestors: String,
120 csp: Option<ContentSecurityPolicy>,
121}
122
123impl Default for SecurityHeaders {
124 fn default() -> Self {
125 Self::new()
126 }
127}
128
129impl SecurityHeaders {
130 #[must_use]
133 pub fn new() -> Self {
134 Self {
135 referrer_policy: DEFAULT_REFERRER_POLICY.to_owned(),
136 permissions_policy: DEFAULT_PERMISSIONS_POLICY.to_owned(),
137 frame_ancestors: DEFAULT_FRAME_ANCESTORS.to_owned(),
138 csp: None,
139 }
140 }
141
142 #[must_use]
144 pub fn referrer_policy(mut self, value: &str) -> Self {
145 value.clone_into(&mut self.referrer_policy);
146 self
147 }
148
149 #[must_use]
151 pub fn permissions_policy(mut self, value: &str) -> Self {
152 value.clone_into(&mut self.permissions_policy);
153 self
154 }
155
156 #[must_use]
159 pub fn frame_ancestors(mut self, sources: &str) -> Self {
160 sources.clone_into(&mut self.frame_ancestors);
161 self
162 }
163
164 #[must_use]
166 pub fn content_security_policy(mut self, policy: ContentSecurityPolicy) -> Self {
167 self.csp = Some(policy);
168 self
169 }
170
171 pub(super) fn build(self) -> Arc<Built> {
172 let frame_options: Option<HeaderValue> = match self.frame_ancestors.trim() {
173 "'none'" => Some(HeaderValue::from_static("DENY")),
174 "'self'" => Some(HeaderValue::from_static("SAMEORIGIN")),
175 _ => None,
176 };
177 let csp: Option<(HeaderName, String, bool)> = self.csp.as_ref().map(|policy| {
178 (
179 policy.header_name(),
180 clean(&policy.template()),
181 policy.uses_nonce(),
182 )
183 });
184 Arc::new(Built {
185 referrer_policy: value(&self.referrer_policy),
186 permissions_policy: value(&self.permissions_policy),
187 frame_policy: value(&format!("frame-ancestors {}", self.frame_ancestors)),
188 frame_options,
189 csp,
190 })
191 }
192}
193
194fn clean(text: &str) -> String {
196 text.chars().filter(|c: &char| !c.is_control()).collect()
197}
198
199fn value(text: &str) -> HeaderValue {
200 HeaderValue::from_str(&clean(text)).unwrap_or_else(|_| HeaderValue::from_static(""))
201}
202
203pub(super) struct Built {
205 referrer_policy: HeaderValue,
206 permissions_policy: HeaderValue,
207 frame_policy: HeaderValue,
208 frame_options: Option<HeaderValue>,
209 csp: Option<(HeaderName, String, bool)>,
210}
211
212const X_FRAME_OPTIONS: HeaderName = HeaderName::from_static("x-frame-options");
213const PERMISSIONS_POLICY: HeaderName = HeaderName::from_static("permissions-policy");
214
215pub(super) fn apply(router: axum::Router, security: Option<SecurityHeaders>) -> axum::Router {
217 let Some(security) = security else {
218 return router;
219 };
220 router.layer(axum::middleware::from_fn_with_state(
221 security.build(),
222 layer,
223 ))
224}
225
226async fn layer(State(built): State<Arc<Built>>, request: Request, next: Next) -> Response {
227 let uses_nonce: bool = built.csp.as_ref().is_some_and(|(_, _, uses)| *uses);
228 let (nonce, mut response): (Option<String>, Response) = if uses_nonce {
229 let nonce: String = Uuid::new_v4().simple().to_string();
230 let response: Response = NONCE
231 .scope(Arc::from(nonce.as_str()), next.run(request))
232 .await;
233 (Some(nonce), response)
234 } else {
235 (None, next.run(request).await)
236 };
237 let headers = response.headers_mut();
238 headers.insert(
239 header::X_CONTENT_TYPE_OPTIONS,
240 HeaderValue::from_static("nosniff"),
241 );
242 headers.insert(header::REFERRER_POLICY, built.referrer_policy.clone());
243 headers.insert(PERMISSIONS_POLICY, built.permissions_policy.clone());
244
245 let is_html: bool = headers
246 .get(header::CONTENT_TYPE)
247 .and_then(|value: &HeaderValue| value.to_str().ok())
248 .is_some_and(|value: &str| {
249 value
250 .trim_start()
251 .to_ascii_lowercase()
252 .starts_with("text/html")
253 });
254 if !is_html {
255 return response;
256 }
257 headers.append(header::CONTENT_SECURITY_POLICY, built.frame_policy.clone());
258 if let Some(options) = &built.frame_options {
259 headers.insert(X_FRAME_OPTIONS, options.clone());
260 }
261 let Some((name, template, _)) = &built.csp else {
262 return response;
263 };
264 let policy: String = nonce.as_deref().map_or_else(
265 || template.clone(),
266 |nonce: &str| template.replace(NONCE_PLACEHOLDER, nonce),
267 );
268 if let Ok(value) = HeaderValue::from_str(&policy) {
269 response.headers_mut().append(name.clone(), value);
270 }
271 response
272}
273
274#[cfg(test)]
275mod tests {
276 use axum::Router;
277 use axum::body::Body;
278 use axum::http::{Request, StatusCode};
279 use axum::middleware::from_fn_with_state;
280 use axum::response::Html;
281 use axum::routing::get;
282 use tower::ServiceExt;
283
284 use super::*;
285
286 fn app(headers: SecurityHeaders) -> Router {
287 Router::new()
288 .route(
289 "/",
290 get(|| async {
291 Html(format!(
292 "<script nonce=\"{}\">1</script><script>injected</script>",
293 current_nonce()
294 ))
295 }),
296 )
297 .route("/api", get(|| async { "{}" }))
298 .layer(from_fn_with_state(headers.build(), layer))
299 }
300
301 async fn get_path(app: &Router, path: &str) -> Response {
302 app.clone()
303 .oneshot(Request::get(path).body(Body::empty()).expect("a request"))
304 .await
305 .expect("infallible")
306 }
307
308 fn header_of<'a>(response: &'a Response, name: &str) -> Vec<&'a str> {
309 response
310 .headers()
311 .get_all(name)
312 .iter()
313 .map(|value: &HeaderValue| value.to_str().expect("ascii"))
314 .collect()
315 }
316
317 #[tokio::test]
318 async fn an_html_page_gets_every_header_and_a_nonce_matching_its_scripts() {
319 let policy: ContentSecurityPolicy = ContentSecurityPolicy::new(CspMode::ReportOnly)
320 .directive("script-src", "'self' 'nonce-{nonce}'")
321 .report_uri("/r");
322 let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
323 let response: Response = get_path(&app, "/").await;
324 assert_eq!(StatusCode::OK, response.status());
325 assert_eq!(
326 vec!["nosniff"],
327 header_of(&response, "x-content-type-options")
328 );
329 assert_eq!(
330 vec!["strict-origin-when-cross-origin"],
331 header_of(&response, "referrer-policy")
332 );
333 assert_eq!(
334 vec![DEFAULT_PERMISSIONS_POLICY],
335 header_of(&response, "permissions-policy")
336 );
337 assert_eq!(vec!["DENY"], header_of(&response, "x-frame-options"));
338 assert_eq!(
339 vec!["frame-ancestors 'none'"],
340 header_of(&response, "content-security-policy")
341 );
342 let report: Vec<&str> = header_of(&response, "content-security-policy-report-only");
343 let nonce: String = report[0]
344 .strip_prefix("script-src 'self' 'nonce-")
345 .and_then(|rest: &str| rest.strip_suffix("'; report-uri /r"))
346 .expect("the nonce is in the policy")
347 .to_owned();
348 assert_eq!(32, nonce.len());
349 let body = axum::body::to_bytes(response.into_body(), usize::MAX)
350 .await
351 .expect("body");
352 assert_eq!(
354 format!("<script nonce=\"{nonce}\">1</script><script>injected</script>"),
355 String::from_utf8_lossy(&body)
356 );
357 }
358
359 #[tokio::test]
360 async fn each_response_gets_its_own_nonce() {
361 let policy: ContentSecurityPolicy =
362 ContentSecurityPolicy::new(CspMode::Enforce).directive("script-src", "'nonce-{nonce}'");
363 let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
364 let first: Response = get_path(&app, "/").await;
365 let second: Response = get_path(&app, "/").await;
366 let a: Vec<&str> = header_of(&first, "content-security-policy");
367 let b: Vec<&str> = header_of(&second, "content-security-policy");
368 assert_eq!("frame-ancestors 'none'", a[0]);
369 assert_ne!(a[1], b[1]);
370 }
371
372 #[tokio::test]
373 async fn a_non_html_response_gets_only_the_always_on_headers() {
374 let policy: ContentSecurityPolicy =
375 ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", "'self'");
376 let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
377 let response: Response = get_path(&app, "/api").await;
378 assert_eq!(
379 vec!["nosniff"],
380 header_of(&response, "x-content-type-options")
381 );
382 assert!(response.headers().get("content-security-policy").is_none());
383 assert!(response.headers().get("x-frame-options").is_none());
384 }
385
386 #[test]
387 fn control_characters_are_removed_from_a_header_value() {
388 let built = SecurityHeaders::new()
389 .referrer_policy("no-ref\nerrer")
390 .build();
391 assert_eq!("no-referrer", built.referrer_policy);
392 }
393
394 #[test]
395 fn the_default_permissions_policy_has_no_interest_cohort() {
396 assert!(!DEFAULT_PERMISSIONS_POLICY.contains("interest-cohort"));
397 }
398}