glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Middleware: code that wraps every request.
//!
//! Middleware runs in registration order around the router, so it also sees
//! requests that end up as 404s or 405s.

use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

use http::Method;

pub use crate::authorization::VerifyAuthorized;
pub use crate::cors::Cors;

use crate::context::Context;
use crate::handler::{BoxFuture, Handler};
use crate::response::Response;

pub trait Middleware: Send + Sync + 'static {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response>;
}

/// The rest of the middleware stack, ending in the router.
#[derive(Clone)]
pub struct Next {
    stack: Arc<[Arc<dyn Middleware>]>,
    endpoint: Arc<dyn Handler>,
    index: usize,
}

impl Next {
    pub(crate) fn new(stack: Arc<[Arc<dyn Middleware>]>, endpoint: Arc<dyn Handler>) -> Self {
        Self {
            stack,
            endpoint,
            index: 0,
        }
    }

    pub async fn run(mut self, ctx: Context) -> Response {
        match self.stack.get(self.index).cloned() {
            Some(middleware) => {
                self.index += 1;
                middleware.handle(ctx, self).await
            }
            None => self.endpoint.call(ctx).await,
        }
    }
}

/// Builds middleware from an async closure.
///
/// ```
/// use glacier::middleware::from_fn;
///
/// let powered_by = from_fn(|ctx, next| async move {
///     next.run(ctx).await.with_header("x-powered-by", "Glacier")
/// });
/// ```
pub fn from_fn<F, Fut>(f: F) -> FromFn<F>
where
    F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Response> + Send + 'static,
{
    FromFn(f)
}

pub struct FromFn<F>(F);

impl<F, Fut> Middleware for FromFn<F>
where
    F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Response> + Send + 'static,
{
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin((self.0)(ctx, next))
    }
}

/// Logs one line per request: method, path, status and duration.
pub struct Logger;

impl Middleware for Logger {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            let method = ctx.method().clone();
            let path = ctx.path().to_owned();
            let start = Instant::now();
            let res = next.run(ctx).await;
            let status = res.status().as_u16();
            let elapsed = start.elapsed();
            match LogFormat::current() {
                // Fields a log shipper can index.
                LogFormat::Json => tracing::info!(
                    target: "glacier",
                    method = %method,
                    path,
                    status,
                    duration_ms = elapsed.as_micros() as f64 / 1000.0,
                    "request"
                ),
                LogFormat::Text => tracing::info!(
                    target: "glacier",
                    "{method} {path} -> {status} in {elapsed:.1?}"
                ),
            }
            res
        })
    }
}

/// How the app's logs are written; chosen when it starts serving.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogFormat {
    /// `GET /posts -> 200 in 1.2ms`, for people.
    Text,
    /// One JSON object per line, for log shippers.
    Json,
}

static JSON_LOGS: AtomicBool = AtomicBool::new(false);

impl LogFormat {
    /// `GLACIER_LOG_FORMAT` (`json` or `text`) if set to one of them,
    /// otherwise JSON in production and text elsewhere.
    pub fn choose(env: crate::Env, requested: Option<&str>) -> Self {
        match requested {
            Some("json") => LogFormat::Json,
            Some("text") => LogFormat::Text,
            _ if env.is_production() => LogFormat::Json,
            _ => LogFormat::Text,
        }
    }

    pub(crate) fn set(format: Self) {
        JSON_LOGS.store(format == LogFormat::Json, Ordering::Relaxed);
    }

    fn current() -> Self {
        if JSON_LOGS.load(Ordering::Relaxed) {
            LogFormat::Json
        } else {
            LogFormat::Text
        }
    }
}

/// A named stack of middleware applied to a group of routes with
/// `Router::pipe_through`, like Phoenix pipelines.
///
/// ```
/// use glacier::middleware::{Pipeline, SecureHeaders};
/// use glacier::csrf::Csrf;
///
/// let browser = Pipeline::new().with(SecureHeaders).with(Csrf);
/// ```
#[derive(Clone, Default)]
pub struct Pipeline {
    pub(crate) stack: Vec<Arc<dyn Middleware>>,
}

impl Pipeline {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with(mut self, middleware: impl Middleware) -> Self {
        self.stack.push(Arc::new(middleware));
        self
    }

    /// The usual stack for HTML pages: security headers and CSRF checks.
    pub fn browser() -> Self {
        Self::new().with(SecureHeaders).with(crate::csrf::Csrf)
    }

    /// The usual stack for JSON APIs: errors as JSON, no CSRF (API clients
    /// send tokens, not cookies).
    pub fn api() -> Self {
        Self::new().with(JsonErrors)
    }
}

/// Error responses as JSON, as Rails' API mode renders them:
/// `{"status": 404, "error": "Not Found"}`. A response the action already
/// made JSON (validation errors, say) passes through untouched.
pub struct JsonErrors;

impl JsonErrors {
    /// Error responses with the app's own JSON body, as a Rails app's
    /// `rescue_from` shapes them:
    /// `JsonErrors::body(|status| json!({"error": t(format!("errors.{}", status_name(status)))}))`.
    pub fn body(body: fn(http::StatusCode) -> serde_json::Value) -> JsonErrorsWith {
        JsonErrorsWith(body)
    }
}

fn default_error_body(status: http::StatusCode) -> serde_json::Value {
    serde_json::json!({
        "status": status.as_u16(),
        "error": status.canonical_reason().unwrap_or("Error"),
    })
}

impl Middleware for JsonErrors {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        JsonErrorsWith(default_error_body).handle(ctx, next)
    }
}

/// [`JsonErrors`] with a body of the app's choosing, from
/// [`JsonErrors::body`].
pub struct JsonErrorsWith(fn(http::StatusCode) -> serde_json::Value);

impl Middleware for JsonErrorsWith {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let make_body = self.0;
        Box::pin(async move {
            let res = next.run(ctx).await;
            let status = res.status();
            let is_json = res
                .header(http::header::CONTENT_TYPE)
                .is_some_and(|ct| ct.starts_with("application/json"));
            if !(status.is_client_error() || status.is_server_error()) || is_json || res.is_head() {
                return res;
            }
            let body = make_body(status);
            let mut json = Response::json(&body).with_status(status);
            // Keep headers such as `Allow` on a 405, and the error report.
            for (name, value) in res.headers() {
                if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
                    json.headers_mut().insert(name.clone(), value.clone());
                }
            }
            if let Some(report) = res.extensions().get::<crate::error::ErrorReport>() {
                json.extensions_mut().insert(report.clone());
            }
            json
        })
    }
}

/// Lets HTML forms send PATCH, PUT and DELETE through a `_method` field on a
/// POST, as Rails does. Register it on the app (not in a pipeline) so it runs
/// before routing.
pub struct MethodOverride;

impl Middleware for MethodOverride {
    fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
        if *ctx.method() == Method::POST {
            let method =
                ctx.form_field("_method")
                    .and_then(|m| match m.to_ascii_uppercase().as_str() {
                        "PATCH" => Some(Method::PATCH),
                        "PUT" => Some(Method::PUT),
                        "DELETE" => Some(Method::DELETE),
                        _ => None,
                    });
            if let Some(method) = method {
                ctx.set_method(method);
            }
        }
        Box::pin(next.run(ctx))
    }
}

/// Conservative security headers for browser responses. Headers already set
/// by the handler are left alone.
pub struct SecureHeaders;

impl Middleware for SecureHeaders {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        Box::pin(async move {
            let mut res = next.run(ctx).await;
            let headers = res.headers_mut();
            for (name, value) in [
                ("x-frame-options", "SAMEORIGIN"),
                ("x-content-type-options", "nosniff"),
                ("referrer-policy", "strict-origin-when-cross-origin"),
                ("cross-origin-opener-policy", "same-origin"),
            ] {
                if !headers.contains_key(name) {
                    headers.insert(name, http::HeaderValue::from_static(value));
                }
            }
            res
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Env;

    #[test]
    fn json_logs_in_production_unless_asked_otherwise() {
        assert_eq!(LogFormat::choose(Env::Production, None), LogFormat::Json);
        assert_eq!(LogFormat::choose(Env::Development, None), LogFormat::Text);
        assert_eq!(
            LogFormat::choose(Env::Development, Some("json")),
            LogFormat::Json
        );
        assert_eq!(
            LogFormat::choose(Env::Production, Some("text")),
            LogFormat::Text
        );
        assert_eq!(
            LogFormat::choose(Env::Production, Some("xml")),
            LogFormat::Json
        );
    }
}

/// Limits how often something happens, as Rack::Attack's `throttle` (and
/// Rails 8's `rate_limit`): `limit` requests per `period` for each key
/// `key` picks out (an email address, a client IP), counted in fixed
/// windows. Requests it picks no key for aren't counted. Over the limit,
/// the answer is `429 Too Many Requests`, "Retry later".
///
/// ```ignore
/// App::new().middleware(Throttle::new("logins/email", 5, Duration::from_secs(60), |ctx| {
///     let email = ctx.params().require("user").ok()?.get("email")?.to_lowercase();
///     ctx.path().contains("/users/sign_in").then_some(email)
/// }))
/// ```
///
/// Counts are kept in memory, per process.
pub struct Throttle {
    name: &'static str,
    limit: u32,
    period: std::time::Duration,
    key: fn(&Context) -> Option<String>,
    counts: std::sync::Mutex<std::collections::HashMap<String, (u64, u32)>>,
}

impl Throttle {
    /// # Panics
    ///
    /// If `period` is shorter than a second.
    pub fn new(
        name: &'static str,
        limit: u32,
        period: std::time::Duration,
        key: fn(&Context) -> Option<String>,
    ) -> Self {
        assert!(
            period.as_secs() > 0,
            "a throttle's period is at least a second"
        );
        Self {
            name,
            limit,
            period,
            key,
            counts: std::sync::Mutex::default(),
        }
    }

    /// Counts a request for `key`; whether it's within the limit.
    fn allow(&self, key: &str, now_secs: u64) -> bool {
        let window = now_secs / self.period.as_secs();
        let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
        // Forget finished windows now and then.
        if counts.len() > 10_000 {
            counts.retain(|_, (w, _)| *w == window);
        }
        let entry = counts.entry(key.to_owned()).or_insert((window, 0));
        if entry.0 != window {
            *entry = (window, 0);
        }
        entry.1 += 1;
        entry.1 <= self.limit
    }
}

impl Middleware for Throttle {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        if let Some(key) = (self.key)(&ctx) {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_secs());
            if !self.allow(&key, now) {
                tracing::info!(throttle = self.name, "request throttled");
                return Box::pin(async {
                    Response::text("Retry later\n").with_status(http::StatusCode::TOO_MANY_REQUESTS)
                });
            }
        }
        Box::pin(next.run(ctx))
    }
}

#[cfg(test)]
mod throttle_tests {
    use super::*;

    #[test]
    fn counts_each_key_in_fixed_windows() {
        let throttle = Throttle::new("t", 2, std::time::Duration::from_secs(60), |_| None);
        assert!(throttle.allow("a", 120));
        assert!(throttle.allow("a", 130));
        assert!(!throttle.allow("a", 179), "a third within the minute");
        assert!(throttle.allow("b", 179), "keys are counted apart");
        assert!(throttle.allow("a", 180), "a new window starts afresh");
    }
}