acme-proxy 0.2.0

An ACME (RFC 8555) server that issues from a local CA, relays to an upstream CA, or delegates to a script
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
//! The web admin's JSON API, driven through the real `build_admin_app`.
//!
//! Every case enters through the router, so the extractors, the layers and the
//! error shape are all exercised together — the same way `tests/orders.rs`
//! drives the ACME side.

mod common;

use acme_proxy::audit::{Actor, AuditEvent, AuditRecord, ClientContext};
use acme_proxy::sqlite::admin_session::AdminSession;
use acme_proxy::sqlite::audit::AuditEntry;
use axum::body::Body;
use axum::http::{Method, Request, StatusCode, header};
use common::*;
use serde_json::json;

// ---------------------------------------------------------------------------
// Sign-in
// ---------------------------------------------------------------------------

#[tokio::test]
async fn login_sets_a_hardened_cookie_and_returns_a_csrf_token() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database)
        .await
        .unwrap();

    let response = admin_request(
        &app,
        Method::POST,
        "/api/session",
        None,
        Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);

    // The cookie attributes, asserted one by one: each is load-bearing and a
    // future edit dropping any of them must fail here rather than in the wild.
    let set_cookie = response
        .headers()
        .get(header::SET_COOKIE)
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    assert!(set_cookie.starts_with("__Host-acme_admin_session="));
    assert!(set_cookie.contains("HttpOnly"));
    assert!(set_cookie.contains("Secure"));
    assert!(set_cookie.contains("SameSite=Strict"));
    assert!(set_cookie.contains("Path=/"));
    assert!(!set_cookie.contains("Domain"));

    let body = json_body(response).await;
    assert_eq!(body["user"]["username"], "alice");
    assert!(body["csrfToken"].as_str().is_some_and(|t| t.len() > 20));
    assert!(body["expiresAt"].as_str().is_some());
    // The response must never echo anything derived from the password.
    assert!(!body.to_string().contains("pbkdf2"));
}

#[tokio::test]
async fn every_login_failure_is_indistinguishable_to_the_client() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    acme_proxy::admin::users::create_user("bob", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    acme_proxy::admin::users::set_status("bob", "disabled", database)
        .await
        .unwrap();

    let mut bodies = Vec::new();
    for (username, password) in [
        ("alice", "the-wrong-password"),
        ("nobody-at-all", ADMIN_PASSWORD),
        ("bob", ADMIN_PASSWORD),
    ] {
        let response = admin_request(
            &app,
            Method::POST,
            "/api/session",
            None,
            Some(json!({ "username": username, "password": password })),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "for {username}"
        );
        assert!(
            session_cookie_token(&response).is_none(),
            "a failed login must not set a session cookie"
        );
        bodies.push(json_body(response).await);
    }

    // Wrong password, unknown user and disabled account: one answer.
    assert_eq!(bodies[0], bodies[1]);
    assert_eq!(bodies[1], bodies[2]);
    assert_eq!(bodies[0]["error"], "invalid_credentials");
}

#[tokio::test]
async fn login_is_rate_limited_before_the_password_hash_runs() {
    let mut config = admin_config();
    config.admin.login_max_attempts = 2;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database)
        .await
        .unwrap();

    let attempt = |password: &'static str| {
        let app = app.clone();
        async move {
            admin_request(
                &app,
                Method::POST,
                "/api/session",
                None,
                Some(json!({ "username": "alice", "password": password })),
            )
            .await
        }
    };

    for _ in 0..2 {
        assert_eq!(attempt("wrong").await.status(), StatusCode::UNAUTHORIZED);
    }

    let limited = attempt("wrong").await;
    assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(limited.headers().contains_key(header::RETRY_AFTER));
    assert_eq!(json_body(limited).await["error"], "rate_limited");

    // Even the *correct* password is refused while the window holds: the
    // limiter is what stops the expensive hash running at all.
    assert_eq!(
        attempt(ADMIN_PASSWORD).await.status(),
        StatusCode::TOO_MANY_REQUESTS
    );
}

/// Two sign-ins from two browsers are two independent sessions. Signing in on
/// a second machine must not log you out on the first.
#[tokio::test]
async fn a_second_login_without_a_cookie_is_a_second_independent_session() {
    let (app, _database, first) = test_admin_app_logged_in(admin_config()).await;
    let second = admin_login(&app, "alice", ADMIN_PASSWORD).await;

    assert_ne!(
        first.cookie, second.cookie,
        "each login mints its own token"
    );
    assert_ne!(first.csrf, second.csrf, "and its own CSRF token");
    for session in [&first, &second] {
        assert_eq!(
            admin_request(&app, Method::GET, "/api/session", Some(session), None)
                .await
                .status(),
            StatusCode::OK
        );
    }
}

/// Session fixation: a login that *carries* a session replaces it, so a cookie
/// planted in the victim's browser before they sign in is dead afterwards
/// rather than promoted to an authenticated one.
#[tokio::test]
async fn logging_in_with_a_cookie_already_set_destroys_that_session() {
    let (app, _database, planted) = test_admin_app_logged_in(admin_config()).await;

    // Log in again, this time presenting the existing cookie.
    let response = admin_request(
        &app,
        Method::POST,
        "/api/session",
        Some(&planted),
        Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let fresh_cookie = session_cookie_token(&response).expect("a new cookie must be set");
    assert_ne!(fresh_cookie, planted.cookie, "the token must rotate");

    // The presented session is gone.
    let refused = admin_request(&app, Method::GET, "/api/session", Some(&planted), None).await;
    assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(json_body(refused).await["error"], "session_invalid");
}

// ---------------------------------------------------------------------------
// Session lifecycle
// ---------------------------------------------------------------------------

#[tokio::test]
async fn whoami_needs_a_session_and_reports_the_operator() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let anonymous = admin_request(&app, Method::GET, "/api/session", None, None).await;
    assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(json_body(anonymous).await["error"], "session_invalid");

    let body =
        json_body(admin_request(&app, Method::GET, "/api/session", Some(&session), None).await)
            .await;
    assert_eq!(body["user"]["username"], "alice");
    assert_eq!(body["csrfToken"], session.csrf);
}

#[tokio::test]
async fn logout_clears_the_cookie_and_the_session_stops_working() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let response = admin_request(&app, Method::DELETE, "/api/session", Some(&session), None).await;
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
    let set_cookie = response
        .headers()
        .get(header::SET_COOKIE)
        .unwrap()
        .to_str()
        .unwrap();
    assert!(set_cookie.contains("Max-Age=0"));

    assert_eq!(
        admin_request(&app, Method::GET, "/api/session", Some(&session), None)
            .await
            .status(),
        StatusCode::UNAUTHORIZED
    );
}

#[tokio::test]
async fn a_session_deleted_out_from_under_the_request_stops_authenticating() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let user = acme_proxy::sqlite::admin_user::AdminUser::find_by_username("alice", &database)
        .await
        .unwrap()
        .unwrap();
    acme_proxy::sqlite::admin_session::AdminSession::delete_for_user(&user.id, &database)
        .await
        .unwrap();

    assert_eq!(
        admin_request(&app, Method::GET, "/api/session", Some(&session), None)
            .await
            .status(),
        StatusCode::UNAUTHORIZED
    );
}

#[tokio::test]
async fn an_expired_session_is_refused_and_swept() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let hash = acme_proxy::webadmin::session::hash_token(&session.cookie);
    sqlx::query("UPDATE admin_sessions SET expires_at = 1 WHERE token_hash = ?;")
        .bind(&hash)
        .execute(&database.pool)
        .await
        .unwrap();

    let response = admin_request(&app, Method::GET, "/api/session", Some(&session), None).await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(json_body(response).await["error"], "session_expired");

    // Refusing it also removed it, rather than leaving a dead row behind.
    assert!(
        acme_proxy::sqlite::admin_session::AdminSession::find_by_token_hash(&hash, &database)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
async fn an_idle_session_is_refused_with_its_own_code() {
    let mut config = admin_config();
    config.admin.session_idle_timeout_seconds = 60;
    let (app, database, session) = test_admin_app_logged_in(config).await;

    let hash = acme_proxy::webadmin::session::hash_token(&session.cookie);
    sqlx::query(
        "UPDATE admin_sessions SET last_seen_at = last_seen_at - 600 WHERE token_hash = ?;",
    )
    .bind(&hash)
    .execute(&database.pool)
    .await
    .unwrap();

    let response = admin_request(&app, Method::GET, "/api/session", Some(&session), None).await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(json_body(response).await["error"], "session_idle");
}

#[tokio::test]
async fn disabling_an_operator_stops_their_live_session() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    assert_eq!(
        admin_request(&app, Method::GET, "/api/session", Some(&session), None)
            .await
            .status(),
        StatusCode::OK
    );

    acme_proxy::admin::users::set_status("alice", "disabled", database)
        .await
        .unwrap();
    assert_eq!(
        admin_request(&app, Method::GET, "/api/session", Some(&session), None)
            .await
            .status(),
        StatusCode::UNAUTHORIZED
    );
}

// ---------------------------------------------------------------------------
// Second factor
// ---------------------------------------------------------------------------

/// The guard on every other admin test in this repository.
///
/// `test_admin_app_logged_in` and `admin_login` are the choke point ~40 cases go
/// through, and adding a second login step must not have moved what an operator
/// with no factor sees. Deliberately first in this section.
#[tokio::test]
async fn a_factorless_login_is_completely_unchanged() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database)
        .await
        .unwrap();

    let response = admin_request(
        &app,
        Method::POST,
        "/api/session",
        None,
        Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);

    let cookie = session_cookie_token(&response).expect("login must set the session cookie");
    let body = json_body(response).await;
    assert_eq!(body["user"]["username"], "alice");
    assert!(body["csrfToken"].as_str().is_some());
    assert!(
        body.get("mfaRequired").is_none(),
        "an operator with no factor must see the pre-MFA response shape: {body}"
    );

    // And the cookie works immediately, with no second step.
    let session = AdminSessionHandle {
        cookie,
        csrf: body["csrfToken"].as_str().unwrap().to_string(),
    };
    assert_eq!(
        admin_request(&app, Method::GET, "/api/accounts", Some(&session), None)
            .await
            .status(),
        StatusCode::OK
    );
}

#[tokio::test]
async fn a_factor_bearing_login_stops_half_way_and_says_so() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    enrol_totp(database, "alice").await;

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };

    // The pending body carries no operator metadata: a half-authenticated
    // session must not read who it belongs to.
    let response = admin_request(
        &app,
        Method::POST,
        "/api/session",
        None,
        Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
    )
    .await;
    let body = json_body(response).await;
    assert_eq!(body["mfaRequired"], true);
    assert_eq!(body["step"], "verify");
    assert!(
        body.get("user").is_none(),
        "a pending session must not read operator metadata: {body}"
    );

    // And the cookie opens nothing.
    for path in ["/api/session", "/api/accounts", "/api/orders", "/api/eab"] {
        assert_eq!(
            admin_request(&app, Method::GET, path, Some(&pending), None)
                .await
                .status(),
            StatusCode::UNAUTHORIZED,
            "{path} must refuse a half-authenticated session"
        );
    }

    // The one route it does open says what it owes.
    let step = admin_request(&app, Method::GET, "/api/session/mfa", Some(&pending), None).await;
    assert_eq!(step.status(), StatusCode::OK);
    assert_eq!(json_body(step).await["step"], "verify");
}

#[tokio::test]
async fn a_valid_code_promotes_the_session_onto_a_brand_new_token() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;
    sqlx::query("UPDATE admin_users SET totp_last_step = NULL WHERE username = 'alice';")
        .execute(&database.pool)
        .await
        .unwrap();

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle {
        cookie: cookie.clone(),
        csrf,
    };

    let response = admin_request(
        &app,
        Method::POST,
        "/api/session/mfa",
        Some(&pending),
        Some(json!({ "code": totp_code(&secret, 0) })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);

    let promoted = session_cookie_token(&response).expect("promotion must set a new cookie");
    assert_ne!(
        promoted, cookie,
        "the pending token crossed the wire before authentication finished; \
         its privilege level changing means its value changes"
    );

    let body = json_body(response).await;
    assert_eq!(body["user"]["username"], "alice");
    let active = AdminSessionHandle {
        cookie: promoted,
        csrf: body["csrfToken"].as_str().unwrap().to_string(),
    };
    assert_ne!(active.csrf, pending.csrf, "the CSRF token rotates with it");

    // The new token works everywhere; the old one nowhere.
    assert_eq!(
        admin_request(&app, Method::GET, "/api/accounts", Some(&active), None)
            .await
            .status(),
        StatusCode::OK
    );
    assert_eq!(
        admin_request(&app, Method::GET, "/api/session", Some(&pending), None)
            .await
            .status(),
        StatusCode::UNAUTHORIZED
    );
}

/// RFC 6238 §5.2. A code observed in flight must not be replayable inside its
/// own thirty-second window.
///
/// Accept-then-replay rather than "the enrolment code is already spent", which
/// would be the same assertion in a form that loses whenever the two requests
/// straddle a step boundary. This shape is correct either way: cross one
/// boundary and the code is still in the ±1 window but the guard refuses it;
/// cross two and it falls out of the window. Both answer `401`.
#[tokio::test]
async fn a_code_cannot_be_spent_twice() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;

    sqlx::query("UPDATE admin_users SET totp_last_step = NULL WHERE username = 'alice';")
        .execute(&database.pool)
        .await
        .unwrap();

    let code = totp_code(&secret, 0);

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let first = AdminSessionHandle { cookie, csrf };
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/session/mfa",
            Some(&first),
            Some(json!({ "code": code.clone() })),
        )
        .await
        .status(),
        StatusCode::OK
    );

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let second = AdminSessionHandle { cookie, csrf };
    let replayed = admin_request(
        &app,
        Method::POST,
        "/api/session/mfa",
        Some(&second),
        Some(json!({ "code": code })),
    )
    .await;
    assert_eq!(replayed.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(json_body(replayed).await["error"], "invalid_credentials");
}

/// A wrong code, a spent recovery code and a replayed one are one refusal to
/// the client — byte-identical to a wrong password, exactly as the three
/// password failures already are.
#[tokio::test]
async fn a_wrong_code_is_indistinguishable_from_a_wrong_password() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    enrol_totp(database, "alice").await;

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };

    let wrong_password = admin_request(
        &app,
        Method::POST,
        "/api/session",
        None,
        Some(json!({ "username": "alice", "password": "not-the-password" })),
    )
    .await;
    let password_status = wrong_password.status();
    let password_body = json_body(wrong_password).await;

    for code in ["000000", "12345", "abcdef", "ZZZZZZZZZZ"] {
        let response = admin_request(
            &app,
            Method::POST,
            "/api/session/mfa",
            Some(&pending),
            Some(json!({ "code": code })),
        )
        .await;
        assert_eq!(response.status(), password_status, "code {code:?}");
        assert_eq!(json_body(response).await, password_body, "code {code:?}");
    }
}

/// The limiter's second call site. Without it, an attacker holding a correct
/// password would guess six-digit codes without limit.
///
/// Spread across **two** pending sessions on purpose. The per-session cap
/// (`the_code_step_is_bounded_per_session_and_not_only_per_address`) would
/// otherwise fire at the same count and destroy the row, so the response would
/// be a `401` for a missing session rather than the `429` this test is about.
/// Two sessions of two and one failure make three against the address while
/// leaving each session's own counter under the cap.
#[tokio::test]
async fn the_code_step_shares_the_login_limiter() {
    let mut config = admin_config();
    config.admin.login_max_attempts = 3;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database, "alice").await;

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let first = AdminSessionHandle { cookie, csrf };
    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let second = AdminSessionHandle { cookie, csrf };

    for pending in [&first, &first, &second] {
        assert_eq!(
            admin_request(
                &app,
                Method::POST,
                "/api/session/mfa",
                Some(pending),
                Some(json!({ "code": "000000" })),
            )
            .await
            .status(),
            StatusCode::UNAUTHORIZED
        );
    }

    // Over the limit, and a *correct* code on a session with attempts to spare
    // is refused too: the budget is per address, not per guess.
    let refused = admin_request(
        &app,
        Method::POST,
        "/api/session/mfa",
        Some(&second),
        Some(json!({ "code": totp_code(&secret, 1) })),
    )
    .await;
    assert_eq!(refused.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(refused.headers().contains_key(header::RETRY_AFTER));

    // One address, one budget: the password step is locked out as well.
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/session",
            None,
            Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
        )
        .await
        .status(),
        StatusCode::TOO_MANY_REQUESTS
    );
}

/// The bound the address-keyed limiter cannot provide.
///
/// A `pending_mfa` cookie is valid from any address by design — `created_ip` is
/// forensics, never compared — so an attacker holding a correct password could
/// otherwise mint one pending session and spend `login_max_attempts` guesses
/// per source address, of which a single IPv6 /64 supplies 2^64. The counter
/// lives on the session row, so rotating addresses buys nothing, and past the
/// cap the row is **deleted**: getting back to a pending session means
/// producing the password again, which `sign_in`'s limiter bounds.
#[tokio::test]
async fn the_code_step_is_bounded_per_session_and_not_only_per_address() {
    let mut config = admin_config();
    config.admin.login_max_attempts = 3;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };
    let token_hash = acme_proxy::webadmin::session::hash_token(&pending.cookie);

    // Each guess arrives from a *different* address, so the address-keyed
    // limiter never accumulates anything. Only the session counter does.
    for attempt in 0..3 {
        let response = admin_request_from(
            &app,
            Method::POST,
            "/api/session/mfa",
            Some(&pending),
            Some(json!({ "code": "000000" })),
            &format!("203.0.113.{}:40000", attempt + 1),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "attempt {attempt} must be a plain refusal, never a rate-limit"
        );
    }

    assert!(
        AdminSession::find_by_token_hash(&token_hash, &database)
            .await
            .unwrap()
            .is_none(),
        "past the cap the half-authenticated row is gone, not merely refused"
    );

    // And a correct code from a fourth fresh address gets nowhere: there is no
    // session left to finish, and the answer says only that.
    let response = admin_request_from(
        &app,
        Method::POST,
        "/api/session/mfa",
        Some(&pending),
        Some(json!({ "code": totp_code(&secret, 1) })),
        "203.0.113.9:40000",
    )
    .await;
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

/// The password step must **not** clear the limiter bucket. If it did, an
/// attacker with a correct password would reset their own budget on every
/// attempt.
#[tokio::test]
async fn the_password_step_does_not_clear_the_limiter_while_a_factor_is_outstanding() {
    let mut config = admin_config();
    config.admin.login_max_attempts = 3;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    enrol_totp(database, "alice").await;

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };

    for _ in 0..3 {
        admin_request(
            &app,
            Method::POST,
            "/api/session/mfa",
            Some(&pending),
            Some(json!({ "code": "000000" })),
        )
        .await;

        // Re-authenticating with the correct password between guesses must not
        // buy another three tries.
        admin_request(
            &app,
            Method::POST,
            "/api/session",
            None,
            Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
        )
        .await;
    }

    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/session",
            None,
            Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
        )
        .await
        .status(),
        StatusCode::TOO_MANY_REQUESTS
    );
}

/// `last_login_at` means "completed a login", not "typed the right password".
#[tokio::test]
async fn last_login_is_stamped_at_promotion_not_at_the_password() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;
    sqlx::query("UPDATE admin_users SET totp_last_step = NULL WHERE username = 'alice';")
        .execute(&database.pool)
        .await
        .unwrap();

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };

    let halfway = acme_proxy::sqlite::admin_user::AdminUser::find_by_username("alice", &database)
        .await
        .unwrap()
        .unwrap();
    assert!(
        halfway.last_login_at.is_none(),
        "a password accepted is not a login completed"
    );

    admin_request(
        &app,
        Method::POST,
        "/api/session/mfa",
        Some(&pending),
        Some(json!({ "code": totp_code(&secret, 0) })),
    )
    .await;

    let after = acme_proxy::sqlite::admin_user::AdminUser::find_by_username("alice", &database)
        .await
        .unwrap()
        .unwrap();
    assert!(after.last_login_at.is_some());
}

/// A recovery code finishes a login just as a TOTP code does, once.
#[tokio::test]
async fn a_recovery_code_finishes_a_login_and_is_then_spent() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    enrol_totp(database.clone(), "alice").await;

    let user = acme_proxy::sqlite::admin_user::AdminUser::find_by_username("alice", &database)
        .await
        .unwrap()
        .unwrap();
    let codes = acme_proxy::admin::mfa::regenerate_recovery_codes(&user, database.clone())
        .await
        .unwrap();

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };
    let response = admin_request(
        &app,
        Method::POST,
        "/api/session/mfa",
        Some(&pending),
        Some(json!({ "code": codes[0].clone() })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        acme_proxy::admin::mfa::recovery_codes_remaining(&user.id, database.clone())
            .await
            .unwrap(),
        9
    );

    // Single-use: the same code again is worth nothing.
    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let second = AdminSessionHandle { cookie, csrf };
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/session/mfa",
            Some(&second),
            Some(json!({ "code": codes[0].clone() })),
        )
        .await
        .status(),
        StatusCode::UNAUTHORIZED
    );
    assert_eq!(
        acme_proxy::admin::mfa::recovery_codes_remaining(&user.id, database)
            .await
            .unwrap(),
        9
    );
}

#[tokio::test]
async fn enrolment_shows_the_secret_once_and_the_codes_once() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let status =
        json_body(admin_request(&app, Method::GET, "/api/mfa", Some(&session), None).await).await;
    assert_eq!(status["totpEnabled"], false);
    assert_eq!(status["enrolmentPending"], false);
    assert_eq!(status["recoveryCodesRemaining"], 0);

    let begun = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp",
        Some(&session),
        Some(json!({})),
    )
    .await;
    assert_eq!(begun.status(), StatusCode::CREATED);
    let enrolment = json_body(begun).await;
    let secret_base32 = enrolment["secret"].as_str().unwrap().to_string();
    assert_eq!(secret_base32.len(), 32);
    assert!(!secret_base32.contains('='));
    assert!(
        enrolment["uri"]
            .as_str()
            .unwrap()
            .starts_with("otpauth://totp/acme-proxy:alice@")
    );
    assert_eq!(enrolment["algorithm"], "SHA1");
    assert_eq!(enrolment["digits"], 6);
    assert_eq!(enrolment["period"], 30);

    // Pending is not enrolled, and the secret is not readable again.
    let status =
        json_body(admin_request(&app, Method::GET, "/api/mfa", Some(&session), None).await).await;
    assert_eq!(status["totpEnabled"], false);
    assert_eq!(status["enrolmentPending"], true);
    assert!(
        !status.to_string().contains(&secret_base32),
        "the secret is shown exactly once: {status}"
    );

    // A wrong code confirms nothing.
    let refused = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp/confirm",
        Some(&session),
        Some(json!({ "code": "000000" })),
    )
    .await;
    assert_eq!(refused.status(), StatusCode::BAD_REQUEST);

    let secret = base32_decode(&secret_base32);
    let confirmed = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp/confirm",
        Some(&session),
        Some(json!({ "code": totp_code(&secret, 0) })),
    )
    .await;
    assert_eq!(confirmed.status(), StatusCode::OK);
    assert!(
        session_cookie_token(&confirmed).is_none(),
        "an already-active session has nothing to promote"
    );

    let body = json_body(confirmed).await;
    let codes = body["recoveryCodes"].as_array().unwrap().clone();
    assert_eq!(codes.len(), 10);

    let status =
        json_body(admin_request(&app, Method::GET, "/api/mfa", Some(&session), None).await).await;
    assert_eq!(status["totpEnabled"], true);
    assert_eq!(status["enrolmentPending"], false);
    assert_eq!(status["recoveryCodesRemaining"], 10);
    for code in &codes {
        assert!(
            !status.to_string().contains(code.as_str().unwrap()),
            "recovery codes are shown exactly once"
        );
    }
}

/// The step-up password is bounded by the same budget sign-in is, and by the
/// *same bucket* — so guessing it cannot buy a second budget.
///
/// The third call site of the login limiter, after the password step and the
/// code step. Until it ran here, somebody holding a stolen cookie could
/// brute-force the account password at unlimited rate, and a correct guess
/// converts that cookie into a factor takeover: enrol their own authenticator,
/// revoke every other session, void the recovery codes.
#[tokio::test]
async fn a_step_up_password_is_rate_limited_and_shares_the_sign_in_budget() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;
    let session = admin_login_mfa(&app, database, "alice", ADMIN_PASSWORD, &secret).await;

    // A distinct address, so the bucket under test is not the one `admin_login`
    // already touched.
    let peer = "203.0.113.9:1234";
    for _ in 0..5 {
        let refused = admin_request_from(
            &app,
            Method::POST,
            "/api/mfa/totp",
            Some(&session),
            Some(json!({ "password": "not the password" })),
            peer,
        )
        .await;
        assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(json_body(refused).await["error"], "invalid_credentials");
    }

    // Past the budget the **correct** password is refused too — which is what
    // proves the limiter runs ahead of the KDF rather than behind it.
    let limited = admin_request_from(
        &app,
        Method::POST,
        "/api/mfa/totp",
        Some(&session),
        Some(json!({ "password": ADMIN_PASSWORD })),
        peer,
    )
    .await;
    assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
    assert!(limited.headers().contains_key("retry-after"));

    // And the bucket is shared with sign-in: a second budget here would hand an
    // attacker twice the guesses against one password.
    let login = send_from(
        &app,
        Request::builder()
            .method(Method::POST)
            .uri("/api/session")
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(
                json!({ "username": "alice", "password": ADMIN_PASSWORD }).to_string(),
            ))
            .unwrap(),
        peer,
    )
    .await;
    assert_eq!(login.status(), StatusCode::TOO_MANY_REQUESTS);
}

#[tokio::test]
async fn recovery_codes_can_be_reissued_and_supersede_the_previous_set() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();

    // No factor: there is nothing for the codes to recover access to.
    let session = admin_login(&app, "alice", ADMIN_PASSWORD).await;
    let refused = admin_request(
        &app,
        Method::POST,
        "/api/mfa/recovery-codes",
        Some(&session),
        Some(json!({})),
    )
    .await;
    assert_eq!(refused.status(), StatusCode::CONFLICT);
    assert_eq!(json_body(refused).await["error"], "mfa_not_enabled");

    let secret = enrol_totp(database.clone(), "alice").await;
    let session = admin_login_mfa(&app, database, "alice", ADMIN_PASSWORD, &secret).await;

    let first = json_body(
        admin_request(
            &app,
            Method::POST,
            "/api/mfa/recovery-codes",
            Some(&session),
            Some(json!({ "password": ADMIN_PASSWORD })),
        )
        .await,
    )
    .await;
    let second = json_body(
        admin_request(
            &app,
            Method::POST,
            "/api/mfa/recovery-codes",
            Some(&session),
            Some(json!({ "password": ADMIN_PASSWORD })),
        )
        .await,
    )
    .await;
    assert_ne!(first["recoveryCodes"], second["recoveryCodes"]);

    // A code from the superseded set no longer finishes a login.
    let stale = first["recoveryCodes"][0].as_str().unwrap().to_string();
    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/session/mfa",
            Some(&pending),
            Some(json!({ "code": stale })),
        )
        .await
        .status(),
        StatusCode::UNAUTHORIZED
    );
}

/// `require_mfa` forces enrolment rather than refusing the login — which is
/// what stops it bricking the panel, since enrolling needs a session.
#[tokio::test]
async fn require_mfa_makes_a_factorless_operator_enrol_before_the_session_works() {
    let mut config = admin_config();
    config.admin.require_mfa = true;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database)
        .await
        .unwrap();

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };

    let step =
        json_body(admin_request(&app, Method::GET, "/api/session/mfa", Some(&pending), None).await)
            .await;
    assert_eq!(step["step"], "enrol");

    // Ordinary routes are still shut.
    assert_eq!(
        admin_request(&app, Method::GET, "/api/accounts", Some(&pending), None)
            .await
            .status(),
        StatusCode::UNAUTHORIZED
    );

    // But the enrolment routes are open, and finishing enrolment finishes the
    // login: the answer carries a rotated cookie.
    let begun = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp",
        Some(&pending),
        Some(json!({})),
    )
    .await;
    assert_eq!(begun.status(), StatusCode::CREATED);
    let secret = base32_decode(json_body(begun).await["secret"].as_str().unwrap());

    let confirmed = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp/confirm",
        Some(&pending),
        Some(json!({ "code": totp_code(&secret, 0) })),
    )
    .await;
    assert_eq!(confirmed.status(), StatusCode::OK);
    let promoted = session_cookie_token(&confirmed)
        .expect("finishing enrolment finishes the login, so the token rotates");
    assert_ne!(promoted, pending.cookie);

    let body = json_body(confirmed).await;
    assert_eq!(body["recoveryCodes"].as_array().unwrap().len(), 10);

    // The rotated cookie is a full session: a read works, and it carries the
    // CSRF token every write from here on needs.
    let active = AdminSessionHandle {
        cookie: promoted,
        csrf: String::new(),
    };
    let whoami = admin_request(&app, Method::GET, "/api/session", Some(&active), None).await;
    assert_eq!(whoami.status(), StatusCode::OK);
    let whoami = json_body(whoami).await;
    assert_eq!(whoami["user"]["username"], "alice");
    assert_eq!(whoami["user"]["totpEnabled"], true);
}

/// **The refusal this whole feature turns on.** A `pending_mfa` session that
/// owes a *code* must never reach an enrolment route — otherwise the second
/// factor is bypassable by enrolling a new one over it.
#[tokio::test]
async fn a_session_that_owes_a_code_cannot_enrol_its_way_past_it() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    enrol_totp(database, "alice").await;

    let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
    let pending = AdminSessionHandle { cookie, csrf };

    for (method, path) in [
        (Method::POST, "/api/mfa/totp"),
        (Method::POST, "/api/mfa/totp/confirm"),
        (Method::POST, "/api/mfa/recovery-codes"),
        (Method::DELETE, "/api/mfa/totp"),
        (Method::GET, "/api/mfa"),
    ] {
        let response = admin_request(
            &app,
            method.clone(),
            path,
            Some(&pending),
            Some(json!({ "code": "123456" })),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "{method} {path} must refuse a session that owes a code"
        );
    }
}

#[tokio::test]
async fn disabling_the_factor_is_refused_while_require_mfa_is_on() {
    let mut config = admin_config();
    config.admin.require_mfa = true;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;
    let session = admin_login_mfa(&app, database, "alice", ADMIN_PASSWORD, &secret).await;

    let refused = admin_request(
        &app,
        Method::DELETE,
        "/api/mfa/totp",
        Some(&session),
        Some(json!({})),
    )
    .await;
    assert_eq!(refused.status(), StatusCode::CONFLICT);
    assert_eq!(json_body(refused).await["error"], "mfa_required");
}

#[tokio::test]
async fn disabling_the_factor_clears_the_codes_and_the_other_sessions() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;

    let other = admin_login_mfa(&app, database.clone(), "alice", ADMIN_PASSWORD, &secret).await;
    let session = admin_login_mfa(&app, database, "alice", ADMIN_PASSWORD, &secret).await;

    assert_eq!(
        admin_request(
            &app,
            Method::DELETE,
            "/api/mfa/totp",
            Some(&session),
            Some(json!({ "password": ADMIN_PASSWORD })),
        )
        .await
        .status(),
        StatusCode::NO_CONTENT
    );

    let status =
        json_body(admin_request(&app, Method::GET, "/api/mfa", Some(&session), None).await).await;
    assert_eq!(status["totpEnabled"], false);
    assert_eq!(status["recoveryCodesRemaining"], 0);

    // The session doing the change survives; every other browser does not.
    assert_eq!(
        admin_request(&app, Method::GET, "/api/session", Some(&other), None)
            .await
            .status(),
        StatusCode::UNAUTHORIZED,
        "a factor removed that left another session alive is a change in name only"
    );

    // And the next login needs no code.
    let response = admin_request(
        &app,
        Method::POST,
        "/api/session",
        None,
        Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
    )
    .await;
    assert!(json_body(response).await.get("mfaRequired").is_none());
}

/// An `active` session is not a pending one, and the mirror-image extractors
/// must each refuse the other's.
#[tokio::test]
async fn the_mfa_step_routes_refuse_a_completed_session() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    for method in [Method::GET, Method::POST] {
        let response = admin_request(
            &app,
            method.clone(),
            "/api/session/mfa",
            Some(&session),
            Some(json!({ "code": "123456" })),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "{method} /api/session/mfa must refuse a session that has nothing outstanding"
        );
    }
}

// ---------------------------------------------------------------------------
// CSRF
// ---------------------------------------------------------------------------

/// The two routes that finish a login: origin-gated, deliberately **not**
/// CSRF-checked.
///
/// They cannot join [`mutating_endpoints`], because with an *active* session
/// they answer `401`/`303` rather than the `403` that table asserts. Keeping
/// them in their own table, with their own tests below, is what stops the
/// exclusion from reading as an oversight.
///
/// The omission is argued in `webadmin::session::PendingMfaSubmit`: the
/// challenge page is a plain form (sign-in must work with JavaScript off) and
/// `check_csrf` reads a header a form cannot set. A cross-site forger would
/// need a valid code for a session they cannot read, and success would only
/// complete the victim's own login.
fn mfa_step_endpoints() -> Vec<(Method, &'static str)> {
    vec![
        (Method::POST, "/api/session/mfa"),
        (Method::POST, "/ui/login/mfa"),
    ]
}

#[tokio::test]
async fn the_mfa_step_endpoints_need_a_pending_session_and_the_origin_gate() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    enrol_totp(database, "alice").await;

    for (method, path) in mfa_step_endpoints() {
        // No session at all.
        let anonymous = admin_request(&app, method.clone(), path, None, Some(json!({}))).await;
        assert!(
            anonymous.status().is_client_error() || anonymous.status().is_redirection(),
            "{method} {path} must refuse an anonymous caller, got {}",
            anonymous.status()
        );

        // A pending session from somewhere else entirely.
        let (cookie, csrf) = admin_login_pending(&app, "alice", ADMIN_PASSWORD).await;
        let pending = AdminSessionHandle { cookie, csrf };
        let cross_origin = send_from(
            &app,
            Request::builder()
                .method(method.clone())
                .uri(path)
                .header(
                    header::COOKIE,
                    format!("__Host-acme_admin_session={}", pending.cookie),
                )
                .header(header::ORIGIN, "https://evil.example.com")
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(json!({ "code": "123456" }).to_string()))
                .unwrap(),
            "127.0.0.1:40000",
        )
        .await;
        assert_eq!(
            cross_origin.status(),
            StatusCode::FORBIDDEN,
            "{method} {path} must be covered by the origin gate, which is what \
             stands in for the CSRF token it cannot have"
        );
    }
}

/// Every mutating endpoint, in one table.
///
/// **This list is the regression suite.** `AuthenticatedWrite` makes the check
/// structural — a mutating handler cannot reach a session without it — but the
/// residual risk is a new handler taking `Authenticated` by mistake, and that
/// is what this catches. An endpoint added below `/api` and not added here is
/// a review catch.
///
/// The `/ui` pages have their own table, `mutating_page_endpoints()` in
/// `tests/admin_pages.rs`, asserted HTML-shaped: a page answering in this
/// suite's JSON error shape would be the bug, not the expectation.
fn mutating_endpoints() -> Vec<(Method, &'static str)> {
    vec![
        (Method::PATCH, "/api/accounts/some-id"),
        (Method::POST, "/api/accounts/some-id/deactivate"),
        (Method::DELETE, "/api/accounts/some-id"),
        (Method::POST, "/api/orders/some-id/revoke"),
        (Method::DELETE, "/api/orders/some-id"),
        (Method::POST, "/api/eab"),
        (Method::POST, "/api/eab/some-kid/revoke"),
        (Method::POST, "/api/nonces/cleanup"),
        (Method::DELETE, "/api/session"),
        (Method::POST, "/api/mfa/totp"),
        (Method::POST, "/api/mfa/totp/confirm"),
        (Method::DELETE, "/api/mfa/totp"),
        (Method::POST, "/api/mfa/recovery-codes"),
    ]
}

#[tokio::test]
async fn every_mutating_endpoint_refuses_a_missing_csrf_token() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    for (method, path) in mutating_endpoints() {
        // The cookie, but no `X-CSRF-Token`.
        let request = axum::http::Request::builder()
            .method(method.clone())
            .uri(path)
            .header(
                header::COOKIE,
                format!("__Host-acme_admin_session={}", session.cookie),
            )
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from("{}"))
            .unwrap();
        let response = send_from(&app, request, "127.0.0.1:40000").await;

        assert_eq!(
            response.status(),
            StatusCode::FORBIDDEN,
            "{method} {path} must refuse a request with no CSRF token"
        );
        assert_eq!(json_body(response).await["error"], "csrf_failed");
    }
}

#[tokio::test]
async fn every_mutating_endpoint_refuses_a_wrong_or_foreign_csrf_token() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;
    // A second, legitimate session — its token must not work here either.
    let other = admin_login(&app, "alice", ADMIN_PASSWORD).await;

    for (method, path) in mutating_endpoints() {
        for (label, token) in [
            ("wrong", "not-the-token"),
            ("another session's", &*other.csrf),
        ] {
            let request = axum::http::Request::builder()
                .method(method.clone())
                .uri(path)
                .header(
                    header::COOKIE,
                    format!("__Host-acme_admin_session={}", session.cookie),
                )
                .header("x-csrf-token", token)
                .header(header::CONTENT_TYPE, "application/json")
                .body(axum::body::Body::from("{}"))
                .unwrap();
            let response = send_from(&app, request, "127.0.0.1:40000").await;
            assert_eq!(
                response.status(),
                StatusCode::FORBIDDEN,
                "{method} {path} must refuse a {label} CSRF token"
            );
        }
    }
}

#[tokio::test]
async fn a_cross_origin_write_is_refused_before_anything_else() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    for (name, value) in [
        ("origin", "http://evil.example"),
        ("sec-fetch-site", "cross-site"),
        // A different port of the same host — the case `SameSite=Strict`
        // does not cover, which is the whole reason the gate exists.
        ("origin", "http://localhost:8080"),
    ] {
        let request = axum::http::Request::builder()
            .method(Method::POST)
            .uri("/api/eab")
            .header(
                header::COOKIE,
                format!("__Host-acme_admin_session={}", session.cookie),
            )
            .header("x-csrf-token", &session.csrf)
            .header(name, value)
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from("{}"))
            .unwrap();
        let response = send_from(&app, request, "127.0.0.1:40000").await;
        assert_eq!(
            response.status(),
            StatusCode::FORBIDDEN,
            "{name}: {value} must be refused even with a valid CSRF token"
        );
    }
}

#[tokio::test]
async fn a_same_origin_write_with_the_right_token_is_allowed() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let request = axum::http::Request::builder()
        .method(Method::POST)
        .uri("/api/eab")
        .header(
            header::COOKIE,
            format!("__Host-acme_admin_session={}", session.cookie),
        )
        .header("x-csrf-token", &session.csrf)
        .header("origin", "http://localhost:3001")
        .header("sec-fetch-site", "same-origin")
        .header(header::CONTENT_TYPE, "application/json")
        .body(axum::body::Body::from("{}"))
        .unwrap();
    let response = send_from(&app, request, "127.0.0.1:40000").await;
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn reads_need_no_csrf_token() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    for path in [
        "/api/session",
        "/api/accounts",
        "/api/orders",
        "/api/audit",
        "/api/eab",
        "/api/nonces",
        "/api/profiles",
    ] {
        let request = axum::http::Request::builder()
            .method(Method::GET)
            .uri(path)
            .header(
                header::COOKIE,
                format!("__Host-acme_admin_session={}", session.cookie),
            )
            .body(axum::body::Body::empty())
            .unwrap();
        let response = send_from(&app, request, "127.0.0.1:40000").await;
        assert_eq!(response.status(), StatusCode::OK, "GET {path}");
    }
}

#[tokio::test]
async fn every_api_route_needs_a_session() {
    let (app, _database, _session) = test_admin_app_logged_in(admin_config()).await;

    let mut routes: Vec<(Method, &'static str)> = vec![
        (Method::GET, "/api/session"),
        (Method::GET, "/api/accounts"),
        (Method::GET, "/api/accounts/some-id"),
        (Method::GET, "/api/accounts/some-id/orders"),
        (Method::GET, "/api/orders"),
        (Method::GET, "/api/orders/some-id"),
        (Method::GET, "/api/audit"),
        (Method::GET, "/api/audit/1"),
        (Method::GET, "/api/eab"),
        (Method::GET, "/api/eab/some-kid"),
        (Method::GET, "/api/nonces"),
        (Method::GET, "/api/profiles"),
        // Refuses a *missing* session for the same reason as the rest, and an
        // `active` one besides — see `the_mfa_step_routes_refuse_a_completed_session`.
        (Method::GET, "/api/session/mfa"),
        (Method::GET, "/api/mfa"),
    ];
    routes.extend(mutating_endpoints());

    for (method, path) in routes {
        let response = admin_request(&app, method.clone(), path, None, Some(json!({}))).await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "{method} {path} must require a session"
        );
    }
}

// ---------------------------------------------------------------------------
// Resources
// ---------------------------------------------------------------------------

/// Seeds `count` accounts, each with one order, and returns their ids.
///
/// Each is created from a real address with a reverse name, so the traceability
/// members the admin renderer adds have something to carry.
async fn seed(
    database: &std::sync::Arc<acme_proxy::sqlite::db::Database>,
    count: u8,
) -> Vec<String> {
    use acme_proxy::sqlite::account::Account;
    use acme_proxy::sqlite::order::{Identifier, Order};

    let mut ids = Vec::new();
    for index in 0..count {
        let (account, _) = Account::find_or_create(
            PROFILE,
            &[1u8, index],
            vec![format!("mailto:user{index}@example.com")],
            &ClientContext {
                ip: Some(format!("203.0.113.{index}")),
                ptr: Some(format!("client{index}.example.net")),
                ..ClientContext::default()
            },
            database,
        )
        .await
        .unwrap();
        Order::create(
            PROFILE,
            &account.id,
            vec![Identifier::dns(format!("host{index}.example.com"))],
            2_000_000_000,
            None,
            None,
            database,
        )
        .await
        .unwrap();
        ids.push(account.id);
    }
    ids
}

#[tokio::test]
async fn accounts_list_pages_and_reports_the_total() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    seed(&database, 5).await;

    let body = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/accounts?limit=2",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(body["total"], 5);
    assert_eq!(body["limit"], 2);
    assert_eq!(body["offset"], 0);
    assert_eq!(body["items"].as_array().unwrap().len(), 2);
    // The renderer's admin-only augmentation is present.
    assert!(body["items"][0]["id"].as_str().is_some());
    assert_eq!(body["items"][0]["profile"], PROFILE);

    let paged = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/accounts?limit=2&offset=4",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(paged["items"].as_array().unwrap().len(), 1);
    assert_eq!(paged["total"], 5);
}

#[tokio::test]
async fn a_limit_over_the_ceiling_is_clamped_rather_than_refused() {
    let mut config = admin_config();
    config.admin.page_size_max = 3;
    let (app, database, session) = test_admin_app_logged_in(config).await;
    seed(&database, 5).await;

    let body = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/accounts?limit=1000",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(body["limit"], 3, "clamped to admin.page_size_max");
    assert_eq!(body["items"].as_array().unwrap().len(), 3);
    assert_eq!(body["total"], 5);
}

#[tokio::test]
async fn an_account_can_be_read_updated_deactivated_and_deleted() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let ids = seed(&database, 1).await;
    let id = &ids[0];

    // Read.
    let body = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/accounts/{id}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(body["id"], *id);
    assert_eq!(body["status"], "valid");
    // The traceability columns, admin-only: `Account::to_json` carries none of
    // them, so their presence here is the renderer's augmentation and the API
    // is an accurate description of what the `/ui` card holds.
    assert_eq!(body["createdIp"], "203.0.113.0");
    assert_eq!(body["createdPtr"], "client0.example.net");
    assert_eq!(body["lastSeenIp"], "203.0.113.0");
    assert_eq!(body["lastSeenPtr"], "client0.example.net");
    assert!(body["lastSeenAt"].as_str().unwrap().ends_with('Z'));

    // Its orders.
    let orders = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/accounts/{id}/orders"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(orders["total"], 1);

    // Update the contacts.
    let updated = json_body(
        admin_request(
            &app,
            Method::PATCH,
            &format!("/api/accounts/{id}"),
            Some(&session),
            Some(json!({ "contact": ["mailto:new@example.com"] })),
        )
        .await,
    )
    .await;
    assert_eq!(updated["contact"][0], "mailto:new@example.com");

    // Deactivate.
    let deactivated = json_body(
        admin_request(
            &app,
            Method::POST,
            &format!("/api/accounts/{id}/deactivate"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(deactivated["status"], "deactivated");

    // Delete, and the response names what cascaded.
    let deleted = json_body(
        admin_request(
            &app,
            Method::DELETE,
            &format!("/api/accounts/{id}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(deleted["deleted"]["orders"], 1);

    assert_eq!(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/accounts/{id}"),
            Some(&session),
            None
        )
        .await
        .status(),
        StatusCode::NOT_FOUND
    );
}

/// The gap the shared `contact_shape_error` closes: the admin API must not
/// write a contact `newAccount` would have refused.
#[tokio::test]
async fn patching_an_account_validates_contacts_the_way_new_account_does() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let ids = seed(&database, 1).await;
    let id = &ids[0];

    for bad in [
        "https://example.com",                // wrong scheme
        "mailto:a@example.com?subject=hi",    // hfields
        "mailto:a@example.com,b@example.com", // two addresses
        "mailto:not-an-address",
    ] {
        let response = admin_request(
            &app,
            Method::PATCH,
            &format!("/api/accounts/{id}"),
            Some(&session),
            Some(json!({ "contact": [bad] })),
        )
        .await;
        assert_eq!(response.status(), StatusCode::BAD_REQUEST, "for `{bad}`");
        let body = json_body(response).await;
        assert_eq!(body["error"], "bad_request");
        assert!(body["message"].as_str().unwrap().contains(bad));
    }
}

#[tokio::test]
async fn unknown_ids_are_json_404s_and_never_acme_problem_documents() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    for (method, path) in [
        (Method::GET, "/api/accounts/nope"),
        (Method::GET, "/api/accounts/nope/orders"),
        (Method::GET, "/api/orders/nope"),
        (Method::GET, "/api/eab/nope"),
        (Method::DELETE, "/api/accounts/nope"),
        (Method::DELETE, "/api/orders/nope"),
        (Method::POST, "/api/eab/nope/revoke"),
    ] {
        let response = admin_request(&app, method.clone(), path, Some(&session), None).await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND, "{method} {path}");
        assert_eq!(
            response.headers()[header::CONTENT_TYPE],
            "application/json",
            "{method} {path} must not answer application/problem+json"
        );
        let body = json_body(response).await;
        assert_eq!(body["error"], "not_found");
        assert!(!body.to_string().contains("urn:ietf:params:acme"));
    }
}

#[tokio::test]
async fn an_unrouted_path_and_a_wrong_method_answer_in_the_admin_error_shape() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let missing = admin_request(&app, Method::GET, "/api/nothing-here", Some(&session), None).await;
    assert_eq!(missing.status(), StatusCode::NOT_FOUND);
    assert_eq!(json_body(missing).await["error"], "not_found");

    let wrong_method = admin_request(
        &app,
        Method::PUT,
        "/api/accounts",
        Some(&session),
        Some(json!({})),
    )
    .await;
    assert_eq!(wrong_method.status(), StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(json_body(wrong_method).await["error"], "method_not_allowed");
}

#[tokio::test]
async fn orders_list_filters_by_account_and_status() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let ids = seed(&database, 3).await;

    let all =
        json_body(admin_request(&app, Method::GET, "/api/orders", Some(&session), None).await)
            .await;
    assert_eq!(all["total"], 3);

    let mine = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/orders?accountId={}", ids[0]),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(mine["total"], 1);

    let pending = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/orders?status=pending",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(pending["total"], 3);

    let ready = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/orders?status=ready",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(ready["total"], 0);
    assert!(ready["items"].as_array().unwrap().is_empty());
}

/// An unknown `status=` is a `400`, not an empty page.
///
/// The two answers are indistinguishable to a caller — `ready` above really
/// does match nothing — so a typo'd filter has to say so itself rather than
/// looking like a true negative. The CLI's `--status` refuses the same way.
#[tokio::test]
async fn an_unknown_order_status_filter_is_refused_rather_than_matching_nothing() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    seed(&database, 2).await;

    let response = admin_request(
        &app,
        Method::GET,
        "/api/orders?status=readyy",
        Some(&session),
        None,
    )
    .await;
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let body = json_body(response).await;
    assert_eq!(body["error"], "invalid_status");
    let message = body["message"].as_str().unwrap();
    assert!(message.contains("`readyy`"), "{message}");
    assert!(
        message.contains("pending, ready, processing, valid, invalid"),
        "{message}"
    );
}

#[tokio::test]
async fn an_order_detail_carries_its_authorizations() {
    use acme_proxy::sqlite::authz::{Authorization, Challenge};
    use acme_proxy::sqlite::order::{Identifier, Order};

    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let ids = seed(&database, 1).await;
    let orders = Order::find_by_account(&ids[0], &database).await.unwrap();
    let order_id = &orders[0].id;

    let authz = Authorization::create(
        order_id,
        Identifier::dns("host0.example.com"),
        2_000_000_000,
        &database,
    )
    .await
    .unwrap();
    Challenge::create(&authz.id, "http-01", &database)
        .await
        .unwrap();

    let body = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/orders/{order_id}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(body["order"]["id"], *order_id);
    assert_eq!(body["authorizations"].as_array().unwrap().len(), 1);
    assert_eq!(
        body["authorizations"][0]["challenges"]
            .as_array()
            .unwrap()
            .len(),
        1
    );
}

#[tokio::test]
async fn revoking_an_order_covers_every_outcome() {
    use acme_proxy::sqlite::order::Order;

    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let ids = seed(&database, 1).await;
    let orders = Order::find_by_account(&ids[0], &database).await.unwrap();
    let order_id = orders[0].id.clone();

    // Never issued.
    let response = admin_request(
        &app,
        Method::POST,
        &format!("/api/orders/{order_id}/revoke"),
        Some(&session),
        None,
    )
    .await;
    assert_eq!(response.status(), StatusCode::CONFLICT);
    assert_eq!(json_body(response).await["error"], "order_not_issued");

    // Unknown order.
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/orders/nope/revoke",
            Some(&session),
            None
        )
        .await
        .status(),
        StatusCode::NOT_FOUND
    );

    // An out-of-range reason code is refused before anything is attempted.
    let bad_reason = admin_request(
        &app,
        Method::POST,
        &format!("/api/orders/{order_id}/revoke"),
        Some(&session),
        Some(json!({ "reason": 99 })),
    )
    .await;
    assert_eq!(bad_reason.status(), StatusCode::CONFLICT);
}

/// An order from a profile this process does not mount cannot be revoked here,
/// and says so rather than reaching for whatever signer is at hand.
#[tokio::test]
async fn revoking_an_order_from_an_unmounted_profile_is_a_conflict() {
    use acme_proxy::sqlite::account::Account;
    use acme_proxy::sqlite::order::{Identifier, Order};

    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let (account, _) = Account::find_or_create(
        "retired",
        &[7u8, 7],
        vec![],
        &ClientContext::default(),
        &database,
    )
    .await
    .unwrap();
    let order = Order::create(
        "retired",
        &account.id,
        vec![Identifier::dns("old.example.com")],
        2_000_000_000,
        None,
        None,
        &database,
    )
    .await
    .unwrap();

    let response = admin_request(
        &app,
        Method::POST,
        &format!("/api/orders/{}/revoke", order.id),
        Some(&session),
        None,
    )
    .await;
    assert_eq!(response.status(), StatusCode::CONFLICT);
    let body = json_body(response).await;
    assert_eq!(body["error"], "profile_not_mounted");
    assert!(body["message"].as_str().unwrap().contains("retired"));
}

#[tokio::test]
async fn an_order_can_be_deleted_and_names_its_cascade() {
    use acme_proxy::sqlite::order::Order;

    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    let ids = seed(&database, 1).await;
    let orders = Order::find_by_account(&ids[0], &database).await.unwrap();
    let order_id = &orders[0].id;

    let body = json_body(
        admin_request(
            &app,
            Method::DELETE,
            &format!("/api/orders/{order_id}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(body["deleted"]["authorizations"], 0);
    assert!(
        Order::find_by_id(order_id, &database)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
async fn an_eab_secret_is_returned_once_and_never_again() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let created = admin_request(
        &app,
        Method::POST,
        "/api/eab",
        Some(&session),
        Some(json!({ "label": "team-a" })),
    )
    .await;
    assert_eq!(created.status(), StatusCode::CREATED);
    let body = json_body(created).await;
    let kid = body["kid"].as_str().unwrap().to_string();
    let secret = body["hmacKey"].as_str().unwrap().to_string();
    assert!(!secret.is_empty());
    assert_eq!(body["label"], "team-a");

    // Neither the detail nor the list ever shows it again.
    let shown = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/eab/{kid}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert!(shown.get("hmacKey").is_none());
    assert!(!shown.to_string().contains(&secret));

    let listed =
        json_body(admin_request(&app, Method::GET, "/api/eab", Some(&session), None).await).await;
    assert!(!listed.to_string().contains(&secret));

    // Revoke keeps the row, moving it to `revoked`.
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            &format!("/api/eab/{kid}/revoke"),
            Some(&session),
            None
        )
        .await
        .status(),
        StatusCode::NO_CONTENT
    );
    let after = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/eab/{kid}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(after["status"], "revoked");
}

#[tokio::test]
async fn creating_an_eab_for_an_unmounted_profile_is_refused() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let response = admin_request(
        &app,
        Method::POST,
        "/api/eab",
        Some(&session),
        Some(json!({ "profile": "no-such-profile" })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    assert!(
        json_body(response).await["message"]
            .as_str()
            .unwrap()
            .contains("no-such-profile")
    );
}

#[tokio::test]
async fn nonces_can_be_counted_and_swept() {
    use acme_proxy::sqlite::nonce::Nonce;

    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    for _ in 0..3 {
        Nonce::new().save(&database).await.unwrap();
    }

    let counted =
        json_body(admin_request(&app, Method::GET, "/api/nonces", Some(&session), None).await)
            .await;
    assert_eq!(counted["count"], 3);
    assert_eq!(counted["ttlSeconds"], 300);

    // A zero TTL sweeps everything.
    let swept = json_body(
        admin_request(
            &app,
            Method::POST,
            "/api/nonces/cleanup",
            Some(&session),
            Some(json!({ "ttlSeconds": 0 })),
        )
        .await,
    )
    .await;
    assert_eq!(swept["removed"], 3);
    assert_eq!(Nonce::count(&database).await.unwrap(), 0);
}

#[tokio::test]
async fn profiles_reports_the_endpoints_actually_mounted() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let body =
        json_body(admin_request(&app, Method::GET, "/api/profiles", Some(&session), None).await)
            .await;
    let profiles = body.as_array().unwrap();
    assert_eq!(profiles.len(), 1);
    assert_eq!(profiles[0]["name"], PROFILE);
    assert_eq!(profiles[0]["baseUrl"], BASE);
    assert_eq!(profiles[0]["directory"], format!("{BASE}/directory"));
}

// ---------------------------------------------------------------------------
// Layers
// ---------------------------------------------------------------------------

#[tokio::test]
async fn every_response_carries_the_hardening_headers() {
    let (app, _database, session) = test_admin_app_logged_in(admin_config()).await;

    let response = admin_request(&app, Method::GET, "/api/profiles", Some(&session), None).await;
    let headers = response.headers();
    assert_eq!(headers[header::CACHE_CONTROL], "no-store");
    assert_eq!(headers[header::REFERRER_POLICY], "same-origin");
    assert_eq!(headers[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
    assert_eq!(headers[header::X_FRAME_OPTIONS], "DENY");
    assert!(headers.contains_key(header::STRICT_TRANSPORT_SECURITY));
    // The access middleware runs here too.
    assert!(headers.contains_key("x-request-id"));
}

/// `/health` is on this listener as well, and needs no session: an
/// orchestrator probing the admin port should not have to hold one.
#[tokio::test]
async fn health_is_served_unauthenticated() {
    let (app, _database) = test_admin_app(admin_config()).await;

    let response = admin_request(&app, Method::GET, "/health", None, None).await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(json_body(response).await["healthy"], true);
}

/// This listener serves no ACME. A client that pointed certbot at it must get
/// nothing, not a half-working directory.
#[tokio::test]
async fn the_admin_listener_serves_no_acme() {
    let (app, _database) = test_admin_app(admin_config()).await;

    for path in [
        "/directory",
        "/newNonce",
        "/profile/default/directory",
        "/profile/default/newNonce",
    ] {
        let response = admin_request(&app, Method::GET, path, None, None).await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND, "GET {path}");
        // And no `Replay-Nonce` was minted on the way out.
        assert!(
            !response.headers().contains_key("replay-nonce"),
            "GET {path}"
        );
    }
}

/// The revoke path with a certificate that genuinely exists: the outcome the
/// other revoke test cannot reach, and the one that actually touches the CA.
#[tokio::test]
async fn revoking_an_issued_order_succeeds_once_and_then_conflicts() {
    use acme_proxy::signer::RequestedValidity;
    use acme_proxy::sqlite::account::Account;
    use acme_proxy::sqlite::order::{Identifier, Order};

    let mut config = admin_config();
    config.admin.enabled = true;
    let (app, database, signer) = test_admin_app_with_signer(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let session = admin_login(&app, "alice", ADMIN_PASSWORD).await;

    // An order, issued through the very backend the handler will revoke
    // against.
    let (account, _) = Account::find_or_create(
        PROFILE,
        &[4u8, 2],
        vec![],
        &ClientContext::default(),
        &database,
    )
    .await
    .unwrap();
    let identifier = Identifier::dns("revoke-me.example.com");
    let mut order = Order::create(
        PROFILE,
        &account.id,
        vec![identifier.clone()],
        2_000_000_000,
        None,
        None,
        &database,
    )
    .await
    .unwrap();

    let csr_der = {
        let csr = make_csr("revoke-me.example.com");
        use base64::prelude::*;
        BASE64_URL_SAFE_NO_PAD.decode(csr).unwrap()
    };
    let issued = signer
        .issue(
            &order.id,
            &csr_der,
            &[identifier],
            RequestedValidity::default(),
        )
        .await
        .expect("the in-memory CA must issue");
    let chain = match issued {
        acme_proxy::signer::IssueOutcome::Issued(chain) => chain,
        other => panic!("expected an inline issuance, got {other:?}"),
    };
    // The leaf's DER out of the PEM chain: `cert_serial_and_spki` parses one
    // certificate, not a chain.
    let (serial, spki) =
        acme_proxy::cert::cert_serial_and_spki(&first_certificate(&chain)).unwrap();
    order
        .finalize(chain, serial, spki, &database)
        .await
        .unwrap();

    // First revocation succeeds and returns the order.
    let response = admin_request(
        &app,
        Method::POST,
        &format!("/api/orders/{}/revoke", order.id),
        Some(&session),
        Some(json!({ "reason": 1 })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let body = json_body(response).await;
    assert_eq!(body["id"], order.id);
    // `render_order_json` surfaces the admin-only revocation columns that
    // `Order::to_json` deliberately omits.
    assert_eq!(body["revocationReason"], 1);
    assert!(body["revokedAt"].as_str().is_some());

    // The CA acted, not just the database: the CRL now names the serial.
    let crl = signer.crl_der().await.expect("a local CA always has a CRL");
    assert!(!crl.is_empty());

    // A repeat is a conflict, not a second revocation.
    let repeat = admin_request(
        &app,
        Method::POST,
        &format!("/api/orders/{}/revoke", order.id),
        Some(&session),
        None,
    )
    .await;
    assert_eq!(repeat.status(), StatusCode::CONFLICT);
    assert_eq!(json_body(repeat).await["error"], "already_revoked");
}

/// Replacing or removing a live second factor takes the account password, not
/// just the cookie.
///
/// The blast radius is what makes a session insufficient authority here: each
/// of these three also calls `revoke_other_sessions` and supersedes the
/// recovery codes. Without the gate, somebody holding one stolen cookie enrols
/// *their* authenticator over the operator's, signs the operator out
/// everywhere, and voids the codes that would let them back — leaving
/// `acme-proxy admin user totp reset` on the host as the only way in.
#[tokio::test]
async fn changing_a_live_factor_requires_the_password_again() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let secret = enrol_totp(database.clone(), "alice").await;
    let session = admin_login_mfa(&app, database.clone(), "alice", ADMIN_PASSWORD, &secret).await;

    // A fresh address per attempt, because `check_step_up` now spends the login
    // limiter's budget and six guesses from one address would be refused as
    // `rate_limited` — a different refusal from the one under test here, which
    // is that a cookie alone is not authority. Rotating addresses is also
    // exactly the residual the address-keyed bound does not close, so spelling
    // it out here keeps that visible rather than incidental.
    let mut attempt = 0;
    for (method, path) in [
        (Method::POST, "/api/mfa/totp"),
        (Method::POST, "/api/mfa/recovery-codes"),
        (Method::DELETE, "/api/mfa/totp"),
    ] {
        // Absent, then wrong: both are the same refusal a wrong password gets
        // at sign-in, so this is not a second oracle for the password.
        for body in [json!({}), json!({ "password": "not-the-password" })] {
            attempt += 1;
            let refused = admin_request_from(
                &app,
                method.clone(),
                path,
                Some(&session),
                Some(body),
                &format!("192.0.2.{attempt}:1234"),
            )
            .await;
            assert_eq!(
                refused.status(),
                StatusCode::UNAUTHORIZED,
                "{method} {path} must not act on a cookie alone"
            );
            assert_eq!(
                json_body(refused).await["error"],
                "invalid_credentials",
                "{method} {path}"
            );
        }
    }

    // Nothing was changed by any of those six attempts.
    let status =
        json_body(admin_request(&app, Method::GET, "/api/mfa", Some(&session), None).await).await;
    assert_eq!(status["totpEnabled"], true);
    assert_eq!(status["enrolmentPending"], false);
    assert_eq!(status["recoveryCodesRemaining"], 10);

    // With the password, the same call goes through.
    assert_eq!(
        admin_request(
            &app,
            Method::POST,
            "/api/mfa/totp",
            Some(&session),
            Some(json!({ "password": ADMIN_PASSWORD })),
        )
        .await
        .status(),
        StatusCode::CREATED
    );
}

/// The gate applies only where there is a factor to protect.
///
/// A first enrolment protects nothing, and demanding a password there would
/// put one in front of the `require_mfa` bootstrap — whose entire design is
/// that enrolling stays reachable, since a session is needed to enrol and a
/// factor would then be needed for a session.
#[tokio::test]
async fn a_first_enrolment_asks_for_no_password() {
    let (app, database) = test_admin_app(admin_config()).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database.clone())
        .await
        .unwrap();
    let session = admin_login(&app, "alice", ADMIN_PASSWORD).await;

    let begun = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp",
        Some(&session),
        Some(json!({})),
    )
    .await;
    assert_eq!(begun.status(), StatusCode::CREATED);

    let secret = json_body(begun).await["secret"]
        .as_str()
        .expect("the secret is readable exactly once")
        .to_string();

    // And confirming is not gated either: it can only ever confirm the secret
    // `POST /api/mfa/totp` already handed out, which is the call that carries
    // the gate once a factor exists.
    let confirmed = admin_request(
        &app,
        Method::POST,
        "/api/mfa/totp/confirm",
        Some(&session),
        Some(json!({ "code": totp_code(&base32_decode(&secret), 0) })),
    )
    .await;
    assert_eq!(confirmed.status(), StatusCode::OK);
}

/// With the database gone, the admin listener fails **closed**.
///
/// The whole listener had no DB-failure coverage — `pool.close()` appeared only
/// in `tests/db_failures.rs`, which is ACME-only. The class of bug this guards
/// against is the worst one an auth layer can have: `resolve_session` cannot
/// read the session row, and *treats that as no constraint* rather than as no
/// session. Every route below is one an unauthenticated caller must never
/// reach, so a `200` from any of them is the finding.
///
/// The limiter is checked too. It is deliberately in-memory and so survives the
/// outage, but `authenticate` reads the user table, so a login must refuse
/// rather than let a caller through on an unreadable password hash.
#[tokio::test]
async fn the_admin_listener_fails_closed_when_the_database_is_gone() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;
    database.pool.close().await;

    for (method, path) in [
        (Method::GET, "/api/session"),
        (Method::GET, "/api/accounts"),
        (Method::GET, "/api/orders"),
        (Method::GET, "/api/eab"),
        (Method::GET, "/api/mfa"),
        (Method::GET, "/api/profiles"),
    ] {
        let response = admin_request(&app, method.clone(), path, Some(&session), None).await;
        assert!(
            response.status().is_client_error() || response.status().is_server_error(),
            "{method} {path} answered {} with no database to authorise against",
            response.status()
        );
    }

    // Signing in cannot succeed either, and must not set a cookie.
    let response = admin_request(
        &app,
        Method::POST,
        "/api/session",
        None,
        Some(json!({ "username": "alice", "password": ADMIN_PASSWORD })),
    )
    .await;
    assert!(
        response.status().is_client_error() || response.status().is_server_error(),
        "a login answered {} against an unreadable user table",
        response.status()
    );
    assert!(
        session_cookie_token(&response).is_none(),
        "a failed login must not hand out a session cookie"
    );

    // And a mutation is refused before it can half-apply.
    let response = admin_request(
        &app,
        Method::DELETE,
        "/api/accounts/00000000-0000-0000-0000-000000000000",
        Some(&session),
        None,
    )
    .await;
    assert!(response.status().is_client_error() || response.status().is_server_error());
}

/// `admin.max_body_bytes`, the admin twin of `tests/admission.rs`'s ACME check.
///
/// This listener deliberately carries no admission control — the availability
/// concern here is credential brute force, which the limiter handles — so the
/// body limit is the only thing bounding what one request can make the process
/// allocate.
#[tokio::test]
async fn an_oversized_admin_request_body_is_refused() {
    let mut config = admin_config();
    config.admin.max_body_bytes = 1024;
    let (app, database) = test_admin_app(config).await;
    acme_proxy::admin::users::create_user("alice", ADMIN_PASSWORD, database)
        .await
        .unwrap();
    let session = admin_login(&app, "alice", ADMIN_PASSWORD).await;

    let oversized = json!({ "contact": ["mailto:a@b.test"], "padding": "x".repeat(4096) });
    let response = admin_request(
        &app,
        Method::PATCH,
        "/api/accounts/00000000-0000-0000-0000-000000000000",
        Some(&session),
        Some(oversized),
    )
    .await;
    assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);

    // The limit is a ceiling, not a refusal of every body: the same request
    // under it reaches the handler, which then answers on its own merits.
    let response = admin_request(
        &app,
        Method::PATCH,
        "/api/accounts/00000000-0000-0000-0000-000000000000",
        Some(&session),
        Some(json!({ "contact": ["mailto:a@b.test"] })),
    )
    .await;
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

/// The audit surface is **read-only**, and that is a security property rather
/// than a missing feature: a panel session that could delete audit history
/// would make the history prove nothing, since a stolen session's first act
/// would be to use it. Pruning is `acme-proxy audit cleanup` on the host, or
/// `audit.retention_days`.
///
/// This is also why `/api/audit` contributes nothing to `mutating_endpoints()`
/// — there is no mutating route to list.
#[tokio::test]
async fn the_audit_api_lists_pages_and_refuses_every_way_of_writing_to_it() {
    let (app, database, session) = test_admin_app_logged_in(admin_config()).await;

    for _ in 0..3 {
        AuditEntry::insert(
            AuditRecord::new(AuditEvent::CertificateIssued, PROFILE, Actor::admin("root"))
                .with_account("acct-1")
                .with_serial("0a0b")
                .with_client(ClientContext {
                    ip: Some("203.0.113.7".to_string()),
                    ptr: Some("host.example.com".to_string()),
                    ..ClientContext::default()
                }),
            &database,
        )
        .await
        .unwrap();
    }
    AuditEntry::insert(
        AuditRecord::new(
            AuditEvent::CertificateRevokeFailed,
            PROFILE,
            Actor::acme_certificate_key(),
        )
        .with_reason("unauthorized"),
        &database,
    )
    .await
    .unwrap();

    let body =
        json_body(admin_request(&app, Method::GET, "/api/audit", Some(&session), None).await).await;
    assert_eq!(body["total"], 4);
    assert_eq!(body["items"].as_array().unwrap().len(), 4);
    // Newest first, and the row carries the address it was written with.
    assert_eq!(body["items"][0]["event"], "certificate_revoke_failed");
    assert_eq!(body["items"][3]["clientIp"], "203.0.113.7");
    assert_eq!(body["items"][3]["clientPtr"], "host.example.com");
    // Absent, not null, for a row that had none.
    assert!(
        !body["items"][0]
            .as_object()
            .unwrap()
            .contains_key("clientIp")
    );

    // Filters and the page window.
    let filtered = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/audit?outcome=failure",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(filtered["total"], 1);

    let paged = json_body(
        admin_request(
            &app,
            Method::GET,
            "/api/audit?limit=2",
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(paged["total"], 4);
    assert_eq!(paged["items"].as_array().unwrap().len(), 2);
    assert_eq!(paged["limit"], 2);

    // One row by id, and an unknown one.
    let id = body["items"][0]["id"].as_i64().unwrap();
    let one = json_body(
        admin_request(
            &app,
            Method::GET,
            &format!("/api/audit/{id}"),
            Some(&session),
            None,
        )
        .await,
    )
    .await;
    assert_eq!(one["id"], id);
    let missing = admin_request(&app, Method::GET, "/api/audit/999999", Some(&session), None).await;
    assert_eq!(missing.status(), StatusCode::NOT_FOUND);

    // Nothing writes: every other verb on both paths is unroutable.
    for (method, path) in [
        (Method::POST, "/api/audit"),
        (Method::DELETE, "/api/audit"),
        (Method::DELETE, "/api/audit/1"),
        (Method::PATCH, "/api/audit/1"),
        (Method::POST, "/api/audit/cleanup"),
    ] {
        let response =
            admin_request(&app, method.clone(), path, Some(&session), Some(json!({}))).await;
        assert!(
            response.status() == StatusCode::METHOD_NOT_ALLOWED
                || response.status() == StatusCode::NOT_FOUND,
            "{method} {path} answered {}",
            response.status()
        );
    }
    // And the rows are all still there.
    assert_eq!(
        json_body(admin_request(&app, Method::GET, "/api/audit", Some(&session), None).await).await
            ["total"],
        4
    );
}