1use std::collections::HashMap;
22use std::future::Future;
23use std::pin::Pin;
24use std::sync::{Arc, Mutex};
25use std::time::{Duration, Instant};
26
27use crate::request::Request;
28use crate::response::Response;
29
30pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
31
32pub trait Middleware: Send + Sync + 'static {
34 fn handle(&self, req: Request, next: Next) -> BoxFuture<Response>;
35}
36
37impl<F, Fut> Middleware for F
38where
39 F: Fn(Request, Next) -> Fut + Send + Sync + 'static,
40 Fut: Future<Output = Response> + Send + 'static,
41{
42 fn handle(&self, req: Request, next: Next) -> BoxFuture<Response> {
43 Box::pin(self(req, next))
44 }
45}
46
47pub trait Endpoint: Send + Sync + 'static {
49 fn call(&self, req: Request) -> BoxFuture<Response>;
50}
51
52impl<F, Fut> Endpoint for F
53where
54 F: Fn(Request) -> Fut + Send + Sync + 'static,
55 Fut: Future<Output = Response> + Send + 'static,
56{
57 fn call(&self, req: Request) -> BoxFuture<Response> {
58 Box::pin(self(req))
59 }
60}
61
62#[derive(Clone)]
64pub struct Next {
65 stack: Arc<[Arc<dyn Middleware>]>,
66 index: usize,
67 endpoint: Arc<dyn Endpoint>,
68}
69
70impl Next {
71 pub fn new(stack: Arc<[Arc<dyn Middleware>]>, endpoint: Arc<dyn Endpoint>) -> Self {
72 Next { stack, index: 0, endpoint }
73 }
74
75 pub async fn run(self, req: Request) -> Response {
77 match self.stack.get(self.index) {
78 Some(mw) => {
79 let mw = mw.clone();
80 let next = Next { stack: self.stack, index: self.index + 1, endpoint: self.endpoint };
81 mw.handle(req, next).await
82 }
83 None => self.endpoint.call(req).await,
84 }
85 }
86}
87
88pub struct FnMiddleware(pub fn(Request, Next) -> BoxFuture<Response>);
90
91impl Middleware for FnMiddleware {
92 fn handle(&self, req: Request, next: Next) -> BoxFuture<Response> {
93 (self.0)(req, next)
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct RequestId(pub String);
104
105pub fn request_id() -> impl Middleware {
108 |mut req: Request, next: Next| async move {
109 let id = req
110 .header("x-request-id")
111 .filter(|v| v.len() <= 128 && v.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
112 .map(str::to_owned)
113 .unwrap_or_else(|| crate::random_hex(16));
114 req.insert_extension(RequestId(id.clone()));
115 let mut res = next.run(req).await;
116 res.set_header("x-request-id", &id);
117 res
118 }
119}
120
121#[derive(Debug, Clone)]
123pub struct Cors {
124 origins: Vec<String>,
125 methods: String,
126 headers: String,
127 expose: Option<String>,
128 credentials: bool,
129 max_age: Option<Duration>,
130}
131
132impl Default for Cors {
133 fn default() -> Self {
134 Cors {
135 origins: Vec::new(),
136 methods: "GET, POST, PUT, PATCH, DELETE, OPTIONS".into(),
137 headers: "content-type, authorization".into(),
138 expose: None,
139 credentials: false,
140 max_age: Some(Duration::from_secs(600)),
141 }
142 }
143}
144
145impl Cors {
146 pub fn permissive() -> Self {
148 Cors { origins: vec!["*".into()], ..Default::default() }
149 }
150
151 pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
152 self.origins.push(origin.into());
153 self
154 }
155
156 pub fn allow_methods(mut self, methods: &[&str]) -> Self {
157 self.methods = methods.join(", ");
158 self
159 }
160
161 pub fn allow_headers(mut self, headers: &[&str]) -> Self {
162 self.headers = headers.join(", ");
163 self
164 }
165
166 pub fn expose_headers(mut self, headers: &[&str]) -> Self {
167 self.expose = Some(headers.join(", "));
168 self
169 }
170
171 pub fn allow_credentials(mut self, v: bool) -> Self {
172 self.credentials = v;
173 self
174 }
175
176 pub fn max_age(mut self, d: Duration) -> Self {
177 self.max_age = Some(d);
178 self
179 }
180
181 fn allowed_origin(&self, origin: &str) -> Option<String> {
182 if self.origins.iter().any(|o| o == origin) {
183 Some(origin.to_owned())
184 } else if self.origins.iter().any(|o| o == "*") {
185 Some(if self.credentials { origin.to_owned() } else { "*".into() })
187 } else {
188 None
189 }
190 }
191}
192
193pub fn cors(config: Cors) -> impl Middleware {
195 let config = Arc::new(config);
196 move |req: Request, next: Next| {
197 let config = config.clone();
198 async move {
199 let origin = req.header("origin").map(str::to_owned);
200 let Some(origin) = origin else { return next.run(req).await };
201 let allowed = config.allowed_origin(&origin);
202 let preflight =
203 req.method() == http::Method::OPTIONS && req.header("access-control-request-method").is_some();
204 let mut res = if preflight { Response::status(204) } else { next.run(req).await };
205 if let Some(allowed) = allowed {
206 res.set_header("access-control-allow-origin", &allowed);
207 if allowed != "*" {
208 res.append_header("vary", "Origin");
209 }
210 if config.credentials {
211 res.set_header("access-control-allow-credentials", "true");
212 }
213 if let Some(e) = &config.expose {
214 res.set_header("access-control-expose-headers", e);
215 }
216 if preflight {
217 res.set_header("access-control-allow-methods", &config.methods);
218 res.set_header("access-control-allow-headers", &config.headers);
219 if let Some(m) = config.max_age {
220 res.set_header("access-control-max-age", &m.as_secs().to_string());
221 }
222 }
223 }
224 res
225 }
226 }
227}
228
229pub type KeyFn = Arc<dyn Fn(&Request) -> String + Send + Sync>;
231
232#[derive(Clone)]
234pub struct RateLimit {
235 capacity: u32,
236 refill_every: Duration,
237 key: KeyFn,
238}
239
240impl RateLimit {
241 pub fn per_minute(n: u32) -> Self {
243 RateLimit::new(n, Duration::from_secs(60))
244 }
245
246 pub fn per_second(n: u32) -> Self {
247 RateLimit::new(n, Duration::from_secs(1))
248 }
249
250 pub fn new(capacity: u32, period: Duration) -> Self {
252 let capacity = capacity.max(1);
253 RateLimit {
254 capacity,
255 refill_every: period / capacity,
256 key: Arc::new(|req: &Request| req.client_ip().map_or_else(|| "unknown".into(), |ip| ip.to_string())),
257 }
258 }
259
260 pub fn key(mut self, f: impl Fn(&Request) -> String + Send + Sync + 'static) -> Self {
262 self.key = Arc::new(f);
263 self
264 }
265}
266
267pub fn rate_limit(config: RateLimit) -> impl Middleware {
271 let buckets: Arc<Mutex<HashMap<String, (f64, Instant)>>> = Arc::new(Mutex::new(HashMap::new()));
272 let config = Arc::new(config);
273 move |req: Request, next: Next| {
274 let buckets = buckets.clone();
275 let config = config.clone();
276 async move {
277 let key = (config.key)(&req);
278 let now = Instant::now();
279 let refill = config.refill_every.as_secs_f64().max(f64::EPSILON);
280 let (allowed, retry) = {
281 let mut map = buckets.lock().unwrap_or_else(|e| e.into_inner());
282 if map.len() > 100_000 {
283 map.retain(|_, (tokens, at)| {
285 *tokens + now.duration_since(*at).as_secs_f64() / refill < config.capacity as f64
286 });
287 }
288 let entry = map.entry(key).or_insert((config.capacity as f64, now));
289 let elapsed = now.duration_since(entry.1).as_secs_f64();
290 entry.0 = (entry.0 + elapsed / refill).min(config.capacity as f64);
291 entry.1 = now;
292 if entry.0 >= 1.0 {
293 entry.0 -= 1.0;
294 (true, 0.0)
295 } else {
296 (false, (1.0 - entry.0) * refill)
297 }
298 };
299 if allowed {
300 next.run(req).await
301 } else {
302 Response::text("Too Many Requests")
303 .with_status(429)
304 .with_header("retry-after", &(retry.ceil() as u64).max(1).to_string())
305 }
306 }
307 }
308}
309
310pub fn protected(check: impl Fn(&Request) -> bool + Send + Sync + 'static, login: &str) -> impl Middleware {
313 let check = Arc::new(check);
314 let login = login.to_owned();
315 move |req: Request, next: Next| {
316 let check = check.clone();
317 let login = login.clone();
318 async move {
319 if check(&req) {
320 return next.run(req).await;
321 }
322 if req.method() == http::Method::GET {
323 let target = format!("{login}?next={}", crate::cookies::percent_encode(&req.uri().to_string()));
324 Response::redirect(&target)
325 } else {
326 Response::text("Unauthorized").with_status(401)
327 }
328 }
329 }
330}
331
332pub fn csrf() -> impl Middleware {
338 |req: Request, next: Next| csrf_check(req, next)
339}
340
341async fn csrf_check(mut req: Request, next: Next) -> Response {
342 let cookie = req.cookies().get(crate::CSRF_COOKIE);
343 let token = cookie.clone().unwrap_or_else(|| crate::random_hex(32));
344 req.insert_extension(crate::CsrfToken(token.clone()));
345 let safe = matches!(*req.method(), http::Method::GET | http::Method::HEAD | http::Method::OPTIONS);
346 if !safe {
347 let mut provided = req.header("x-csrf-token").map(str::to_owned);
348 let is_form = req.header("content-type").is_some_and(|c| c.starts_with("application/x-www-form-urlencoded"));
349 if provided.is_none() && is_form {
350 provided = form_field(&mut req, "_csrf").await;
351 }
352 let valid = match (&cookie, &provided) {
353 (Some(c), Some(p)) => crate::constant_time_eq(c.as_bytes(), p.as_bytes()),
354 _ => false,
355 };
356 if !valid {
357 return Response::text("Invalid CSRF token").with_status(403);
358 }
359 }
360 if cookie.is_none() {
361 req.cookies().set(crate::Cookie::new(crate::CSRF_COOKIE, token).http_only(false));
363 }
364 next.run(req).await
365}
366
367pub(crate) async fn form_field(req: &mut Request, name: &str) -> Option<String> {
368 let bytes = req.bytes().await.ok()?;
369 let fields: Vec<(String, String)> = serde_urlencoded::from_bytes(&bytes).ok()?;
370 fields.into_iter().find(|(k, _)| k == name).map(|(_, v)| v)
371}
372
373pub const STRICT_CSP: &str = "default-src 'self'; \
379script-src 'self' 'nonce-{nonce}' 'strict-dynamic'; \
380style-src 'self' 'unsafe-inline'; \
381img-src 'self' data: blob:; \
382font-src 'self' data:; \
383connect-src 'self'; \
384media-src 'self' blob:; \
385worker-src 'self' blob:; \
386object-src 'none'; \
387base-uri 'self'; \
388form-action 'self'; \
389frame-ancestors 'self'";
390
391pub(crate) fn apply_security_headers(res: &mut Response, csp: Option<&str>, nonce: &str, hsts_max_age: u64) {
394 let csp = csp.map(|c| if c.trim() == "strict" { STRICT_CSP } else { c });
395 let defaults = [
396 ("x-content-type-options", "nosniff"),
397 ("x-frame-options", "SAMEORIGIN"),
398 ("referrer-policy", "strict-origin-when-cross-origin"),
399 ("cross-origin-opener-policy", "same-origin"),
400 ("permissions-policy", "camera=(), microphone=(), geolocation=()"),
401 ];
402 for (k, v) in defaults {
403 if !res.headers.contains_key(k) {
404 res.set_header(k, v);
405 }
406 }
407 if let Some(csp) = csp
408 && !res.headers.contains_key("content-security-policy")
409 {
410 res.set_header("content-security-policy", &csp.replace("{nonce}", nonce));
411 }
412 if hsts_max_age > 0 && !res.headers.contains_key("strict-transport-security") {
413 res.set_header("strict-transport-security", &format!("max-age={hsts_max_age}; includeSubDomains"));
414 }
415}
416
417pub fn security_headers() -> impl Middleware {
419 |req: Request, next: Next| async move {
420 let mut res = next.run(req).await;
421 apply_security_headers(&mut res, None, "", 0);
422 res
423 }
424}