1use std::collections::{BTreeMap, HashSet};
28use std::convert::Infallible;
29
30use axum::extract::{FromRequestParts, MatchedPath, Request, State};
31use axum::http::header::{
32 CONTENT_SECURITY_POLICY, REFERRER_POLICY, STRICT_TRANSPORT_SECURITY, X_CONTENT_TYPE_OPTIONS,
33 X_FRAME_OPTIONS,
34};
35use axum::http::request::Parts;
36use axum::http::{HeaderName, HeaderValue, Method};
37use axum::middleware::Next;
38use axum::response::{IntoResponse, Response};
39
40use crate::AppState;
41use crate::config::{Config, CspMode, Environment, PermissionsMode};
42use crate::routing::RouteInfo;
43
44#[derive(Debug, Clone, Default)]
46pub struct Csp {
47 extra: BTreeMap<String, Vec<String>>,
48}
49
50impl Csp {
51 pub fn allow(&mut self, directive: &str, source: &str) -> &mut Self {
54 self.extra
55 .entry(directive.trim().to_ascii_lowercase())
56 .or_default()
57 .push(source.trim().to_owned());
58 self
59 }
60}
61
62const DEFAULT_OFF: &[&str] = &[
68 "accelerometer",
69 "autoplay",
70 "bluetooth",
71 "camera",
72 "display-capture",
73 "geolocation",
74 "gyroscope",
75 "hid",
76 "magnetometer",
77 "microphone",
78 "midi",
79 "payment",
80 "serial",
81 "usb",
82 "xr-spatial-tracking",
83];
84
85#[derive(Debug, Clone, Default)]
103#[non_exhaustive]
104pub struct PermissionsPolicy {
105 extra: Vec<(String, String)>,
106}
107
108impl PermissionsPolicy {
109 pub fn allow(&mut self, feature: &str, origin: &str) -> &mut Self {
120 self.extra.push((
121 feature.trim().to_ascii_lowercase(),
122 origin.trim().to_owned(),
123 ));
124 self
125 }
126}
127
128type Feature = (String, Vec<String>);
131
132fn check_feature(name: &str) -> anyhow::Result<()> {
133 if name.is_empty()
134 || !name
135 .bytes()
136 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
137 {
138 anyhow::bail!("`{name}` is not a feature name (lowercase letters, digits and dashes)");
139 }
140 Ok(())
141}
142
143fn origin_token(origin: &str) -> anyhow::Result<String> {
145 let origin = origin.trim().trim_matches('"');
146 match origin {
147 "self" | "*" | "src" => Ok(origin.to_owned()),
148 _ if origin.is_empty()
149 || origin
150 .bytes()
151 .any(|b| b.is_ascii_control() || b" \"(),;".contains(&b)) =>
152 {
153 anyhow::bail!("`{origin}` is not an origin (`self`, `*` or like `https://x.example`)")
154 }
155 _ => Ok(format!("\"{origin}\"")),
156 }
157}
158
159pub(crate) fn parse_permissions_policy(value: &str) -> anyhow::Result<Vec<Feature>> {
161 let mut features: Vec<Feature> = Vec::new();
162 for part in value.split(',').map(str::trim).filter(|p| !p.is_empty()) {
163 let (name, list) = part
164 .split_once('=')
165 .ok_or_else(|| anyhow::anyhow!("`{part}` should look like `feature=(self)`"))?;
166 let name = name.trim();
167 check_feature(name)?;
168 let list = list.trim();
169 let inner = match list.strip_prefix('(') {
170 Some(rest) => rest
171 .strip_suffix(')')
172 .ok_or_else(|| anyhow::anyhow!("`{part}` is missing a `)`"))?,
173 None => list,
174 };
175 let tokens = inner
176 .split_whitespace()
177 .map(|token| {
178 if !matches!(token, "self" | "*" | "src") && !token.starts_with('"') {
179 anyhow::bail!("`{token}` needs quotes: `\"{token}\"`");
180 }
181 origin_token(token)
182 })
183 .collect::<anyhow::Result<Vec<_>>>()?;
184 features.push((name.to_owned(), tokens));
185 }
186 if features.is_empty() {
187 anyhow::bail!("it names no feature");
188 }
189 Ok(features)
190}
191
192fn permissions_header(
194 mode: &PermissionsMode,
195 app: &PermissionsPolicy,
196) -> anyhow::Result<Option<String>> {
197 let mut features: Vec<Feature> = match mode {
198 PermissionsMode::Off => return Ok(None),
199 PermissionsMode::Default => DEFAULT_OFF
200 .iter()
201 .map(|name| ((*name).to_owned(), Vec::new()))
202 .collect(),
203 PermissionsMode::Custom(value) => parse_permissions_policy(value)?,
204 };
205 for (name, origin) in &app.extra {
206 check_feature(name).map_err(|e| anyhow::anyhow!("App::permissions_policy: {e}"))?;
207 let token = origin_token(origin)
208 .map_err(|e| anyhow::anyhow!("App::permissions_policy({name}): {e}"))?;
209 let at = match features.iter().position(|(n, _)| n == name) {
210 Some(at) => at,
211 None => {
212 features.push((name.clone(), Vec::new()));
213 features.len() - 1
214 }
215 };
216 if !features[at].1.contains(&token) {
217 features[at].1.push(token);
218 }
219 }
220 Ok(Some(
221 features
222 .iter()
223 .map(|(name, tokens)| {
224 if tokens.iter().any(|t| t == "*") {
225 format!("{name}=*")
226 } else {
227 format!("{name}=({})", tokens.join(" "))
228 }
229 })
230 .collect::<Vec<_>>()
231 .join(", "),
232 ))
233}
234
235#[derive(Debug, Clone)]
237pub struct CspNonce(pub String);
238
239impl<S: Send + Sync> FromRequestParts<S> for CspNonce {
240 type Rejection = Infallible;
241
242 async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Infallible> {
243 Ok(parts
244 .extensions
245 .get::<CspNonce>()
246 .cloned()
247 .unwrap_or(CspNonce(String::new())))
248 }
249}
250
251const NONCE: &str = "{nonce}";
252
253#[derive(Debug)]
255pub(crate) struct Security {
256 pub mode: CspMode,
257 policy: Option<String>,
259 permissions: Option<String>,
261 hsts: bool,
262 csrf_exempt: HashSet<(String, String)>,
264 webhook_paths: HashSet<String>,
266 pub xsrf_cookie: bool,
268 trusted_hosts: Vec<String>,
270}
271
272impl Security {
273 pub fn new(
274 config: &Config,
275 csp: &Csp,
276 permissions: &PermissionsPolicy,
277 routes: &[RouteInfo],
278 ) -> anyhow::Result<Self> {
279 let permissions = permissions_header(&config.permissions_policy, permissions)?;
280 let script = match config.csp {
281 CspMode::Strict => format!("'self' 'nonce-{NONCE}'"),
282 _ => "'self' 'unsafe-inline' 'unsafe-eval'".to_owned(),
283 };
284 let mut directives: Vec<(String, String)> = [
285 ("default-src", "'self'".to_owned()),
286 ("script-src", script),
287 ("style-src", "'self' 'unsafe-inline'".to_owned()),
288 ("img-src", "'self' data: blob: https:".to_owned()),
289 ("font-src", "'self' data: https:".to_owned()),
290 ("connect-src", "'self'".to_owned()),
291 ("frame-ancestors", "'self'".to_owned()),
292 ("base-uri", "'self'".to_owned()),
293 ("object-src", "'none'".to_owned()),
294 ]
295 .into_iter()
296 .map(|(name, value)| (name.to_owned(), value))
297 .collect();
298 let mut extra = csp.extra.clone();
299 for (directive, source) in crate::seo::csp_sources(config) {
300 extra
301 .entry(directive.to_owned())
302 .or_default()
303 .push(source.to_owned());
304 }
305 for (name, sources) in &extra {
306 let sources = sources.join(" ");
307 match directives.iter_mut().find(|(n, _)| n == name) {
308 Some((_, value)) => {
309 value.push(' ');
310 value.push_str(&sources);
311 }
312 None => directives.push((name.clone(), format!("'self' {sources}"))),
315 }
316 }
317 let policy = (config.csp != CspMode::Off).then(|| {
318 directives
319 .iter()
320 .map(|(name, value)| format!("{name} {value}"))
321 .collect::<Vec<_>>()
322 .join("; ")
323 });
324 let csrf_exempt = routes
325 .iter()
326 .filter(|route| route.middleware.iter().any(|m| m == "no-csrf"))
327 .flat_map(|route| {
329 route
330 .method
331 .split('|')
332 .map(|method| (method.to_owned(), route.path.clone()))
333 })
334 .collect();
335 let webhook_paths = routes
336 .iter()
337 .filter(|route| route.middleware.iter().any(|m| m.starts_with("webhook:")))
338 .map(|route| route.path.clone())
339 .collect();
340 Ok(Self {
341 webhook_paths,
342 mode: config.csp,
343 policy,
344 permissions,
345 hsts: config.env == Environment::Production && config.url.starts_with("https://"),
346 csrf_exempt,
347 xsrf_cookie: false,
348 trusted_hosts: trusted_hosts(config),
349 })
350 }
351
352 pub fn allows_host(&self, host: Option<&str>) -> bool {
354 if self.trusted_hosts.is_empty() {
355 return true;
356 }
357 let Some(host) = host.map(str::to_ascii_lowercase) else {
358 return false;
359 };
360 self.trusted_hosts
361 .iter()
362 .any(|allowed| match allowed.strip_prefix("*.") {
363 Some(parent) => host
364 .strip_suffix(parent)
365 .is_some_and(|sub| sub.len() > 1 && sub.ends_with('.')),
366 None => *allowed == host,
367 })
368 }
369
370 pub fn is_webhook(&self, path: Option<&MatchedPath>) -> bool {
372 path.is_some_and(|path| self.webhook_paths.contains(path.as_str()))
373 }
374
375 pub fn skips_csrf(&self, method: &Method, path: Option<&MatchedPath>) -> bool {
377 let Some(path) = path else {
378 return false;
379 };
380 let path = path.as_str().to_owned();
381 self.csrf_exempt
382 .contains(&(method.as_str().to_owned(), path.clone()))
383 || self.csrf_exempt.contains(&("*".to_owned(), path))
384 }
385}
386
387#[derive(Debug, Clone, Copy)]
389pub(crate) struct WantsEtag;
390
391const ETAG_LIMIT: u64 = 2 * 1024 * 1024;
393
394async fn etag(
400 res: Response,
401 method: &Method,
402 if_none_match: Option<HeaderValue>,
403 nonce: &str,
404) -> Response {
405 use axum::body::HttpBody as _;
406 use axum::http::StatusCode;
407 let wanted = res.extensions().get::<WantsEtag>().is_some()
408 && matches!(*method, Method::GET | Method::HEAD)
409 && res.status() == StatusCode::OK
410 && !res.headers().contains_key(axum::http::header::ETAG)
411 && res
412 .body()
413 .size_hint()
414 .exact()
415 .is_some_and(|size| size <= ETAG_LIMIT);
416 if !wanted {
417 return res;
418 }
419 let (mut parts, body) = res.into_parts();
420 let Ok(bytes) = axum::body::to_bytes(body, ETAG_LIMIT as usize).await else {
421 return (StatusCode::INTERNAL_SERVER_ERROR, "could not read the page").into_response();
422 };
423 let hash = crate::webhook::sha256_hex(without(&bytes, nonce.as_bytes()));
424 let tag = format!("\"{}\"", &hash[..32]);
425 let matches = if_none_match
426 .as_ref()
427 .and_then(|v| v.to_str().ok())
428 .is_some_and(|v| {
429 v.split(',')
430 .map(|t| t.trim().trim_start_matches("W/"))
431 .any(|t| t == tag || t == "*")
432 });
433 if let Ok(value) = HeaderValue::from_str(&tag) {
434 parts.headers.insert(axum::http::header::ETAG, value);
435 }
436 if matches {
437 parts.status = StatusCode::NOT_MODIFIED;
438 parts.headers.remove(axum::http::header::CONTENT_LENGTH);
439 parts.headers.remove(axum::http::header::CONTENT_TYPE);
440 return Response::from_parts(parts, axum::body::Body::empty());
441 }
442 Response::from_parts(parts, axum::body::Body::from(bytes))
443}
444
445fn without<'a>(bytes: &'a [u8], needle: &[u8]) -> std::borrow::Cow<'a, [u8]> {
448 if needle.is_empty() || !bytes.windows(needle.len()).any(|w| w == needle) {
449 return std::borrow::Cow::Borrowed(bytes);
450 }
451 let mut out = Vec::with_capacity(bytes.len());
452 let mut rest = bytes;
453 while let Some(at) = rest.windows(needle.len()).position(|w| w == needle) {
454 out.extend_from_slice(&rest[..at]);
455 rest = &rest[at + needle.len()..];
456 }
457 out.extend_from_slice(rest);
458 std::borrow::Cow::Owned(out)
459}
460
461fn trusted_hosts(config: &Config) -> Vec<String> {
462 let mut hosts = config.trusted_hosts.clone();
463 if !hosts.is_empty()
464 && let Ok(url) = config.url.parse::<axum::http::Uri>()
465 && let Some(host) = url.host()
466 {
467 hosts.push(host.to_ascii_lowercase());
468 }
469 hosts
470}
471
472pub(crate) async fn middleware(
473 State(state): State<AppState>,
474 mut req: Request,
475 next: Next,
476) -> Response {
477 if req.uri().path() != "/health"
481 && !state
482 .security
483 .allows_host(crate::domain::host(&req).as_deref())
484 {
485 return (
486 axum::http::StatusCode::BAD_REQUEST,
487 "This host is not served here.",
488 )
489 .into_response();
490 }
491 let client = crate::client_ip::resolve(&req, &state.config.trusted_proxies);
492 req.extensions_mut().insert(client);
493 let security = &state.security;
494 let nonce = crate::crypto::random_token();
495 req.extensions_mut().insert(CspNonce(nonce.clone()));
496 let wants_json = crate::error::wants_json(req.headers());
497 let method = req.method().clone();
498 let if_none_match = req
499 .headers()
500 .get(axum::http::header::IF_NONE_MATCH)
501 .cloned();
502 let mut res = next.run(req).await;
503 res = etag(res, &method, if_none_match, &nonce).await;
504 if wants_json && let Some(page) = res.extensions_mut().remove::<crate::error::ErrorPage>() {
506 res = page.json(state.config.debug);
507 }
508
509 let not_modified = res.status() == axum::http::StatusCode::NOT_MODIFIED;
510 let headers = res.headers_mut();
511 let mut set = |name: HeaderName, value: &str| {
512 if !headers.contains_key(&name)
513 && let Ok(value) = HeaderValue::from_str(value)
514 {
515 headers.insert(name, value);
516 }
517 };
518 set(X_CONTENT_TYPE_OPTIONS, "nosniff");
519 set(REFERRER_POLICY, "strict-origin-when-cross-origin");
520 set(X_FRAME_OPTIONS, "SAMEORIGIN");
521 if security.hsts {
522 set(STRICT_TRANSPORT_SECURITY, "max-age=31536000");
523 }
524 if let Some(policy) = &security.permissions {
525 set(HeaderName::from_static("permissions-policy"), policy);
526 }
527 if let Some(policy) = &security.policy
530 && !not_modified
531 {
532 set(CONTENT_SECURITY_POLICY, &policy.replace(NONCE, &nonce));
533 }
534 res
535}
536
537#[cfg(test)]
538mod tests {
539 use std::pin::Pin;
540 use std::task::{Context, Poll};
541
542 use axum::body::{Body, Bytes, HttpBody};
543 use axum::http::StatusCode;
544 use axum::response::IntoResponse;
545
546 use super::*;
547
548 fn header(mode: PermissionsMode, build: impl FnOnce(&mut PermissionsPolicy)) -> String {
549 let mut app = PermissionsPolicy::default();
550 build(&mut app);
551 permissions_header(&mode, &app).unwrap().unwrap()
552 }
553
554 #[test]
555 fn the_default_policy_switches_features_off() {
556 let h = header(PermissionsMode::Default, |_| {});
557 assert!(
558 h.starts_with("accelerometer=(), autoplay=(), bluetooth=()"),
559 "{h}"
560 );
561 assert!(
562 h.contains("camera=()") && h.contains("xr-spatial-tracking=()"),
563 "{h}"
564 );
565 assert!(!h.contains("clipboard") && !h.contains("fullscreen"), "{h}");
566 }
567
568 #[test]
569 fn an_app_allows_features_back() {
570 let h = header(PermissionsMode::Default, |p| {
571 p.allow("geolocation", "self")
572 .allow("payment", "https://pay.example.com")
573 .allow("payment", "self")
574 .allow("camera", "*")
575 .allow("fullscreen", "self");
576 });
577 assert!(h.contains("geolocation=(self)"), "{h}");
578 assert!(
579 h.contains(r#"payment=("https://pay.example.com" self)"#),
580 "{h}"
581 );
582 assert!(h.contains("camera=*"), "{h}");
583 assert!(h.ends_with("fullscreen=(self)"), "{h}");
584 }
585
586 #[test]
587 fn a_custom_value_is_the_base_and_off_is_none() {
588 let mode = PermissionsMode::Custom("geolocation=(self), camera=()".into());
589 assert_eq!(
590 header(mode.clone(), |_| {}),
591 "geolocation=(self), camera=()"
592 );
593 assert_eq!(
594 header(mode, |p| {
595 p.allow("camera", "self");
596 }),
597 "geolocation=(self), camera=(self)"
598 );
599 assert!(
600 permissions_header(&PermissionsMode::Off, &PermissionsPolicy::default())
601 .unwrap()
602 .is_none()
603 );
604 }
605
606 #[test]
607 fn a_bad_feature_or_origin_is_an_error() {
608 for (feature, origin) in [
609 ("Bad Name", "self"),
610 ("camera", "two words"),
611 ("camera", ""),
612 ] {
613 let mut app = PermissionsPolicy::default();
614 app.allow(feature, origin);
615 assert!(
616 permissions_header(&PermissionsMode::Default, &app).is_err(),
617 "{feature} {origin}"
618 );
619 }
620 }
621
622 #[test]
624 fn the_nonce_is_left_out_of_the_hash() {
625 assert_eq!(&*without(b"a-NONCE-b-NONCE", b"NONCE"), b"a--b-");
626 assert_eq!(&*without(b"plain", b"NONCE"), b"plain");
627 assert_eq!(&*without(b"plain", b""), b"plain");
628 }
629
630 struct Broken;
632
633 impl HttpBody for Broken {
634 type Data = Bytes;
635 type Error = std::io::Error;
636
637 fn poll_frame(
638 self: Pin<&mut Self>,
639 _: &mut Context<'_>,
640 ) -> Poll<Option<Result<http_body::Frame<Bytes>, std::io::Error>>> {
641 Poll::Ready(Some(Err(std::io::Error::other("disk went away"))))
642 }
643
644 fn size_hint(&self) -> http_body::SizeHint {
645 http_body::SizeHint::with_exact(10)
646 }
647 }
648
649 #[tokio::test]
650 async fn an_etag_page_that_cant_be_read_is_a_500() {
651 let mut res = (StatusCode::OK, Body::new(Broken)).into_response();
652 res.extensions_mut().insert(WantsEtag);
653 let res = etag(res, &Method::GET, None, "").await;
654 assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
655 }
656}