larust-http 0.9.0

A Laravel-shaped web framework for Rust.
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
use axum::body::Body;
use axum::extract::Request;
use axum::http::{header, HeaderName, HeaderValue, StatusCode};
use axum::middleware::Next;
use axum::response::Response;
use larust_http::session::Session;
use larust_http::{csrf, Route, Router};
use tower::ServiceExt;

async fn show_token(session: Session) -> String {
    csrf::token(&session).await
}

async fn submit() -> &'static str {
    "ok"
}

/// Every test in this file that needs a pool shares one process-wide
/// pool - `larust_orm::connect()` is a real once-per-process singleton
/// (like every other test suite in this codebase that uses it), so the
/// first call here wins and every later call's "already connected" error
/// is deliberately swallowed. A real temp-file database, not
/// `sqlite::memory:`: a pool can open more than one physical connection,
/// and pooled `:memory:` connections each get their own private, empty
/// database without explicit shared-cache URI mode - the same reasoning
/// `larust_testing::db::test_db`'s own doc comment gives for avoiding it.
/// Harmless for what these tests exercise (cookie/CSRF-attribute checks
/// through independent request pairs, never cross-test data isolation).
/// Exercises the same `AnySessionStore`/migration code path production
/// uses either way.
async fn test_pool() -> sqlx::AnyPool {
    let dir = tempfile::tempdir().unwrap().keep();
    let database_url = format!("sqlite://{}/test.sqlite", dir.display());
    let _ = larust_orm::connect(&database_url).await;
    larust_orm::pool().unwrap().clone()
}

#[tokio::test]
async fn router_middleware_and_with_sessions_compose_regardless_of_call_order() {
    // `.middleware(csrf::verify)` is declared *before* `.with_sessions()`
    // here - session must still end up outermost (available to CSRF's
    // extractors) regardless of that ordering, per `Router`'s contract.
    let pool = test_pool().await;
    let router = Route::get("/token", show_token)
        .post("/submit", submit)
        .middleware(axum::middleware::from_fn(csrf::verify))
        .with_sessions(&pool, true)
        .await
        .unwrap()
        .into_axum_router();

    let response = router
        .clone()
        .oneshot(Request::get("/token").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let cookie = response
        .headers()
        .get(header::SET_COOKIE)
        .expect("Router::with_sessions() should set a session cookie")
        .to_str()
        .unwrap()
        .split(';')
        .next()
        .unwrap()
        .to_string();
    let token = String::from_utf8(
        axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap()
            .to_vec(),
    )
    .unwrap();

    let ok_response = router
        .clone()
        .oneshot(
            Request::post("/submit")
                .header(header::COOKIE, &cookie)
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from(format!("_csrf_token={token}")))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ok_response.status(), StatusCode::OK);

    let rejected_response = router
        .oneshot(
            Request::post("/submit")
                .header(header::COOKIE, &cookie)
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from("_csrf_token=wrong"))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        rejected_response.status(),
        StatusCode::from_u16(419).unwrap()
    );
}

#[tokio::test]
async fn with_sessions_called_before_middleware_still_places_sessions_outermost() {
    // The reverse of the call order in the test above - `.with_sessions()`
    // comes first this time.
    let pool = test_pool().await;
    let router = Route::get("/token", show_token)
        .post("/submit", submit)
        .with_sessions(&pool, true)
        .await
        .unwrap()
        .middleware(axum::middleware::from_fn(csrf::verify))
        .into_axum_router();

    let response = router
        .clone()
        .oneshot(Request::get("/token").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let cookie = response
        .headers()
        .get(header::SET_COOKIE)
        .expect("session cookie should still be set regardless of call order")
        .to_str()
        .unwrap()
        .split(';')
        .next()
        .unwrap()
        .to_string();
    let token = String::from_utf8(
        axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap()
            .to_vec(),
    )
    .unwrap();

    let ok_response = router
        .oneshot(
            Request::post("/submit")
                .header(header::COOKIE, &cookie)
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from(format!("_csrf_token={token}")))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(ok_response.status(), StatusCode::OK);
}

#[tokio::test]
async fn with_sessions_secure_flag_controls_the_cookies_secure_attribute() {
    // `with_sessions(true)` (the default apps get unless SESSION_SECURE_COOKIE=false
    // is set) must keep the `Secure` attribute - regression guard for the
    // framework's safe-by-default posture.
    let secure_pool = test_pool().await;
    let secure_router = Route::get("/token", show_token)
        .with_sessions(&secure_pool, true)
        .await
        .unwrap()
        .into_axum_router();
    let secure_response = secure_router
        .oneshot(Request::get("/token").body(Body::empty()).unwrap())
        .await
        .unwrap();
    let secure_cookie = secure_response
        .headers()
        .get(header::SET_COOKIE)
        .unwrap()
        .to_str()
        .unwrap();
    assert!(
        secure_cookie.to_lowercase().contains("secure"),
        "with_sessions(true) should set a Secure cookie, got: {secure_cookie}"
    );

    // `with_sessions(false)` (SESSION_SECURE_COOKIE=false, for local dev on
    // a custom hostname like a `.test` domain) must drop it - this is the
    // actual fix: without it, browsers silently discard the Set-Cookie
    // header on any host outside their loopback/localhost allowlist, and
    // sessions (so CSRF) break with no error surfaced anywhere.
    let insecure_pool = test_pool().await;
    let insecure_router = Route::get("/token", show_token)
        .with_sessions(&insecure_pool, false)
        .await
        .unwrap()
        .into_axum_router();
    let insecure_response = insecure_router
        .oneshot(Request::get("/token").body(Body::empty()).unwrap())
        .await
        .unwrap();
    let insecure_cookie = insecure_response
        .headers()
        .get(header::SET_COOKIE)
        .unwrap()
        .to_str()
        .unwrap();
    assert!(
        !insecure_cookie.to_lowercase().contains("secure"),
        "with_sessions(false) should not set a Secure cookie, got: {insecure_cookie}"
    );
}

async fn mark_a(req: Request, next: Next) -> Response {
    let mut response = next.run(req).await;
    response.headers_mut().append(
        HeaderName::from_static("x-order"),
        HeaderValue::from_static("a"),
    );
    response
}

async fn mark_b(req: Request, next: Next) -> Response {
    let mut response = next.run(req).await;
    response.headers_mut().append(
        HeaderName::from_static("x-order"),
        HeaderValue::from_static("b"),
    );
    response
}

async fn mark_c(req: Request, next: Next) -> Response {
    let mut response = next.run(req).await;
    response.headers_mut().append(
        HeaderName::from_static("x-order"),
        HeaderValue::from_static("c"),
    );
    response
}

fn order_header(response: &Response) -> Vec<&str> {
    response
        .headers()
        .get_all("x-order")
        .iter()
        .map(|v| v.to_str().unwrap())
        .collect()
}

#[tokio::test]
async fn middleware_call_order_is_execution_order() {
    // A registered first, B registered second. A middleware's own logic
    // that runs *after* `next.run()` (like this header append) only fires
    // once everything nested inside it - every later-registered middleware,
    // then the handler - has finished. So if call order is execution order
    // (A runs first / is outermost, per the fix), B's post-`next.run()`
    // append happens first (it's innermost) and A's happens last: headers
    // come out ["b", "a"]. Before the ordering fix, this would have come
    // out reversed ("a" first) since the last-registered middleware used
    // to end up outermost instead.
    let router = Route::get("/", || async { "ok" })
        .middleware(axum::middleware::from_fn(mark_a))
        .middleware(axum::middleware::from_fn(mark_b))
        .into_axum_router();

    let response = router
        .oneshot(Request::get("/").body(Body::empty()).unwrap())
        .await
        .unwrap();

    let order: Vec<&str> = response
        .headers()
        .get_all("x-order")
        .iter()
        .map(|v| v.to_str().unwrap())
        .collect();
    assert_eq!(order, vec!["b", "a"]);
}

#[tokio::test]
async fn group_scoped_middleware_only_affects_routes_inside_the_group() {
    let router = Route::get("/public", || async { "public" })
        .group("/admin", |r: Router| {
            r.middleware(axum::middleware::from_fn(mark_a))
                .get("/dashboard", || async { "dashboard" })
        })
        .into_axum_router();

    let public_response = router
        .clone()
        .oneshot(Request::get("/public").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert!(
        !public_response.headers().contains_key("x-order"),
        "middleware registered inside a group must not affect routes outside it"
    );

    let admin_response = router
        .oneshot(
            Request::get("/admin/dashboard")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        admin_response
            .headers()
            .get("x-order")
            .and_then(|v| v.to_str().ok()),
        Some("a"),
        "middleware registered inside a group must affect that group's own routes"
    );
}

#[tokio::test]
async fn top_level_middleware_still_covers_routes_added_via_group() {
    let router = Route::get("/public", || async { "public" })
        .group("/admin", |r: Router| {
            r.get("/dashboard", || async { "dashboard" })
        })
        .middleware(axum::middleware::from_fn(mark_a))
        .into_axum_router();

    let admin_response = router
        .oneshot(
            Request::get("/admin/dashboard")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        admin_response
            .headers()
            .get("x-order")
            .and_then(|v| v.to_str().ok()),
        Some("a"),
        "a top-level .middleware() call must still cover routes registered via .group()"
    );
}

#[tokio::test]
async fn group_and_top_level_middleware_compose_with_group_innermost() {
    // A group's middleware is baked into its entries before those entries
    // are merged into the parent router, and the parent's own top-level
    // middleware is applied on top of that afterwards - so top-level
    // middleware is always outermost relative to a group's own, regardless
    // of registration order between the two.
    let router = Route::get("/public", || async { "public" })
        .middleware(axum::middleware::from_fn(mark_a))
        .group("/admin", |r: Router| {
            r.middleware(axum::middleware::from_fn(mark_b))
                .get("/dashboard", || async { "dashboard" })
        })
        .into_axum_router();

    let admin_response = router
        .oneshot(
            Request::get("/admin/dashboard")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    let order: Vec<&str> = admin_response
        .headers()
        .get_all("x-order")
        .iter()
        .map(|v| v.to_str().unwrap())
        .collect();
    // Group middleware (mark_b) is baked into the entry's own MethodRouter
    // first, then the top-level middleware (mark_a) wraps the whole
    // MethodRouter afterwards in `into_axum_router` - so mark_a is
    // outermost/runs first, mark_b is innermost. A post-`next.run()` header
    // append therefore fires on mark_b first (innermost finishes first),
    // then mark_a: ["b", "a"].
    assert_eq!(order, vec!["b", "a"]);
}

#[tokio::test]
async fn group_registered_before_top_level_middleware_still_composes_with_group_innermost() {
    // The reverse call order of the test above (`.group()` before
    // `.middleware()` this time) - `self.middlewares` is only applied
    // uniformly to every entry at `into_axum_router()` time, so which of
    // `.group()`/`.middleware()` was called first on the *parent* router
    // doesn't change the result: group middleware is always innermost.
    let router = Route::get("/public", || async { "public" })
        .group("/admin", |r: Router| {
            r.middleware(axum::middleware::from_fn(mark_b))
                .get("/dashboard", || async { "dashboard" })
        })
        .middleware(axum::middleware::from_fn(mark_a))
        .into_axum_router();

    let admin_response = router
        .oneshot(
            Request::get("/admin/dashboard")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(order_header(&admin_response), vec!["b", "a"]);
}

#[tokio::test]
async fn nested_groups_compose_middleware_innermost_by_depth() {
    // mark_a: outer group's own middleware. mark_b: inner group's own
    // middleware. The inner group is built and merged first (innermost),
    // then the outer group's middleware wraps around the merged result -
    // so mark_b should be innermost (fires first) and mark_a outermost.
    let router = Route::group("/outer", |outer: Router| {
        outer
            .middleware(axum::middleware::from_fn(mark_a))
            .group("/inner", |inner: Router| {
                inner
                    .middleware(axum::middleware::from_fn(mark_b))
                    .get("/leaf", || async { "leaf" })
            })
    })
    .into_axum_router();

    let response = router
        .oneshot(
            Request::get("/outer/inner/leaf")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(order_header(&response), vec!["b", "a"]);
}

#[tokio::test]
async fn sibling_groups_do_not_share_each_others_middleware() {
    let router = Route::group("/a", |r: Router| {
        r.middleware(axum::middleware::from_fn(mark_a))
            .get("/route", || async { "a" })
    })
    .group("/b", |r: Router| {
        r.middleware(axum::middleware::from_fn(mark_b))
            .get("/route", || async { "b" })
    })
    .into_axum_router();

    let a_response = router
        .clone()
        .oneshot(Request::get("/a/route").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(order_header(&a_response), vec!["a"]);

    let b_response = router
        .oneshot(Request::get("/b/route").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(order_header(&b_response), vec!["b"]);
}

#[tokio::test]
async fn top_level_middleware_covers_routes_added_both_before_and_after_a_group() {
    // mark_c is registered *between* a route added before the group and a
    // route added after it - global middleware doesn't care about
    // registration order relative to routes/groups, only about being
    // applied once at `into_axum_router()` time to every entry that ends
    // up in `self.entries`.
    let router = Route::get("/before", || async { "before" })
        .group("/admin", |r: Router| {
            r.get("/dashboard", || async { "dashboard" })
        })
        .middleware(axum::middleware::from_fn(mark_c))
        .get("/after", || async { "after" })
        .into_axum_router();

    for path in ["/before", "/admin/dashboard", "/after"] {
        let response = router
            .clone()
            .oneshot(Request::get(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            order_header(&response),
            vec!["c"],
            "top-level middleware should cover `{path}` regardless of when it was registered relative to .middleware()"
        );
    }
}

struct TestPlugin;

impl larust_http::Plugin for TestPlugin {
    fn routes(&self) -> Router {
        Router::new().get("/__test_plugin/route", || async { "plugin" })
    }
}

#[tokio::test]
async fn top_level_middleware_still_covers_routes_added_via_plugin() {
    // The exact regression `Router::plugin` shipped with, then fixed:
    // `.plugin()` used to be sugar over `.merge("", ...)`, which
    // (correctly, for `.merge`'s own real use case - see the
    // `merge_does_not_leak_...`/`merge_leaves_a_csrf_protected_...` tests
    // below) marks every incoming entry immune to the parent router's own
    // top-level middleware. A plugin's routes are ordinary, first-class
    // app routes contributed by a crate, not a separate router tree with
    // independent concerns - they must inherit `.middleware(...)` the
    // same way a hand-written `.get(...)` call in their place would.
    let router = Route::get("/public", || async { "public" })
        .plugin(TestPlugin)
        .middleware(axum::middleware::from_fn(mark_a))
        .into_axum_router();

    let response = router
        .oneshot(
            Request::get("/__test_plugin/route")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        order_header(&response),
        vec!["a"],
        "a top-level .middleware() call must still cover routes registered via .plugin()"
    );
}

#[tokio::test]
async fn plugin_routes_are_subject_to_the_apps_own_csrf_middleware() {
    // The literal real-world bug: `WirePlugin`'s `/__larust_wire/
    // {component_id}` POST route silently stopped being CSRF-protected
    // the moment `demo`/`scaffold.rs` switched from a hand-written
    // `.post(...)` registration to `.plugin(WirePlugin)`, because the
    // pre-fix `.plugin()` marked it immune to the app's own trailing
    // `.middleware(csrf::verify)` call - the exact opposite of
    // `merge_leaves_a_csrf_protected_web_router_from_rejecting_a_merged_
    // in_api_post` below, which proves `.merge()` correctly keeps CSRF
    // OFF a merged-in api router. A plugin-contributed mutating route
    // must be rejected without a valid token, same as if it had been
    // hand-registered directly.
    struct PostPlugin;
    impl larust_http::Plugin for PostPlugin {
        fn routes(&self) -> Router {
            Router::new().post("/__test_plugin/submit", submit)
        }
    }

    let pool = test_pool().await;
    let router = Route::get("/token", show_token)
        .plugin(PostPlugin)
        .middleware(axum::middleware::from_fn(csrf::verify))
        .with_sessions(&pool, true)
        .await
        .unwrap()
        .into_axum_router();

    let rejected = router
        .oneshot(
            Request::post("/__test_plugin/submit")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from("_csrf_token=wrong"))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        rejected.status(),
        StatusCode::from_u16(419).unwrap(),
        "a plugin-contributed mutating route must still be covered by the app's own CSRF \
         middleware, the same as a hand-registered route would be"
    );
}

#[tokio::test]
async fn merge_does_not_leak_either_sides_top_level_middleware_onto_the_other() {
    // The exact regression this method exists to fix: `web`-shaped router
    // has its own top-level middleware (mark_a), `api`-shaped router has a
    // *different* one (mark_b) - after merging, each side's routes must
    // carry only their own, never the other's. `.group(...)` deliberately
    // does NOT have this property (see `top_level_middleware_still_covers_
    // routes_added_via_group` above) - `.merge` exists specifically for
    // when that sharing is unwanted.
    let web = Route::get("/", || async { "home" }).middleware(axum::middleware::from_fn(mark_a));
    let api =
        Route::get("/users", || async { "users" }).middleware(axum::middleware::from_fn(mark_b));
    let router = web.merge("/api", api).into_axum_router();

    let home_response = router
        .clone()
        .oneshot(Request::get("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(
        order_header(&home_response),
        vec!["a"],
        "the web router's own middleware must still cover its own routes"
    );
    assert!(
        !order_header(&home_response).contains(&"b"),
        "the api router's middleware must never leak onto the web router's routes"
    );

    let users_response = router
        .oneshot(Request::get("/api/users").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(
        order_header(&users_response),
        vec!["b"],
        "the api router's own middleware must still cover its own (merged) routes"
    );
    assert!(
        !order_header(&users_response).contains(&"a"),
        "the web router's middleware must never leak onto the api router's merged-in routes"
    );
}

#[tokio::test]
async fn merge_prefixes_the_other_routers_paths_and_preserves_names() {
    let web = Route::get("/", || async { "home" });
    let api = Route::get("/users", || async { "users" }).name("api.users");
    let router = web.merge("/api", api);

    let infos = router.routes();
    let api_users = infos
        .iter()
        .find(|info| info.path == "/api/users")
        .expect("merged route should be prefixed");
    assert_eq!(api_users.name.as_deref(), Some("api.users"));
}

#[tokio::test]
async fn merge_leaves_a_csrf_protected_web_router_from_rejecting_a_merged_in_api_post() {
    // The literal real-world bug this method fixes: a `web`-shaped router
    // wraps itself in `csrf::verify`, then merges in an `api`-shaped
    // router with its own unrelated middleware and no CSRF at all - a POST
    // to the merged-in api route must succeed with no CSRF token at all,
    // proving CSRF genuinely never reaches it (unlike `.group`, which the
    // `top_level_middleware_covers_routes_added_both_before_and_after_a_
    // group` test above proves *would* leak it).
    let web =
        Route::get("/", || async { "home" }).middleware(axum::middleware::from_fn(csrf::verify));
    let api = Route::post("/tokens", || async { "token" });
    let router = web.merge("/api", api).into_axum_router();

    let response = router
        .oneshot(Request::post("/api/tokens").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(
        response.status(),
        StatusCode::OK,
        "a merged-in api route must never be subject to the web router's own CSRF middleware"
    );
}