rustango 0.40.0

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! Django-shape access decorators — `login_required` middleware +
//! `?next=` round-trip helpers. Issue #11.
//!
//! Gates a handler so anonymous requests get 302'd to a login URL
//! with the original URL preserved in `?next=`. After the user
//! authenticates, the login handler reads `?next=` and 302s back —
//! the canonical "click-through-then-resume" UX every Django app
//! ships.
//!
//! ## Wiring
//!
//! ```ignore
//! use rustango::auth_decorators::login_required;
//!
//! let app = Router::new()
//!     .route("/", get(home))                         // public
//!     .route("/profile", get(profile))               // gated
//!     .route("/settings", get(settings))             // gated
//!     .layer(login_required("/login"))               // protects every route below
//!     .route("/about", get(about));                  // public (added after layer)
//! ```
//!
//! Or scope the gate to a sub-router (the more idiomatic shape):
//!
//! ```ignore
//! let private = Router::new()
//!     .route("/profile", get(profile))
//!     .route("/settings", get(settings))
//!     .layer(login_required("/login"));
//!
//! let app = Router::new()
//!     .route("/", get(home))
//!     .merge(private);
//! ```
//!
//! ## Login-handler side
//!
//! The login handler reads `?next=` to know where to send the user
//! after a successful auth. Use [`extract_next`] for the read +
//! [`safe_next`] to defend against open-redirect attacks:
//!
//! ```ignore
//! async fn login_post(Query(q): Query<HashMap<String, String>>, …) -> Response {
//!     // … verify credentials …
//!     let next = auth_decorators::extract_next(&q)
//!         .and_then(|n| auth_decorators::safe_next(&n))
//!         .unwrap_or_else(|| "/".to_owned());
//!     Redirect::to(&next).into_response()
//! }
//! ```
//!
//! ## Out of scope (queued as follow-ups)
//!
//! - `permission_required(perm)` — needs the tenancy permission
//!   registry; pairs naturally with `login_required` but warrants its
//!   own slice once the auth-flow API stabilizes.
//! - `LoginRequiredMixin` on the CBV surface — small wiring on
//!   `TemplateView` / `DetailView` etc.
//! - Single-tenant / non-tenancy variant — `login_required` today
//!   pulls `SessionUser` which is tenancy-shaped. Apps using
//!   non-session auth (JWT, basic auth) plug their own predicate.

use std::collections::HashMap;
use std::sync::Arc;

use axum::body::Body;
use axum::extract::Request;
use axum::http::{header, HeaderValue, StatusCode};
use axum::middleware::Next;
use axum::response::Response;

/// Configuration for [`login_required`]. Defaults match Django:
/// `login_url = "/login"`, `redirect_field = "next"`.
#[derive(Debug, Clone)]
pub struct LoginRequiredConfig {
    /// Where to send anonymous users. Default `"/login"`.
    pub login_url: String,
    /// Query-param name carrying the original URL. Default `"next"`.
    pub redirect_field: String,
}

impl Default for LoginRequiredConfig {
    fn default() -> Self {
        Self {
            login_url: "/login".into(),
            redirect_field: "next".into(),
        }
    }
}

/// Construct an [`axum::middleware::FromFnLayer`] that 302s
/// anonymous requests to `login_url` with the original URL preserved
/// in `?next=`. Equivalent to Django's
/// `@login_required(login_url=login_url)`. Issue #11.
///
/// "Anonymous" means `SessionUser.0.is_none()` — the existing tenancy
/// extractor returns `None` when no session cookie is present or the
/// cookie is for a different tenant. Apps using non-session auth
/// (JWT, basic) need a different gating shape (queued).
///
/// See the module-level docs for full wiring + login-handler examples.
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn login_required(
    login_url: impl Into<String>,
) -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone {
    let cfg = Arc::new(LoginRequiredConfig {
        login_url: login_url.into(),
        ..Default::default()
    });
    axum::middleware::from_fn(move |req: Request<Body>, next: Next| {
        let cfg = cfg.clone();
        async move { handle_login_required(cfg, req, next).await }
    })
}

/// Predicate-based access gate. Django's
/// `@user_passes_test(test_func, login_url=…)`. Runs `predicate`
/// against the resolved [`crate::extractors::SessionUser`]; on
/// `true` the request continues, on `false` (or anonymous) it 302s
/// to `login_url` with `?next=` preserved — same shape as
/// [`login_required`].
///
/// The predicate receives a reference to the
/// [`crate::tenancy::auth::User`] row so it can inspect any field
/// (`is_superuser`, `active`, role flags, custom permissions
/// expressed on the row, etc.).
///
/// ```ignore
/// use rustango::auth_decorators::user_passes_test;
///
/// // Superuser-only sub-router:
/// let admin_only = Router::new()
///     .route("/admin/dashboard", get(dashboard))
///     .layer(user_passes_test("/login", |u| u.is_superuser));
/// ```
///
/// Note that anonymous requests don't reach the predicate — they
/// short-circuit straight to the login redirect. Pair with
/// [`login_required`] only if you want anonymous to be the *only*
/// reason for the redirect (this gate already handles it).
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn user_passes_test<F>(
    login_url: impl Into<String>,
    predicate: F,
) -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone
where
    F: Fn(&crate::tenancy::auth::User) -> bool + Send + Sync + 'static,
{
    let cfg = Arc::new(LoginRequiredConfig {
        login_url: login_url.into(),
        ..Default::default()
    });
    let pred = Arc::new(predicate);
    axum::middleware::from_fn(move |req: Request<Body>, next: Next| {
        let cfg = cfg.clone();
        let pred = pred.clone();
        async move { handle_user_passes_test(cfg, pred, req, next).await }
    })
}

#[cfg(all(feature = "tenancy", feature = "postgres"))]
async fn handle_user_passes_test<F>(
    cfg: Arc<LoginRequiredConfig>,
    pred: Arc<F>,
    req: Request<Body>,
    next: Next,
) -> Response
where
    F: Fn(&crate::tenancy::auth::User) -> bool + Send + Sync + 'static,
{
    use axum::extract::FromRequestParts as _;
    let (mut parts, body) = req.into_parts();
    let user = crate::extractors::SessionUser::from_request_parts(&mut parts, &())
        .await
        .unwrap_or(crate::extractors::SessionUser(None));
    if let Some(u) = user.0.as_ref() {
        if pred(u) {
            let req = Request::from_parts(parts, body);
            return next.run(req).await;
        }
    }
    // Anonymous OR predicate failed — redirect to login with ?next=.
    let original = parts
        .uri
        .path_and_query()
        .map(|p| p.as_str().to_owned())
        .unwrap_or_else(|| "/".to_owned());
    redirect_to_login(&cfg.login_url, &cfg.redirect_field, &original)
}

/// Predicate-based access gate that returns `403 Forbidden` on
/// failure instead of redirecting to a login page. Same shape as
/// [`user_passes_test`] but suited to JSON API endpoints where a
/// 302 to `/login` makes no sense — clients can't follow it and
/// shouldn't render an HTML login page.
///
/// Anonymous requests get 401 (Unauthorized) so the client can
/// distinguish "you need to authenticate" from "you authenticated
/// but lack the required permission" — matches IETF's RFC 7231
/// guidance.
///
/// ```ignore
/// use rustango::auth_decorators::user_passes_test_or_403;
///
/// let api = Router::new()
///     .route("/api/admin/stats", get(stats))
///     .layer(user_passes_test_or_403(|u| u.is_superuser));
/// ```
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn user_passes_test_or_403<F>(
    predicate: F,
) -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone
where
    F: Fn(&crate::tenancy::auth::User) -> bool + Send + Sync + 'static,
{
    let pred = Arc::new(predicate);
    axum::middleware::from_fn(move |req: Request<Body>, next: Next| {
        let pred = pred.clone();
        async move { handle_user_passes_test_or_403(pred, req, next).await }
    })
}

#[cfg(all(feature = "tenancy", feature = "postgres"))]
async fn handle_user_passes_test_or_403<F>(pred: Arc<F>, req: Request<Body>, next: Next) -> Response
where
    F: Fn(&crate::tenancy::auth::User) -> bool + Send + Sync + 'static,
{
    use axum::extract::FromRequestParts as _;
    let (mut parts, body) = req.into_parts();
    let user = crate::extractors::SessionUser::from_request_parts(&mut parts, &())
        .await
        .unwrap_or(crate::extractors::SessionUser(None));
    match user.0.as_ref() {
        None => Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .body(Body::empty())
            .expect("401 + empty body is always valid"),
        Some(u) if pred(u) => {
            let req = Request::from_parts(parts, body);
            next.run(req).await
        }
        Some(_) => Response::builder()
            .status(StatusCode::FORBIDDEN)
            .body(Body::empty())
            .expect("403 + empty body is always valid"),
    }
}

/// Authentication-only gate that returns 401 on anonymous requests
/// (instead of redirecting). The API-endpoint counterpart to
/// [`login_required`]; equivalent to
/// `user_passes_test_or_403(|_| true)` but reads tighter at call
/// sites.
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn login_required_or_401() -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone {
    user_passes_test_or_403(|_| true)
}

/// Convenience wrapper: gate a route to active superusers only.
/// Equivalent to
/// `user_passes_test(login_url, |u| u.is_superuser && u.active)`
/// but reads tighter at call sites and pins the common
/// "is_superuser && active" predicate so individual handlers don't
/// silently diverge on whether `active = false` users still count.
///
/// ```ignore
/// use rustango::auth_decorators::superuser_required;
///
/// let admin_routes = Router::new()
///     .route("/admin/dashboard", get(dashboard))
///     .layer(superuser_required("/login"));
/// ```
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn superuser_required(
    login_url: impl Into<String>,
) -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone {
    user_passes_test(login_url, |u| u.is_superuser && u.active)
}

/// API-endpoint variant of [`superuser_required`] — returns
/// 401 for anonymous and 403 for non-superuser, instead of
/// redirecting.
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn superuser_required_or_403() -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone {
    user_passes_test_or_403(|u| u.is_superuser && u.active)
}

/// Convenience wrapper: gate a route to active users only.
/// Anonymous sessions and deactivated accounts (`active = false`)
/// are 302'd to `login_url`. Equivalent to
/// `user_passes_test(login_url, |u| u.active)`.
///
/// Useful when a route should be open to any logged-in user, but
/// the operator console has marked some accounts as inactive
/// (suspended billing, security freeze, etc.) and those shouldn't
/// be able to access ANYTHING.
///
/// Note that [`login_required`] already only counts logged-in
/// users — but if the underlying SessionUser extractor was extended
/// to surface deactivated accounts (it currently filters them out
/// via `u.active` already), this gate would still be correct. Use
/// it when you want the active-only invariant explicit at the call
/// site.
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn active_required(
    login_url: impl Into<String>,
) -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone {
    user_passes_test(login_url, |u| u.active)
}

/// API-endpoint variant of [`active_required`] — returns 401 for
/// anonymous and 403 for deactivated accounts, instead of
/// redirecting.
#[cfg(all(feature = "tenancy", feature = "postgres"))]
pub fn active_required_or_403() -> impl tower::Layer<
    axum::routing::Route,
    Service = impl tower::Service<
        Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Send + 'static,
    > + Clone
                  + Send
                  + Sync
                  + 'static,
> + Clone {
    user_passes_test_or_403(|u| u.active)
}

#[cfg(all(feature = "tenancy", feature = "postgres"))]
async fn handle_login_required(
    cfg: Arc<LoginRequiredConfig>,
    req: Request<Body>,
    next: Next,
) -> Response {
    use axum::extract::FromRequestParts as _;
    // Run the SessionUser extractor manually so we don't have to pass
    // it as a `from_fn` argument (which would require SessionUser to
    // implement `FromRequest`, not just `FromRequestParts`).
    let (mut parts, body) = req.into_parts();
    let user = crate::extractors::SessionUser::from_request_parts(&mut parts, &())
        .await
        .unwrap_or(crate::extractors::SessionUser(None));
    if user.0.is_some() {
        let req = Request::from_parts(parts, body);
        return next.run(req).await;
    }
    // Anonymous — build the 302 target from the original URL.
    let original = parts
        .uri
        .path_and_query()
        .map(|p| p.as_str().to_owned())
        .unwrap_or_else(|| "/".to_owned());
    redirect_to_login(&cfg.login_url, &cfg.redirect_field, &original)
}

/// Build the 302 response that points at `login_url` with `?next=`
/// carrying the URL-encoded `original` path. Surfaces as `pub` so
/// non-session auth flavors that gate handlers manually can reuse
/// the same redirect shape.
#[must_use]
pub fn redirect_to_login(login_url: &str, redirect_field: &str, original: &str) -> Response {
    let target = build_login_url(login_url, redirect_field, original);
    let mut res = Response::builder()
        .status(StatusCode::FOUND)
        .body(Body::empty())
        .expect("302 + empty body is always valid");
    if let Ok(v) = HeaderValue::from_str(&target) {
        res.headers_mut().insert(header::LOCATION, v);
    }
    res
}

fn build_login_url(login_url: &str, redirect_field: &str, original: &str) -> String {
    let encoded = crate::url_codec::url_encode(original);
    let sep = if login_url.contains('?') { '&' } else { '?' };
    format!("{login_url}{sep}{redirect_field}={encoded}")
}

// ------------------------------------------------------------------ login-handler helpers

/// Read the `next` query parameter out of a `Query<HashMap<...>>`-like
/// map. Returns `None` when absent or empty (callers fall back to a
/// default destination — typically `"/"`).
#[must_use]
pub fn extract_next(query: &HashMap<String, String>) -> Option<String> {
    extract_next_named(query, "next")
}

/// Same as [`extract_next`] but with a custom field name to match a
/// non-default [`LoginRequiredConfig::redirect_field`].
#[must_use]
pub fn extract_next_named(query: &HashMap<String, String>, field: &str) -> Option<String> {
    query
        .get(field)
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty())
}

/// Open-redirect defense: returns `Some(next)` only when `next` is
/// safe to redirect to — a same-origin, root-relative path. Rejects:
///
/// - Scheme-prefixed URLs (`http://evil.example/`, `//evil.example/x`)
/// - Backslash variants the browser normalizes to a host
///   (`/\evil.example/x`)
/// - Percent-encoded variants of the above
///   (`%2F%2Fevil.example/x` decodes to `//evil.example/x`)
/// - Empty / whitespace
///
/// ```rust
/// use rustango::auth_decorators::safe_next;
/// assert_eq!(safe_next("/profile"), Some("/profile".to_owned()));
/// assert_eq!(safe_next("http://evil.example/x"), None);
/// assert_eq!(safe_next("//evil.example/x"), None);
/// assert_eq!(safe_next("/\\evil.example/x"), None);
/// assert_eq!(safe_next("%2F%2Fevil.example/x"), None);  // decoded → //evil
/// assert_eq!(safe_next(""), None);
/// ```
///
/// **Does NOT validate** that the path resolves to a real route —
/// that's a feature, not a bug. A 404 after login is far better than
/// shipping a phishing redirect through your auth handler.
#[must_use]
pub fn safe_next(next: &str) -> Option<String> {
    let trimmed = next.trim();
    if trimmed.is_empty() {
        return None;
    }
    // Percent-decode first so encoded bypass attempts
    // (`%2F%2Fevil.example/x` → `//evil.example/x`) are caught by the
    // string-shape checks below. We discard the decoded form after
    // validation and return the original trimmed input — that way
    // double-encoded sequences in legitimate paths survive the
    // redirect intact.
    let decoded = crate::url_codec::url_decode(trimmed);
    if !is_safe_path(&decoded) {
        return None;
    }
    // Original may differ from decoded if it contained percent-escapes;
    // both forms must be path-shaped.
    if !is_safe_path(trimmed) {
        return None;
    }
    Some(trimmed.to_owned())
}

/// Shared check used on both the raw and percent-decoded forms of
/// the `next` value. Path must start with `/` and must NOT start
/// with `//` (scheme-relative) or `/\` (backslash-host).
fn is_safe_path(s: &str) -> bool {
    if !s.starts_with('/') {
        return false;
    }
    if s.starts_with("//") {
        return false;
    }
    if s.starts_with("/\\") {
        return false;
    }
    true
}

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

    #[test]
    fn build_login_url_appends_next_as_query() {
        let url = build_login_url("/login", "next", "/protected");
        assert_eq!(url, "/login?next=%2Fprotected");
    }

    #[test]
    fn build_login_url_uses_ampersand_when_login_already_has_query() {
        let url = build_login_url("/login?foo=1", "next", "/protected");
        assert_eq!(url, "/login?foo=1&next=%2Fprotected");
    }

    #[test]
    fn build_login_url_url_encodes_path_with_special_chars() {
        let url = build_login_url("/login", "next", "/posts/hello world?page=2");
        // Space → %20, `?` → %3F, `=` → %3D so the inner query is
        // safely captured as a single `next` value.
        assert!(url.contains("%20"));
        assert!(url.contains("%3F") || url.contains("%26") || url.contains("page%3D2"));
    }

    #[test]
    fn redirect_to_login_returns_302_with_location() {
        let res = redirect_to_login("/login", "next", "/profile");
        assert_eq!(res.status(), StatusCode::FOUND);
        let loc = res
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert_eq!(loc, "/login?next=%2Fprofile");
    }

    #[test]
    fn redirect_to_login_drops_location_on_crlf_attempt() {
        // CRLF in original URL is a response-splitting vector. The
        // builder percent-encodes the value before insertion so no
        // raw CRLF reaches the header — that's the safety invariant
        // worth asserting (not the specific encoded form, which is
        // a url_encode implementation detail).
        let res = redirect_to_login("/login", "next", "/profile\r\nSet-Cookie: pwned=1");
        assert_eq!(res.status(), StatusCode::FOUND);
        let loc = res
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert!(!loc.contains('\r'), "raw \\r in Location header: {loc}");
        assert!(!loc.contains('\n'), "raw \\n in Location header: {loc}");
    }

    #[test]
    fn extract_next_returns_value_when_present() {
        let mut q = HashMap::new();
        q.insert("next".to_owned(), "/profile".to_owned());
        assert_eq!(extract_next(&q), Some("/profile".to_owned()));
    }

    #[test]
    fn extract_next_returns_none_when_absent_or_empty() {
        assert_eq!(extract_next(&HashMap::new()), None);
        let mut q = HashMap::new();
        q.insert("next".to_owned(), "".to_owned());
        assert_eq!(extract_next(&q), None);
        q.insert("next".to_owned(), "   ".to_owned());
        assert_eq!(extract_next(&q), None);
    }

    #[test]
    fn extract_next_named_uses_custom_field() {
        let mut q = HashMap::new();
        q.insert("redirect_to".to_owned(), "/profile".to_owned());
        assert_eq!(extract_next(&q), None);
        assert_eq!(
            extract_next_named(&q, "redirect_to"),
            Some("/profile".to_owned())
        );
    }

    #[test]
    fn safe_next_accepts_root_relative_paths() {
        assert_eq!(safe_next("/profile"), Some("/profile".to_owned()));
        assert_eq!(safe_next("/posts/42"), Some("/posts/42".to_owned()));
        assert_eq!(
            safe_next("/search?q=hello"),
            Some("/search?q=hello".to_owned())
        );
    }

    #[test]
    fn safe_next_rejects_absolute_urls() {
        assert_eq!(safe_next("http://evil.example/x"), None);
        assert_eq!(safe_next("https://evil.example/x"), None);
        assert_eq!(safe_next("ftp://evil.example/"), None);
        // Scheme-relative (network-path reference) is a phishing
        // vector — browsers route this to <host>/x.
        assert_eq!(safe_next("//evil.example/x"), None);
    }

    #[test]
    fn safe_next_rejects_backslash_variant() {
        // `/\evil.example/x` — some browsers normalize the backslash
        // to a forward slash, producing `//evil.example/x` which
        // routes to the attacker's host.
        assert_eq!(safe_next("/\\evil.example/x"), None);
    }

    #[test]
    fn safe_next_rejects_percent_encoded_bypass() {
        // The raw `next` value passes the path-starts-with-`/` check
        // but percent-decodes to `//evil.example/x` — a phishing
        // redirect. Defense: decode before validating.
        assert_eq!(safe_next("%2F%2Fevil.example/x"), None);
        assert_eq!(safe_next("%2f%2fevil.example/x"), None);
        // Double-slash with the second slash encoded.
        assert_eq!(safe_next("/%2Fevil.example/x"), None);
        // Backslash variant percent-encoded.
        assert_eq!(safe_next("/%5Cevil.example/x"), None);
    }

    #[test]
    fn safe_next_accepts_legitimate_percent_encodes_in_path() {
        // A path containing literal `%20` (encoded space) should still
        // be valid — `safe_next` doesn't reject every percent-encode,
        // just the ones that decode to host-routing patterns.
        assert_eq!(
            safe_next("/profile/hello%20world"),
            Some("/profile/hello%20world".to_owned())
        );
    }

    #[test]
    fn safe_next_rejects_empty_and_whitespace() {
        assert_eq!(safe_next(""), None);
        assert_eq!(safe_next("   "), None);
        assert_eq!(safe_next("\t\n"), None);
    }

    #[test]
    fn safe_next_strips_surrounding_whitespace() {
        assert_eq!(safe_next("  /profile  "), Some("/profile".to_owned()));
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn login_required_layer_redirects_anonymous_to_login_url() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

        async fn protected() -> &'static str {
            "secret"
        }

        let app = Router::new()
            .route("/profile", get(protected))
            .layer(login_required("/login"));

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/profile")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // No SessionUser → no TenantContext → extractor returns None
        // → middleware 302s to /login?next=/profile.
        assert_eq!(res.status(), StatusCode::FOUND);
        let loc = res
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert_eq!(loc, "/login?next=%2Fprofile");
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn user_passes_test_redirects_anonymous_to_login_url() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

        async fn staff_only() -> &'static str {
            "staff zone"
        }

        // Predicate is never called when the request is anonymous —
        // the gate short-circuits to the redirect.
        let app = Router::new()
            .route("/admin/dashboard", get(staff_only))
            .layer(user_passes_test("/login", |u| u.is_superuser));

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/admin/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::FOUND);
        let loc = res
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert_eq!(loc, "/login?next=%2Fadmin%2Fdashboard");
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[test]
    fn user_passes_test_signature_compiles_with_closure_predicate() {
        // Compile-only: pin the signature so the predicate can be
        // a closure capturing locals. The body never runs.
        let _ = || {
            let _layer = user_passes_test("/login", |u: &crate::tenancy::auth::User| {
                u.is_superuser && u.active
            });
        };
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn user_passes_test_or_403_returns_401_for_anonymous() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

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

        let app = Router::new()
            .route("/api/admin/stats", get(admin_only))
            .layer(user_passes_test_or_403(|u| u.is_superuser));

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/api/admin/stats")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // No SessionUser → 401 (not authenticated). Distinct from
        // 403 (authenticated-but-not-allowed) so clients can
        // distinguish.
        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[test]
    fn login_required_or_401_signature_compiles() {
        // Compile-only: the no-arg variant is sugar over
        // `user_passes_test_or_403(|_| true)`. Pin the signature.
        let _ = || {
            let _layer = login_required_or_401();
        };
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn superuser_required_redirects_anonymous_to_login() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

        async fn admin_only() -> &'static str {
            "admin zone"
        }

        let app = Router::new()
            .route("/admin/dashboard", get(admin_only))
            .layer(superuser_required("/login"));

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/admin/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::FOUND);
        let loc = res
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert_eq!(loc, "/login?next=%2Fadmin%2Fdashboard");
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn superuser_required_or_403_returns_401_for_anonymous() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

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

        let app = Router::new()
            .route("/api/admin", get(admin_api))
            .layer(superuser_required_or_403());

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/api/admin")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn active_required_redirects_anonymous_to_login() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

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

        let app = Router::new()
            .route("/dashboard", get(dashboard))
            .layer(active_required("/login"));

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::FOUND);
        let loc = res
            .headers()
            .get(header::LOCATION)
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert_eq!(loc, "/login?next=%2Fdashboard");
    }

    #[cfg(all(feature = "tenancy", feature = "postgres"))]
    #[tokio::test]
    async fn active_required_or_403_returns_401_for_anonymous() {
        use axum::body::Body;
        use axum::routing::get;
        use axum::Router;
        use tower::ServiceExt as _;

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

        let app = Router::new()
            .route("/api/me", get(me_api))
            .layer(active_required_or_403());

        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/api/me")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    }
}