rustio-admin 0.5.0

Django Admin, but for Rust. A small, focused admin framework.
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Admin route registration with permission checks.
//!
//! Every admin URL is gated by a specific permission:
//!   GET  /admin/:model            → posts.view_post
//!   GET  /admin/:model/new        → posts.add_post
//!   POST /admin/:model/new        → posts.add_post
//!   GET  /admin/:model/:id/edit   → posts.change_post
//!   POST /admin/:model/:id/edit   → posts.change_post
//!   GET  /admin/:model/:id/delete → posts.delete_post
//!   POST /admin/:model/:id/delete → posts.delete_post
//!
//! Administrator + Developer bypass every check (see
//! `Role::bypasses_group_checks`). Staff and Supervisor need the
//! specific permission granted either directly or via a group.
//!
//! Slimmed for Tier 1: the legacy file's developer stub routes
//! (`__schema__`, `__logs__`, `__sql_console__`) and the FK remote-
//! search endpoint have been dropped. Everything else — `/static/admin.css`
//! and `/static/admin.js` (P8), login/logout, dashboard,
//! /admin/users/*, /admin/groups/*, /admin/history,
//! /admin/password_change, /admin/:model/* CRUD,
//! /admin/:model/:id/history — is wired below.

use std::sync::Arc;

use crate::auth::{self, Identity, Role};
use crate::error::{Error, Result};
use crate::http::{Request, Response};
use crate::orm::Db;
use crate::router::Router;
use crate::templates::Templates;

/// Embedded stylesheet baked into the binary. P8 ships a single
/// hand-written CSS file; project overrides happen via
/// `Admin::theme(...)` (CSS custom properties) rather than an asset
/// override, so we don't expose a disk path here.
const ADMIN_CSS: &str = include_str!("../../assets/static/admin.css");

/// Embedded admin JS (theme toggle + sidebar drawer). ≤200 LOC, no
/// build step.
const ADMIN_JS: &str = include_str!("../../assets/static/admin.js");

/// Self-hosted fonts (SIL OFL-1.1, see assets/static/fonts/LICENSE.txt).
/// Bundling them as bytes keeps the single-binary deploy story intact
/// and avoids the FOUT/CDN round-trip every consuming app would
/// otherwise inherit from a Google Fonts <link>.
///
/// Latin: Geist (variable wght 100..900) + Geist Mono (variable wght
/// 100..900). Arabic: Tajawal (UI surfaces — buttons, sidebar, tables)
/// in 400/500/700, plus Noto Naskh Arabic (paragraph body, variable
/// wght 400..700).
const FONT_GEIST: &[u8] = include_bytes!("../../assets/static/fonts/Geist-Variable.woff2");
const FONT_GEIST_MONO: &[u8] = include_bytes!("../../assets/static/fonts/GeistMono-Variable.woff2");
const FONT_TAJAWAL_REG: &[u8] = include_bytes!("../../assets/static/fonts/Tajawal-Regular.woff2");
const FONT_TAJAWAL_MED: &[u8] = include_bytes!("../../assets/static/fonts/Tajawal-Medium.woff2");
const FONT_TAJAWAL_BOLD: &[u8] = include_bytes!("../../assets/static/fonts/Tajawal-Bold.woff2");
const FONT_NOTO_NASKH_AR: &[u8] =
    include_bytes!("../../assets/static/fonts/NotoNaskhArabic-Variable.woff2");

use super::handlers::{self, AdminCtx};
use super::render;
use super::types::Admin;

/// Either an identity + a permission check passed, or any non-Allow
/// response the route closure should return as-is (a 303 redirect to
/// /admin/login, a 403 forbidden body, etc.).
enum Guard {
    Allow(Identity),
    Redirect(Response),
}

async fn login_guard(ctx: &AdminCtx, req: &Request) -> Result<Guard> {
    let cookie = match req.header("cookie") {
        Some(c) => c,
        None => return Ok(Guard::Redirect(Response::redirect("/admin/login"))),
    };
    let token = match auth::session_token_from_cookie(cookie) {
        Some(t) => t,
        None => return Ok(Guard::Redirect(Response::redirect("/admin/login"))),
    };
    let ident = match auth::identity_from_session(&ctx.db, &token).await? {
        Some(i) => i,
        None => return Ok(Guard::Redirect(Response::redirect("/admin/login"))),
    };
    if !ident.is_active {
        return Ok(Guard::Redirect(Response::redirect("/admin/login")));
    }
    Ok(Guard::Allow(ident))
}

async fn role_guard(ctx: &AdminCtx, req: &Request, min: Role) -> Result<Guard> {
    match login_guard(ctx, req).await? {
        Guard::Redirect(r) => Ok(Guard::Redirect(r)),
        Guard::Allow(ident) => {
            if ident.role.includes(min) {
                Ok(Guard::Allow(ident))
            } else {
                let body = render::render_forbidden_body(
                    &ctx.admin,
                    &ctx.templates,
                    &ident,
                    handlers::csrf_token(req),
                    None,
                    Some(min.label()),
                )?;
                Ok(Guard::Redirect(
                    Response::html(body).with_status(hyper::StatusCode::FORBIDDEN),
                ))
            }
        }
    }
}

async fn perm_guard(ctx: &AdminCtx, req: &Request, perm: &str) -> Result<Guard> {
    match role_guard(ctx, req, Role::Staff).await? {
        Guard::Redirect(r) => Ok(Guard::Redirect(r)),
        Guard::Allow(ident) => {
            if ident.role.bypasses_group_checks() {
                return Ok(Guard::Allow(ident));
            }
            if auth::check_permission(&ctx.db, &ident, perm).await? {
                Ok(Guard::Allow(ident))
            } else {
                let body = render::render_forbidden_body(
                    &ctx.admin,
                    &ctx.templates,
                    &ident,
                    handlers::csrf_token(req),
                    Some(perm.to_string()),
                    None,
                )?;
                Ok(Guard::Redirect(
                    Response::html(body).with_status(hyper::StatusCode::FORBIDDEN),
                ))
            }
        }
    }
}

/// Pure decision logic for `perm_guard`, factored out so it can be
/// unit-tested without a `Db`.
#[cfg(test)]
fn perm_guard_verdict(ident: &Identity, perm_held: bool) -> bool {
    if !ident.is_active {
        return false;
    }
    if ident.role.bypasses_group_checks() {
        return true;
    }
    perm_held
}

fn parse_id(raw: Option<&str>) -> Result<i64> {
    raw.and_then(|s| s.parse().ok())
        .ok_or_else(|| Error::BadRequest("invalid id".into()))
}

fn model_name_from_req(req: &Request) -> Result<String> {
    req.param("admin_name")
        .map(|s| s.to_string())
        .ok_or_else(|| Error::BadRequest("missing model".into()))
}

fn perm_for(ctx: &AdminCtx, admin_name: &str, action: &str) -> Result<String> {
    let entry = ctx
        .admin
        .find(admin_name)
        .ok_or_else(|| Error::NotFound(format!("no admin model: {admin_name}")))?;
    let singular = entry.singular_name.to_ascii_lowercase();
    Ok(format!("{admin_name}.{action}_{singular}"))
}

/// Pure verdict for the R1 strict-mailer boot guard
/// (`DESIGN_RECOVERY.md` §12.1). Returns an operator-facing error
/// string when the policy demands a real mailer but `Admin::new()`'s
/// default `LogMailer` is still in place; returns `Ok(())`
/// otherwise.
///
/// Detection is deterministic and structural: it reads
/// [`Admin::has_custom_mailer`] (set whenever
/// [`Admin::mailer`] has been called). No `Arc::ptr_eq` against a
/// freshly-constructed `LogMailer`; no environment heuristics; no
/// hostname checks; no "production mode" guessing — the operator
/// declares intent by calling `Admin::mailer(...)` (and opts the
/// policy in via `RecoveryPolicy::strict_mailer_required(true)`).
///
/// The framework treats an explicit `Admin::mailer(...)` call as
/// satisfying the guard even when the supplied mailer is itself a
/// `LogMailer` — this is the documented escape hatch for projects
/// that want to silence the guard during a migration window
/// without yet wiring a real transport.
fn strict_mailer_guard_check(admin: &Admin) -> std::result::Result<(), String> {
    if admin.active_recovery_policy().strict_mailer_required() && !admin.has_custom_mailer() {
        Err(
            "rustio-admin: RecoveryPolicy::strict_mailer_required() = true but no mailer \
             was registered via Admin::mailer(...).\n\n\
             The framework's default LogMailer writes recovery emails to log::info! instead \
             of sending them, which is unsuitable for production. Recovery routes are NOT \
             registered with this configuration.\n\n\
             To resolve, choose one:\n\
              (a) register a real mailer before calling register_admin_routes:\n\
                  Admin::mailer(Arc::new(MyProjectMailer::new(...)))\n\
              (b) opt the policy out of strict mode (the framework default — dev / CI / \
                  testing baseline):\n\
                  RecoveryPolicy::strict_mailer_required(false)\n\n\
             See DESIGN_RECOVERY.md §12.1 for the contract."
                .to_string(),
        )
    } else {
        Ok(())
    }
}

pub fn register_admin_routes(
    router: Router,
    admin: Admin,
    db: Db,
    templates: Arc<Templates>,
) -> Router {
    // R1 commit #9 — strict-mailer boot guard. Runs BEFORE any
    // route registration so a misconfigured deployment fails
    // loudly at startup rather than registering recovery routes
    // against a production-unsafe default mailer
    // (`DESIGN_RECOVERY.md` §12.1). The check is structural: see
    // [`strict_mailer_guard_check`] for why we don't do
    // pointer-equality tricks against the default LogMailer.
    if let Err(msg) = strict_mailer_guard_check(&admin) {
        panic!("{msg}");
    }

    let ctx = Arc::new(AdminCtx::new(
        Arc::new(admin),
        db.clone(),
        templates.clone(),
    ));

    // Bespoke user/group pages share the same DB / templates / Admin
    // arc but live in their own ctx type with the same shape.
    let auth_ctx = Arc::new(super::builtin::AuthAdminCtx {
        admin: ctx.admin.clone(),
        db,
        templates,
    });

    // Render `Err(_)` from /admin/* handlers as styled HTML instead of
    // the framework default `text/plain`. Non-admin paths bubble
    // through unchanged so JSON / curl consumers still get the text
    // body. `Error::Forbidden` (handled by `role_guard` via
    // `admin/forbidden.html`) and login-required redirects come
    // through as `Ok` responses and bypass this branch.
    let err_admin = ctx.admin.clone();
    let err_templates = ctx.templates.clone();
    let router = router.middleware(move |req, next| {
        let admin = err_admin.clone();
        let templates = err_templates.clone();
        Box::pin(async move {
            let is_admin_path = req.path().starts_with("/admin");
            let result = next.run(req).await;
            match result {
                Ok(resp) => Ok(resp),
                Err(err) if is_admin_path => Ok(render::render_admin_error_response(
                    &admin,
                    &templates,
                    None,
                    err.status(),
                    err.client_message().to_string(),
                )),
                Err(err) => Err(err),
            }
        })
    });

    // Embedded stylesheet + JS. The bytes are baked into the binary
    // so single-binary deploy is preserved. CSS/JS use `no-cache`
    // (revalidate every request) so theme + design tweaks roll out the
    // moment the binary restarts; fonts (next block) keep their long
    // immutable cache because their bytes never change per release.
    let router = router.get("/static/admin.css", |_req| async move {
        Ok(Response::new(
            hyper::StatusCode::OK,
            bytes::Bytes::from_static(ADMIN_CSS.as_bytes()),
        )
        .with_header("content-type", "text/css; charset=utf-8")
        .with_header("cache-control", "no-cache, must-revalidate"))
    });
    let router = router.get("/static/admin.js", |_req| async move {
        Ok(Response::new(
            hyper::StatusCode::OK,
            bytes::Bytes::from_static(ADMIN_JS.as_bytes()),
        )
        .with_header("content-type", "application/javascript; charset=utf-8")
        .with_header("cache-control", "no-cache, must-revalidate"))
    });

    // Self-hosted fonts. Cache aggressively: file contents are
    // immutable per build, so a 1-year cache is safe — the binary
    // ships a fresh copy on the next release.
    fn font_response(bytes: &'static [u8]) -> Response {
        Response::new(hyper::StatusCode::OK, bytes::Bytes::from_static(bytes))
            .with_header("content-type", "font/woff2")
            .with_header("cache-control", "public, max-age=31536000, immutable")
    }
    let router = router.get("/static/fonts/Geist-Variable.woff2", |_req| async move {
        Ok(font_response(FONT_GEIST))
    });
    let router = router.get(
        "/static/fonts/GeistMono-Variable.woff2",
        |_req| async move { Ok(font_response(FONT_GEIST_MONO)) },
    );
    let router = router.get("/static/fonts/Tajawal-Regular.woff2", |_req| async move {
        Ok(font_response(FONT_TAJAWAL_REG))
    });
    let router = router.get("/static/fonts/Tajawal-Medium.woff2", |_req| async move {
        Ok(font_response(FONT_TAJAWAL_MED))
    });
    let router = router.get("/static/fonts/Tajawal-Bold.woff2", |_req| async move {
        Ok(font_response(FONT_TAJAWAL_BOLD))
    });
    let router = router.get(
        "/static/fonts/NotoNaskhArabic-Variable.woff2",
        |_req| async move { Ok(font_response(FONT_NOTO_NASKH_AR)) },
    );

    // Public: login/logout.
    let c = ctx.clone();
    let router = router.get("/admin/login", move |req| {
        let c = c.clone();
        async move { handlers::show_login(&c, req).await }
    });

    let c = ctx.clone();
    let router = router.post("/admin/login", move |req| {
        let c = c.clone();
        async move { handlers::do_login(&c, req).await }
    });

    let c = ctx.clone();
    let router = router.post("/admin/logout", move |req| {
        let c = c.clone();
        async move { handlers::do_logout(&c, req).await }
    });

    // === R1 recovery routes ====================================
    //
    // MUST be registered BEFORE the `/admin/:admin_name` model
    // wildcards lower down — without that ordering, a request to
    // `/admin/forgot-password` would match `:admin_name =
    // "forgot-password"` and route into the model CRUD handler.
    //
    // Recovery state (the rate-limit buckets) is built once here
    // and cloned into each route closure so the buckets persist
    // for the process lifetime. No global / static / OnceLock —
    // the Arc lives in the closures.
    //
    // Strict-mailer boot guard already ran at the top of this fn
    // (would have panicked if misconfigured); reaching this block
    // means we have the operator's blessing to wire recovery.

    let recovery_state = Arc::new(super::recovery_handlers::RecoveryState::from_admin(
        &ctx.admin,
    ));

    let c = ctx.clone();
    let router = router.get("/admin/forgot-password", move |req| {
        let c = c.clone();
        async move { super::recovery_handlers::show_forgot_password(&c, &req).await }
    });

    let c = ctx.clone();
    let rs = recovery_state.clone();
    let router = router.post("/admin/forgot-password", move |req| {
        let c = c.clone();
        let rs = rs.clone();
        async move { super::recovery_handlers::do_forgot_password(&c, &rs, req).await }
    });

    let c = ctx.clone();
    let router = router.get("/admin/forgot-password/sent", move |req| {
        let c = c.clone();
        async move { super::recovery_handlers::show_forgot_password_sent(&c, &req).await }
    });

    let c = ctx.clone();
    let router = router.get("/admin/reset-password/:token", move |req| {
        let c = c.clone();
        async move {
            let token = req
                .param("token")
                .ok_or_else(|| Error::BadRequest("missing token".into()))?
                .to_string();
            super::recovery_handlers::show_reset_password(&c, &req, &token).await
        }
    });

    let c = ctx.clone();
    let rs = recovery_state.clone();
    let router = router.post("/admin/reset-password/:token", move |req| {
        let c = c.clone();
        let rs = rs.clone();
        async move {
            let token = req
                .param("token")
                .ok_or_else(|| Error::BadRequest("missing token".into()))?
                .to_string();
            super::recovery_handlers::do_reset_password(&c, &rs, req, &token).await
        }
    });

    // Dashboard — Staff floor. User-tier sees the forbidden page.
    let c = ctx.clone();
    let router = router.get("/admin", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::Staff).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::dashboard(&c, ident, &req).await,
            }
        }
    });

    // Global history log (admin-only; high-signal page).
    let c = ctx.clone();
    let router = router.get("/admin/history", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::show_log_entries(&c, ident, &req).await,
            }
        }
    });

    // Self-service active-sessions listing (R0). Any logged-in user
    // (User-tier and above) can see their own active sessions.
    let c = ctx.clone();
    let router = router.get("/admin/account/sessions", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::show_account_sessions(&c, ident, &req).await,
            }
        }
    });

    // R1 commit #10 — active-sessions revoke buttons. All three
    // POST routes go through `auth::invalidate_sessions` (Doctrine
    // 22) and write `AuditEvent::SessionsRevokedSelf` per revoked
    // id. The `/revoke-others` and `/revoke-all` literal segments
    // sit at depth-4 while `:id/revoke` sits at depth-5, so segment
    // count alone disambiguates them — no explicit ordering
    // constraint between the three.
    let c = ctx.clone();
    let router = router.post("/admin/account/sessions/revoke-others", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::do_revoke_other_sessions(&c, ident, req).await,
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/account/sessions/revoke-all", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::do_revoke_all_sessions(&c, ident, req).await,
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/account/sessions/:id/revoke", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    handlers::do_revoke_session(&c, ident, req, id).await
                }
            }
        }
    });

    // Self-service password change. Any logged-in user (User-tier and
    // above). User-tier can change their own password even though
    // they can't access the dashboard.
    let c = ctx.clone();
    let router = router.get("/admin/password_change", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::show_password_change(&c, ident, &req).await,
            }
        }
    });
    let c = ctx.clone();
    let router = router.post("/admin/password_change", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::do_password_change(&c, ident, req).await,
            }
        }
    });

    // --- Built-in users admin (admin-only) ---
    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/users", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::builtin::list_users(&ac, ident, handlers::csrf_token(&req)).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/users/new", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::builtin::show_new_user(&ac, ident, handlers::csrf_token(&req)).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.post("/admin/users/new", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::builtin::do_new_user(&ac, ident, req).await,
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/users/:id/edit", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::show_user_edit(&ac, ident, id, handlers::csrf_token(&req)).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.post("/admin/users/:id/edit", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::do_user_edit(&ac, ident, id, req).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/users/:id/delete", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::show_user_delete(&ac, ident, id, handlers::csrf_token(&req))
                        .await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.post("/admin/users/:id/delete", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::do_user_delete(&ac, ident, id, req).await
                }
            }
        }
    });

    // Read-only user profile view. MUST be registered AFTER
    // `/admin/users/new` and the `:id/edit` + `:id/delete` routes
    // above: the router matches in insertion order, and `:id` is a
    // wildcard that would happily swallow "new" or extra path
    // segments. Putting this last preserves the more-specific routes'
    // priority.
    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/users/:id", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    let q = req.query();
                    let tab = q.get("tab").map(|s| s.to_string());
                    let page: i64 = q.get("page").and_then(|s| s.parse().ok()).unwrap_or(1);
                    super::builtin::show_user_view(
                        &ac,
                        ident,
                        id,
                        handlers::csrf_token(&req),
                        tab,
                        page,
                    )
                    .await
                }
            }
        }
    });

    // --- Built-in groups admin (admin-only) ---
    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/groups", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::builtin::list_groups(&ac, ident, handlers::csrf_token(&req)).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/groups/new", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::builtin::show_new_group(&ac, ident, handlers::csrf_token(&req)).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.post("/admin/groups/new", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::builtin::do_new_group(&ac, ident, req).await,
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/groups/:id/edit", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::show_group_edit(&ac, ident, id, handlers::csrf_token(&req))
                        .await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.post("/admin/groups/:id/edit", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::do_group_edit(&ac, ident, id, req).await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.get("/admin/groups/:id/delete", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::show_group_delete(&ac, ident, id, handlers::csrf_token(&req))
                        .await
                }
            }
        }
    });

    let c = ctx.clone();
    let ac = auth_ctx.clone();
    let router = router.post("/admin/groups/:id/delete", move |req| {
        let c = c.clone();
        let ac = ac.clone();
        async move {
            match role_guard(&c, &req, Role::Administrator).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    super::builtin::do_group_delete(&ac, ident, id, req).await
                }
            }
        }
    });

    // Per-model list — needs `view` permission.
    let c = ctx.clone();
    let router = router.get("/admin/:admin_name", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "view")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::list_model(&c, ident, &name, &req).await,
            }
        }
    });

    // Create.
    let c = ctx.clone();
    let router = router.get("/admin/:admin_name/new", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "add")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::show_new_form(&c, ident, &name, &req).await,
            }
        }
    });
    let c = ctx.clone();
    let router = router.post("/admin/:admin_name/new", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "add")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::do_create(&c, ident, &name, req).await,
            }
        }
    });

    // Edit.
    let c = ctx.clone();
    let router = router.get("/admin/:admin_name/:id/edit", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "change")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    handlers::show_edit_form(&c, ident, &name, id, &req).await
                }
            }
        }
    });
    let c = ctx.clone();
    let router = router.post("/admin/:admin_name/:id/edit", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "change")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    handlers::do_update(&c, ident, &name, id, req).await
                }
            }
        }
    });

    // Per-object history. Read-only; same `view` permission as the
    // changelist (if you can list, you can read the audit trail).
    let c = ctx.clone();
    let router = router.get("/admin/:admin_name/:id/history", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "view")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    handlers::show_object_history(&c, ident, &name, id, &req).await
                }
            }
        }
    });

    // Delete.
    let c = ctx.clone();
    let router = router.get("/admin/:admin_name/:id/delete", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "delete")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    handlers::show_delete_confirm(&c, ident, &name, id, &req).await
                }
            }
        }
    });
    let c = ctx.clone();
    let router = router.post("/admin/:admin_name/:id/delete", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "delete")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    let id = parse_id(req.param("id"))?;
                    handlers::do_delete(&c, ident, &name, id).await
                }
            }
        }
    });

    // Bulk delete — same permission gate as the per-row delete.
    // Two-step flow: first POST renders the confirm page, second POST
    // (with `_confirmed=1`) executes. See `handlers::handle_bulk_delete`
    // for the full contract.
    let c = ctx.clone();
    let router = router.post("/admin/:admin_name/bulk_delete", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let perm = perm_for(&c, &name, "delete")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => handlers::handle_bulk_delete(&c, ident, &name, &req).await,
            }
        }
    });

    // Project-defined bulk actions. Permission gated on `change` —
    // bulk actions modify rows but don't delete them (delete has its
    // own route). Project-side guard against further write-vs-read
    // distinctions belongs inside `execute_bulk_action`.
    let c = ctx.clone();
    router.post("/admin/:admin_name/bulk/:action", move |req| {
        let c = c.clone();
        async move {
            let name = model_name_from_req(&req)?;
            let action = req
                .param("action")
                .ok_or_else(|| Error::BadRequest("missing bulk action name".into()))?
                .to_string();
            let perm = perm_for(&c, &name, "change")?;
            match perm_guard(&c, &req, &perm).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    handlers::handle_bulk_action(&c, ident, &name, &action, &req).await
                }
            }
        }
    })
}

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

    fn make_identity(role: Role, is_active: bool) -> Identity {
        Identity {
            user_id: 42,
            email: "test@example.com".into(),
            role,
            is_active,
            is_demo: false,
            demo_label: None,
        }
    }

    // role_guard's decision is `Role::includes(min)`. The 25-case
    // matrix lives in `auth::role::tests::includes_matrix_…`; the
    // cases below pin the most operator-relevant pairings.

    #[test]
    fn role_guard_decision_admin_meets_staff_floor() {
        let id = make_identity(Role::Administrator, true);
        assert!(id.role.includes(Role::Staff));
    }

    #[test]
    fn role_guard_decision_user_does_not_meet_staff() {
        let id = make_identity(Role::User, true);
        assert!(!id.role.includes(Role::Staff));
    }

    #[test]
    fn role_guard_decision_administrator_does_not_meet_developer() {
        let id = make_identity(Role::Administrator, true);
        assert!(!id.role.includes(Role::Developer));
    }

    #[test]
    fn role_guard_decision_developer_meets_everything() {
        let id = make_identity(Role::Developer, true);
        for &min in &[
            Role::User,
            Role::Staff,
            Role::Supervisor,
            Role::Administrator,
            Role::Developer,
        ] {
            assert!(id.role.includes(min), "Developer should meet {min:?}");
        }
    }

    // ---- perm_guard_verdict matrix --------------------------------------

    #[test]
    fn perm_guard_admin_short_circuits_without_perm() {
        let id = make_identity(Role::Administrator, true);
        assert!(perm_guard_verdict(&id, false));
    }

    #[test]
    fn perm_guard_developer_short_circuits_without_perm() {
        let id = make_identity(Role::Developer, true);
        assert!(perm_guard_verdict(&id, false));
    }

    #[test]
    fn perm_guard_staff_with_perm_passes() {
        let id = make_identity(Role::Staff, true);
        assert!(perm_guard_verdict(&id, true));
    }

    #[test]
    fn perm_guard_staff_without_perm_denies() {
        let id = make_identity(Role::Staff, true);
        assert!(!perm_guard_verdict(&id, false));
    }

    #[test]
    fn perm_guard_inactive_admin_denies_even_with_bypass() {
        // Defense-in-depth invariant.
        let id = make_identity(Role::Administrator, false);
        assert!(!perm_guard_verdict(&id, true));
    }

    #[test]
    fn perm_guard_supervisor_without_perm_denies() {
        // Supervisor doesn't bypass; needs the per-model perm.
        let id = make_identity(Role::Supervisor, true);
        assert!(!perm_guard_verdict(&id, false));
    }

    // ---- strict_mailer_guard_check ----------------------------------------

    /// Default `Admin::new()` doesn't override the mailer AND
    /// doesn't enable strict mode — the guard passes.
    #[test]
    fn strict_mailer_guard_passes_for_default_admin() {
        let admin = super::super::types::Admin::new();
        assert!(strict_mailer_guard_check(&admin).is_ok());
    }

    /// Strict-mailer mode + default LogMailer = boot guard fires.
    /// The error message is operator-actionable.
    #[test]
    fn strict_mailer_guard_fails_when_required_but_default_mailer() {
        use crate::auth::DefaultRecoveryPolicy;
        let admin = super::super::types::Admin::new().recovery_policy(std::sync::Arc::new(
            DefaultRecoveryPolicy::new().with_strict_mailer_required(true),
        ));
        let err = strict_mailer_guard_check(&admin).expect_err("guard should fail");
        assert!(
            err.contains("strict_mailer_required"),
            "error message must name the policy method: {err}"
        );
        assert!(
            err.contains("Admin::mailer"),
            "error message must direct the operator to the fix: {err}"
        );
    }

    /// Strict-mailer mode + project-supplied mailer = guard passes.
    /// Note: the explicit override flips the flag even when the
    /// supplied value happens to be another LogMailer — the
    /// operator's intent is what matters, not the concrete type.
    #[test]
    fn strict_mailer_guard_passes_when_mailer_was_explicitly_overridden() {
        use crate::auth::DefaultRecoveryPolicy;
        use crate::email::LogMailer;
        let admin = super::super::types::Admin::new()
            .recovery_policy(std::sync::Arc::new(
                DefaultRecoveryPolicy::new().with_strict_mailer_required(true),
            ))
            .mailer(std::sync::Arc::new(LogMailer));
        assert!(strict_mailer_guard_check(&admin).is_ok());
    }

    /// Project NOT in strict mode + default LogMailer = passes
    /// (dev / CI / testing baseline).
    #[test]
    fn strict_mailer_guard_passes_when_strict_mode_disabled() {
        let admin = super::super::types::Admin::new();
        assert!(strict_mailer_guard_check(&admin).is_ok());
    }
}