rustio-admin 0.7.1

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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//! 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),
}

/// Paths a user with `must_change_password = TRUE` is allowed to
/// reach without first completing the forced rotation.
/// Locked-decision per `DESIGN_R2_ORGANISATIONAL.md` §12.
///
/// Exact-path match (no prefix matching). Sub-paths of
/// `/admin/account/sessions` (e.g. `/admin/account/sessions/revoke`)
/// are intentionally NOT whitelisted — a user being forced to
/// rotate may view their active sessions but must finish the
/// rotation before revoking siblings.
const MUST_CHANGE_WHITELIST: &[&str] = &[
    "/admin/must-change-password",
    "/admin/logout",
    "/admin/account/sessions",
];

/// Whether `path` is on the must-change-password whitelist.
/// Pulled out as a free fn so the rule is unit-testable without a
/// `Request`. See [`MUST_CHANGE_WHITELIST`] for the contract.
fn is_must_change_whitelisted_path(path: &str) -> bool {
    MUST_CHANGE_WHITELIST.contains(&path)
}

/// Paths reachable when `MfaPolicy::Required` is active and the
/// user has not yet enrolled (R3 commit #18). Forward-only
/// enforcement per `DESIGN_R3_MFA.md` D6: existing sessions
/// continue to work, but every non-whitelisted request from a
/// not-yet-enrolled user redirects to the enrolment form.
/// Mirrors [`MUST_CHANGE_WHITELIST`]'s shape so the two
/// interstitial flows compose identically when both gates fire.
///
/// Exact-path match. Sub-paths of `/admin/account/sessions`
/// (e.g. `/admin/account/sessions/revoke`) are NOT whitelisted
/// — a user being forced to enrol may view their active
/// sessions but must finish enrolment before revoking siblings.
const MFA_ENROLL_WHITELIST: &[&str] = &[
    "/admin/account/mfa/enroll",
    "/admin/logout",
    "/admin/account/sessions",
];

fn is_mfa_enroll_whitelisted_path(path: &str) -> bool {
    MFA_ENROLL_WHITELIST.contains(&path)
}

/// Paths reachable when the user has MFA enrolled but the
/// current session has not yet been promoted to `mfa_verified`
/// (the post-password, pre-MFA-verify window from R3 commit
/// #16's `do_login`). The user can complete the second-factor
/// verify, log out, or inspect their active sessions — nothing
/// else.
///
/// Exact-path match. See [`MFA_ENROLL_WHITELIST`] for the
/// rationale around the sessions page.
const MFA_VERIFY_WHITELIST: &[&str] = &[
    "/admin/mfa/verify",
    "/admin/logout",
    "/admin/account/sessions",
];

fn is_mfa_verify_whitelisted_path(path: &str) -> bool {
    MFA_VERIFY_WHITELIST.contains(&path)
}

/// Whether the active `MfaPolicy` requires MFA for a given
/// role. Pulled out as a free fn so the rule is unit-testable
/// without an `Admin` context.
///
/// `MfaPolicy::Disabled` / `Optional` → never required.
/// `MfaPolicy::Required` → required for every role.
/// `MfaPolicy::RequiredForRoles(roles)` → required iff the
///   user's role appears in the slice. An empty slice reads
///   as "no role requires MFA" — equivalent to `Optional`.
fn mfa_required_for_role(policy: crate::auth::MfaPolicy, role: Role) -> bool {
    use crate::auth::MfaPolicy;
    match policy {
        MfaPolicy::Disabled | MfaPolicy::Optional => false,
        MfaPolicy::Required => true,
        MfaPolicy::RequiredForRoles(roles) => roles.contains(&role),
    }
}

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")));
    }

    // R2 forced-rotation gate (`DESIGN_R2_ORGANISATIONAL.md` §3.4 +
    // §9.2). When the flag is set, every authenticated request EXCEPT
    // the whitelist redirects to `/admin/must-change-password`. The
    // check sits BEFORE any role gate so even Administrators /
    // Developers with the flag set are funnelled through.
    if ident.must_change_password && !is_must_change_whitelisted_path(req.path()) {
        return Ok(Guard::Redirect(Response::redirect(
            "/admin/must-change-password",
        )));
    }

    // R3 MFA-required gate — forward-only per D6
    // (`DESIGN_R3_MFA.md` §12.3). When the active MfaPolicy
    // requires MFA for this user's role AND they have not
    // enrolled, every non-whitelisted request redirects to the
    // enrolment form. Existing sessions continue to work; the
    // redirect kicks in at the NEXT request, not at the moment
    // the policy flips. This matches R2's must-change-password
    // shape — see MFA_ENROLL_WHITELIST for the reachable paths.
    let policy = ctx.admin.active_mfa_policy();
    if mfa_required_for_role(policy, ident.role)
        && !ident.mfa_enabled
        && !is_mfa_enroll_whitelisted_path(req.path())
    {
        return Ok(Guard::Redirect(Response::redirect(
            "/admin/account/mfa/enroll",
        )));
    }

    // R3 pending-MFA-verify gate (`DESIGN_R3_MFA.md` §4.2 +
    // §12.3). When the user has MFA enrolled but the current
    // session has not yet been promoted to mfa_verified (the
    // post-password, pre-MFA-verify window from commit #16's
    // do_login), restrict access to the MFA verify whitelist.
    // The verify POST handler rotates the session via
    // promote_session_to_mfa_verified once both factors land.
    use crate::auth::SessionTrust;
    if ident.mfa_enabled
        && ident.trust_level != SessionTrust::MfaVerified
        && !is_mfa_verify_whitelisted_path(req.path())
    {
        return Ok(Guard::Redirect(Response::redirect("/admin/mfa/verify")));
    }

    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,
            }
        }
    });

    // === R2 re-auth wall (R2 commit #11) ====================================
    //
    // Standalone wall: any authenticated user can promote their own
    // session into the elevated band by re-entering their password.
    // The handler validates `return_to` strictly (only `/admin*`
    // paths; see `admin_recovery_handlers::validate_return_to`).
    // Any role from User-tier upward.

    let c = ctx.clone();
    let router = router.get("/admin/reauth", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::admin_recovery_handlers::show_reauth(&c, ident, &req).await
                }
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/reauth", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::admin_recovery_handlers::do_reauth(&c, ident, req).await
                }
            }
        }
    });

    // === R2 forced password rotation (R2 commit #12) ========================
    //
    // The `must_change_password` interstitial is the only writeable
    // surface a user can reach while their flag is TRUE. The path is
    // on `MUST_CHANGE_WHITELIST`; the `login_guard` redirect therefore
    // skips it (otherwise the rotation would be unreachable). Role::User
    // matches: any authenticated user can be forced to rotate, even a
    // User-tier account that can't access the dashboard.

    let c = ctx.clone();
    let router = router.get("/admin/must-change-password", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::admin_recovery_handlers::show_must_change_password(&c, ident, &req).await
                }
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/must-change-password", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => {
                    super::admin_recovery_handlers::do_must_change_password(&c, ident, req).await
                }
            }
        }
    });

    // === R3 MFA surface (R3 commits #12-#15) ================================
    //
    // Eight routes:
    //   /admin/mfa/verify                        — login second factor (#12)
    //   /admin/account/mfa/enroll                — provision + confirm (#13)
    //   /admin/account/mfa/regenerate-codes      — atomic batch swap   (#14)
    //   /admin/account/mfa/disable               — self-disable        (#15)
    //
    // All gated by `Role::User` — every authenticated user can manage
    // their own MFA. The /admin/mfa/verify path is on
    // `MFA_VERIFY_WHITELIST`; the enrol path is on
    // `MFA_ENROLL_WHITELIST` — so `login_guard` does NOT redirect
    // away from these routes even when the user is in the pending-
    // verify or required-enrol state. Otherwise the interstitial
    // pages would be unreachable.

    // --- /admin/mfa/verify (R3 commit #12) ---
    let c = ctx.clone();
    let router = router.get("/admin/mfa/verify", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::show_verify(&c, ident, &req).await,
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/mfa/verify", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::do_verify(&c, ident, req).await,
            }
        }
    });

    // --- /admin/account/mfa/enroll (R3 commit #13) ---
    let c = ctx.clone();
    let router = router.get("/admin/account/mfa/enroll", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::show_enroll(&c, ident, &req).await,
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/account/mfa/enroll", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::do_enroll(&c, ident, req).await,
            }
        }
    });

    // --- /admin/account/mfa/regenerate-codes (R3 commit #14) ---
    let c = ctx.clone();
    let router = router.get("/admin/account/mfa/regenerate-codes", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::show_regenerate(&c, ident, &req).await,
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/account/mfa/regenerate-codes", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::do_regenerate(&c, ident, req).await,
            }
        }
    });

    // --- /admin/account/mfa/disable (R3 commit #15) ---
    let c = ctx.clone();
    let router = router.get("/admin/account/mfa/disable", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::show_disable(&c, ident, &req).await,
            }
        }
    });

    let c = ctx.clone();
    let router = router.post("/admin/account/mfa/disable", move |req| {
        let c = c.clone();
        async move {
            match role_guard(&c, &req, Role::User).await? {
                Guard::Redirect(r) => Ok(r),
                Guard::Allow(ident) => super::mfa_handlers::do_disable(&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
                }
            }
        }
    });

    // === R2 admin-driven recovery routes ====================================
    //
    // Registered alongside the existing `/admin/users/:id/...` cluster
    // (per `DESIGN_R2_ORGANISATIONAL.md` §7.2 — user-related cluster
    // contiguous). All gated `Role::Administrator`; the cross-rank
    // safety check + the re-auth wall are enforced INSIDE the
    // handlers (commits #15 / #16) so a Supervisor probe doesn't even
    // reach the form.
    //
    // Insertion-order note: these are 4-segment routes, so the
    // 3-segment `/admin/users/:id` read-only view further down doesn't
    // conflict regardless of order. Placing them before the 3-segment
    // view keeps the user routes lexically clustered.

    // GET /admin/users/:id/reset-password — admin reset form (R2 #15).
    let c = ctx.clone();
    let router = router.get("/admin/users/:id/reset-password", move |req| {
        let c = c.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::admin_recovery_handlers::show_admin_reset_password(&c, ident, id, &req)
                        .await
                }
            }
        }
    });

    // POST /admin/users/:id/reset-password — apply admin reset (R2 #15).
    let c = ctx.clone();
    let router = router.post("/admin/users/:id/reset-password", move |req| {
        let c = c.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::admin_recovery_handlers::do_admin_reset_password(&c, ident, id, req)
                        .await
                }
            }
        }
    });

    // GET /admin/users/:id/lock — lock confirmation form (R2 #16).
    let c = ctx.clone();
    let router = router.get("/admin/users/:id/lock", move |req| {
        let c = c.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::admin_recovery_handlers::show_lock_user(&c, ident, id, &req).await
                }
            }
        }
    });

    // POST /admin/users/:id/lock — apply manual lock (R2 #16).
    let c = ctx.clone();
    let router = router.post("/admin/users/:id/lock", move |req| {
        let c = c.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::admin_recovery_handlers::do_lock_user(&c, ident, id, req).await
                }
            }
        }
    });

    // GET /admin/users/:id/unlock — unlock confirmation form (R2 #16).
    let c = ctx.clone();
    let router = router.get("/admin/users/:id/unlock", move |req| {
        let c = c.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::admin_recovery_handlers::show_unlock_user(&c, ident, id, &req).await
                }
            }
        }
    });

    // POST /admin/users/:id/unlock — clear lock (R2 #16).
    let c = ctx.clone();
    let router = router.post("/admin/users/:id/unlock", move |req| {
        let c = c.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::admin_recovery_handlers::do_unlock_user(&c, ident, id, req).await
                }
            }
        }
    });

    // GET /admin/users/:id/revoke-sessions — revoke confirmation form
    // (R2 #16).
    let c = ctx.clone();
    let router = router.get("/admin/users/:id/revoke-sessions", move |req| {
        let c = c.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::admin_recovery_handlers::show_admin_revoke_sessions(&c, ident, id, &req)
                        .await
                }
            }
        }
    });

    // POST /admin/users/:id/revoke-sessions — revoke all sessions (R2 #16).
    let c = ctx.clone();
    let router = router.post("/admin/users/:id/revoke-sessions", move |req| {
        let c = c.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::admin_recovery_handlers::do_admin_revoke_sessions(&c, 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,
            must_change_password: false,
            mfa_enabled: false,
            trust_level: crate::auth::SessionTrust::Authenticated,
        }
    }

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

    // ---- must-change-password whitelist (R2 commit #13) --------------------

    #[test]
    fn whitelist_accepts_the_three_locked_paths() {
        // Locked-decision per DESIGN_R2_ORGANISATIONAL.md §12.
        assert!(super::is_must_change_whitelisted_path(
            "/admin/must-change-password"
        ));
        assert!(super::is_must_change_whitelisted_path("/admin/logout"));
        assert!(super::is_must_change_whitelisted_path(
            "/admin/account/sessions"
        ));
    }

    #[test]
    fn whitelist_rejects_subpaths_of_account_sessions() {
        // Sub-paths of /admin/account/sessions (revoke buttons) are
        // intentionally NOT whitelisted — a user being forced to
        // rotate may VIEW their sessions but must finish the
        // rotation before revoking siblings.
        assert!(!super::is_must_change_whitelisted_path(
            "/admin/account/sessions/revoke"
        ));
        assert!(!super::is_must_change_whitelisted_path(
            "/admin/account/sessions/revoke-others"
        ));
        assert!(!super::is_must_change_whitelisted_path(
            "/admin/account/sessions/"
        ));
    }

    #[test]
    fn whitelist_rejects_other_admin_paths() {
        for path in [
            "/admin",
            "/admin/",
            "/admin/users",
            "/admin/users/42",
            "/admin/login",
            "/admin/password_change",
            "/admin/forgot-password",
            "/admin/reauth",
            "/admin/must-change-password/", // trailing slash → not exact
        ] {
            assert!(
                !super::is_must_change_whitelisted_path(path),
                "expected reject for {path:?}"
            );
        }
    }

    #[test]
    fn whitelist_rejects_paths_outside_admin_surface() {
        for path in ["/", "/login", "/static/admin.css", "/api"] {
            assert!(
                !super::is_must_change_whitelisted_path(path),
                "expected reject for {path:?}"
            );
        }
    }
}