| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | use topcoat::{ |
| 24 | Result, |
| 25 | context::CxBuilder, |
| 26 | router::{ |
| 27 | Body, HeaderValue, IntoResponse, Next, Response, |
| 28 | header::{ |
| 29 | CACHE_CONTROL, CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, |
| 30 | X_FRAME_OPTIONS, |
| 31 | }, |
| 32 | headers, layer, uri, |
| 33 | }, |
| 34 | }; |
| 35 | |
| 36 | use crate::infrastructure::{metrics::metrics, web::body_limit}; |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | const POLICY: &str = "default-src 'none'; \ |
| 51 | style-src 'self' 'unsafe-inline'; \ |
| 52 | img-src 'self' data:; \ |
| 53 | font-src 'self'; \ |
| 54 | form-action 'self'; \ |
| 55 | frame-ancestors 'none'; \ |
| 56 | base-uri 'none'"; |
| 57 | |
| 58 | #[layer("/")] |
| 59 | async fn security_headers(cx: &mut CxBuilder, body: Body, next: Next<'_>) -> Result<Response> { |
| 60 | |
| 61 | |
| 62 | let path = uri(cx).path().to_owned(); |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | let body = match body_limit::capped(&path, headers(cx), body) { |
| 70 | Ok(body) => body, |
| 71 | Err(refused) => { |
| 72 | metrics().record_request(&path, refused.status().as_u16()); |
| 73 | return Ok(*refused); |
| 74 | } |
| 75 | }; |
| 76 | |
| 77 | let mut response = match next.run(cx, body).await { |
| 78 | Ok(response) => response, |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | Err(error) => error.into_response(cx)?, |
| 89 | }; |
| 90 | |
| 91 | metrics().record_request(&path, response.status().as_u16()); |
| 92 | |
| 93 | let headers = response.headers_mut(); |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | headers |
| 99 | .entry(CONTENT_SECURITY_POLICY) |
| 100 | .or_insert(HeaderValue::from_static(POLICY)); |
| 101 | |
| 102 | headers |
| 103 | .entry(X_CONTENT_TYPE_OPTIONS) |
| 104 | .or_insert(HeaderValue::from_static("nosniff")); |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | headers |
| 111 | .entry(REFERRER_POLICY) |
| 112 | .or_insert(HeaderValue::from_static("no-referrer")); |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | headers |
| 118 | .entry(X_FRAME_OPTIONS) |
| 119 | .or_insert(HeaderValue::from_static("DENY")); |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | headers |
| 134 | .entry(CACHE_CONTROL) |
| 135 | .or_insert(HeaderValue::from_static("private, no-cache")); |
| 136 | |
| 137 | Ok(response) |
| 138 | } |