Skip to main content

next_rust_server/
middleware.rs

1//! Middleware.
2//!
3//! A middleware is any `async fn(Request, Next) -> Response`:
4//!
5//! ```ignore
6//! pub async fn middleware(req: Request, next: Next) -> Response {
7//!     let start = std::time::Instant::now();
8//!     let res = next.run(req).await;
9//!     res.with_header("x-elapsed", &format!("{:?}", start.elapsed()))
10//! }
11//! ```
12//!
13//! Execution order for a request to `/dashboard/settings`:
14//!
15//! 1. global middleware registered with `App::middleware` (in order)
16//! 2. `app/middleware.rs` (runs before routing, so it may rewrite the path)
17//! 3. nested `middleware.rs` files from the outermost to the innermost
18//!    matched segment (e.g. `app/dashboard/middleware.rs`)
19//! 4. the page, API handler or server action
20
21use 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
32/// Middleware trait; implemented for all matching async functions/closures.
33pub 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
47/// Terminal handler at the end of a middleware chain.
48pub 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/// The rest of the chain.
63#[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    /// Run the remaining middleware and the endpoint.
76    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
88/// Wrap a middleware function pointer generated from `middleware.rs`.
89pub 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// ---------------------------------------------------------------------------
98// Built-in middleware
99// ---------------------------------------------------------------------------
100
101/// Request identifier inserted by [`request_id`].
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct RequestId(pub String);
104
105/// Ensure every request has an `x-request-id` (reused from the client when
106/// it is a short, safe token) and echo it on the response.
107pub 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/// CORS configuration.
122#[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    /// Allow any origin (without credentials).
147    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            // Credentials cannot be combined with a wildcard; echo the origin instead.
186            Some(if self.credentials { origin.to_owned() } else { "*".into() })
187        } else {
188            None
189        }
190    }
191}
192
193/// CORS middleware, including preflight handling.
194pub 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
229/// Key extractor for rate limiting.
230pub type KeyFn = Arc<dyn Fn(&Request) -> String + Send + Sync>;
231
232/// Fixed-window-with-token-bucket rate limiter configuration.
233#[derive(Clone)]
234pub struct RateLimit {
235    capacity: u32,
236    refill_every: Duration,
237    key: KeyFn,
238}
239
240impl RateLimit {
241    /// `n` requests per minute per client IP (burst up to `n`).
242    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    /// `capacity` tokens refilled evenly over `period`.
251    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| {
257                req.header("x-forwarded-for")
258                    .filter(|_| crate::trust_proxy())
259                    .and_then(|v| v.split(',').next())
260                    .map(|s| s.trim().to_owned())
261                    .or_else(|| req.remote_addr().map(|a| a.ip().to_string()))
262                    .unwrap_or_else(|| "unknown".into())
263            }),
264        }
265    }
266
267    /// Custom key, e.g. an API key or user id.
268    pub fn key(mut self, f: impl Fn(&Request) -> String + Send + Sync + 'static) -> Self {
269        self.key = Arc::new(f);
270        self
271    }
272}
273
274/// In-memory token bucket rate limiting (per process). Responds 429 with
275/// `Retry-After` when exhausted. For multi-instance deployments, implement
276/// your own middleware backed by a shared store.
277pub fn rate_limit(config: RateLimit) -> impl Middleware {
278    let buckets: Arc<Mutex<HashMap<String, (f64, Instant)>>> = Arc::new(Mutex::new(HashMap::new()));
279    let config = Arc::new(config);
280    move |req: Request, next: Next| {
281        let buckets = buckets.clone();
282        let config = config.clone();
283        async move {
284            let key = (config.key)(&req);
285            let now = Instant::now();
286            let refill = config.refill_every.as_secs_f64().max(f64::EPSILON);
287            let (allowed, retry) = {
288                let mut map = buckets.lock().unwrap_or_else(|e| e.into_inner());
289                if map.len() > 100_000 {
290                    // Drop full buckets to bound memory.
291                    map.retain(|_, (tokens, at)| {
292                        *tokens + now.duration_since(*at).as_secs_f64() / refill < config.capacity as f64
293                    });
294                }
295                let entry = map.entry(key).or_insert((config.capacity as f64, now));
296                let elapsed = now.duration_since(entry.1).as_secs_f64();
297                entry.0 = (entry.0 + elapsed / refill).min(config.capacity as f64);
298                entry.1 = now;
299                if entry.0 >= 1.0 {
300                    entry.0 -= 1.0;
301                    (true, 0.0)
302                } else {
303                    (false, (1.0 - entry.0) * refill)
304                }
305            };
306            if allowed {
307                next.run(req).await
308            } else {
309                Response::text("Too Many Requests")
310                    .with_status(429)
311                    .with_header("retry-after", &(retry.ceil() as u64).max(1).to_string())
312            }
313        }
314    }
315}
316
317/// Protect routes: when `check` returns false the user is redirected to
318/// `login` (with `?next=` set) — or receives 401 for non-GET requests.
319pub fn protected(check: impl Fn(&Request) -> bool + Send + Sync + 'static, login: &str) -> impl Middleware {
320    let check = Arc::new(check);
321    let login = login.to_owned();
322    move |req: Request, next: Next| {
323        let check = check.clone();
324        let login = login.clone();
325        async move {
326            if check(&req) {
327                return next.run(req).await;
328            }
329            if req.method() == http::Method::GET {
330                let target = format!("{login}?next={}", crate::cookies::percent_encode(&req.uri().to_string()));
331                Response::redirect(&target)
332            } else {
333                Response::text("Unauthorized").with_status(401)
334            }
335        }
336    }
337}
338
339/// Double-submit CSRF token protection for unsafe methods.
340///
341/// A random token is kept in the `nr_csrf` cookie (readable by the page via
342/// [`crate::CsrfToken`]); unsafe requests must echo it in the
343/// `x-csrf-token` header or a `_csrf` form field.
344pub fn csrf() -> impl Middleware {
345    |req: Request, next: Next| csrf_check(req, next)
346}
347
348async fn csrf_check(mut req: Request, next: Next) -> Response {
349    let cookie = req.cookies().get(crate::CSRF_COOKIE);
350    let token = cookie.clone().unwrap_or_else(|| crate::random_hex(32));
351    req.insert_extension(crate::CsrfToken(token.clone()));
352    let safe = matches!(*req.method(), http::Method::GET | http::Method::HEAD | http::Method::OPTIONS);
353    if !safe {
354        let mut provided = req.header("x-csrf-token").map(str::to_owned);
355        let is_form = req.header("content-type").is_some_and(|c| c.starts_with("application/x-www-form-urlencoded"));
356        if provided.is_none() && is_form {
357            provided = form_field(&mut req, "_csrf").await;
358        }
359        let valid = match (&cookie, &provided) {
360            (Some(c), Some(p)) => crate::constant_time_eq(c.as_bytes(), p.as_bytes()),
361            _ => false,
362        };
363        if !valid {
364            return Response::text("Invalid CSRF token").with_status(403);
365        }
366    }
367    if cookie.is_none() {
368        // Readable by scripts so JS clients can send the header.
369        req.cookies().set(crate::Cookie::new(crate::CSRF_COOKIE, token).http_only(false));
370    }
371    next.run(req).await
372}
373
374async fn form_field(req: &mut Request, name: &str) -> Option<String> {
375    let bytes = req.bytes().await.ok()?;
376    let fields: Vec<(String, String)> = serde_urlencoded::from_bytes(&bytes).ok()?;
377    fields.into_iter().find(|(k, _)| k == name).map(|(_, v)| v)
378}
379
380/// Apply a conservative set of security headers (enabled by default through
381/// `[security] headers = true`).
382pub(crate) fn apply_security_headers(res: &mut Response, csp: Option<&str>, nonce: &str, hsts_max_age: u64) {
383    let defaults = [
384        ("x-content-type-options", "nosniff"),
385        ("x-frame-options", "SAMEORIGIN"),
386        ("referrer-policy", "strict-origin-when-cross-origin"),
387        ("cross-origin-opener-policy", "same-origin"),
388        ("permissions-policy", "camera=(), microphone=(), geolocation=()"),
389    ];
390    for (k, v) in defaults {
391        if !res.headers.contains_key(k) {
392            res.set_header(k, v);
393        }
394    }
395    if let Some(csp) = csp
396        && !res.headers.contains_key("content-security-policy")
397    {
398        res.set_header("content-security-policy", &csp.replace("{nonce}", nonce));
399    }
400    if hsts_max_age > 0 && !res.headers.contains_key("strict-transport-security") {
401        res.set_header("strict-transport-security", &format!("max-age={hsts_max_age}; includeSubDomains"));
402    }
403}
404
405/// Middleware form of the security headers (for custom setups).
406pub fn security_headers() -> impl Middleware {
407    |req: Request, next: Next| async move {
408        let mut res = next.run(req).await;
409        apply_security_headers(&mut res, None, "", 0);
410        res
411    }
412}