glacier-web 0.5.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
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
//! Phase 1 web essentials: sessions, flash, cookies, CSRF, pipelines,
//! method override, static files, config and the dev error page.

use glacier::csrf::Csrf;
use glacier::files::Static;
use glacier::middleware::{MethodOverride, SecureHeaders, from_fn};
use glacier::prelude::*;
use glacier::testing::TestClient;

const SECRET: &str = "a-test-secret-that-is-at-least-32-bytes-long";

#[tokio::test]
async fn session_persists_across_requests() {
    let c = TestClient::new(App::new().routes(|r| {
        r.post("/login", |ctx: Context| async move {
            ctx.session().insert("user_id", 42)?;
            Ok::<_, Error>(Response::redirect("/me"))
        })
        .get("/me", |ctx: Context| async move {
            match ctx.session().get::<u32>("user_id") {
                Some(id) => format!("user {id}"),
                None => "anonymous".into(),
            }
        })
        .post("/logout", |ctx: Context| async move {
            ctx.session().clear();
            Response::redirect("/me")
        });
    }));

    assert_eq!(c.get("/me").await.body_text(), "anonymous");
    // Reading an empty session doesn't set a cookie.
    assert!(c.cookie("_glacier_session").is_none());

    c.post_form("/login", &[("", "")]).await;
    let raw = c.cookie("_glacier_session").expect("session cookie");
    // Ciphertext can contain "42" by chance; the key name never survives.
    assert!(!raw.contains("user_id"), "session must be encrypted: {raw}");
    assert_eq!(c.get("/me").await.body_text(), "user 42");

    c.post_form("/logout", &[("", "")]).await;
    assert!(c.cookie("_glacier_session").is_none());
    assert_eq!(c.get("/me").await.body_text(), "anonymous");
}

#[tokio::test]
async fn tampered_sessions_are_ignored() {
    let app = || {
        App::new().routes(|r| {
            r.post("/set", |ctx: Context| async move {
                ctx.session().insert("admin", true)?;
                Ok::<_, Error>("ok")
            })
            .get("/admin", |ctx: Context| async move {
                if ctx.session().get::<bool>("admin") == Some(true) {
                    "yes"
                } else {
                    "no"
                }
            });
        })
    };

    let c = TestClient::new(app());
    c.post_form("/set", &[("", "")]).await;
    let raw = c.cookie("_glacier_session").unwrap();

    let forged = http::Request::get("/admin")
        .header("cookie", format!("_glacier_session=x{raw}"))
        .body(Default::default())
        .unwrap();
    assert_eq!(c.request(forged).await.body_text(), "no");

    // A different app instance has a different random key, so it can't read it.
    let other = TestClient::new(app());
    let replayed = http::Request::get("/admin")
        .header("cookie", format!("_glacier_session={raw}"))
        .body(Default::default())
        .unwrap();
    assert_eq!(other.request(replayed).await.body_text(), "no");
}

#[tokio::test]
async fn sessions_survive_restarts_with_a_shared_secret() {
    let app = || {
        App::new().secret_key_base(SECRET).unwrap().routes(|r| {
            r.post("/set", |ctx: Context| async move {
                ctx.session().insert("n", 7)?;
                Ok::<_, Error>("ok")
            })
            .get("/get", |ctx: Context| async move {
                format!("{:?}", ctx.session().get::<u32>("n"))
            });
        })
    };
    let first = TestClient::new(app());
    first.post_form("/set", &[("", "")]).await;
    let raw = first.cookie("_glacier_session").unwrap();

    let second = TestClient::new(app());
    let req = http::Request::get("/get")
        .header("cookie", format!("_glacier_session={raw}"))
        .body(Default::default())
        .unwrap();
    assert_eq!(second.request(req).await.body_text(), "Some(7)");
}

#[tokio::test]
async fn flash_is_shown_exactly_once() {
    let c = TestClient::new(App::new().routes(|r| {
        r.post("/posts", |ctx: Context| async move {
            ctx.put_flash("notice", "Post created");
            Response::redirect("/posts")
        })
        .get("/posts", |ctx: Context| async move {
            ctx.flash("notice").unwrap_or_default()
        })
        .get("/ping", |ctx: Context| async move {
            // Touches the session, but not the flash.
            ctx.session().insert("seen", true).unwrap();
            "pong"
        })
        .post("/again", |ctx: Context| async move {
            // Shown on this page only.
            ctx.flash_now("alert", "Try again");
            ctx.flash("alert").unwrap_or_default()
        });
    }));

    c.post_form("/posts", &[("", "")]).await;
    // A request that doesn't read the flash (or a 404) leaves it.
    c.get("/ping").await;
    c.get("/missing").await;
    assert_eq!(c.get("/posts").await.body_text(), "Post created");
    assert_eq!(c.get("/posts").await.body_text(), "");

    assert_eq!(
        c.post_form("/again", &[("", "")]).await.body_text(),
        "Try again"
    );
    assert_eq!(
        c.get("/posts").await.body_text(),
        "",
        "flash_now isn't kept"
    );
}

#[tokio::test]
async fn signed_cookies_reject_tampering() {
    let c = TestClient::new(App::new().routes(|r| {
        r.post("/remember", |ctx: Context| async move {
            ctx.cookies().add_signed(("theme", "dark"));
            ctx.cookies().add(("plain", "visible"));
            "ok"
        })
        .get("/theme", |ctx: Context| async move {
            ctx.cookies().get_signed("theme").unwrap_or("none".into())
        });
    }));

    c.post_form("/remember", &[("", "")]).await;
    assert_eq!(c.cookie("plain").as_deref(), Some("visible"));
    assert!(c.cookie("theme").unwrap().ends_with("dark"));
    assert_eq!(c.get("/theme").await.body_text(), "dark");

    let forged = http::Request::get("/theme")
        .header("cookie", "theme=AAAAdark")
        .body(Default::default())
        .unwrap();
    assert_eq!(c.request(forged).await.body_text(), "none");
}

fn csrf_app() -> App {
    App::new().routes(|r| {
        r.pipe_through(&Pipeline::new().with(Csrf), |r| {
            r.get("/form", |ctx: Context| async move { ctx.csrf_token() })
                .post("/submit", |_ctx| async { "accepted" });
        });
        r.post("/webhook", |_ctx| async { "no csrf here" });
    })
}

#[tokio::test]
async fn csrf_rejects_requests_without_a_valid_token() {
    let c = TestClient::new(csrf_app());

    // No session yet, so no token.
    let res = c.post_form("/submit", &[("title", "x")]).await;
    assert_eq!(res.status(), StatusCode::FORBIDDEN);

    let token = c.get("/form").await.body_text();
    assert_eq!(token.len(), 64);
    // Stable within a session.
    assert_eq!(c.get("/form").await.body_text(), token);

    let wrong = c.post_form("/submit", &[("_csrf_token", "nope")]).await;
    assert_eq!(wrong.status(), StatusCode::FORBIDDEN);

    let ok = c
        .post_form("/submit", &[("_csrf_token", token.as_str())])
        .await;
    assert_eq!(ok.body_text(), "accepted");

    let via_header = http::Request::post("/submit")
        .header("x-csrf-token", &token)
        .body(Default::default())
        .unwrap();
    assert_eq!(c.request(via_header).await.body_text(), "accepted");

    // Routes outside the pipeline are unaffected.
    let res = c.post_form("/webhook", &[("", "")]).await;
    assert_eq!(res.body_text(), "no csrf here");
}

#[tokio::test]
async fn upload_forms_send_their_token_and_method_in_the_multipart_body() {
    let c = TestClient::new(App::new().middleware(MethodOverride).routes(|r| {
        r.pipe_through(&Pipeline::new().with(Csrf), |r| {
            r.get("/form", |ctx: Context| async move { ctx.csrf_token() })
                .patch("/photos/:id", |ctx: Context| async move {
                    format!(
                        "updated {} with {}",
                        ctx.param("id").unwrap(),
                        ctx.files().len()
                    )
                });
        });
    }));
    let token = c.get("/form").await.body_text();
    // As a browser sends a form with a file input.
    let multipart = |token: &str| {
        let body = format!(
            "--b\r\nContent-Disposition: form-data; name=\"_csrf_token\"\r\n\r\n{token}\r\n\
             --b\r\nContent-Disposition: form-data; name=\"_method\"\r\n\r\npatch\r\n\
             --b\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"a.txt\"\r\n\
             Content-Type: text/plain\r\n\r\nhello\r\n--b--\r\n"
        );
        http::Request::post("/photos/3")
            .header("content-type", "multipart/form-data; boundary=b")
            .body(body.into())
            .unwrap()
    };
    let res = c.request(multipart(&token)).await;
    assert_eq!(res.body_text(), "updated 3 with 1");
    let forged = c.request(multipart("nope")).await;
    assert_eq!(forged.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn method_override_lets_forms_delete() {
    let c = TestClient::new(App::new().middleware(MethodOverride).routes(|r| {
        r.delete("/posts/:id", |ctx: Context| async move {
            format!("deleted {}", ctx.param("id").unwrap())
        });
    }));

    let res = c.post_form("/posts/3", &[("_method", "delete")]).await;
    assert_eq!(res.body_text(), "deleted 3");

    let res = c.post_form("/posts/3", &[("_method", "get")]).await;
    assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn pipelines_apply_only_inside_their_block_and_nest_in_order() {
    let tag = |name: &'static str| {
        from_fn(move |ctx, next| async move {
            let res = next.run(ctx).await;
            let trail = match res.header("x-trail") {
                Some(inner) => format!("{name},{inner}"),
                None => name.to_owned(),
            };
            res.with_header("x-trail", trail)
        })
    };
    let outer = Pipeline::new().with(tag("outer"));
    let inner = Pipeline::new().with(tag("inner"));

    let c = TestClient::new(App::new().routes(|r| {
        r.get("/public", |_ctx| async { "" });
        r.pipe_through(&outer, |r| {
            r.get("/a", |_ctx| async { "" });
            r.scope("/admin", |r| {
                r.pipe_through(&inner, |r| {
                    r.get("/b", |_ctx| async { "" });
                });
            });
        });
    }));

    assert_eq!(c.get("/public").await.header("x-trail"), None);
    assert_eq!(c.get("/a").await.header("x-trail"), Some("outer"));
    assert_eq!(
        c.get("/admin/b").await.header("x-trail"),
        Some("outer,inner")
    );
}

#[tokio::test]
async fn browser_pipeline_sets_security_headers() {
    let c = TestClient::new(App::new().routes(|r| {
        r.pipe_through(&Pipeline::new().with(SecureHeaders), |r| {
            r.get("/", |_ctx| async { "" })
                .get("/embeddable", |_ctx| async {
                    Response::text("").with_header("x-frame-options", "ALLOWALL")
                });
        });
    }));

    let res = c.get("/").await;
    assert_eq!(res.header("x-frame-options"), Some("SAMEORIGIN"));
    assert_eq!(res.header("x-content-type-options"), Some("nosniff"));
    let res = c.get("/embeddable").await;
    assert_eq!(res.header("x-frame-options"), Some("ALLOWALL"));
}

#[tokio::test]
async fn serves_static_files() {
    let dir = std::env::temp_dir().join(format!("glacier-static-{}", std::process::id()));
    std::fs::create_dir_all(dir.join("css")).unwrap();
    std::fs::write(dir.join("css/app.css"), "body{}").unwrap();

    let c = TestClient::new(App::new().middleware(Static::new(&dir)).routes(|r| {
        r.get("/", |_ctx| async { "home" });
    }));

    let res = c.get("/css/app.css").await;
    assert_eq!(res.status(), StatusCode::OK);
    assert_eq!(res.header("content-type"), Some("text/css; charset=utf-8"));
    assert_eq!(res.body_text(), "body{}");
    let etag = res.header("etag").unwrap().to_owned();

    let cached = http::Request::get("/css/app.css")
        .header("if-none-match", &etag)
        .body(Default::default())
        .unwrap();
    assert_eq!(c.request(cached).await.status(), StatusCode::NOT_MODIFIED);

    // Directories, missing files and traversal fall through to the router.
    assert_eq!(c.get("/").await.body_text(), "home");
    assert_eq!(c.get("/css").await.status(), StatusCode::NOT_FOUND);
    assert_eq!(c.get("/nope.css").await.status(), StatusCode::NOT_FOUND);
    assert_eq!(
        c.get("/css/%2e%2e/%2e%2e/etc/passwd").await.status(),
        StatusCode::NOT_FOUND
    );

    std::fs::remove_dir_all(dir).unwrap();
}

fn failing_app(env: Env) -> App {
    App::new().env(env).routes(|r| {
        r.get("/io", |_ctx| async {
            std::fs::read_to_string("/definitely/not/here")?;
            Ok::<_, Error>("unreachable")
        })
        .get("/panic", |_ctx| async {
            if true {
                panic!("the <flux capacitor> broke");
            }
            ""
        });
    })
}

#[tokio::test]
async fn development_shows_a_debug_page() {
    let c = TestClient::new(failing_app(Env::Development));

    let res = c.get("/io").await;
    assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
    let body = res.body_text();
    assert!(body.contains("No such file or directory"), "{body}");
    assert!(body.contains("GET /io"), "{body}");

    let body = c.get("/panic").await.body_text();
    assert!(
        body.contains("panic: the &lt;flux capacitor&gt; broke"),
        "{body}"
    );
}

#[tokio::test]
async fn other_environments_hide_error_details() {
    for env in [Env::Test, Env::Production] {
        let c = TestClient::new(failing_app(env));
        let res = c.get("/io").await;
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(res.body_text(), "Internal Server Error");
    }
}

#[tokio::test]
async fn production_requires_a_secret() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let err = App::new()
        .env(Env::Production)
        .build()
        .serve_with_shutdown(listener, async {})
        .await
        .unwrap_err();
    assert!(err.message().contains("secret_key_base"));

    assert!(App::new().secret_key_base("too short").is_err());
}

#[tokio::test]
async fn applies_config() {
    let config = Config::from_toml(
        Env::Test,
        &format!(
            "secret_key_base = \"{SECRET}\"\nsite_name = \"Glacier Blog\"\n[server]\nmax_body_size = 16\n"
        ),
    )
    .unwrap();
    let app = App::new().config(config).unwrap().routes(|r| {
        r.get("/name", |ctx: Context| async move {
            ctx.state::<Config>()?.get::<String>("site_name")
        });
    });
    let service = app.build();
    assert_eq!(service.env(), Env::Test);

    let res = service
        .call(
            http::Request::get("/name")
                .body(Default::default())
                .unwrap(),
        )
        .await;
    assert_eq!(res.body_text(), "Glacier Blog");
}

#[glacier::test]
async fn throttle_answers_429_with_retry_after() {
    use glacier::middleware::Throttle;
    let c = TestClient::new(
        App::new()
            .middleware(Throttle::new(
                "web-test",
                2,
                std::time::Duration::from_secs(60),
                |ctx| Some(ctx.path().to_owned()),
            ))
            .routes(|r| {
                r.get("/a", |_ctx: Context| async { "a" })
                    .get("/b", |_ctx: Context| async { "b" });
            }),
    );
    assert_eq!(c.get("/a").await.status(), 200);
    assert_eq!(c.get("/a").await.status(), 200);
    let res = c.get("/a").await;
    assert_eq!(res.status(), 429);
    let wait: i64 = res.header("retry-after").unwrap().parse().unwrap();
    assert!((1..=60).contains(&wait));
    assert_eq!(c.get("/b").await.status(), 200, "keys are counted apart");
    glacier::testing::travel(chrono::TimeDelta::seconds(61));
    assert_eq!(
        c.get("/a").await.status(),
        200,
        "a new window starts afresh"
    );
}