Skip to main content

glacier/
middleware.rs

1//! Middleware: code that wraps every request.
2//!
3//! Middleware runs in registration order around the router, so it also sees
4//! requests that end up as 404s or 405s.
5
6use std::future::Future;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::Instant;
10
11use http::{Method, StatusCode};
12
13pub use crate::authorization::VerifyAuthorized;
14pub use crate::basic_auth::BasicAuth;
15pub use crate::cors::Cors;
16
17use crate::context::Context;
18use crate::handler::{BoxFuture, Handler};
19use crate::response::Response;
20
21pub trait Middleware: Send + Sync + 'static {
22    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response>;
23}
24
25/// The rest of the middleware stack, ending in the router.
26#[derive(Clone)]
27pub struct Next {
28    stack: Arc<[Arc<dyn Middleware>]>,
29    endpoint: Arc<dyn Handler>,
30    index: usize,
31}
32
33impl Next {
34    pub(crate) fn new(stack: Arc<[Arc<dyn Middleware>]>, endpoint: Arc<dyn Handler>) -> Self {
35        Self {
36            stack,
37            endpoint,
38            index: 0,
39        }
40    }
41
42    pub async fn run(mut self, ctx: Context) -> Response {
43        match self.stack.get(self.index).cloned() {
44            Some(middleware) => {
45                self.index += 1;
46                middleware.handle(ctx, self).await
47            }
48            None => self.endpoint.call(ctx).await,
49        }
50    }
51}
52
53/// Builds middleware from an async closure.
54///
55/// ```
56/// use glacier::middleware::from_fn;
57///
58/// let powered_by = from_fn(|ctx, next| async move {
59///     next.run(ctx).await.with_header("x-powered-by", "Glacier")
60/// });
61/// ```
62pub fn from_fn<F, Fut>(f: F) -> FromFn<F>
63where
64    F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
65    Fut: Future<Output = Response> + Send + 'static,
66{
67    FromFn(f)
68}
69
70pub struct FromFn<F>(F);
71
72impl<F, Fut> Middleware for FromFn<F>
73where
74    F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
75    Fut: Future<Output = Response> + Send + 'static,
76{
77    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
78        Box::pin((self.0)(ctx, next))
79    }
80}
81
82/// Logs one line per request: method, path, status and duration.
83pub struct Logger;
84
85impl Middleware for Logger {
86    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
87        Box::pin(async move {
88            let method = ctx.method().clone();
89            let path = ctx.path().to_owned();
90            let start = Instant::now();
91            let res = next.run(ctx).await;
92            let status = res.status().as_u16();
93            let elapsed = start.elapsed();
94            match LogFormat::current() {
95                // Fields a log shipper can index.
96                LogFormat::Json => tracing::info!(
97                    target: "glacier",
98                    method = %method,
99                    path,
100                    status,
101                    request_id = crate::request::id().unwrap_or_default(),
102                    duration_ms = elapsed.as_micros() as f64 / 1000.0,
103                    "request"
104                ),
105                LogFormat::Text => tracing::info!(
106                    target: "glacier",
107                    "{method} {path} -> {status} in {elapsed:.1?}"
108                ),
109            }
110            res
111        })
112    }
113}
114
115/// How the app's logs are written; chosen when it starts serving.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum LogFormat {
118    /// `GET /posts -> 200 in 1.2ms`, for people.
119    Text,
120    /// One JSON object per line, for log shippers.
121    Json,
122}
123
124static JSON_LOGS: AtomicBool = AtomicBool::new(false);
125
126impl LogFormat {
127    /// `GLACIER_LOG_FORMAT` (`json` or `text`) if set to one of them,
128    /// otherwise JSON in production and text elsewhere.
129    pub fn choose(env: crate::Env, requested: Option<&str>) -> Self {
130        match requested {
131            Some("json") => LogFormat::Json,
132            Some("text") => LogFormat::Text,
133            _ if env.is_production() => LogFormat::Json,
134            _ => LogFormat::Text,
135        }
136    }
137
138    pub(crate) fn set(format: Self) {
139        JSON_LOGS.store(format == LogFormat::Json, Ordering::Relaxed);
140    }
141
142    fn current() -> Self {
143        if JSON_LOGS.load(Ordering::Relaxed) {
144            LogFormat::Json
145        } else {
146            LogFormat::Text
147        }
148    }
149}
150
151/// A named stack of middleware applied to a group of routes with
152/// `Router::pipe_through`, like Phoenix pipelines.
153///
154/// ```
155/// use glacier::middleware::{Pipeline, SecureHeaders};
156/// use glacier::csrf::Csrf;
157///
158/// let browser = Pipeline::new().with(SecureHeaders).with(Csrf);
159/// ```
160#[derive(Clone, Default)]
161pub struct Pipeline {
162    pub(crate) stack: Vec<Arc<dyn Middleware>>,
163}
164
165impl Pipeline {
166    pub fn new() -> Self {
167        Self::default()
168    }
169
170    pub fn with(mut self, middleware: impl Middleware) -> Self {
171        self.stack.push(Arc::new(middleware));
172        self
173    }
174
175    /// The usual stack for HTML pages: security headers and CSRF checks.
176    pub fn browser() -> Self {
177        Self::new()
178            .with(ETag)
179            .with(SecureHeaders)
180            .with(crate::csrf::Csrf)
181    }
182
183    /// The usual stack for JSON APIs: errors as JSON, no CSRF (API clients
184    /// send tokens, not cookies).
185    pub fn api() -> Self {
186        Self::new().with(ETag).with(JsonErrors)
187    }
188}
189
190/// ETags and conditional GETs, as Rails' default `Rack::ETag` and
191/// `Rack::ConditionalGet`: a `200` or `201` with a body gets a weak `ETag`
192/// from it (and `Cache-Control: max-age=0, private, must-revalidate`
193/// unless it has one), and a GET or HEAD that sends that tag back in
194/// `If-None-Match` gets `304 Not Modified` with no body. Other responses
195/// get `Cache-Control: no-cache` unless they say otherwise. A response
196/// with its own `ETag` or `Last-Modified` (from `fresh_when`), or marked
197/// `no-cache` or `no-store`, keeps its own. In both default pipelines.
198pub struct ETag;
199
200impl Middleware for ETag {
201    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
202        let conditional = matches!(*ctx.method(), Method::GET | Method::HEAD);
203        let if_none_match = ctx.header(http::header::IF_NONE_MATCH).map(str::to_owned);
204        Box::pin(async move {
205            let mut res = next.run(ctx).await;
206            let cache_control = res
207                .header(http::header::CACHE_CONTROL)
208                .unwrap_or("")
209                .to_owned();
210            // As Rack::ETag: a 200 or 201 with a body gets a tag, whatever
211            // the method; only GET and HEAD can answer 304.
212            let tagged = matches!(res.status().as_u16(), 200 | 201)
213                && !res.headers().contains_key(http::header::ETAG)
214                && !res.headers().contains_key(http::header::LAST_MODIFIED)
215                && !cache_control.contains("no-cache")
216                && !cache_control.contains("no-store")
217                && !res.body().is_empty();
218            if !tagged {
219                if cache_control.is_empty() {
220                    // Tagged already (`fresh_when`): revalidate, as Rails'
221                    // own validators do; anything else isn't to be cached.
222                    let validated = res.headers().contains_key(http::header::ETAG)
223                        || res.headers().contains_key(http::header::LAST_MODIFIED);
224                    let value = if validated {
225                        "max-age=0, private, must-revalidate"
226                    } else {
227                        "no-cache"
228                    };
229                    res.headers_mut().insert(
230                        http::header::CACHE_CONTROL,
231                        http::HeaderValue::from_static(value),
232                    );
233                }
234                return res;
235            }
236            // A weak tag only has to change when the body does: SipHash and
237            // the length, about ten times cheaper than SHA-256 here.
238            let mut hasher = std::hash::DefaultHasher::new();
239            std::hash::Hasher::write(&mut hasher, res.body());
240            let tag = format!(
241                "W/\"{:x}-{:016x}\"",
242                res.body().len(),
243                std::hash::Hasher::finish(&hasher)
244            );
245            if cache_control.is_empty() {
246                res.headers_mut().insert(
247                    http::header::CACHE_CONTROL,
248                    http::HeaderValue::from_static("max-age=0, private, must-revalidate"),
249                );
250            }
251            let matches = conditional
252                && if_none_match.is_some_and(|sent| {
253                    sent.split(',').any(|candidate| {
254                        let candidate = candidate.trim();
255                        candidate == "*"
256                            || candidate.trim_start_matches("W/") == tag.trim_start_matches("W/")
257                    })
258                });
259            if matches {
260                let mut not_modified = Response::new(StatusCode::NOT_MODIFIED);
261                for (name, value) in res.headers() {
262                    if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
263                        not_modified
264                            .headers_mut()
265                            .insert(name.clone(), value.clone());
266                    }
267                }
268                res = not_modified;
269            }
270            if let Ok(value) = http::HeaderValue::from_str(&tag) {
271                res.headers_mut().insert(http::header::ETAG, value);
272            }
273            res
274        })
275    }
276}
277
278/// Headers every response gets unless it sets its own, as Rails'
279/// `config.action_dispatch.default_headers`:
280/// `DefaultHeaders::new().header("X-Frame-Options", "ALLOWALL")`.
281#[derive(Clone, Default)]
282pub struct DefaultHeaders(Vec<(http::HeaderName, http::HeaderValue)>);
283
284impl DefaultHeaders {
285    pub fn new() -> Self {
286        Self::default()
287    }
288
289    /// # Panics
290    ///
291    /// If the name or value isn't valid in a header.
292    #[must_use]
293    pub fn header(mut self, name: &str, value: &str) -> Self {
294        self.0.push((
295            http::HeaderName::try_from(name).expect("invalid header name"),
296            http::HeaderValue::try_from(value).expect("invalid header value"),
297        ));
298        self
299    }
300}
301
302impl Middleware for DefaultHeaders {
303    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
304        let headers = self.0.clone();
305        Box::pin(async move {
306            let mut res = next.run(ctx).await;
307            for (name, value) in headers {
308                if !res.headers().contains_key(&name) {
309                    res.headers_mut().insert(name, value);
310                }
311            }
312            res
313        })
314    }
315}
316
317/// Error responses as JSON, as Rails' API mode renders them:
318/// `{"status": 404, "error": "Not Found"}`. A response the action already
319/// made JSON (validation errors, say) passes through untouched.
320pub struct JsonErrors;
321
322impl JsonErrors {
323    /// Error responses with the app's own JSON body, as a Rails app's
324    /// `rescue_from` shapes them:
325    /// `JsonErrors::body(|status| json!({"error": t(format!("errors.{}", status_name(status)))}))`.
326    pub fn body(body: fn(http::StatusCode) -> serde_json::Value) -> JsonErrorsWith {
327        JsonErrorsWith(body)
328    }
329}
330
331fn default_error_body(status: http::StatusCode) -> serde_json::Value {
332    serde_json::json!({
333        "status": status.as_u16(),
334        "error": status.canonical_reason().unwrap_or("Error"),
335    })
336}
337
338impl Middleware for JsonErrors {
339    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
340        JsonErrorsWith(default_error_body).handle(ctx, next)
341    }
342}
343
344/// [`JsonErrors`] with a body of the app's choosing, from
345/// [`JsonErrors::body`].
346pub struct JsonErrorsWith(fn(http::StatusCode) -> serde_json::Value);
347
348impl Middleware for JsonErrorsWith {
349    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
350        let make_body = self.0;
351        Box::pin(async move {
352            let res = next.run(ctx).await;
353            let status = res.status();
354            let is_json = res
355                .header(http::header::CONTENT_TYPE)
356                .is_some_and(|ct| ct.starts_with("application/json"));
357            if !(status.is_client_error() || status.is_server_error()) || is_json || res.is_head() {
358                return res;
359            }
360            let body = make_body(status);
361            let mut json = Response::json(&body).with_status(status);
362            // Keep headers such as `Allow` on a 405, and the error report.
363            for (name, value) in res.headers() {
364                if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
365                    json.headers_mut().insert(name.clone(), value.clone());
366                }
367            }
368            if let Some(report) = res.extensions().get::<crate::error::ErrorReport>() {
369                json.extensions_mut().insert(report.clone());
370            }
371            json
372        })
373    }
374}
375
376/// Lets HTML forms send PATCH, PUT and DELETE through a `_method` field on a
377/// POST, as Rails does. Register it on the app (not in a pipeline) so it runs
378/// before routing.
379pub struct MethodOverride;
380
381impl Middleware for MethodOverride {
382    fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
383        if *ctx.method() == Method::POST {
384            let method =
385                ctx.form_field("_method")
386                    .and_then(|m| match m.to_ascii_uppercase().as_str() {
387                        "PATCH" => Some(Method::PATCH),
388                        "PUT" => Some(Method::PUT),
389                        "DELETE" => Some(Method::DELETE),
390                        _ => None,
391                    });
392            if let Some(method) = method {
393                ctx.set_method(method);
394            }
395        }
396        Box::pin(next.run(ctx))
397    }
398}
399
400/// A path that starts with an id, `/42/projects/7`, as Basecamp's URLs do
401/// for an account: the id comes off before the route is matched (it's
402/// `ctx.path_prefix()`), and every path the app builds during the request
403/// starts with it again. An app's own middleware decides what the id means
404/// (`InOrg`: the org). Paths without one pass through as they are.
405pub struct IdPrefix;
406
407impl Middleware for IdPrefix {
408    fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
409        let path = ctx.path().to_owned();
410        let mut segments = path.splitn(3, '/');
411        let (Some(""), Some(id)) = (segments.next(), segments.next()) else {
412            return Box::pin(next.run(ctx));
413        };
414        if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
415            return Box::pin(next.run(ctx));
416        }
417        let id = id.to_owned();
418        let rest = format!("/{}", segments.next().unwrap_or(""));
419        ctx.set_path(&rest);
420        ctx.set_path_prefix(id.clone());
421        Box::pin(crate::router::with_path_prefix(
422            format!("/{id}"),
423            next.run(ctx),
424        ))
425    }
426}
427
428/// Conservative security headers for browser responses. Headers already set
429/// by the handler are left alone.
430pub struct SecureHeaders;
431
432impl Middleware for SecureHeaders {
433    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
434        Box::pin(async move {
435            let mut res = next.run(ctx).await;
436            let headers = res.headers_mut();
437            for (name, value) in [
438                ("x-frame-options", "SAMEORIGIN"),
439                ("x-content-type-options", "nosniff"),
440                ("referrer-policy", "strict-origin-when-cross-origin"),
441                ("cross-origin-opener-policy", "same-origin"),
442            ] {
443                if !headers.contains_key(name) {
444                    headers.insert(name, http::HeaderValue::from_static(value));
445                }
446            }
447            res
448        })
449    }
450}
451
452/// Limits how often something happens, as Rack::Attack's `throttle` (and
453/// Rails 8's `rate_limit`): `limit` requests per `period` for each key
454/// `key` picks out (an email address, a client IP), counted in fixed
455/// windows. Requests it picks no key for aren't counted. Over the limit,
456/// the answer is `429 Too Many Requests`, "Retry later", with
457/// `Retry-After` saying when the window ends.
458///
459/// ```ignore
460/// App::new().middleware(Throttle::new("logins/email", 5, Duration::from_secs(60), |ctx| {
461///     let email = ctx.params().require("user").ok()?.get("email")?.to_lowercase();
462///     ctx.path().contains("/users/sign_in").then_some(email)
463/// }))
464/// ```
465///
466/// Counts are kept by [`RateLimit`](crate::rate_limit::RateLimit) in the
467/// cache: per process with the memory store, shared by every server with
468/// `[cache] store = "database"`. If the cache can't be reached, requests
469/// are let through (and the error logged).
470pub struct Throttle {
471    name: &'static str,
472    limit: u32,
473    period: std::time::Duration,
474    key: fn(&Context) -> Option<String>,
475}
476
477impl Throttle {
478    /// # Panics
479    ///
480    /// If `period` is shorter than a second.
481    pub fn new(
482        name: &'static str,
483        limit: u32,
484        period: std::time::Duration,
485        key: fn(&Context) -> Option<String>,
486    ) -> Self {
487        assert!(
488            period.as_secs() > 0,
489            "a throttle's period is at least a second"
490        );
491        Self {
492            name,
493            limit,
494            period,
495            key,
496        }
497    }
498}
499
500impl Middleware for Throttle {
501    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
502        let Some(key) = (self.key)(&ctx) else {
503            return Box::pin(next.run(ctx));
504        };
505        let (name, limit, period) = (self.name, self.limit, self.period);
506        Box::pin(async move {
507            let key = format!("throttle:{name}:{key}");
508            use crate::rate_limit::RateLimit;
509            match RateLimit::attempt(&key, limit, period).await {
510                Ok(true) => {}
511                Ok(false) => {
512                    tracing::info!(throttle = name, "request throttled");
513                    let wait = RateLimit::available_in(&key, period).num_seconds().max(1);
514                    return Response::text("Retry later\n")
515                        .with_status(http::StatusCode::TOO_MANY_REQUESTS)
516                        .with_header(http::header::RETRY_AFTER, wait.to_string());
517                }
518                Err(error) => {
519                    tracing::error!(throttle = name, %error, "throttle couldn't count; letting the request through");
520                }
521            }
522            next.run(ctx).await
523        })
524    }
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530    use crate::Env;
531
532    #[test]
533    fn json_logs_in_production_unless_asked_otherwise() {
534        assert_eq!(LogFormat::choose(Env::Production, None), LogFormat::Json);
535        assert_eq!(LogFormat::choose(Env::Development, None), LogFormat::Text);
536        assert_eq!(
537            LogFormat::choose(Env::Development, Some("json")),
538            LogFormat::Json
539        );
540        assert_eq!(
541            LogFormat::choose(Env::Production, Some("text")),
542            LogFormat::Text
543        );
544        assert_eq!(
545            LogFormat::choose(Env::Production, Some("xml")),
546            LogFormat::Json
547        );
548    }
549}