glacier-web 0.4.1

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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! 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, StatusCode};

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(ETag)
            .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(ETag).with(JsonErrors)
    }
}

/// ETags and conditional GETs, as Rails' default `Rack::ETag` and
/// `Rack::ConditionalGet`: a `200` or `201` with a body gets a weak `ETag`
/// from it (and `Cache-Control: max-age=0, private, must-revalidate`
/// unless it has one), and a GET or HEAD that sends that tag back in
/// `If-None-Match` gets `304 Not Modified` with no body. Other responses
/// get `Cache-Control: no-cache` unless they say otherwise. A response
/// with its own `ETag` or `Last-Modified` (from `fresh_when`), or marked
/// `no-cache` or `no-store`, keeps its own. In both default pipelines.
pub struct ETag;

impl Middleware for ETag {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let conditional = matches!(*ctx.method(), Method::GET | Method::HEAD);
        let if_none_match = ctx.header(http::header::IF_NONE_MATCH).map(str::to_owned);
        Box::pin(async move {
            let mut res = next.run(ctx).await;
            let cache_control = res
                .header(http::header::CACHE_CONTROL)
                .unwrap_or("")
                .to_owned();
            // As Rack::ETag: a 200 or 201 with a body gets a tag, whatever
            // the method; only GET and HEAD can answer 304.
            let tagged = matches!(res.status().as_u16(), 200 | 201)
                && !res.headers().contains_key(http::header::ETAG)
                && !res.headers().contains_key(http::header::LAST_MODIFIED)
                && !cache_control.contains("no-cache")
                && !cache_control.contains("no-store")
                && !res.body().is_empty();
            if !tagged {
                if cache_control.is_empty() {
                    // Tagged already (`fresh_when`): revalidate, as Rails'
                    // own validators do; anything else isn't to be cached.
                    let validated = res.headers().contains_key(http::header::ETAG)
                        || res.headers().contains_key(http::header::LAST_MODIFIED);
                    let value = if validated {
                        "max-age=0, private, must-revalidate"
                    } else {
                        "no-cache"
                    };
                    res.headers_mut().insert(
                        http::header::CACHE_CONTROL,
                        http::HeaderValue::from_static(value),
                    );
                }
                return res;
            }
            // A weak tag only has to change when the body does: SipHash and
            // the length, about ten times cheaper than SHA-256 here.
            let mut hasher = std::hash::DefaultHasher::new();
            std::hash::Hasher::write(&mut hasher, res.body());
            let tag = format!(
                "W/\"{:x}-{:016x}\"",
                res.body().len(),
                std::hash::Hasher::finish(&hasher)
            );
            if cache_control.is_empty() {
                res.headers_mut().insert(
                    http::header::CACHE_CONTROL,
                    http::HeaderValue::from_static("max-age=0, private, must-revalidate"),
                );
            }
            let matches = conditional
                && if_none_match.is_some_and(|sent| {
                    sent.split(',').any(|candidate| {
                        let candidate = candidate.trim();
                        candidate == "*"
                            || candidate.trim_start_matches("W/") == tag.trim_start_matches("W/")
                    })
                });
            if matches {
                let mut not_modified = Response::new(StatusCode::NOT_MODIFIED);
                for (name, value) in res.headers() {
                    if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
                        not_modified
                            .headers_mut()
                            .insert(name.clone(), value.clone());
                    }
                }
                res = not_modified;
            }
            if let Ok(value) = http::HeaderValue::from_str(&tag) {
                res.headers_mut().insert(http::header::ETAG, value);
            }
            res
        })
    }
}

/// Headers every response gets unless it sets its own, as Rails'
/// `config.action_dispatch.default_headers`:
/// `DefaultHeaders::new().header("X-Frame-Options", "ALLOWALL")`.
#[derive(Clone, Default)]
pub struct DefaultHeaders(Vec<(http::HeaderName, http::HeaderValue)>);

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

    /// # Panics
    ///
    /// If the name or value isn't valid in a header.
    #[must_use]
    pub fn header(mut self, name: &str, value: &str) -> Self {
        self.0.push((
            http::HeaderName::try_from(name).expect("invalid header name"),
            http::HeaderValue::try_from(value).expect("invalid header value"),
        ));
        self
    }
}

impl Middleware for DefaultHeaders {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let headers = self.0.clone();
        Box::pin(async move {
            let mut res = next.run(ctx).await;
            for (name, value) in headers {
                if !res.headers().contains_key(&name) {
                    res.headers_mut().insert(name, value);
                }
            }
            res
        })
    }
}

/// 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))
    }
}

/// A path that starts with an id, `/42/projects/7`, as Basecamp's URLs do
/// for an account: the id comes off before the route is matched (it's
/// `ctx.path_prefix()`), and every path the app builds during the request
/// starts with it again. An app's own middleware decides what the id means
/// (`InOrg`: the org). Paths without one pass through as they are.
pub struct IdPrefix;

impl Middleware for IdPrefix {
    fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
        let path = ctx.path().to_owned();
        let mut segments = path.splitn(3, '/');
        let (Some(""), Some(id)) = (segments.next(), segments.next()) else {
            return Box::pin(next.run(ctx));
        };
        if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
            return Box::pin(next.run(ctx));
        }
        let id = id.to_owned();
        let rest = format!("/{}", segments.next().unwrap_or(""));
        ctx.set_path(&rest);
        ctx.set_path_prefix(id.clone());
        Box::pin(crate::router::with_path_prefix(
            format!("/{id}"),
            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) {
            // Glacier's clock, so a test can stop it (`freeze_time()`).
            let now = u64::try_from(crate::time::now().timestamp()).unwrap_or(0);
            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");
    }
}