nora-registry 1.2.0

Cloud-Native Artifact Registry - Fast, lightweight, multi-protocol
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
// Copyright (c) 2026 The NORA Authors
// SPDX-License-Identifier: MIT

//! Authentication module — middleware, providers, and token routes.
//!
//! Supports:
//! - Basic auth via htpasswd files
//! - Bearer token auth (opaque tokens with Argon2 verification)
//! - Brute-force protection with exponential backoff

mod htpasswd;
mod namespace;
pub mod oidc;
mod token_routes;

pub use htpasswd::HtpasswdAuth;
pub use namespace::{enforce_namespace_scope, NamespaceAuthority};
pub use oidc::OidcValidator;
pub use token_routes::{token_routes, TokenListItem, TokenListResponse};

/// Authenticated username carried in request extensions after successful auth.
#[derive(Clone, Debug)]
pub struct AuthenticatedUser(pub String);

/// The verified role carried in request extensions after successful auth.
/// Basic-auth (htpasswd) identities have no role concept and are recorded as
/// `Write` (never admin), so role-gated owner-scope treats them as non-admin.
#[derive(Clone, Debug)]
pub struct AuthenticatedRole(pub crate::tokens::Role);

use axum::{
    body::Body,
    extract::{ConnectInfo, State},
    http::{header, HeaderMap, Request, StatusCode},
    middleware::Next,
    response::{IntoResponse, Response},
};
use base64::{engine::general_purpose::STANDARD, Engine};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::time::Instant;

use crate::AppState;

/// Tracks failed authentication attempts per IP for brute-force protection.
///
/// After `max_failures` consecutive failures, the IP is locked out with
/// exponential backoff: 2^(failures - max_failures) seconds, capped at 15 minutes.
pub struct AuthFailureTracker {
    /// IP -> (consecutive failures, last failure time)
    entries: parking_lot::Mutex<HashMap<IpAddr, (u32, Instant)>>,
    /// Number of failures before lockout kicks in (default: 5)
    max_failures: u32,
    /// Maximum lockout duration in seconds (default: 900 = 15 minutes)
    max_lockout_secs: u64,
}

impl AuthFailureTracker {
    pub fn new(max_failures: u32, max_lockout_secs: u64) -> Self {
        Self {
            entries: parking_lot::Mutex::new(HashMap::new()),
            max_failures,
            max_lockout_secs,
        }
    }

    /// Check if IP is currently locked out. Returns remaining lockout seconds if blocked.
    pub fn check_blocked(&self, ip: &IpAddr) -> Option<u64> {
        let entries = self.entries.lock();
        let (failures, last_failure) = entries.get(ip)?;
        if *failures < self.max_failures {
            return None;
        }
        let exponent = (*failures - self.max_failures).min(20);
        let lockout_secs = (1u64 << exponent).min(self.max_lockout_secs);
        let elapsed = last_failure.elapsed().as_secs();
        if elapsed < lockout_secs {
            Some(lockout_secs - elapsed)
        } else {
            None
        }
    }

    /// Record a failed auth attempt for an IP.
    pub fn record_failure(&self, ip: IpAddr) {
        let mut entries = self.entries.lock();
        let entry = entries.entry(ip).or_insert_with(|| (0, Instant::now()));
        entry.0 += 1;
        entry.1 = Instant::now();
    }

    /// Clear failure count on successful auth.
    pub fn record_success(&self, ip: &IpAddr) {
        let mut entries = self.entries.lock();
        entries.remove(ip);
    }

    /// Remove entries older than max_lockout_secs (call periodically).
    pub fn cleanup(&self) {
        let mut entries = self.entries.lock();
        entries.retain(|_, (_, last)| last.elapsed().as_secs() < self.max_lockout_secs * 2);
    }
}

/// Check if path is public (no auth required)
/// Paths that are public UNCONDITIONALLY: probes (a gated /health takes the
/// whole deployment down behind an LB) and the token endpoints, which do
/// their own credential handling.
fn is_public_path(path: &str) -> bool {
    matches!(
        path,
        "/" | "/health" | "/ready" | "/api/tokens" | "/api/tokens/list" | "/api/tokens/revoke"
    )
}

/// The browse web surface: UI pages, their JSON API, and the API docs. All
/// of it enumerates repositories and packages, so under an auth-enabled
/// deployment it is gated unless `anonymous_read` or `public_web_ui` opens
/// it (token-management pages stay ALWAYS gated — they were before, too).
fn is_web_surface(path: &str) -> bool {
    if path.starts_with("/ui/tokens") || path.starts_with("/api/ui/tokens") {
        return false;
    }
    path.starts_with("/ui") || path.starts_with("/api/ui") || path.starts_with("/api-docs")
}

/// Check if a path belongs to the Docker/OCI registry (`/v2`, `/v2/…`).
///
/// Docker anonymous access is governed by `docker_anon_pull` (separate from
/// the general `anonymous_read`), so all `/v2` paths are matched as one group:
/// the `/v2/` auth-challenge ping and every manifest/blob/tag endpoint. Per the
/// Docker Registry V2 spec, an unauthenticated `GET /v2/` returns 401 with a
/// WWW-Authenticate header (so clients send credentials) UNLESS anonymous Docker
/// pull is explicitly enabled.
fn is_docker_path(path: &str) -> bool {
    path == "/v2" || path.starts_with("/v2/")
}

/// Check if path is an admin-only control-plane endpoint.
///
/// Admin paths require a token whose role satisfies `can_admin()` regardless of
/// HTTP method, and are never served anonymously (not even under
/// `anonymous_read`). Basic-auth has no role concept, so it can never satisfy
/// an admin path — it is denied fail-closed. Scoped strictly to `/api/v1/admin/`
/// so it never widens the privilege bar of existing routes (e.g. `/raw/-/reindex`
/// stays at write-level).
fn is_admin_path(path: &str) -> bool {
    path.starts_with("/api/v1/admin/")
}

/// Extract client IP from request, honoring XFF/X-Real-IP only from trusted proxies.
///
/// If the direct peer IP is not in `trusted_proxies`, XFF/X-Real-IP headers are
/// ignored and the peer IP is returned. This prevents attackers from spoofing
/// their IP to bypass `AuthFailureTracker` lockout.
pub(crate) fn resolve_client_ip(
    peer: IpAddr,
    headers: &HeaderMap,
    trusted_proxies: &crate::config::TrustedProxies,
) -> IpAddr {
    if !trusted_proxies.contains(peer) {
        return peer;
    }

    // Try X-Forwarded-For first (first IP in chain is the client)
    if let Some(xff) = headers.get("x-forwarded-for") {
        if let Ok(s) = xff.to_str() {
            if let Some(first) = s.split(',').next() {
                if let Ok(ip) = first.trim().parse::<IpAddr>() {
                    return ip;
                }
            }
        }
    }
    // Try X-Real-IP
    if let Some(xri) = headers.get("x-real-ip") {
        if let Ok(s) = xri.to_str() {
            if let Ok(ip) = s.trim().parse::<IpAddr>() {
                return ip;
            }
        }
    }
    // No forwarding headers — use peer IP
    peer
}

fn extract_client_ip(
    request: &Request<Body>,
    trusted_proxies: &crate::config::TrustedProxies,
) -> Option<IpAddr> {
    let peer = request
        .extensions()
        .get::<ConnectInfo<SocketAddr>>()
        .map(|ci| ci.0.ip())?;
    Some(resolve_client_ip(peer, request.headers(), trusted_proxies))
}

/// Insert the anonymous identity (read-only role, unrestricted namespace) and
/// run the downstream handler. Shared by the `anonymous_read` (non-Docker) and
/// `docker_anon_pull` (Docker `/v2`) bypass paths.
async fn anonymous_read_passthrough(mut request: Request<Body>, next: Next) -> Response {
    request
        .extensions_mut()
        .insert(NamespaceAuthority::Unrestricted);
    request
        .extensions_mut()
        .insert(AuthenticatedUser("anonymous".to_string()));
    request
        .extensions_mut()
        .insert(AuthenticatedRole(crate::tokens::Role::Read));
    next.run(request).await
}

/// Auth middleware - supports Basic auth, Bearer tokens, and OIDC JWT
pub async fn auth_middleware(
    State(state): State<AppState>,
    mut request: Request<Body>,
    next: Next,
) -> Response {
    // Skip auth if disabled (neither htpasswd nor OIDC configured)
    if !state.config.auth.enabled {
        request
            .extensions_mut()
            .insert(NamespaceAuthority::Unrestricted);
        request
            .extensions_mut()
            .insert(AuthenticatedUser("anonymous".to_string()));
        return next.run(request).await;
    }

    // Skip auth for public endpoints
    {
        let path = request.uri().path();
        // Unconditional publics (probes, token endpoints), plus the web
        // surface and /metrics when the config opens them. The web surface
        // enumerates every repository, so it follows `anonymous_read` (the
        // registry read APIs would expose the same names) or the explicit
        // `public_web_ui` escape; /metrics has its own default-open switch —
        // labels carry registry formats, not repository names.
        let config = &state.config.auth;
        let open = is_public_path(path)
            || (is_web_surface(path) && (config.anonymous_read || config.public_web_ui))
            || (path == "/metrics" && config.public_metrics);
        if open {
            let mut request = request;
            request
                .extensions_mut()
                .insert(NamespaceAuthority::Unrestricted);
            request
                .extensions_mut()
                .insert(AuthenticatedUser("anonymous".to_string()));
            return next.run(request).await;
        }
        // A gated web-surface request without credentials gets a Basic
        // challenge so browsers prompt instead of rendering a bare 401.
        if (is_web_surface(path) || path == "/metrics")
            && request
                .headers()
                .get(axum::http::header::AUTHORIZATION)
                .is_none()
        {
            return axum::http::Response::builder()
                .status(axum::http::StatusCode::UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic realm=\"nora\"")
                .body(axum::body::Body::from("Authentication required"))
                .expect("valid response");
        }
    }

    let path = request.uri().path();

    // Docker/OCI paths (`/v2`, `/v2/…`) are governed by `docker_anon_pull`,
    // NOT the general `anonymous_read`: anonymous Docker pull changes the `/v2/`
    // auth-challenge handshake, so it is opted into explicitly and enabling
    // anonymous Maven/raw/npm never silently exposes container images.
    let is_docker = is_docker_path(path);

    // `/v2/_catalog` enumerates every repository — never served anonymously, even
    // under docker_anon_pull (anonymous pull-by-name is not list-all-repos).
    let is_docker_catalog = path == "/v2/_catalog";

    // Token management always requires auth, even with anonymous_read
    let is_token_management = path.starts_with("/ui/tokens") || path.starts_with("/api/ui/tokens");

    // npm whoami always requires auth (otherwise it returns "anonymous" for every user)
    let is_whoami = path.ends_with("/-/whoami");

    // Admin control-plane paths always require an admin token — never anonymous,
    // even under anonymous_read, and method-independent (covers a future GET).
    let is_admin = is_admin_path(path);

    let is_read_method = matches!(
        *request.method(),
        axum::http::Method::GET | axum::http::Method::HEAD
    );

    // npm audit (#597) is a read-semantics query that npm sends as a POST (npm7
    // `advisories/bulk`, npm6 `audits/quick`). Treat it as read-eligible under
    // `anonymous_read` so anonymous `npm audit` works wherever anonymous install
    // works. Safe: the handler (registry/npm.rs) mutates nothing (forwards to the
    // configured upstream, returns advisories), caps the body, strips internal
    // package names under a filter, and never forwards the client credential.
    let is_npm_audit = *request.method() == axum::http::Method::POST
        && (path == "/npm/-/npm/v1/security/advisories/bulk"
            || path == "/npm/-/npm/v1/security/audits/quick");

    // A request that presents credentials is always validated below (honest
    // `docker login`, correct audit attribution) — never short-circuited to
    // anonymous. Anonymous Docker bypass applies only when no Authorization sent.
    let has_auth_header = request.headers().contains_key(header::AUTHORIZATION);

    // Anonymous read for non-Docker registries (Maven/raw/npm/…) if configured.
    // Token management, whoami, admin, and all Docker `/v2` paths are excluded.
    if state.config.auth.anonymous_read
        && (is_read_method || is_npm_audit)
        && !is_docker
        && !is_token_management
        && !is_whoami
        && !is_admin
    {
        return anonymous_read_passthrough(request, next).await;
    }

    // Anonymous Docker/OCI pull, when explicitly enabled. The `/v2/` ping then
    // returns 200 (so the client proceeds without a Basic challenge) and
    // manifest/blob/tag reads are served without auth; writes (POST/PUT/PATCH/
    // DELETE) are not read methods, so they fall through and still require auth.
    // With the flag off (default), `/v2/` returns 401 + WWW-Authenticate: Basic
    // so `docker login` works and the basic-auth-accepts-api-token contract holds.
    if state.config.auth.docker_anon_pull
        && is_read_method
        && is_docker
        && !is_docker_catalog
        && !has_auth_header
    {
        return anonymous_read_passthrough(request, next).await;
    }

    // Compute realm from public_url for WWW-Authenticate header
    let realm = state.config.server.public_url.as_deref().unwrap_or("Nora");

    // Check if client IP is blocked due to too many failed attempts
    let client_ip = extract_client_ip(&request, &state.config.auth.trusted_proxies);
    if let Some(ip) = client_ip {
        if let Some(retry_after) = state.auth_failures.check_blocked(&ip) {
            return (
                StatusCode::TOO_MANY_REQUESTS,
                [
                    (header::RETRY_AFTER, retry_after.to_string()),
                    (header::CONTENT_TYPE, "application/json".to_string()),
                ],
                format!(
                    r#"{{"error":"Too many failed attempts. Retry after {} seconds."}}"#,
                    retry_after
                ),
            )
                .into_response();
        }
    }

    // Extract Authorization header
    let auth_header = request
        .headers()
        .get(header::AUTHORIZATION)
        .and_then(|h| h.to_str().ok());

    let auth_header = match auth_header {
        Some(h) => h,
        None => return unauthorized_response("Authentication required", realm),
    };

    // Try Bearer token first (opaque nra_ tokens, then OIDC JWT)
    if let Some(token) = auth_header.strip_prefix("Bearer ") {
        // 1. Try opaque token (nra_ prefix)
        if let Some(ref token_store) = state.tokens {
            match token_store.verify_token(token) {
                Ok((user, role)) => {
                    if let Some(ip) = client_ip {
                        state.auth_failures.record_success(&ip);
                    }
                    let method = request.method().clone();
                    if (method == axum::http::Method::PUT
                        || method == axum::http::Method::POST
                        || method == axum::http::Method::DELETE
                        || method == axum::http::Method::PATCH)
                        && !role.can_write()
                    {
                        return (StatusCode::FORBIDDEN, "Read-only token").into_response();
                    }
                    if is_admin && !role.can_admin() {
                        return (StatusCode::FORBIDDEN, "Admin role required").into_response();
                    }
                    // Opaque (nra_) tokens are not namespace-scoped (#583 is OIDC-only).
                    request
                        .extensions_mut()
                        .insert(NamespaceAuthority::Unrestricted);
                    request.extensions_mut().insert(AuthenticatedUser(user));
                    request.extensions_mut().insert(AuthenticatedRole(role));
                    return next.run(request).await;
                }
                // A store I/O/parse failure is not a credential verdict. Only an
                // `nra_`-prefixed token reaches disk (anything else returns
                // `InvalidFormat` first), so there is no OIDC identity to fall
                // through to: answer 503 so the client retries, instead of a 401
                // that makes valid creds flap during a storage blip.
                Err(crate::tokens::TokenError::Storage(e)) => {
                    tracing::error!(error = %e, "token store read failed during Bearer auth");
                    return (
                        StatusCode::SERVICE_UNAVAILABLE,
                        "Token verification unavailable",
                    )
                        .into_response();
                }
                Err(_) => {
                    // Token verification failed — fall through to OIDC
                }
            }
        }

        // 2. Try OIDC JWT validation
        if let Some(ref oidc_validator) = state.oidc {
            if oidc_validator.is_active() {
                match oidc_validator.validate_token(token).await {
                    Ok(identity) => {
                        if let Some(ip) = client_ip {
                            state.auth_failures.record_success(&ip);
                        }
                        tracing::debug!(
                            provider = %identity.provider,
                            subject = %identity.subject,
                            role = ?identity.role,
                            "OIDC authentication successful"
                        );
                        let method = request.method().clone();
                        if (method == axum::http::Method::PUT
                            || method == axum::http::Method::POST
                            || method == axum::http::Method::DELETE
                            || method == axum::http::Method::PATCH)
                            && !identity.role.can_write()
                        {
                            return (StatusCode::FORBIDDEN, "Read-only OIDC identity")
                                .into_response();
                        }
                        if is_admin && !identity.role.can_admin() {
                            return (StatusCode::FORBIDDEN, "Admin role required").into_response();
                        }
                        // Carry the namespace scopes into the request so write
                        // handlers can enforce them on the artifact coordinate
                        // (#583). Provider scope and rule scope are a conjunction:
                        // the provider scope is a ceiling a rule cannot widen.
                        let authority = NamespaceAuthority::from_oidc_scopes(
                            &identity.provider,
                            std::iter::once(identity.namespace_scope.as_slice())
                                .chain(identity.rule_namespace_scope.as_deref()),
                            identity.namespace_scope_enforcement,
                        );
                        request.extensions_mut().insert(authority);
                        request
                            .extensions_mut()
                            .insert(AuthenticatedUser(identity.subject.clone()));
                        request
                            .extensions_mut()
                            .insert(AuthenticatedRole(identity.role));
                        return next.run(request).await;
                    }
                    Err(_) => {
                        // OIDC also failed
                    }
                }
            }
        }

        // Both token and OIDC failed
        if let Some(ip) = client_ip {
            state.auth_failures.record_failure(ip);
        }
        return unauthorized_response("Invalid or expired token", realm);
    }

    // Parse Basic auth
    if !auth_header.starts_with("Basic ") {
        return unauthorized_response("Basic or Bearer authentication required", realm);
    }

    // htpasswd provider required for Basic auth
    let auth = match &state.auth {
        Some(auth) => auth,
        None => return unauthorized_response("Basic auth not configured", realm),
    };

    let encoded = &auth_header[6..];
    let decoded = match STANDARD.decode(encoded) {
        Ok(d) => d,
        Err(_) => return unauthorized_response("Invalid credentials encoding", realm),
    };

    let credentials = match String::from_utf8(decoded) {
        Ok(c) => c,
        Err(_) => return unauthorized_response("Invalid credentials encoding", realm),
    };

    let (username, password) = match credentials.split_once(':') {
        Some((u, p)) => (u, p),
        None => return unauthorized_response("Invalid credentials format", realm),
    };

    // Verify credentials. htpasswd first; if that fails, the password may be an API
    // token (`nra_…`). Docker, twine and Maven send the token as the Basic-auth
    // password and never use Bearer (the `/v2/` challenge is Basic), so the Basic
    // path must fall through to token verification for token auth to work at all. (#736)
    if !auth.authenticate(username, password) {
        let token_result = state.tokens.as_ref().map(|ts| ts.verify_token(password));
        // Same fail-closed rule as the Bearer path: a store I/O/parse failure is
        // not "wrong password". A 401 here makes valid token creds flap and feeds
        // the failure tracker toward lockout for the duration of a storage blip.
        if let Some(Err(crate::tokens::TokenError::Storage(ref e))) = token_result {
            tracing::error!(error = %e, "token store read failed during Basic auth fallback");
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                "Token verification unavailable",
            )
                .into_response();
        }
        if let Some(Ok((token_user, role))) = token_result {
            if let Some(ip) = client_ip {
                state.auth_failures.record_success(&ip);
            }
            let method = request.method().clone();
            if (method == axum::http::Method::PUT
                || method == axum::http::Method::POST
                || method == axum::http::Method::DELETE
                || method == axum::http::Method::PATCH)
                && !role.can_write()
            {
                return (StatusCode::FORBIDDEN, "Read-only token").into_response();
            }
            // An API token sent as the Basic password is a full bearer identity
            // (#737), so it must clear the admin gate too — else a write token via
            // Basic would reach /api/v1/admin/* unchecked.
            if is_admin && !role.can_admin() {
                return (StatusCode::FORBIDDEN, "Admin role required").into_response();
            }
            // Opaque (nra_) tokens are not namespace-scoped (#583 is OIDC-only).
            request
                .extensions_mut()
                .insert(NamespaceAuthority::Unrestricted);
            request
                .extensions_mut()
                .insert(AuthenticatedUser(token_user));
            request.extensions_mut().insert(AuthenticatedRole(role));
            return next.run(request).await;
        }
        if let Some(ip) = client_ip {
            state.auth_failures.record_failure(ip);
        }
        return unauthorized_response("Invalid username or password", realm);
    }

    // Auth successful — clear failure counter
    if let Some(ip) = client_ip {
        state.auth_failures.record_success(&ip);
    }
    // Basic-auth carries no role, so it can never satisfy an admin path: deny
    // fail-closed (403 — authenticated but not authorized).
    if is_admin {
        return (StatusCode::FORBIDDEN, "Admin role required").into_response();
    }
    // Basic-auth identities are not namespace-scoped (#583 is OIDC-only).
    request
        .extensions_mut()
        .insert(NamespaceAuthority::Unrestricted);
    request
        .extensions_mut()
        .insert(AuthenticatedUser(username.to_string()));
    request
        .extensions_mut()
        .insert(AuthenticatedRole(crate::tokens::Role::Write));
    next.run(request).await
}

fn unauthorized_response(message: &str, realm: &str) -> Response {
    (
        StatusCode::UNAUTHORIZED,
        [
            (
                header::WWW_AUTHENTICATE,
                format!("Basic realm=\"{}\"", realm),
            ),
            (header::CONTENT_TYPE, "application/json".to_string()),
        ],
        format!(r#"{{"error":"{}"}}"#, message),
    )
        .into_response()
}

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

    #[test]
    fn test_public_path_classification() {
        // Unconditional publics: probes + token endpoints only.
        for p in [
            "/",
            "/health",
            "/ready",
            "/api/tokens",
            "/api/tokens/list",
            "/api/tokens/revoke",
        ] {
            assert!(is_public_path(p), "{p}");
        }
        // The web surface is NOT unconditionally public any more — it is
        // config-gated in the middleware (repository enumeration).
        for p in [
            "/ui",
            "/ui/dashboard",
            "/api-docs",
            "/api-docs/openapi.json",
            "/api/ui/stats",
            "/metrics",
        ] {
            assert!(!is_public_path(p), "{p}");
        }
        for p in ["/ui", "/ui/rpm", "/api/ui/stats", "/api-docs"] {
            assert!(is_web_surface(p), "{p}");
        }
        // Token pages are part of the always-gated set, not the web surface.
        assert!(!is_web_surface("/ui/tokens"));
        assert!(!is_web_surface("/api/ui/tokens"));
        // Docker /v2/ is neither.
        assert!(!is_public_path("/v2/"));
        assert!(!is_web_surface("/v2/"));
    }

    #[test]
    fn test_is_public_path_health() {
        assert!(is_public_path("/health"));
        assert!(is_public_path("/ready"));
        // /metrics is config-gated now (auth.public_metrics), not unconditional.
        assert!(!is_public_path("/metrics"));
    }

    #[test]
    fn test_v2_is_not_public_path() {
        // Docker /v2/ must NOT be public — it needs auth challenge per V2 spec
        assert!(!is_public_path("/v2/"));
        assert!(!is_public_path("/v2"));
        // The /v2/ ping and all sub-paths are Docker registry paths, gated as a
        // group by docker_anon_pull.
        assert!(is_docker_path("/v2/"));
        assert!(is_docker_path("/v2"));
        assert!(is_docker_path("/v2/alpine/manifests/latest"));
        // Non-Docker paths are not.
        assert!(!is_docker_path("/raw/file.txt"));
        assert!(!is_docker_path("/v2x/sneaky"));
    }

    #[test]
    fn test_is_public_path_ui() {
        // The UI is the config-gated web surface, not unconditionally public.
        for p in ["/ui", "/ui/dashboard", "/ui/repos"] {
            assert!(!is_public_path(p), "{p}");
            assert!(is_web_surface(p), "{p}");
        }
    }

    #[test]
    fn test_is_public_path_api_docs() {
        for p in ["/api-docs", "/api-docs/openapi.json", "/api/ui"] {
            assert!(!is_public_path(p), "{p}");
            assert!(is_web_surface(p), "{p}");
        }
    }

    #[test]
    fn test_is_public_path_tokens() {
        assert!(is_public_path("/api/tokens"));
        assert!(is_public_path("/api/tokens/list"));
        assert!(is_public_path("/api/tokens/revoke"));
    }

    #[test]
    fn test_is_public_path_root() {
        assert!(is_public_path("/"));
    }

    #[test]
    fn test_is_not_public_path_registry() {
        assert!(!is_public_path("/v2/library/alpine/manifests/latest"));
        assert!(!is_public_path("/npm/lodash"));
        assert!(!is_public_path("/maven/com/example"));
        assert!(!is_public_path("/pypi/simple/flask"));
    }

    #[test]
    fn test_is_not_public_path_random() {
        assert!(!is_public_path("/admin"));
        assert!(!is_public_path("/secret"));
        assert!(!is_public_path("/api/data"));
    }

    #[test]
    fn test_token_ui_paths_not_public() {
        // Token management UI must require authentication
        assert!(!is_public_path("/ui/tokens"));
        assert!(!is_public_path("/ui/tokens/"));
        assert!(!is_public_path("/api/ui/tokens/create"));
        assert!(!is_public_path("/api/ui/tokens/list"));
        assert!(!is_public_path("/api/ui/tokens/abcd1234abcd1234/revoke"));
    }

    #[test]
    fn test_xff_trusted_proxy_uses_forwarded_ip() {
        use crate::config::TrustedProxies;
        let proxies = TrustedProxies::parse("127.0.0.1,::1");
        let mut request = Request::builder()
            .uri("/test")
            .header("x-forwarded-for", "1.2.3.4, 127.0.0.1")
            .body(Body::empty())
            .unwrap();
        request.extensions_mut().insert(ConnectInfo(SocketAddr::new(
            "127.0.0.1".parse().unwrap(),
            1234,
        )));
        let ip = extract_client_ip(&request, &proxies);
        assert_eq!(ip, Some("1.2.3.4".parse().unwrap()));
    }

    #[test]
    fn test_xff_untrusted_proxy_uses_peer_ip() {
        use crate::config::TrustedProxies;
        let proxies = TrustedProxies::parse("127.0.0.1,::1");
        let mut request = Request::builder()
            .uri("/test")
            .header("x-forwarded-for", "1.2.3.4")
            .body(Body::empty())
            .unwrap();
        // Peer is NOT in trusted list
        request.extensions_mut().insert(ConnectInfo(SocketAddr::new(
            "5.6.7.8".parse().unwrap(),
            1234,
        )));
        let ip = extract_client_ip(&request, &proxies);
        assert_eq!(ip, Some("5.6.7.8".parse().unwrap()));
    }

    #[test]
    fn test_xff_no_header_uses_peer_ip() {
        use crate::config::TrustedProxies;
        let proxies = TrustedProxies::parse("127.0.0.1,::1");
        let mut request = Request::builder().uri("/test").body(Body::empty()).unwrap();
        request.extensions_mut().insert(ConnectInfo(SocketAddr::new(
            "127.0.0.1".parse().unwrap(),
            1234,
        )));
        let ip = extract_client_ip(&request, &proxies);
        assert_eq!(ip, Some("127.0.0.1".parse().unwrap()));
    }

    #[test]
    fn test_trusted_proxies_parse_cidr() {
        use crate::config::TrustedProxies;
        let proxies = TrustedProxies::parse("10.0.0.0/8");
        assert!(proxies.contains("10.1.2.3".parse().unwrap()));
        assert!(proxies.contains("10.255.255.255".parse().unwrap()));
        assert!(!proxies.contains("11.0.0.1".parse().unwrap()));
    }

    #[test]
    fn test_trusted_proxies_parse_single_ip() {
        use crate::config::TrustedProxies;
        let proxies = TrustedProxies::parse("192.168.1.1");
        assert!(proxies.contains("192.168.1.1".parse().unwrap()));
        assert!(!proxies.contains("192.168.1.2".parse().unwrap()));
    }

    #[test]
    fn test_trusted_proxies_default_loopback() {
        use crate::config::TrustedProxies;
        let proxies = TrustedProxies::default_loopback();
        assert!(proxies.contains("127.0.0.1".parse().unwrap()));
        assert!(proxies.contains("::1".parse().unwrap()));
        assert!(!proxies.contains("10.0.0.1".parse().unwrap()));
    }

    #[test]
    fn test_auth_failure_tracker_allows_under_threshold() {
        let tracker = AuthFailureTracker::new(5, 900);
        let ip: IpAddr = "10.0.0.1".parse().unwrap();
        for _ in 0..4 {
            tracker.record_failure(ip);
        }
        assert!(tracker.check_blocked(&ip).is_none());
    }

    #[test]
    fn test_auth_failure_tracker_blocks_at_threshold() {
        let tracker = AuthFailureTracker::new(5, 900);
        let ip: IpAddr = "10.0.0.1".parse().unwrap();
        for _ in 0..5 {
            tracker.record_failure(ip);
        }
        assert!(tracker.check_blocked(&ip).is_some());
    }

    #[test]
    fn test_auth_failure_tracker_success_clears() {
        let tracker = AuthFailureTracker::new(5, 900);
        let ip: IpAddr = "10.0.0.1".parse().unwrap();
        for _ in 0..10 {
            tracker.record_failure(ip);
        }
        assert!(tracker.check_blocked(&ip).is_some());
        tracker.record_success(&ip);
        assert!(tracker.check_blocked(&ip).is_none());
    }

    #[test]
    fn test_auth_failure_tracker_independent_ips() {
        let tracker = AuthFailureTracker::new(3, 900);
        let ip1: IpAddr = "10.0.0.1".parse().unwrap();
        let ip2: IpAddr = "10.0.0.2".parse().unwrap();
        for _ in 0..3 {
            tracker.record_failure(ip1);
        }
        assert!(tracker.check_blocked(&ip1).is_some());
        assert!(tracker.check_blocked(&ip2).is_none());
    }

    #[test]
    fn test_auth_failure_tracker_cleanup() {
        let tracker = AuthFailureTracker::new(3, 1); // 1 sec max lockout
        let ip: IpAddr = "10.0.0.1".parse().unwrap();
        for _ in 0..5 {
            tracker.record_failure(ip);
        }
        // Cleanup should remove entries older than 2x max_lockout_secs
        std::thread::sleep(std::time::Duration::from_secs(3));
        tracker.cleanup();
        assert!(tracker.check_blocked(&ip).is_none());
    }

    #[test]
    fn test_auth_failure_tracker_exponential_backoff() {
        let tracker = AuthFailureTracker::new(5, 900);
        let ip: IpAddr = "10.0.0.1".parse().unwrap();
        // 5 failures = threshold, lockout = 2^0 = 1 sec
        for _ in 0..5 {
            tracker.record_failure(ip);
        }
        let retry1 = tracker.check_blocked(&ip).unwrap();
        assert!(
            retry1 <= 1,
            "first lockout should be ~1 sec, got {}",
            retry1
        );

        // 6 failures = 2^1 = 2 sec
        tracker.record_failure(ip);
        let retry2 = tracker.check_blocked(&ip).unwrap();
        assert!(
            retry2 <= 2,
            "second lockout should be ~2 sec, got {}",
            retry2
        );

        // 7 failures = 2^2 = 4 sec
        tracker.record_failure(ip);
        let retry3 = tracker.check_blocked(&ip).unwrap();
        assert!(
            retry3 <= 4,
            "third lockout should be ~4 sec, got {}",
            retry3
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod integration_tests {
    use crate::test_helpers::*;
    use axum::http::{Method, StatusCode};
    use base64::{engine::general_purpose::STANDARD, Engine};

    #[tokio::test]
    async fn test_auth_disabled_passes_all() {
        let ctx = create_test_context();
        let response = send(&ctx.app, Method::PUT, "/raw/test.txt", b"data".to_vec()).await;
        assert_eq!(response.status(), StatusCode::CREATED);
    }

    #[tokio::test]
    async fn test_auth_public_paths_always_pass() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let response = send(&ctx.app, Method::GET, "/health", "").await;
        assert_eq!(response.status(), StatusCode::OK);
        let response = send(&ctx.app, Method::GET, "/ready", "").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// Docker Registry V2 spec: GET /v2/ without credentials must return 401
    /// with WWW-Authenticate header when auth is enabled (issue #219)
    #[tokio::test]
    async fn test_docker_v2_requires_auth_when_enabled() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);

        // Without credentials: must return 401 + WWW-Authenticate
        let response = send(&ctx.app, Method::GET, "/v2/", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert!(response.headers().contains_key("www-authenticate"));

        // With valid credentials: must return 200
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/v2/",
            vec![("authorization", &header_val)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// Docker /v2/ must NOT pass through anonymous_read bypass.
    /// Even with anonymous_read=true, /v2/ must require auth so Docker
    /// clients know to send credentials on subsequent push/pull requests.
    #[tokio::test]
    async fn test_docker_v2_ignores_anonymous_read() {
        let ctx = create_test_context_with_anonymous_read(&[("admin", "secret")]);

        // /v2/ without auth: must still return 401 even with anonymous_read=true
        let response = send(&ctx.app, Method::GET, "/v2/", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert!(response.headers().contains_key("www-authenticate"));

        // Other read endpoints should still work anonymously
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            b"data".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::CREATED);
        let response = send(&ctx.app, Method::GET, "/raw/test.txt", "").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    // --- #778: anonymous Docker pull via the `docker_anon_pull` opt-in ---

    /// docker_anon_pull=true: the `GET /v2/` ping is served anonymously
    /// (200, no challenge) so the Docker client proceeds without credentials.
    #[tokio::test]
    async fn test_docker_anon_pull_allows_v2_ping() {
        let ctx = create_test_context_with_docker_anon_pull(&[("admin", "secret")]);
        let response = send(&ctx.app, Method::GET, "/v2/", "").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// docker_anon_pull=true: an anonymous manifest read passes the auth
    /// gate and reaches the handler (404 for a missing tag, NOT 401).
    #[tokio::test]
    async fn test_docker_anon_pull_allows_manifest_read() {
        let ctx = create_test_context_with_docker_anon_pull(&[("admin", "secret")]);
        let response = send(&ctx.app, Method::GET, "/v2/alpine/manifests/latest", "").await;
        assert_ne!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "anonymous manifest read must pass the auth gate under docker_anon_pull"
        );
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    /// docker_anon_pull=true: writes are not read methods → still require
    /// auth. The Docker handler does not self-check role, so the middleware is
    /// the only write-stop — anonymous push/delete MUST be rejected.
    #[tokio::test]
    async fn test_docker_anon_pull_blocks_anonymous_writes() {
        let ctx = create_test_context_with_docker_anon_pull(&[("admin", "secret")]);

        // Start a blob upload (push) anonymously -> 401.
        let response = send(&ctx.app, Method::POST, "/v2/alpine/blobs/uploads/", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        // Push a manifest anonymously -> 401.
        let response = send(
            &ctx.app,
            Method::PUT,
            "/v2/alpine/manifests/latest",
            b"{}".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        // Delete a manifest anonymously -> 401.
        let response = send(
            &ctx.app,
            Method::DELETE,
            "/v2/alpine/manifests/sha256:0000000000000000000000000000000000000000000000000000000000000000",
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    /// docker_anon_pull=true must NOT break authenticated push: a write with
    /// valid credentials starts the upload (202), exactly as without the flag.
    #[tokio::test]
    async fn test_docker_anon_pull_authenticated_push_still_works() {
        let ctx = create_test_context_with_docker_anon_pull(&[("admin", "secret")]);
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/v2/alpine/blobs/uploads/",
            vec![("authorization", &header_val)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::ACCEPTED);
    }

    /// docker_anon_pull=true: `/v2/_catalog` stays authenticated — anonymous
    /// repository enumeration is not part of anonymous pull-by-name.
    #[tokio::test]
    async fn test_docker_anon_pull_catalog_requires_auth() {
        let ctx = create_test_context_with_docker_anon_pull(&[("admin", "secret")]);

        let response = send(&ctx.app, Method::GET, "/v2/_catalog", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/v2/_catalog",
            vec![("authorization", &header_val)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// docker_anon_pull=true: presented credentials are still validated —
    /// the anonymous bypass applies only when no Authorization header is sent.
    /// Wrong creds on the `/v2/` ping return 401 (honest `docker login`).
    #[tokio::test]
    async fn test_docker_anon_pull_validates_presented_credentials() {
        let ctx = create_test_context_with_docker_anon_pull(&[("admin", "secret")]);

        let bad = format!("Basic {}", STANDARD.encode("admin:wrong"));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/v2/",
            vec![("authorization", &bad)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        let good = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/v2/",
            vec![("authorization", &good)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// The general `anonymous_read` switch must NOT open Docker (#778): with
    /// anonymous_read=true but docker_anon_pull=false, Docker `/v2` paths
    /// still require auth, so exposing Maven/raw never exposes images.
    #[tokio::test]
    async fn test_anonymous_read_does_not_open_docker() {
        let ctx = create_test_context_with_anonymous_read(&[("admin", "secret")]);

        // /v2/ ping still challenges.
        let response = send(&ctx.app, Method::GET, "/v2/", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        // Manifest read still requires auth — the general flag does not open Docker.
        let response = send(&ctx.app, Method::GET, "/v2/alpine/manifests/latest", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    /// When auth is disabled, /v2/ should pass through normally
    #[tokio::test]
    async fn test_docker_v2_passes_when_auth_disabled() {
        let ctx = create_test_context();
        let response = send(&ctx.app, Method::GET, "/v2/", "").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_auth_blocks_without_credentials() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let response = send(&ctx.app, Method::PUT, "/raw/test.txt", b"data".to_vec()).await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert!(response.headers().contains_key("www-authenticate"));
    }

    #[tokio::test]
    async fn test_auth_basic_works() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            b"data".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::CREATED);
    }

    #[tokio::test]
    async fn test_auth_basic_wrong_password() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let header_val = format!("Basic {}", STANDARD.encode("admin:wrong"));
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            b"data".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    /// #736: an API token presented as the Basic-auth password (any username) must
    /// authenticate — Docker/twine/Maven send the token as the Basic password and never
    /// use Bearer, so without this the documented `docker login -u token -p nra_…` fails.
    #[tokio::test]
    async fn test_basic_auth_accepts_api_token() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let token = ctx
            .state
            .tokens
            .as_ref()
            .unwrap()
            .create_token("admin", 30, None, crate::tokens::Role::Write)
            .unwrap();
        // Docker sends Basic base64("<user>:<token>"); the username is ignored.
        let header_val = format!("Basic {}", STANDARD.encode(format!("token:{token}")));
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            b"data".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::CREATED);
    }

    /// #736: a read-only API token as the Basic-auth password must be rejected for writes,
    /// matching the Bearer path's role gate.
    #[tokio::test]
    async fn test_basic_auth_read_only_token_cannot_write() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let token = ctx
            .state
            .tokens
            .as_ref()
            .unwrap()
            .create_token("admin", 30, None, crate::tokens::Role::Read)
            .unwrap();
        let header_val = format!("Basic {}", STANDARD.encode(format!("token:{token}")));
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            b"data".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    /// Path of a stored token's on-disk file inside a test context.
    fn token_file_path(ctx: &crate::test_helpers::TestContext, token: &str) -> std::path::PathBuf {
        use sha2::Digest;
        let prefix = hex::encode(sha2::Sha256::digest(token.as_bytes()));
        ctx._tempdir
            .path()
            .join("tokens")
            .join(format!("{}.json", &prefix[..16]))
    }

    /// A token-store read failure (torn/corrupt file, I/O error) is an outage,
    /// not a credential verdict: Basic auth with a valid-format token must
    /// answer 503 (retryable), never 401 — a 401 makes valid creds flap and
    /// walks the per-IP failure tracker toward lockout for the duration of a
    /// storage blip. Regression for the 2026-08 same-creds 200↔401 flap.
    #[tokio::test]
    async fn test_basic_auth_token_store_error_returns_503_not_401() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let token = ctx
            .state
            .tokens
            .as_ref()
            .unwrap()
            .create_token("ci", 30, None, crate::tokens::Role::Read)
            .unwrap();
        // Corrupt the file the way a torn in-place rewrite would. The token was
        // never verified, so the in-memory cache is cold and the disk is read.
        std::fs::write(token_file_path(&ctx, &token), "{\"token_ha").unwrap();

        let header_val = format!("Basic {}", STANDARD.encode(format!("ci:{token}")));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            Vec::new(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    /// Same rule on the Bearer path: an `nra_` token that cannot be verified
    /// because the store read failed must 503, not fall through to OIDC and 401.
    #[tokio::test]
    async fn test_bearer_token_store_error_returns_503_not_401() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let token = ctx
            .state
            .tokens
            .as_ref()
            .unwrap()
            .create_token("ci", 30, None, crate::tokens::Role::Read)
            .unwrap();
        std::fs::write(token_file_path(&ctx, &token), "{\"token_ha").unwrap();

        let header_val = format!("Bearer {token}");
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            Vec::new(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn test_auth_anonymous_read() {
        let ctx = create_test_context_with_anonymous_read(&[("admin", "secret")]);
        // Upload with auth
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/test.txt",
            vec![("authorization", &header_val)],
            b"data".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::CREATED);
        // Read without auth should work
        let response = send(&ctx.app, Method::GET, "/raw/test.txt", "").await;
        assert_eq!(response.status(), StatusCode::OK);
        // Write without auth should fail
        let response = send(&ctx.app, Method::PUT, "/raw/test2.txt", b"data".to_vec()).await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    /// Token management must require auth even with anonymous_read=true (#221)
    #[tokio::test]
    async fn test_token_ui_requires_auth_with_anonymous_read() {
        let ctx = create_test_context_with_anonymous_read(&[("admin", "secret")]);

        // GET /ui/tokens without auth must return 401 even with anonymous_read
        let response = send(&ctx.app, Method::GET, "/ui/tokens", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        // GET /api/ui/tokens/list without auth must also return 401
        let response = send(&ctx.app, Method::GET, "/api/ui/tokens/list", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        // With auth, token UI should work
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/ui/tokens",
            vec![("authorization", &header_val)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);

        // Other read endpoints should still work anonymously
        let response = send(&ctx.app, Method::GET, "/health", "").await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_token_ui_requires_auth() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);

        // Token UI page without auth should return 401
        let response = send(&ctx.app, Method::GET, "/ui/tokens", "").await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

        // Token UI page with auth should work
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/ui/tokens",
            vec![("authorization", &header_val)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_token_ui_create_requires_htmx() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));

        // POST without HX-Request header should be rejected (CSRF)
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/ui/tokens/create",
            vec![
                ("authorization", &header_val),
                ("content-type", "application/x-www-form-urlencoded"),
            ],
            "description=test&role=read&ttl_days=30",
        )
        .await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN);

        // POST with HX-Request header should work
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/ui/tokens/create",
            vec![
                ("authorization", &header_val),
                ("content-type", "application/x-www-form-urlencoded"),
                ("hx-request", "true"),
            ],
            "description=test&role=read&ttl_days=30",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_token_ui_revoke_validates_file_id() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));

        // Invalid file_id (not hex, no slashes so route matches)
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/ui/tokens/not_valid_hex_xx/revoke",
            vec![("authorization", &header_val), ("hx-request", "true")],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);

        // Valid hex but non-existent
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/ui/tokens/abcd1234abcd1234/revoke",
            vec![("authorization", &header_val), ("hx-request", "true")],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    /// Token API endpoints are public (in is_public_path) because they validate
    /// credentials in the handler body. Verify that empty/missing credentials
    /// are properly rejected with 401 — defense-in-depth against any future
    /// refactor that might accidentally remove body-level auth checks.
    #[tokio::test]
    async fn test_token_create_without_credentials_returns_401() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/tokens",
            vec![("content-type", "application/json")],
            r#"{}"#,
        )
        .await;
        // Empty JSON body has no username/password — serde fails or handler rejects
        assert!(
            response.status() == StatusCode::UNAUTHORIZED
                || response.status() == StatusCode::UNPROCESSABLE_ENTITY
                || response.status() == StatusCode::BAD_REQUEST,
            "Expected 401/422/400, got {}",
            response.status()
        );
    }

    #[tokio::test]
    async fn test_token_list_without_credentials_returns_401() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/tokens/list",
            vec![("content-type", "application/json")],
            r#"{}"#,
        )
        .await;
        assert!(
            response.status() == StatusCode::UNAUTHORIZED
                || response.status() == StatusCode::UNPROCESSABLE_ENTITY
                || response.status() == StatusCode::BAD_REQUEST,
            "Expected 401/422/400, got {}",
            response.status()
        );
    }

    #[tokio::test]
    async fn test_token_revoke_without_credentials_returns_401() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/tokens/revoke",
            vec![("content-type", "application/json")],
            r#"{}"#,
        )
        .await;
        assert!(
            response.status() == StatusCode::UNAUTHORIZED
                || response.status() == StatusCode::UNPROCESSABLE_ENTITY
                || response.status() == StatusCode::BAD_REQUEST,
            "Expected 401/422/400, got {}",
            response.status()
        );
    }

    #[tokio::test]
    async fn test_token_ui_full_lifecycle() {
        let ctx = create_test_context_with_auth(&[("admin", "secret")]);
        let header_val = format!("Basic {}", STANDARD.encode("admin:secret"));

        // Create a token via UI endpoint
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            "/api/ui/tokens/create",
            vec![
                ("authorization", &header_val),
                ("content-type", "application/x-www-form-urlencoded"),
                ("hx-request", "true"),
            ],
            "description=CI+Pipeline&role=write&ttl_days=30",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = String::from_utf8(body_bytes(response).await.to_vec()).unwrap();
        assert!(body.contains("nra_"), "Response should contain raw token");

        // List tokens
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/api/ui/tokens/list",
            vec![("authorization", &header_val)],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = String::from_utf8(body_bytes(response).await.to_vec()).unwrap();
        assert!(body.contains("CI Pipeline"), "List should show description");

        // Get file_id from the token store directly for revoke test
        let tokens = ctx.state.tokens.as_ref().unwrap().list_all_tokens();
        assert_eq!(tokens.len(), 1);
        let file_id = &tokens[0].file_id;

        // Revoke
        let revoke_url = format!("/api/ui/tokens/{}/revoke", file_id);
        let response = send_with_headers(
            &ctx.app,
            Method::POST,
            &revoke_url,
            vec![("authorization", &header_val), ("hx-request", "true")],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);

        // Verify token is gone
        let tokens = ctx.state.tokens.as_ref().unwrap().list_all_tokens();
        assert_eq!(tokens.len(), 0);
    }
}

// ---------------------------------------------------------------------------
// OIDC Integration Tests — full middleware flow with mock JWKS server
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod oidc_integration_tests {
    use crate::auth::oidc::OidcValidator;
    use crate::config::{OidcConfig, OidcProvider, OidcRoleRule};
    use crate::test_helpers::*;
    use axum::http::{Method, StatusCode};
    use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
    use serde_json::json;
    use std::sync::Arc;
    use std::time::{SystemTime, UNIX_EPOCH};
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Test RSA private key (2048-bit, for test JWT signing only)
    const TEST_RSA_PRIVATE_KEY: &str = r#"-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7657FVL7gwmjj
PEfl4A+ajG3DFj6YHmS9gargHMChpdLMbt8ybqu1hHPUNKQyndUvFJ6q+xJFEds3
eBtjB5GLLtlj9lScvGPsV7386rypeHq30IErgm2beQJyF9ldtrVHBBPbz7eAo4+i
wCJ/m5IsuoLCYZPQrDUdpax0dUEa/eP6badqjZ2r0recnHw1+zGyozzSHNvPtK9I
PsKwBcbGjt5n5+9nWN322/mISAuLNwtv7l3Lja8U7m0ixH0ZLwFSgTLtzEfJISux
+ngGR4k2PBVeo+yDOZtuatx7Aixa1FerOwiq2xsoGOs2dhXagwFGdwbs8x/MvEj0
67Mm3OrLAgMBAAECggEAHXZkjyWpQ43XagESeKz3ZVCtCNAdAjaJrth8lOSNIwrf
kOO1JLALRcs9acDTGYh7WwVNlxsEE0Yoa3ruOEmAfSTcOnrtayFyPSTIibW33I4i
F12eUtcBHkYLpx2sG7BAnaC7CFR5vbZnF6ot/nnCojaft6Aaz7WgIkTOU/fqPDPb
WOSn4PQmgZS34non7y0NWmxxeIwqJk3aBeeEKisO2AS0YCHOgx2uBTIt2lcIzjK8
RHwQjLRRfhzxuhHuQtz/hMVQ17W3l7ehYTnW0D+UJJTXBjPgElICmWdGm9NMX9YH
HzVSBdH+tzTZ/hUhKe+nEZ5vrWT2wqx/h0med2P3eQKBgQDYNURqK7dfo2QBsy/F
pdUg7UaXfWe+c6guu32aZhnxYsHUE68cuV7Bz/awjMJYvF9VKhoJ+iuHI0myo9In
HITzbSDwFrWCme7DAIPbfbQU9nQqJLK/g3nUpYSpjFQEnIPJSr1aS/fVpUURAoBg
RSktyRTY3ak7+6x1I54HLxPk3QKBgQDegZEqK6B28fQklCPgdimwnNr92oJe5hoY
9cHUDz3A1Uyek40LQ1yR7W/imDCJMcQXqM7Lo54+55eHEkBvh6H/TTmnGMzj5L7t
HoKYMjYdBK7waFYGM6ULfVXqs6JqVmKFU7LX+ZVmOB5kgcQMQrAhio0GrG97iDqz
aKHqOthfxwKBgQDKa+SnulIumlzRMqAxXfdSopOK1YBB0SrOxf7shVcYpitukRdL
v0m2DyyZUs/KIGLo60gBu1TxatpfA/2HXK4k8jD6V2iM4+2kaGELKH9neO59Xmpz
33Y63tR7oMQwpRDFbtIlLibUwa0OJddnSpkpIq//8le1rwVhjn0voKXxiQKBgQDS
2qPO+6LHtQewdjX9atydAjfAooYzGgkXKCTzKTJS/47pI1hgmQgrPX9uktxD1sZF
yXGWpsm6QMtmc5ReXIDWp77/q0/WkpmfqO8G/WYsX5jMN4N1wxEfbzmw/WPnM0+P
mz56zoiWYo3intpC6Bty3ZJBBb1rqjA+feQaTINpVwKBgF/M0Lj9Sq9G2Ec7yBnm
xhBlLwCNzAk33Fy+6w6ANXTsGRwMm0zGdTjC3e6LHMrD0ZtF0M2blWAUh3sZ6ItQ
2Ak5ScO0q3MRQvo4HZkFK2wuZvNLYExq6gGy3P6l8xXbvQTzg5nl9UWDKfY1gifz
Jd74nq6dNCjpWG4drIsyhqX+
-----END PRIVATE KEY-----"#;

    // Corresponding JWKS (public key in JWK format)
    const TEST_JWKS_JSON: &str = r#"{"keys":[{"kty":"RSA","kid":"test-key-1","use":"sig","alg":"RS256","n":"u-uexVS-4MJo4zxH5eAPmoxtwxY-mB5kvYGq4BzAoaXSzG7fMm6rtYRz1DSkMp3VLxSeqvsSRRHbN3gbYweRiy7ZY_ZUnLxj7Fe9_Oq8qXh6t9CBK4Jtm3kCchfZXba1RwQT28-3gKOPosAif5uSLLqCwmGT0Kw1HaWsdHVBGv3j-m2nao2dq9K3nJx8NfsxsqM80hzbz7SvSD7CsAXGxo7eZ-fvZ1jd9tv5iEgLizcLb-5dy42vFO5tIsR9GS8BUoEy7cxHySErsfp4BkeJNjwVXqPsgzmbbmrcewIsWtRXqzsIqtsbKBjrNnYV2oMBRncG7PMfzLxI9OuzJtzqyw","e":"AQAB"}]}"#;

    fn now_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }

    /// Create a signed JWT with given claims.
    fn make_jwt(issuer: &str, subject: &str, audience: &str, iat: u64, exp: u64) -> String {
        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("test-key-1".to_string());

        let claims = json!({
            "iss": issuer,
            "sub": subject,
            "aud": audience,
            "iat": iat,
            "exp": exp,
        });

        let key = EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY.as_bytes()).unwrap();
        encode(&header, &claims, &key).unwrap()
    }

    /// Build a TestContext with OIDC enabled, pointing at the given mock JWKS URL.
    fn create_oidc_test_context(mock_issuer_url: &str) -> TestContext {
        create_oidc_test_context_scoped(mock_issuer_url, &["*"], None)
    }

    /// Like [`create_oidc_test_context`], with the provider `namespace_scope`
    /// and the main-branch rule's `namespace_scope` injectable.
    fn create_oidc_test_context_scoped(
        mock_issuer_url: &str,
        provider_scope: &[&str],
        main_rule_scope: Option<Vec<String>>,
    ) -> TestContext {
        let issuer = mock_issuer_url.to_string();
        let provider_scope: Vec<String> = provider_scope.iter().map(|s| s.to_string()).collect();
        let mut ctx = create_test_context_with_config(move |cfg| {
            cfg.auth.enabled = true;
            cfg.auth.anonymous_read = false;
            cfg.auth.oidc = OidcConfig {
                enabled: true,
                leeway_secs: 60,
                jwks_cache_secs: 300,
                providers: vec![OidcProvider {
                    name: "test-ci".to_string(),
                    issuer: issuer.clone(),
                    jwks_uri: None,
                    audience: "nora".to_string(),
                    algorithms: vec!["RS256".to_string()],
                    max_token_lifetime_secs: 900,
                    namespace_scope: provider_scope.clone(),
                    namespace_scope_enforcement: crate::config::ScopeEnforcement::Enforce,
                    enabled: true,
                    role_rules: vec![
                        OidcRoleRule {
                            pattern: "repo:myorg/*:ref:refs/heads/main".to_string(),
                            role: "write".to_string(),
                            namespace_scope: main_rule_scope.clone(),
                        },
                        OidcRoleRule {
                            pattern: "repo:myorg/*:pull_request".to_string(),
                            role: "write".to_string(),
                            namespace_scope: Some(vec!["ci-transport/**".to_string()]),
                        },
                        OidcRoleRule {
                            pattern: "repo:myorg/*".to_string(),
                            role: "read".to_string(),
                            namespace_scope: None,
                        },
                    ],
                }],
            };
        });

        // Wire up the OidcValidator on the existing state
        let oidc_validator =
            OidcValidator::new(ctx.state.config.auth.oidc.clone(), reqwest::Client::new());
        // We need to rebuild the state with oidc set — use Arc::get_mut or rebuild
        let state = crate::AppState {
            storage: ctx.state.storage.clone(),
            config: ctx.state.config.clone(),
            enabled_registries: ctx.state.enabled_registries.clone(),
            start_time: ctx.state.start_time,
            startup_duration_ms: ctx.state.startup_duration_ms,
            auth: ctx.state.auth.clone(),
            tokens: ctx.state.tokens.clone(),
            metrics: Arc::new(crate::dashboard_metrics::DashboardMetrics::new()),
            activity: Arc::new(crate::activity_log::ActivityLog::new(50)),
            audit: ctx.state.audit.clone(),
            docker_auth: Arc::new(crate::registry::DockerAuth::new(reqwest::Client::new(), 5)),
            repo_index: Arc::new(crate::repo_index::RepoIndex::new()),
            http_client: reqwest::Client::new(),
            upload_sessions: Arc::new(parking_lot::RwLock::new(std::collections::HashMap::new())),
            publish_locks: Arc::new(parking_lot::Mutex::new(std::collections::HashMap::new())),
            reloadable: Arc::new(arc_swap::ArcSwap::from_pointee(crate::ReloadableConfig {
                curation_engine: crate::curation::CurationEngine::new(
                    crate::config::CurationConfig::default(),
                ),
                bypass_token: None,
            })),
            auth_failures: Arc::new(crate::auth::AuthFailureTracker::new(5, 900)),
            oidc: Some(Arc::new(oidc_validator)),
            circuit_breaker: Arc::new(crate::circuit_breaker::CircuitBreakerRegistry::new(
                ctx.state.config.circuit_breaker.clone(),
            )),
            proxy_coalesce: crate::proxy_coalesce::InflightMap::new(),
            digest_store: ctx.state.digest_store.clone(),
            signer: ctx.state.signer.clone(),
            leak_finders: ctx.state.leak_finders.clone(),
            cancel_token: tokio_util::sync::CancellationToken::new(),
        };

        // Rebuild router with new state
        use axum::{extract::DefaultBodyLimit, middleware, Router};
        let mut registry_routes = Router::new();
        for reg in state.enabled_registries.iter() {
            match reg {
                crate::registry_type::RegistryType::Raw => {
                    registry_routes = registry_routes.merge(crate::registry::raw_routes());
                }
                _ => {}
            }
        }
        let public_routes = Router::new().merge(crate::health::routes());
        let app_routes = Router::new()
            .merge(crate::auth::token_routes())
            .merge(crate::ui::routes())
            .merge(registry_routes);
        let app = Router::new()
            .merge(public_routes)
            .merge(app_routes)
            .layer(DefaultBodyLimit::max(
                state.config.server.body_limit_mb * 1024 * 1024,
            ))
            .layer(middleware::from_fn(
                crate::request_id::request_id_middleware,
            ))
            .layer(middleware::from_fn_with_state(
                state.clone(),
                crate::auth::auth_middleware,
            ))
            .with_state(state.clone());

        ctx.state = state;
        ctx.app = app;
        ctx
    }

    #[tokio::test]
    async fn test_oidc_valid_jwt_write_access() {
        let mock_server = MockServer::start().await;

        // Serve JWKS at /.well-known/jwks.json
        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/main",
            "nora",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/oidc-test.txt",
            vec![("authorization", &bearer)],
            b"hello from ci".to_vec(),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::CREATED,
            "Write with main-branch OIDC token should succeed"
        );
    }

    #[tokio::test]
    async fn test_oidc_rule_scope_narrows_writes() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        // pull_request rule: role=write, namespace_scope=["ci-transport/**"]
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:pull_request",
            "nora",
            now,
            now + 600,
        );
        let bearer = format!("Bearer {}", token);

        // In-scope write is allowed…
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/ci-transport/run-1/artifact.txt",
            vec![("authorization", &bearer)],
            b"transport".to_vec(),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::CREATED,
            "PR token should write inside its rule scope"
        );

        // …but the same identity cannot write outside the rule's scope, even
        // though the provider scope is ["*"].
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/prod/artifact.txt",
            vec![("authorization", &bearer)],
            b"escape".to_vec(),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::FORBIDDEN,
            "PR token must not write outside its rule scope"
        );
    }

    #[tokio::test]
    async fn test_oidc_rule_scope_cannot_widen_provider_ceiling() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        // Narrow provider ceiling, rule that tries to widen to ["*"].
        let ctx = create_oidc_test_context_scoped(
            &mock_server.uri(),
            &["myorg/**"],
            Some(vec!["*".to_string()]),
        );
        let now = now_secs();
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/main",
            "nora",
            now,
            now + 600,
        );
        let bearer = format!("Bearer {}", token);

        // Inside the provider ceiling: allowed.
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/myorg/repo/artifact.txt",
            vec![("authorization", &bearer)],
            b"inside".to_vec(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::CREATED);

        // The rule's ["*"] must not lift the provider ceiling.
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/other/artifact.txt",
            vec![("authorization", &bearer)],
            b"escape".to_vec(),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::FORBIDDEN,
            "a rule namespace_scope of [\"*\"] must not widen past the provider scope"
        );
    }

    #[tokio::test]
    async fn test_oidc_valid_jwt_read_only_blocks_write() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        // dev branch → read-only role
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/dev",
            "nora",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::PUT,
            "/raw/oidc-test.txt",
            vec![("authorization", &bearer)],
            b"hello".to_vec(),
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::FORBIDDEN,
            "Write with read-only OIDC token should be forbidden"
        );
    }

    #[tokio::test]
    async fn test_oidc_valid_jwt_read_only_allows_get() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/dev",
            "nora",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        // GET should succeed (even if file doesn't exist — 404 not 401/403)
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/nonexistent.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_ne!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Read with valid OIDC token should not be 401"
        );
        assert_ne!(
            response.status(),
            StatusCode::FORBIDDEN,
            "Read with read-only OIDC token should not be 403"
        );
    }

    #[tokio::test]
    async fn test_oidc_expired_token_rejected() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        // Token expired 2 minutes ago (beyond 60s leeway)
        let now = now_secs();
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/main",
            "nora",
            now - 600,
            now - 120,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Expired OIDC token should be rejected"
        );
    }

    #[tokio::test]
    async fn test_oidc_wrong_issuer_rejected() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        // Token has a different issuer than configured
        let token = make_jwt(
            "https://evil-issuer.example.com",
            "repo:myorg/app:ref:refs/heads/main",
            "nora",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Token with wrong issuer should be rejected"
        );
    }

    #[tokio::test]
    async fn test_oidc_wrong_audience_rejected() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        // Token has wrong audience
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/main",
            "wrong-audience",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Token with wrong audience should be rejected"
        );
    }

    #[tokio::test]
    async fn test_oidc_no_matching_role_rejected() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        // Subject from a different org → no role_rules match
        let token = make_jwt(
            &mock_server.uri(),
            "repo:otherorg/app:ref:refs/heads/main",
            "nora",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Token with no matching role should be rejected"
        );
    }

    #[tokio::test]
    async fn test_oidc_token_lifetime_exceeded() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        // Token lifetime = 2000s, exceeds max_token_lifetime_secs = 900
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/main",
            "nora",
            now,
            now + 2000,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Token exceeding max lifetime should be rejected"
        );
    }

    #[tokio::test]
    async fn test_oidc_jwks_fetch_failure_returns_401() {
        let mock_server = MockServer::start().await;

        // Don't mount any mock → JWKS fetch will 404
        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();
        let token = make_jwt(
            &mock_server.uri(),
            "repo:myorg/app:ref:refs/heads/main",
            "nora",
            now,
            now + 600,
        );

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "Should fail gracefully when JWKS cannot be fetched"
        );
    }

    #[tokio::test]
    async fn test_oidc_symmetric_algorithm_rejected() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/.well-known/jwks.json"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(TEST_JWKS_JSON, "application/json"),
            )
            .mount(&mock_server)
            .await;

        let ctx = create_oidc_test_context(&mock_server.uri());
        let now = now_secs();

        // Create token signed with HS256 (symmetric) — should be rejected
        // even before JWKS fetch because of algorithm whitelist
        let mut header = Header::new(Algorithm::HS256);
        header.kid = Some("test-key-1".to_string());
        let claims = json!({
            "iss": mock_server.uri(),
            "sub": "repo:myorg/app:ref:refs/heads/main",
            "aud": "nora",
            "iat": now,
            "exp": now + 600,
        });
        let key = EncodingKey::from_secret(b"fake-secret");
        let token = encode(&header, &claims, &key).unwrap();

        let bearer = format!("Bearer {}", token);
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/raw/test.txt",
            vec![("authorization", &bearer)],
            "",
        )
        .await;
        assert_eq!(
            response.status(),
            StatusCode::UNAUTHORIZED,
            "HS256 tokens must be rejected for OIDC"
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod web_surface_gating_tests {
    use crate::test_helpers::{create_test_context_with_auth, send, send_with_headers};
    use axum::http::{Method, StatusCode};
    use base64::Engine;

    fn basic(user: &str, pass: &str) -> String {
        format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(format!("{user}:{pass}"))
        )
    }

    /// With auth on and no anonymous read, the whole web surface requires
    /// credentials — it enumerates every repository — while probes stay open.
    #[tokio::test]
    async fn test_web_surface_gated_when_private() {
        let ctx = create_test_context_with_auth(&[("alice", "pw")]);

        for p in [
            "/ui/",
            "/ui/rpm",
            "/api/ui/stats",
            "/api/ui/dashboard",
            "/api-docs/openapi.json",
        ] {
            let resp = send(&ctx.app, Method::GET, p, "").await;
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{p}");
            assert!(
                resp.headers().get("www-authenticate").is_some(),
                "{p} must challenge so browsers prompt"
            );
        }
        // Probes stay unconditionally open (LB/liveness would break).
        for p in ["/health", "/ready"] {
            let resp = send(&ctx.app, Method::GET, p, "").await;
            assert_eq!(resp.status(), StatusCode::OK, "{p}");
        }
        // /metrics defaults to open for scrapers.
        let resp = send(&ctx.app, Method::GET, "/metrics", "").await;
        assert_eq!(resp.status(), StatusCode::OK);

        // Valid credentials open the web surface.
        let cred = basic("alice", "pw");
        let resp = send_with_headers(
            &ctx.app,
            Method::GET,
            "/api/ui/stats",
            vec![("authorization", cred.as_str())],
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    /// anonymous_read (which already exposes repo names through the registry
    /// read APIs) or the explicit public_web_ui switch reopen the surface;
    /// public_metrics=false closes /metrics.
    #[tokio::test]
    async fn test_gating_switches() {
        let ctx = crate::test_helpers::create_test_context_with_config(|c| {
            c.auth.enabled = true;
            c.auth.anonymous_read = true;
        });
        let resp = send(&ctx.app, Method::GET, "/ui/", "").await;
        assert_eq!(resp.status(), StatusCode::OK, "anonymous_read opens the UI");

        let ctx = crate::test_helpers::create_test_context_with_config(|c| {
            c.auth.enabled = true;
            c.auth.public_web_ui = true;
        });
        let resp = send(&ctx.app, Method::GET, "/api/ui/stats", "").await;
        assert_eq!(resp.status(), StatusCode::OK, "public_web_ui opens the UI");

        let ctx = crate::test_helpers::create_test_context_with_config(|c| {
            c.auth.enabled = true;
            c.auth.public_metrics = false;
        });
        let resp = send(&ctx.app, Method::GET, "/metrics", "").await;
        assert_eq!(
            resp.status(),
            StatusCode::UNAUTHORIZED,
            "public_metrics=false gates metrics"
        );
    }

    /// Token management pages stay gated even when the web surface is open.
    #[tokio::test]
    async fn test_token_pages_stay_gated() {
        let ctx = crate::test_helpers::create_test_context_with_config(|c| {
            c.auth.enabled = true;
            c.auth.public_web_ui = true;
        });
        let resp = send(&ctx.app, Method::GET, "/api/ui/tokens", "").await;
        assert_ne!(resp.status(), StatusCode::OK);
    }
}