nora-registry 1.2.2

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
// Copyright (c) 2026 The NORA Authors
// SPDX-License-Identifier: MIT

//! PyPI registry — PEP 503 (Simple HTML) + PEP 691 (JSON) + twine upload.
//!
//! Implements:
//!   GET  /simple/                     — package index (HTML or JSON)
//!   GET  /simple/{name}/              — package versions (HTML or JSON)
//!   GET  /simple/{name}/{filename}    — download file
//!   POST /simple/                     — twine upload (multipart/form-data)

use crate::activity_log::{ActionType, ActivityEntry};
use crate::audit::AuditEntry;
use crate::auth::{enforce_namespace_scope, NamespaceAuthority};
use crate::registry::{
    circuit_open_response, method_not_allowed, nora_base_url, proxy_fetch, proxy_fetch_text,
};
use crate::registry_type::RegistryType;
use crate::ui::components::html_escape;
use crate::validation::ends_with_ci;
use crate::AppState;
use axum::{
    extract::{Multipart, Path, State},
    http::{header, HeaderMap, StatusCode},
    response::{Html, IntoResponse, Response},
    routing::get,
    Extension, Router,
};
use sha2::Digest;
use std::fmt::Write;
use std::sync::Arc;
use std::time::Duration;

/// PEP 691 JSON content type
const PEP691_JSON: &str = "application/vnd.pypi.simple.v1+json";

pub fn routes() -> Router<AppState> {
    Router::new()
        .route(
            "/simple/",
            get(list_packages)
                .post(upload)
                .fallback(|| async { method_not_allowed("GET, POST") }),
        )
        .route("/simple/{name}/", get(package_versions))
        .route("/simple/{name}/{filename}", get(download_file))
}

// ============================================================================
// Package index
// ============================================================================

/// GET /simple/ — list all packages (PEP 503 HTML or PEP 691 JSON).
async fn list_packages(State(state): State<AppState>, headers: HeaderMap) -> impl IntoResponse {
    let keys = match state.storage.list("pypi/").await {
        Ok(k) => k,
        Err(e) => {
            tracing::error!(error = ?e, "pypi: failed to list storage for packages");
            return StatusCode::SERVICE_UNAVAILABLE.into_response();
        }
    };
    let mut packages = std::collections::HashSet::new();

    for key in keys {
        if let Some(pkg) = key.strip_prefix("pypi/").and_then(|k| k.split('/').next()) {
            if !pkg.is_empty() {
                packages.insert(pkg.to_string());
            }
        }
    }

    let mut pkg_list: Vec<_> = packages.into_iter().collect();
    pkg_list.sort();

    if wants_json(&headers) {
        // PEP 691 JSON response
        let projects: Vec<serde_json::Value> = pkg_list
            .iter()
            .map(|name| serde_json::json!({"name": name}))
            .collect();
        let body = serde_json::json!({
            "meta": {"api-version": "1.0"},
            "projects": projects,
        });
        (
            StatusCode::OK,
            [
                (header::CONTENT_TYPE, PEP691_JSON),
                (header::CACHE_CONTROL, "public, max-age=60, must-revalidate"),
            ],
            serde_json::to_string(&body).unwrap_or_default(),
        )
            .into_response()
    } else {
        // PEP 503 HTML
        let mut html = String::from(
            "<!DOCTYPE html>\n<html><head><title>Simple Index</title></head><body><h1>Simple Index</h1>\n",
        );
        for pkg in pkg_list {
            let _ = writeln!(
                html,
                "<a href=\"/simple/{}/\">{}</a><br>",
                html_escape(&pkg),
                html_escape(&pkg)
            );
        }
        html.push_str("</body></html>");
        (
            StatusCode::OK,
            [(header::CACHE_CONTROL, "public, max-age=60, must-revalidate")],
            Html(html),
        )
            .into_response()
    }
}

// ============================================================================
// Package versions
// ============================================================================

/// GET /simple/{name}/ — list files for a package (PEP 503 HTML or PEP 691 JSON).
///
/// When proxy is configured, always fetches the upstream index and merges with
/// locally cached/uploaded files. This ensures pip sees all available wheels
/// (e.g. both cp310 and cp314) regardless of which were cached first.
/// Falls back to local-only when upstream is unavailable.
async fn package_versions(
    State(state): State<AppState>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Response {
    let normalized = normalize_name(&name);
    let prefix = format!("pypi/{}/", normalized);
    let base_url = nora_base_url(&state);

    // Collect local files with their hashes
    let keys = match state.storage.list(&prefix).await {
        Ok(k) => k,
        Err(e) => {
            tracing::error!(error = ?e, "pypi: failed to list storage for package versions");
            return StatusCode::SERVICE_UNAVAILABLE.into_response();
        }
    };
    let mut local_files: Vec<FileEntry> = Vec::new();
    for key in &keys {
        if let Some(filename) = key.strip_prefix(&prefix) {
            if !filename.is_empty()
                && !ends_with_ci(filename, ".sha256")
                && is_valid_pypi_filename(filename)
            {
                let sha256 = state
                    .storage
                    .get(&format!("{}.sha256", key))
                    .await
                    .ok()
                    .and_then(|d| String::from_utf8(d.to_vec()).ok());
                local_files.push(FileEntry {
                    filename: filename.to_string(),
                    sha256,
                });
            }
        }
    }

    // When proxy is configured, fetch upstream index and merge with local files.
    // This fixes the case where a cp314 wheel is cached but pip 3.10 needs to
    // see the full upstream file list to find a compatible cp310 wheel.
    // Fetch each configured upstream's index and merge them (#663). Precedence is
    // the upstream order: the first upstream that lists a file wins (local files
    // win over all upstreams). One upstream's failure or open breaker must not
    // sink the others — skip it and serve the merge of what answered.
    // #68 namespace isolation: an internal-namespace package must never be fetched
    // upstream (dependency confusion). Skip the upstream merge entirely; a locally
    // published copy is still served from the local-only branch below, and an
    // internal name with no local copy is blocked (never proxied). Computed without
    // the `blocked` metric — the metric fires only on the actual block path below.
    let is_internal = crate::curation::is_internal_namespace(
        &state.curation().curation_engine,
        crate::curation::RegistryType::PyPI,
        &normalized,
    );

    let upstreams = state.config.pypi.upstreams();
    let mut circuit_open = false;
    if !is_internal && !upstreams.is_empty() {
        let mut upstream_files: Vec<FileEntry> = Vec::new();
        for up in &upstreams {
            let url = format!("{}/{}/", up.url().trim_end_matches('/'), normalized);
            match proxy_fetch_text(
                &state.http_client,
                &url,
                Duration::from_secs(state.config.pypi.proxy_timeout),
                up.auth(),
                Some(("Accept", "text/html")),
                &state.circuit_breaker,
                RegistryType::PyPI,
            )
            .await
            {
                Ok(html) => upstream_files.extend(parse_upstream_files(&html)),
                Err(crate::registry::ProxyError::CircuitOpen(_)) => {
                    circuit_open = true;
                    continue;
                }
                Err(e) => {
                    tracing::debug!(error = ?e, package = %normalized, upstream = %up.url(), "PyPI upstream index fetch failed, skipping");
                    continue;
                }
            }
        }
        let merged = merge_file_lists(upstream_files, &local_files);
        if !merged.is_empty() {
            return if wants_json(&headers) {
                versions_json_response(&normalized, &merged, &base_url)
            } else {
                versions_html_response(&normalized, &merged, &base_url)
            };
        }
    }

    // Local files only — degrade gracefully when upstreams list nothing or are down.
    if !local_files.is_empty() {
        return if wants_json(&headers) {
            versions_json_response(&normalized, &local_files, &base_url)
        } else {
            versions_html_response(&normalized, &local_files, &base_url)
        };
    }

    // #68: an internal-namespace package with no local copy is blocked, never
    // proxied — return the namespace 403 (the only pypi metadata path that
    // increments the blocked metric).
    if is_internal {
        if let Some(response) = crate::curation::check_namespace_isolation(
            &state.curation().curation_engine,
            crate::curation::RegistryType::PyPI,
            &normalized,
        ) {
            return response;
        }
    }

    // No upstream result and no local copy: a tripped breaker means the upstream is
    // temporarily down — return 503 (retryable) rather than 404, which would poison
    // pip's negative cache.
    if circuit_open {
        return circuit_open_response(RegistryType::PyPI.as_str());
    }

    StatusCode::NOT_FOUND.into_response()
}

// ============================================================================
// Download
// ============================================================================

/// GET /simple/{name}/{filename} — download a specific file.
// LOCK-SAFE: cache-through proxy — get miss → fetch upstream → put; no RMW race
async fn download_file(
    State(state): State<AppState>,
    headers: HeaderMap,
    Path((name, filename)): Path<(String, String)>,
) -> Response {
    let normalized = normalize_name(&name);

    // Block download of internal bookkeeping files (dates.json, etc.) that
    // live alongside packages in storage but are not real artifacts (#891).
    if !is_valid_pypi_filename(&filename) {
        return StatusCode::NOT_FOUND.into_response();
    }

    // Curation check — before storage access
    let version = crate::curation::parse_pypi_version(&normalized, &filename);

    // Extract the upstream release date for this file (PEP 700 `upload-time` from
    // the PEP 691 simple JSON, cached as dates.json). Seeds the digest-quarantine
    // first-seen clock so a provably-old release is not held as "new to this
    // mirror" (#748/#750). Only consulted when upstream dates are trusted.
    let dates_key = format!("pypi/{}/dates.json", normalized);
    if state.config.server.trust_upstream_dates {
        ensure_pypi_dates_cached(&state, &normalized).await;
    }
    let publish_date = extract_pypi_publish_date(
        &state.storage,
        &dates_key,
        &filename,
        state.config.server.trust_upstream_dates,
    )
    .await;

    // #733 serve-local: an internal-namespace package is operator-owned — skip curation
    // and serve any local copy below; the upstream branch is blocked separately (never proxy).
    let internal = crate::curation::is_internal_namespace(
        &state.curation().curation_engine,
        crate::curation::RegistryType::PyPI,
        &normalized,
    );
    if !internal {
        if let Some(response) = crate::curation::check_download(
            &state.curation().curation_engine,
            state.bypass_token().as_deref(),
            &headers,
            crate::curation::RegistryType::PyPI,
            &normalized,
            version.as_deref(),
            publish_date,
        ) {
            return response;
        }
    }

    let key = format!("pypi/{}/{}", normalized, filename);

    // Digest-quarantine: first-seen hold for proxy artifacts (generalizes the
    // Docker-only wiring). Resolved once; applied at each serve point below.
    let (q_mode, q_secs) = crate::digest_quarantine::resolve_global(
        state.config.curation.pypi.quarantine.as_ref().or(state
            .config
            .curation
            .quarantine
            .as_ref()),
        state
            .config
            .curation
            .pypi
            .quarantine_ttl
            .as_deref()
            .or(state.config.curation.quarantine_ttl.as_deref()),
    );

    // Resumable download (#657): serve the requested bytes from the backend and skip
    // the full read below. Package files only — the simple index is generated, never
    // ranged. A partial read cannot be hashed, so neither the quarantine gate nor the
    // curation integrity check can run on it: the range serve stands down while
    // quarantine holds artifacts, and integrity is the client's own hash (the PEP 691
    // `hashes` field), as docker does.
    if headers.contains_key(header::RANGE)
        && matches!(q_mode, crate::digest_quarantine::QuarantineMode::Off)
    {
        if let Some(meta) = state.storage.stat(&key).await {
            if let Some(response) = crate::registry::range::range_response(
                &state.storage,
                &[&key],
                &headers,
                meta.size,
                pypi_content_type(&filename),
                &[(
                    header::CACHE_CONTROL,
                    "public, max-age=31536000, immutable".to_string(),
                )],
            )
            .await
            {
                if response.status() == StatusCode::PARTIAL_CONTENT {
                    state.metrics.record_download("pypi");
                    state.metrics.record_cache_hit("pypi");
                }
                return response;
            }
        }
    }

    // Try local storage first. get_verified discharges the integrity witness at
    // the serve site (compile-time guarantee — see crate::verified).
    if let Ok(outcome) = state.storage.get_verified(&key).await {
        use nora_registry::verified::{verified_body, GateOutcome};
        let data = match outcome {
            GateOutcome::Verified(blob) => verified_body(blob),
            GateOutcome::Unpinned(blob) => blob.into_inner(),
        };
        // Curation integrity verification (issue #189)
        if let Some(response) = crate::curation::verify_integrity(
            &state.curation().curation_engine,
            crate::curation::RegistryType::PyPI,
            &normalized,
            version.as_deref(),
            &data,
        ) {
            return response;
        }

        state.metrics.record_download("pypi");
        state.metrics.record_cache_hit("pypi");
        state.activity.push(ActivityEntry::new(
            ActionType::CacheHit,
            format!("{}/{}", name, filename),
            crate::registry_type::RegistryType::PyPI,
            "CACHE",
        ));
        state
            .audit
            .log(AuditEntry::new("cache_hit", "api", "", "pypi", ""));

        if let Some(resp) = crate::digest_quarantine::proxy_gate_dated(
            &state.digest_store,
            "pypi",
            &data,
            &q_mode,
            q_secs,
            "cache",
            publish_date,
        ) {
            return resp;
        }

        let content_type = pypi_content_type(&filename);
        return (
            StatusCode::OK,
            [
                (header::CONTENT_TYPE, content_type),
                (header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
                (header::ACCEPT_RANGES, "bytes"),
            ],
            data,
        )
            .into_response();
    }

    // #733: an internal-namespace package with no local copy is never proxied upstream.
    if internal {
        return crate::curation::check_namespace_isolation(
            &state.curation().curation_engine,
            crate::curation::RegistryType::PyPI,
            &normalized,
        )
        .unwrap_or_else(|| StatusCode::NOT_FOUND.into_response());
    }

    // Try each configured upstream in order; the first whose index lists the file
    // serves it, fetched from that same upstream with that upstream's auth. One
    // upstream's failure or open breaker skips to the next rather than failing (#663).
    let mut circuit_open = false;
    for up in &state.config.pypi.upstreams() {
        let page_url = format!("{}/{}/", up.url().trim_end_matches('/'), normalized);

        let html = match proxy_fetch_text(
            &state.http_client,
            &page_url,
            Duration::from_secs(state.config.pypi.proxy_timeout),
            up.auth(),
            Some(("Accept", "text/html")),
            &state.circuit_breaker,
            RegistryType::PyPI,
        )
        .await
        {
            Ok(html) => html,
            Err(crate::registry::ProxyError::CircuitOpen(_)) => {
                circuit_open = true;
                continue;
            }
            Err(e) => {
                tracing::debug!(error = ?e, package = %normalized, upstream = %up.url(), "PyPI page proxy fetch failed, trying next upstream");
                continue;
            }
        };

        // The file may live on a later upstream — keep walking the list.
        let Some(file_url) = find_file_url(&html, &filename, &page_url) else {
            continue;
        };

        match proxy_fetch(
            &state.http_client,
            &file_url,
            Duration::from_secs(state.config.pypi.proxy_timeout),
            up.auth(),
            &state.circuit_breaker,
            RegistryType::PyPI,
        )
        .await
        {
            Ok(data) => {
                state.metrics.record_download("pypi");
                state.metrics.record_cache_miss("pypi");
                state.activity.push(ActivityEntry::new(
                    ActionType::ProxyFetch,
                    format!("{}/{}", name, filename),
                    crate::registry_type::RegistryType::PyPI,
                    "PROXY",
                ));
                state
                    .audit
                    .log(AuditEntry::new("proxy_fetch", "api", "", "pypi", ""));

                // Cache in background + compute hash, invalidate AFTER write
                let storage = state.storage.clone();
                let key_clone = key.clone();
                let data_clone = data.clone();
                let repo_index = Arc::clone(&state.repo_index);
                tokio::spawn(async move {
                    if storage.put(&key_clone, &data_clone).await.is_ok() {
                        let hash = hex::encode(sha2::Sha256::digest(&data_clone));
                        let _ = storage
                            .put(&format!("{}.sha256", key_clone), hash.as_bytes())
                            .await;
                        repo_index.invalidate("pypi");
                    }
                });

                if let Some(resp) = crate::digest_quarantine::proxy_gate_dated(
                    &state.digest_store,
                    "pypi",
                    &data,
                    &q_mode,
                    q_secs,
                    &file_url,
                    publish_date,
                ) {
                    return resp;
                }

                let content_type = pypi_content_type(&filename);
                return (StatusCode::OK, [(header::CONTENT_TYPE, content_type)], data)
                    .into_response();
            }
            Err(crate::registry::ProxyError::CircuitOpen(_)) => {
                circuit_open = true;
                continue;
            }
            Err(e) => {
                tracing::debug!(error = ?e, package = %normalized, filename = %filename, upstream = %up.url(), "PyPI file proxy fetch failed, trying next upstream");
                continue;
            }
        }
    }

    // A tripped breaker means an upstream is temporarily down — 503 (retryable)
    // rather than 404, which would poison pip's negative cache.
    if circuit_open {
        return circuit_open_response(RegistryType::PyPI.as_str());
    }

    StatusCode::NOT_FOUND.into_response()
}

// ============================================================================
// Twine upload (PEP 503 — POST /simple/)
// ============================================================================

/// POST /simple/ — upload a package via twine.
///
/// twine sends multipart/form-data with fields:
///   :action = "file_upload"
///   name = package name
///   version = package version
///   filetype = "sdist" | "bdist_wheel"
///   content = the file bytes
///   sha256_digest = hex SHA-256 of file (optional)
///   metadata_version, summary, etc. (optional metadata)
async fn upload(
    State(state): State<AppState>,
    Extension(authority): Extension<NamespaceAuthority>,
    mut multipart: Multipart,
) -> Response {
    let mut action = String::new();
    let mut name = String::new();
    let mut version = String::new();
    let mut filename = String::new();
    let mut file_data: Option<Vec<u8>> = None;
    let mut sha256_digest = String::new();

    // Parse multipart fields
    while let Ok(Some(field)) = multipart.next_field().await {
        let field_name = field.name().unwrap_or("").to_string();

        match field_name.as_str() {
            ":action" => {
                action = field.text().await.ok().unwrap_or_default();
            }
            "name" => {
                name = field.text().await.ok().unwrap_or_default();
            }
            "version" => {
                version = field.text().await.ok().unwrap_or_default();
            }
            "sha256_digest" => {
                sha256_digest = field.text().await.ok().unwrap_or_default();
            }
            "content" => {
                filename = field.file_name().unwrap_or("unknown").to_string();
                match field.bytes().await {
                    Ok(b) => file_data = Some(b.to_vec()),
                    Err(e) => {
                        return (
                            StatusCode::BAD_REQUEST,
                            format!("Failed to read file: {}", e),
                        )
                            .into_response()
                    }
                }
            }
            _ => {
                // Skip other metadata fields (summary, author, etc.)
                let _ = field.bytes().await;
            }
        }
    }

    // Validate required fields
    if action != "file_upload" {
        return (StatusCode::BAD_REQUEST, "Unsupported action").into_response();
    }

    if name.is_empty() || version.is_empty() {
        return (StatusCode::BAD_REQUEST, "Missing name or version").into_response();
    }

    let data = match file_data {
        Some(d) if !d.is_empty() => d,
        _ => return (StatusCode::BAD_REQUEST, "Missing file content").into_response(),
    };

    // Validate filename
    if filename.is_empty() || !is_valid_pypi_filename(&filename) {
        return (StatusCode::BAD_REQUEST, "Invalid filename").into_response();
    }

    // Verify SHA-256 if provided
    let computed_hash = hex::encode(sha2::Sha256::digest(&data));
    if !sha256_digest.is_empty() && sha256_digest != computed_hash {
        tracing::warn!(
            package = %name,
            expected = %sha256_digest,
            computed = %computed_hash,
            "SECURITY: PyPI upload SHA-256 mismatch"
        );
        return (StatusCode::BAD_REQUEST, "SHA-256 digest mismatch").into_response();
    }

    // Normalize name and store
    let normalized = normalize_name(&name);

    // Enforce OIDC namespace_scope on the project coordinate (#583).
    if enforce_namespace_scope(&authority, &normalized).is_err() {
        return StatusCode::FORBIDDEN.into_response();
    }

    // TOCTOU protection: lock per file to prevent concurrent uploads
    let file_key = format!("pypi/{}/{}", normalized, filename);
    let lock = state.publish_lock(&file_key);
    let _guard = lock.lock().await;

    // Check immutability (same filename = already exists)
    if state.storage.stat(&file_key).await.is_some() {
        return (
            StatusCode::CONFLICT,
            format!("File {} already exists", filename),
        )
            .into_response();
    }

    // Store file
    if state.storage.put(&file_key, &data).await.is_err() {
        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
    }

    // Store SHA-256 hash
    let hash_key = format!("{}.sha256", file_key);
    if let Err(e) = state.storage.put(&hash_key, computed_hash.as_bytes()).await {
        tracing::warn!(key = %hash_key, error = %e, "pypi: failed to store hash sidecar");
    }

    state.metrics.record_upload("pypi");
    let artifact = format!("{}-{}", name, version);
    state
        .audit
        .log(AuditEntry::new("push", "api", &artifact, "pypi", ""));
    state.activity.push(ActivityEntry::new(
        ActionType::Push,
        artifact,
        crate::registry_type::RegistryType::PyPI,
        "LOCAL",
    ));
    state.repo_index.invalidate("pypi");

    StatusCode::OK.into_response()
}

// ============================================================================
// PEP 691 JSON responses — typed structs per spec
// ============================================================================

struct FileEntry {
    filename: String,
    sha256: Option<String>,
}

/// PEP 691 top-level response — typed to prevent field-name drift.
#[derive(serde::Serialize)]
struct Pep691Response<'a> {
    meta: Pep691Meta,
    name: &'a str,
    files: Vec<Pep691File>,
}

#[derive(serde::Serialize)]
struct Pep691Meta {
    #[serde(rename = "api-version")]
    api_version: &'static str,
}

/// PEP 691 file entry — field `hashes` (NOT `digests`) per spec.
#[derive(serde::Serialize)]
struct Pep691File {
    filename: String,
    url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    hashes: Option<Pep691Hashes>,
}

#[derive(serde::Serialize)]
struct Pep691Hashes {
    sha256: String,
}

fn versions_json_response(normalized: &str, files: &[FileEntry], base_url: &str) -> Response {
    let base = base_url.trim_end_matches('/');
    let pep691_files: Vec<Pep691File> = files
        .iter()
        .map(|f| Pep691File {
            filename: f.filename.clone(),
            url: format!("{}/simple/{}/{}", base, normalized, f.filename),
            hashes: f
                .sha256
                .as_ref()
                .map(|h| Pep691Hashes { sha256: h.clone() }),
        })
        .collect();

    let body = Pep691Response {
        meta: Pep691Meta { api_version: "1.0" },
        name: normalized,
        files: pep691_files,
    };

    (
        StatusCode::OK,
        [(header::CONTENT_TYPE, PEP691_JSON)],
        serde_json::to_string(&body).unwrap_or_default(),
    )
        .into_response()
}

fn versions_html_response(normalized: &str, files: &[FileEntry], base_url: &str) -> Response {
    let base = base_url.trim_end_matches('/');
    let escaped = html_escape(normalized);
    let mut html = format!(
        "<!DOCTYPE html>\n<html><head><title>Links for {}</title></head><body><h1>Links for {}</h1>\n",
        escaped, escaped
    );

    for f in files {
        let hash_fragment = f
            .sha256
            .as_ref()
            .map(|h| format!("#sha256={}", h))
            .unwrap_or_default();
        let _ = writeln!(
            html,
            "<a href=\"{}/simple/{}/{}{}\">{}</a><br>",
            base,
            normalized,
            html_escape(&f.filename),
            hash_fragment,
            html_escape(&f.filename)
        );
    }
    html.push_str("</body></html>");

    (StatusCode::OK, Html(html)).into_response()
}

// ============================================================================
// Helpers
// ============================================================================

/// Extract a file's upstream upload-time from the cached `dates.json`
/// (filename → PEP 700 `upload-time`, populated by [`ensure_pypi_dates_cached`]).
async fn extract_pypi_publish_date(
    storage: &crate::storage::Storage,
    dates_key: &str,
    filename: &str,
    trust_upstream: bool,
) -> Option<i64> {
    // #513: untrusted upstream dates → use NORA's own cache mtime, never the
    // (spoofable) upstream upload-time.
    if !trust_upstream {
        return crate::curation::extract_mtime_as_publish_date(storage, dates_key).await;
    }
    let data = storage.get(dates_key).await.ok()?;
    let json: serde_json::Value = serde_json::from_slice(&data).ok()?;
    let date_str = json.get(filename)?.as_str()?;
    crate::curation::parse_iso8601_to_unix(date_str)
}

/// Cache a `filename → upload-time` map (`pypi/{name}/dates.json`) from the
/// upstream PEP 691 simple JSON (PEP 700 `upload-time`). No-op if already cached
/// or no upstream supplies a date. Best-effort: any failure leaves no dates and
/// the quarantine clock falls back to NORA's own time. The PEP 503 HTML index
/// NORA fetches for the file *listing* carries no dates, hence this JSON fetch.
async fn ensure_pypi_dates_cached(state: &AppState, normalized: &str) {
    let key = format!("pypi/{}/dates.json", normalized);
    if state.storage.get(&key).await.is_ok() {
        return;
    }
    // #68: never fetch an internal-namespace package's metadata upstream.
    if crate::curation::is_internal_namespace(
        &state.curation().curation_engine,
        crate::curation::RegistryType::PyPI,
        normalized,
    ) {
        return;
    }
    let mut map = serde_json::Map::new();
    for up in &state.config.pypi.upstreams() {
        let url = format!("{}/{}/", up.url().trim_end_matches('/'), normalized);
        let Ok(text) = proxy_fetch_text(
            &state.http_client,
            &url,
            Duration::from_secs(state.config.pypi.proxy_timeout),
            up.auth(),
            Some(("Accept", PEP691_JSON)),
            &state.circuit_breaker,
            RegistryType::PyPI,
        )
        .await
        else {
            continue;
        };
        let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) else {
            continue;
        };
        if let Some(files) = json.get("files").and_then(|f| f.as_array()) {
            for fe in files {
                if let (Some(fname), Some(ut)) = (
                    fe.get("filename").and_then(|v| v.as_str()),
                    fe.get("upload-time").and_then(|v| v.as_str()),
                ) {
                    map.entry(fname.to_string())
                        .or_insert_with(|| serde_json::Value::String(ut.to_string()));
                }
            }
        }
        if !map.is_empty() {
            break; // first upstream that listed dated files wins
        }
    }
    if !map.is_empty() {
        if let Ok(bytes) = serde_json::to_vec(&serde_json::Value::Object(map)) {
            let _ = state.storage.put(&key, &bytes).await;
        }
    }
}

/// Normalize package name according to PEP 503.
fn normalize_name(name: &str) -> String {
    name.to_lowercase().replace(['-', '_', '.'], "-")
}

/// Check Accept header for PEP 691 JSON.
fn wants_json(headers: &HeaderMap) -> bool {
    headers
        .get(header::ACCEPT)
        .and_then(|v| v.to_str().ok())
        .map(|v| v.contains(PEP691_JSON))
        .unwrap_or(false)
}

/// Content-type for PyPI files.
fn pypi_content_type(filename: &str) -> &'static str {
    if ends_with_ci(filename, ".whl") {
        "application/zip"
    } else if ends_with_ci(filename, ".tar.gz") || ends_with_ci(filename, ".tgz") {
        "application/gzip"
    } else {
        "application/octet-stream"
    }
}

/// Validate PyPI filename.
fn is_valid_pypi_filename(name: &str) -> bool {
    !name.is_empty()
        && !name.contains("..")
        && !name.contains('/')
        && !name.contains('\\')
        && !name.contains('\0')
        && (ends_with_ci(name, ".tar.gz")
            || ends_with_ci(name, ".tgz")
            || ends_with_ci(name, ".whl")
            || ends_with_ci(name, ".zip")
            || ends_with_ci(name, ".egg"))
}

/// Extract filename from PyPI download URL.
fn extract_filename(url: &str) -> Option<&str> {
    let url = url.split('#').next()?;
    let filename = url.rsplit('/').next()?;

    if ends_with_ci(filename, ".tar.gz")
        || ends_with_ci(filename, ".tgz")
        || ends_with_ci(filename, ".whl")
        || ends_with_ci(filename, ".zip")
        || ends_with_ci(filename, ".egg")
    {
        Some(filename)
    } else {
        None
    }
}

/// Parse upstream PyPI simple index HTML into file entries.
///
/// Extracts filenames and optional `#sha256=` fragments from `<a href="...">` links.
fn parse_upstream_files(html: &str) -> Vec<FileEntry> {
    let mut files = Vec::new();
    let mut remaining = html;

    while let Some(href_start) = remaining.find("href=\"") {
        remaining = &remaining[href_start + 6..];
        if let Some(href_end) = remaining.find('"') {
            let url = &remaining[..href_end];
            if let Some(filename) = extract_filename(url) {
                let sha256 = url.find("#sha256=").map(|pos| url[pos + 8..].to_string());
                files.push(FileEntry {
                    filename: filename.to_string(),
                    sha256,
                });
            }
            remaining = &remaining[href_end..];
        }
    }
    files
}

/// Merge upstream and local file lists.
///
/// Local entries take precedence (they have verified hashes from storage).
/// Upstream entries are added only if no local file with the same name exists.
fn merge_file_lists(upstream: Vec<FileEntry>, local: &[FileEntry]) -> Vec<FileEntry> {
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut result = Vec::with_capacity(upstream.len() + local.len());

    // Local first (highest precedence). Dedup local against itself too: storage
    // listings are unique by construction, but keep the merge total so the output
    // never carries a duplicate filename regardless of caller input.
    for f in local {
        if seen.insert(f.filename.clone()) {
            result.push(FileEntry {
                filename: f.filename.clone(),
                sha256: f.sha256.clone(),
            });
        }
    }

    // `upstream` is concatenated across upstreams in precedence order; keep the
    // first entry seen for each filename so the highest-precedence upstream wins
    // and a file present on several upstreams (or already local) is not listed
    // twice (#663).
    for f in upstream {
        if seen.insert(f.filename.clone()) {
            result.push(f);
        }
    }

    result
}

/// Find the download URL for a specific file in the HTML.
///
/// `page_url` is the simple-index page URL used to resolve relative hrefs
/// returned by some mirrors (Tsinghua, USTC, Aliyun) (#877).
fn find_file_url(html: &str, target_filename: &str, page_url: &str) -> Option<String> {
    let mut remaining = html;

    while let Some(href_start) = remaining.find("href=\"") {
        remaining = &remaining[href_start + 6..];

        if let Some(href_end) = remaining.find('"') {
            let url = &remaining[..href_end];

            if let Some(filename) = extract_filename(url) {
                // Index hrefs percent-encode characters such as '+' (PyTorch's
                // "+cu124" -> "%2Bcu124"); the requested filename arrives already
                // decoded, so compare decoded forms. The URL itself is returned
                // unchanged — it must stay encoded to fetch from the upstream (#664).
                let decoded = percent_encoding::percent_decode_str(filename).decode_utf8_lossy();
                if decoded.as_ref() == target_filename {
                    let raw = url.split('#').next().unwrap_or(url).to_string();
                    // Resolve relative URLs against the page URL (#877).
                    if raw.starts_with("http://") || raw.starts_with("https://") {
                        return Some(raw);
                    }
                    return reqwest::Url::parse(page_url)
                        .ok()
                        .and_then(|base| base.join(&raw).ok())
                        .map(|u| u.to_string())
                        .or(Some(raw));
                }
            }

            remaining = &remaining[href_end..];
        }
    }

    None
}

// ============================================================================
// Unit Tests
// ============================================================================

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

    proptest! {
        #[test]
        fn extract_filename_never_panics(s in "\\PC{0,500}") {
            let _ = extract_filename(&s);
        }

        #[test]
        fn extract_filename_valid_tarball(
            name in "[a-z][a-z0-9_-]{0,20}",
            version in "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"
        ) {
            let url = format!("https://files.example.com/packages/{}-{}.tar.gz", name, version);
            let result = extract_filename(&url);
            prop_assert!(result.is_some());
            prop_assert!(result.unwrap().ends_with(".tar.gz"));
        }

        #[test]
        fn extract_filename_valid_wheel(
            name in "[a-z][a-z0-9_]{0,20}",
            version in "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"
        ) {
            let url = format!("https://files.example.com/{}-{}-py3-none-any.whl", name, version);
            let result = extract_filename(&url);
            prop_assert!(result.is_some());
            prop_assert!(result.unwrap().ends_with(".whl"));
        }

        #[test]
        fn extract_filename_strips_hash(
            name in "[a-z]{1,10}",
            hash in "[a-f0-9]{64}"
        ) {
            let url = format!("https://example.com/{}.tar.gz#sha256={}", name, hash);
            let result = extract_filename(&url);
            prop_assert!(result.is_some());
            let fname = result.unwrap();
            prop_assert!(!fname.contains('#'));
        }

        #[test]
        fn extract_filename_rejects_unknown_ext(
            name in "[a-z]{1,10}",
            ext in "(exe|dll|so|bin|dat)"
        ) {
            let url = format!("https://example.com/{}.{}", name, ext);
            prop_assert!(extract_filename(&url).is_none());
        }
    }

    #[test]
    fn test_normalize_name_lowercase() {
        assert_eq!(normalize_name("Flask"), "flask");
        assert_eq!(normalize_name("REQUESTS"), "requests");
    }

    #[test]
    fn find_file_url_matches_percent_encoded_plus() {
        // #664: PyTorch indexes encode '+' as %2B in hrefs, but the requested
        // filename arrives decoded — matching must decode, and the returned URL
        // must stay encoded so the upstream fetch resolves.
        let html = concat!(
            r#"<a href="https://download.pytorch.org/whl/cu124/"#,
            r#"torch-2.4.0%2Bcu124-cp310-cp310-linux_x86_64.whl#sha256=abc">"#,
            r#"torch-2.4.0+cu124-cp310-cp310-linux_x86_64.whl</a>"#,
        );
        assert_eq!(
            find_file_url(html, "torch-2.4.0+cu124-cp310-cp310-linux_x86_64.whl", "https://pypi.org/simple/torch/").as_deref(),
            Some(
                "https://download.pytorch.org/whl/cu124/torch-2.4.0%2Bcu124-cp310-cp310-linux_x86_64.whl"
            )
        );
        // A plain filename (no encoding) still matches.
        let plain = r#"<a href="https://x/torch-0.1.10-cp36-cp36m-macosx.whl">x</a>"#;
        assert_eq!(
            find_file_url(
                plain,
                "torch-0.1.10-cp36-cp36m-macosx.whl",
                "https://pypi.org/simple/torch/"
            )
            .as_deref(),
            Some("https://x/torch-0.1.10-cp36-cp36m-macosx.whl")
        );
    }

    #[test]
    fn test_normalize_name_separators() {
        assert_eq!(normalize_name("my-package"), "my-package");
        assert_eq!(normalize_name("my_package"), "my-package");
        assert_eq!(normalize_name("my.package"), "my-package");
    }

    #[test]
    fn test_normalize_name_mixed() {
        assert_eq!(
            normalize_name("My_Complex.Package-Name"),
            "my-complex-package-name"
        );
    }

    #[test]
    fn test_normalize_name_empty() {
        assert_eq!(normalize_name(""), "");
    }

    #[test]
    fn test_normalize_name_already_normal() {
        assert_eq!(normalize_name("simple"), "simple");
    }

    #[test]
    fn test_extract_filename_tarball() {
        assert_eq!(
            extract_filename(
                "https://files.pythonhosted.org/packages/aa/bb/flask-2.0.0.tar.gz#sha256=abc123"
            ),
            Some("flask-2.0.0.tar.gz")
        );
    }

    #[test]
    fn test_extract_filename_wheel() {
        assert_eq!(
            extract_filename(
                "https://files.pythonhosted.org/packages/aa/bb/flask-2.0.0-py3-none-any.whl"
            ),
            Some("flask-2.0.0-py3-none-any.whl")
        );
    }

    #[test]
    fn test_extract_filename_tgz() {
        assert_eq!(
            extract_filename("https://example.com/package-1.0.tgz"),
            Some("package-1.0.tgz")
        );
    }

    #[test]
    fn test_extract_filename_zip() {
        assert_eq!(
            extract_filename("https://example.com/package-1.0.zip"),
            Some("package-1.0.zip")
        );
    }

    #[test]
    fn test_extract_filename_egg() {
        assert_eq!(
            extract_filename("https://example.com/package-1.0.egg"),
            Some("package-1.0.egg")
        );
    }

    #[test]
    fn test_extract_filename_unknown_ext() {
        assert_eq!(extract_filename("https://example.com/readme.txt"), None);
    }

    #[test]
    fn test_extract_filename_no_path() {
        assert_eq!(extract_filename(""), None);
    }

    #[test]
    fn test_extract_filename_bare() {
        assert_eq!(
            extract_filename("package-1.0.tar.gz"),
            Some("package-1.0.tar.gz")
        );
    }

    #[test]
    fn test_find_file_url_found() {
        let html = r#"<a href="https://files.pythonhosted.org/packages/aa/bb/flask-2.0.tar.gz#sha256=abc">flask-2.0.tar.gz</a>"#;
        let result = find_file_url(html, "flask-2.0.tar.gz", "https://pypi.org/simple/flask/");
        assert_eq!(
            result,
            Some("https://files.pythonhosted.org/packages/aa/bb/flask-2.0.tar.gz".to_string())
        );
    }

    #[test]
    fn test_find_file_url_not_found() {
        let html = r#"<a href="https://example.com/other-1.0.tar.gz">other</a>"#;
        let result = find_file_url(html, "flask-2.0.tar.gz", "https://pypi.org/simple/flask/");
        assert_eq!(result, None);
    }

    #[test]
    fn test_find_file_url_strips_hash() {
        let html = r#"<a href="https://example.com/pkg-1.0.whl#sha256=deadbeef">pkg</a>"#;
        let result = find_file_url(html, "pkg-1.0.whl", "https://pypi.org/simple/pkg/");
        assert_eq!(result, Some("https://example.com/pkg-1.0.whl".to_string()));
    }

    // -- #877: relative URL resolution --

    #[test]
    fn test_find_file_url_relative() {
        let html = r#"<a href="../../packages/torch-2.4.0.whl#sha256=abc">torch-2.4.0.whl</a>"#;
        let result = find_file_url(
            html,
            "torch-2.4.0.whl",
            "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/torch/",
        );
        assert_eq!(
            result,
            Some(
                "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/torch-2.4.0.whl"
                    .to_string()
            )
        );
    }

    #[test]
    fn test_find_file_url_absolute_unchanged() {
        let html = r#"<a href="https://files.pythonhosted.org/packages/ab/cd/pkg-1.0.whl">pkg-1.0.whl</a>"#;
        let result = find_file_url(
            html,
            "pkg-1.0.whl",
            "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/pkg/",
        );
        assert_eq!(
            result,
            Some("https://files.pythonhosted.org/packages/ab/cd/pkg-1.0.whl".to_string())
        );
    }

    #[test]
    fn test_find_file_url_path_only() {
        let html = r#"<a href="/packages/pkg-1.0.whl#sha256=ff">pkg-1.0.whl</a>"#;
        let result = find_file_url(html, "pkg-1.0.whl", "https://pypi.example.com/simple/pkg/");
        assert_eq!(
            result,
            Some("https://pypi.example.com/packages/pkg-1.0.whl".to_string())
        );
    }

    #[test]
    fn test_is_valid_pypi_filename() {
        assert!(is_valid_pypi_filename("flask-2.0.tar.gz"));
        assert!(is_valid_pypi_filename("flask-2.0-py3-none-any.whl"));
        assert!(is_valid_pypi_filename("flask-2.0.tgz"));
        assert!(is_valid_pypi_filename("flask-2.0.zip"));
        assert!(is_valid_pypi_filename("flask-2.0.egg"));
        assert!(!is_valid_pypi_filename(""));
        assert!(!is_valid_pypi_filename("../evil.tar.gz"));
        assert!(!is_valid_pypi_filename("evil/path.tar.gz"));
        assert!(!is_valid_pypi_filename("noext"));
        assert!(!is_valid_pypi_filename("bad.exe"));
    }

    #[test]
    fn test_wants_json_pep691() {
        let mut headers = HeaderMap::new();
        headers.insert(header::ACCEPT, PEP691_JSON.parse().unwrap());
        assert!(wants_json(&headers));
    }

    #[test]
    fn test_wants_json_html() {
        let mut headers = HeaderMap::new();
        headers.insert(header::ACCEPT, "text/html".parse().unwrap());
        assert!(!wants_json(&headers));
    }

    #[test]
    fn test_wants_json_no_header() {
        let headers = HeaderMap::new();
        assert!(!wants_json(&headers));
    }

    // --- parse_upstream_files ---

    #[test]
    fn test_parse_upstream_files_basic() {
        let html = r#"<a href="https://files.example.com/pkg-1.0-cp310-cp310-linux_x86_64.whl#sha256=aaa">pkg</a>
<a href="https://files.example.com/pkg-1.0-cp314-cp314-linux_x86_64.whl#sha256=bbb">pkg</a>"#;
        let files = parse_upstream_files(html);
        assert_eq!(files.len(), 2);
        assert_eq!(files[0].filename, "pkg-1.0-cp310-cp310-linux_x86_64.whl");
        assert_eq!(files[0].sha256.as_deref(), Some("aaa"));
        assert_eq!(files[1].filename, "pkg-1.0-cp314-cp314-linux_x86_64.whl");
        assert_eq!(files[1].sha256.as_deref(), Some("bbb"));
    }

    #[test]
    fn test_parse_upstream_files_no_hash() {
        let html = r#"<a href="https://example.com/pkg-1.0.tar.gz">pkg</a>"#;
        let files = parse_upstream_files(html);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].filename, "pkg-1.0.tar.gz");
        assert!(files[0].sha256.is_none());
    }

    #[test]
    fn test_parse_upstream_files_empty() {
        assert!(parse_upstream_files("").is_empty());
        assert!(parse_upstream_files("<html><body></body></html>").is_empty());
    }

    #[test]
    fn test_parse_upstream_files_skips_non_package_links() {
        let html = r#"<a href="https://example.com/readme.txt">readme</a>
<a href="https://example.com/pkg-1.0.whl#sha256=abc">pkg</a>"#;
        let files = parse_upstream_files(html);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].filename, "pkg-1.0.whl");
    }

    // --- merge_file_lists ---

    #[test]
    fn test_merge_disjoint() {
        let upstream = vec![FileEntry {
            filename: "pkg-1.0-cp314-cp314-linux_x86_64.whl".to_string(),
            sha256: Some("uuu".to_string()),
        }];
        let local = vec![FileEntry {
            filename: "pkg-1.0-cp310-cp310-linux_x86_64.whl".to_string(),
            sha256: Some("lll".to_string()),
        }];
        let merged = merge_file_lists(upstream, &local);
        assert_eq!(merged.len(), 2);
        // Local first
        assert_eq!(merged[0].filename, "pkg-1.0-cp310-cp310-linux_x86_64.whl");
        assert_eq!(merged[1].filename, "pkg-1.0-cp314-cp314-linux_x86_64.whl");
    }

    #[test]
    fn test_merge_local_wins_on_duplicate() {
        let upstream = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".to_string(),
            sha256: Some("upstream-hash".to_string()),
        }];
        let local = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".to_string(),
            sha256: Some("local-verified-hash".to_string()),
        }];
        let merged = merge_file_lists(upstream, &local);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].sha256.as_deref(), Some("local-verified-hash"));
    }

    #[test]
    fn test_merge_empty_upstream() {
        let local = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".to_string(),
            sha256: None,
        }];
        let merged = merge_file_lists(vec![], &local);
        assert_eq!(merged.len(), 1);
    }

    #[test]
    fn test_merge_empty_local() {
        let upstream = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".to_string(),
            sha256: Some("hash".to_string()),
        }];
        let merged = merge_file_lists(upstream, &[]);
        assert_eq!(merged.len(), 1);
    }

    #[test]
    fn test_merge_both_empty() {
        let merged = merge_file_lists(vec![], &[]);
        assert!(merged.is_empty());
    }

    #[test]
    fn test_merge_first_upstream_wins_and_dedups() {
        // Multi-upstream (#663): `upstream` is the upstreams concatenated in
        // precedence order. The same filename from upstream A (first) and B must
        // be deduped to a single entry, and A wins.
        let upstream = vec![
            FileEntry {
                filename: "torch-1.0.whl".to_string(),
                sha256: Some("from-A".to_string()),
            },
            FileEntry {
                filename: "torch-1.0.whl".to_string(),
                sha256: Some("from-B".to_string()),
            },
            FileEntry {
                filename: "torchvision-1.0.whl".to_string(),
                sha256: Some("from-B".to_string()),
            },
        ];
        let merged = merge_file_lists(upstream, &[]);
        assert_eq!(
            merged.len(),
            2,
            "duplicate filename across upstreams deduped"
        );
        let torch = merged
            .iter()
            .find(|f| f.filename == "torch-1.0.whl")
            .unwrap();
        assert_eq!(
            torch.sha256.as_deref(),
            Some("from-A"),
            "first upstream (A) wins precedence"
        );
        assert!(merged.iter().any(|f| f.filename == "torchvision-1.0.whl"));
    }

    proptest! {
        #[test]
        fn prop_merge_no_duplicate_filenames_and_local_wins(
            upstream_names in prop::collection::vec("[a-z]{1,6}", 0..20),
            local_names in prop::collection::vec("[a-z]{1,6}", 0..6),
        ) {
            let upstream: Vec<FileEntry> = upstream_names
                .iter()
                .map(|n| FileEntry { filename: n.clone(), sha256: None })
                .collect();
            let local: Vec<FileEntry> = local_names
                .iter()
                .map(|n| FileEntry { filename: n.clone(), sha256: Some("L".to_string()) })
                .collect();
            let merged = merge_file_lists(upstream, &local);
            // No filename appears twice.
            let mut seen = std::collections::HashSet::new();
            for f in &merged {
                prop_assert!(seen.insert(f.filename.clone()), "duplicate filename in merge");
            }
            // Every local file survives, and local wins on collision.
            for ln in &local_names {
                let e = merged.iter().find(|f| &f.filename == ln);
                prop_assert!(e.is_some());
                prop_assert_eq!(e.unwrap().sha256.as_deref(), Some("L"));
            }
        }
    }
}

// ============================================================================
// Integration Tests
// ============================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod integration_tests {
    use crate::test_helpers::{body_bytes, create_test_context, send, send_with_headers};
    use axum::http::{header, Method, StatusCode};

    #[tokio::test]
    async fn test_pypi_list_empty() {
        let ctx = create_test_context();
        let response = send(&ctx.app, Method::GET, "/simple/", "").await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let html = String::from_utf8_lossy(&body);
        assert!(html.contains("Simple Index"));
    }

    #[tokio::test]
    async fn test_pypi_list_with_packages() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", b"fake-tarball-data")
            .await
            .unwrap();

        let response = send(&ctx.app, Method::GET, "/simple/", "").await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let html = String::from_utf8_lossy(&body);
        assert!(html.contains("flask"));
    }

    #[tokio::test]
    async fn test_pypi_list_json_pep691() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", b"data")
            .await
            .unwrap();

        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/simple/",
            vec![("Accept", "application/vnd.pypi.simple.v1+json")],
            "",
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(json["meta"]["api-version"].as_str() == Some("1.0"));
        assert!(json["projects"].as_array().unwrap().len() == 1);
    }

    #[tokio::test]
    async fn test_pypi_versions_local() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", b"fake-data")
            .await
            .unwrap();

        let response = send(&ctx.app, Method::GET, "/simple/flask/", "").await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let html = String::from_utf8_lossy(&body);
        assert!(html.contains("flask-2.0.tar.gz"));
        // URL should contain base_url + /simple/flask/flask-2.0.tar.gz
        assert!(html.contains("/simple/flask/flask-2.0.tar.gz"));
    }

    #[tokio::test]
    async fn test_pypi_versions_with_hash() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", b"fake-data")
            .await
            .unwrap();
        ctx.state
            .storage
            .put(
                "pypi/flask/flask-2.0.tar.gz.sha256",
                b"abc123def456abc123def456abc123def456abc123def456abc123def456abcd",
            )
            .await
            .unwrap();

        let response = send(&ctx.app, Method::GET, "/simple/flask/", "").await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let html = String::from_utf8_lossy(&body);
        assert!(html.contains("#sha256=abc123"));
    }

    #[tokio::test]
    async fn test_pypi_versions_json_pep691() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", b"data")
            .await
            .unwrap();
        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz.sha256", b"deadbeef")
            .await
            .unwrap();

        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/simple/flask/",
            vec![("Accept", "application/vnd.pypi.simple.v1+json")],
            "",
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["name"], "flask");
        assert_eq!(json["files"].as_array().unwrap().len(), 1);
        assert_eq!(json["files"][0]["filename"], "flask-2.0.tar.gz");
        assert_eq!(json["files"][0]["hashes"]["sha256"], "deadbeef");
    }

    #[tokio::test]
    async fn test_pypi_download_local() {
        let ctx = create_test_context();

        let tarball_data = b"fake-tarball-content";
        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", tarball_data)
            .await
            .unwrap();

        let response = send(&ctx.app, Method::GET, "/simple/flask/flask-2.0.tar.gz", "").await;

        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        assert_eq!(&body[..], tarball_data);
    }

    #[tokio::test]
    async fn test_pypi_download_range_request() {
        let ctx = create_test_context();
        let sdist = b"0123456789abcdef";
        ctx.state
            .storage
            .put("pypi/flask/flask-2.0.tar.gz", sdist)
            .await
            .unwrap();
        let url = "/simple/flask/flask-2.0.tar.gz";

        let resp =
            send_with_headers(&ctx.app, Method::GET, url, vec![("range", "bytes=2-5")], "").await;
        assert_eq!(resp.status(), StatusCode::PARTIAL_CONTENT);
        assert_eq!(
            resp.headers()
                .get(header::CONTENT_RANGE)
                .unwrap()
                .to_str()
                .unwrap(),
            format!("bytes 2-5/{}", sdist.len())
        );
        assert_eq!(
            resp.headers()
                .get(header::ACCEPT_RANGES)
                .unwrap()
                .to_str()
                .unwrap(),
            "bytes"
        );
        assert_eq!(
            resp.headers()
                .get(header::CONTENT_TYPE)
                .unwrap()
                .to_str()
                .unwrap(),
            "application/gzip"
        );
        assert_eq!(body_bytes(resp).await.as_ref(), &sdist[2..=5]);

        // A client that already holds the whole file resumes with `bytes=<size>-`.
        let resp = send_with_headers(
            &ctx.app,
            Method::GET,
            url,
            vec![("range", &format!("bytes={}-", sdist.len())[..])],
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
        assert_eq!(
            resp.headers()
                .get(header::CONTENT_RANGE)
                .unwrap()
                .to_str()
                .unwrap(),
            format!("bytes */{}", sdist.len())
        );

        let resp = send(&ctx.app, Method::GET, url, "").await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get(header::ACCEPT_RANGES)
                .unwrap()
                .to_str()
                .unwrap(),
            "bytes"
        );
        assert_eq!(body_bytes(resp).await.as_ref(), &sdist[..]);
    }

    #[tokio::test]
    async fn test_pypi_not_found_no_proxy() {
        let ctx = create_test_context();

        let response = send(&ctx.app, Method::GET, "/simple/nonexistent/", "").await;

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    /// Regression test for #891 path 1: internal `dates.json` must not leak
    /// into the PEP 691 simple index. `uv` and other strict clients require
    /// `hashes` on every file entry; `dates.json` has no sidecar → parse failure.
    #[tokio::test]
    async fn test_pypi_dates_json_excluded_from_index() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put("pypi/loguru/loguru-0.7.0.tar.gz", b"fake-sdist")
            .await
            .unwrap();
        ctx.state
            .storage
            .put("pypi/loguru/loguru-0.7.0.tar.gz.sha256", b"aabbccdd")
            .await
            .unwrap();
        ctx.state
            .storage
            .put(
                "pypi/loguru/dates.json",
                br#"{"loguru-0.7.0.tar.gz":"2023-08-20T12:00:00Z"}"#,
            )
            .await
            .unwrap();

        // HTML index must not contain dates.json
        let response = send(&ctx.app, Method::GET, "/simple/loguru/", "").await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let html = String::from_utf8_lossy(&body);
        assert!(
            html.contains("loguru-0.7.0.tar.gz"),
            "real package must appear"
        );
        assert!(
            !html.contains("dates.json"),
            "dates.json must NOT appear in index (#891)"
        );

        // PEP 691 JSON index must also exclude dates.json
        let response = send_with_headers(
            &ctx.app,
            Method::GET,
            "/simple/loguru/",
            vec![("Accept", "application/vnd.pypi.simple.v1+json")],
            "",
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = body_bytes(response).await;
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let files = json["files"].as_array().unwrap();
        assert_eq!(files.len(), 1, "only the real package file, not dates.json");
        assert_eq!(files[0]["filename"], "loguru-0.7.0.tar.gz");
    }

    /// Regression test for #891 path 2: `GET /simple/{name}/dates.json` must
    /// return 404, not serve the internal bookkeeping file.
    #[tokio::test]
    async fn test_pypi_dates_json_not_downloadable() {
        let ctx = create_test_context();

        ctx.state
            .storage
            .put(
                "pypi/loguru/dates.json",
                br#"{"loguru-0.7.0.tar.gz":"2023-08-20T12:00:00Z"}"#,
            )
            .await
            .unwrap();

        let response = send(&ctx.app, Method::GET, "/simple/loguru/dates.json", "").await;
        assert_eq!(
            response.status(),
            StatusCode::NOT_FOUND,
            "internal dates.json must not be downloadable (#891)"
        );
    }

    /// Regression test for #905: `ensure_pypi_dates_cached` must never fetch
    /// an internal-namespace package's metadata upstream (#68 dependency
    /// confusion). Verify that a tarball download for an internal-namespace
    /// package does not trigger any upstream requests for the dates endpoint.
    #[tokio::test]
    async fn test_pypi_self_prime_skips_internal_namespace() {
        use crate::test_helpers::create_test_context_with_config;
        use wiremock::matchers::any;
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let upstream = MockServer::start().await;

        // Any request to the upstream = test failure (the guard must prevent it).
        Mock::given(any())
            .respond_with(ResponseTemplate::new(200).set_body_string("LEAKED"))
            .mount(&upstream)
            .await;

        let ctx = create_test_context_with_config(|cfg| {
            cfg.pypi.proxy = Some(upstream.uri());
            cfg.server.trust_upstream_dates = true;
            cfg.curation.mode = crate::config::CurationMode::Enforce;
            cfg.curation.internal_namespaces = vec!["internal-*".to_string()];
        });

        // Pre-populate a tarball so the download path is exercised.
        ctx.state
            .storage
            .put(
                "pypi/internal-secret/internal_secret-1.0.0.tar.gz",
                b"fake-sdist",
            )
            .await
            .unwrap();
        ctx.state
            .storage
            .put(
                "pypi/internal-secret/internal_secret-1.0.0.tar.gz.sha256",
                b"aabbccdd",
            )
            .await
            .unwrap();

        // Download the tarball — this triggers ensure_pypi_dates_cached.
        let _resp = send(
            &ctx.app,
            Method::GET,
            "/simple/internal-secret/internal_secret-1.0.0.tar.gz",
            "",
        )
        .await;

        // The internal-namespace guard must have prevented any upstream fetch.
        let upstream_hits = upstream.received_requests().await.unwrap().len();
        assert_eq!(
            upstream_hits, 0,
            "internal-namespace package dates must never be fetched upstream (#68, #905)"
        );

        // dates.json must NOT have been written for an internal package.
        assert!(
            ctx.state
                .storage
                .get("pypi/internal-secret/dates.json")
                .await
                .is_err(),
            "dates.json must not be created for internal-namespace packages"
        );
    }
}

// ============================================================================
// PEP 691 spec conformance tests
// ============================================================================

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

    /// PEP 691 requires the field name `hashes`, NOT `digests`.
    /// Regression test for bug where `digests` was used instead.
    #[test]
    fn test_pep691_uses_hashes_not_digests() {
        let files = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".into(),
            sha256: Some("abcdef1234567890".into()),
        }];
        let response = versions_json_response("pkg", &files, "http://nora:4000");
        let body = response.into_body();
        let bytes = futures::executor::block_on(axum::body::to_bytes(body, 1024 * 1024)).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert!(
            json["files"][0].get("hashes").is_some(),
            "PEP 691 requires 'hashes' field, not 'digests'"
        );
        assert!(
            json["files"][0].get("digests").is_none(),
            "PEP 691 forbids 'digests' — must be 'hashes'"
        );
        assert_eq!(json["files"][0]["hashes"]["sha256"], "abcdef1234567890");
    }

    /// PEP 691 requires `meta.api-version` field.
    #[test]
    fn test_pep691_meta_api_version() {
        let files = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".into(),
            sha256: None,
        }];
        let response = versions_json_response("pkg", &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert_eq!(
            json["meta"]["api-version"], "1.0",
            "PEP 691 requires meta.api-version = '1.0'"
        );
    }

    /// PEP 691 JSON Content-Type must be `application/vnd.pypi.simple.v1+json`.
    #[test]
    fn test_pep691_content_type() {
        let files = vec![];
        let response = versions_json_response("pkg", &files, "http://nora:4000");
        let ct = response
            .headers()
            .get(header::CONTENT_TYPE)
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(
            ct, PEP691_JSON,
            "PEP 691 requires Content-Type: {PEP691_JSON}"
        );
    }

    /// PEP 691: `hashes` field must be omitted when no hash is available,
    /// not set to null or empty object.
    #[test]
    fn test_pep691_hashes_omitted_when_none() {
        let files = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".into(),
            sha256: None,
        }];
        let response = versions_json_response("pkg", &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert!(
            json["files"][0].get("hashes").is_none(),
            "hashes must be omitted (not null) when no hash available"
        );
    }

    /// PEP 691: `name` field must match the normalized package name.
    #[test]
    fn test_pep691_name_is_normalized() {
        let files = vec![];
        let normalized = normalize_name("Flask-RESTful");
        let response = versions_json_response(&normalized, &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert_eq!(json["name"], "flask-restful");
    }

    /// PEP 691: file URLs must point to NORA, not upstream.
    #[test]
    fn test_pep691_urls_point_to_nora() {
        let files = vec![
            FileEntry {
                filename: "pkg-1.0.tar.gz".into(),
                sha256: Some("aaa".into()),
            },
            FileEntry {
                filename: "pkg-2.0.whl".into(),
                sha256: Some("bbb".into()),
            },
        ];
        let response = versions_json_response("pkg", &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        for file in json["files"].as_array().unwrap() {
            let url = file["url"].as_str().unwrap();
            assert!(
                url.starts_with("http://nora:4000/simple/"),
                "file URL must point to NORA base: {url}"
            );
        }
    }

    // ========================================================================
    // URL-rewrite systematic tests (#387)
    // ========================================================================

    /// URLs in HTML response must point to NORA, not upstream (#387).
    #[test]
    fn test_html_urls_point_to_nora_no_upstream_leak() {
        let files = vec![
            FileEntry {
                filename: "requests-2.31.0.tar.gz".into(),
                sha256: Some("aaa111".into()),
            },
            FileEntry {
                filename: "requests-2.31.0-py3-none-any.whl".into(),
                sha256: Some("bbb222".into()),
            },
        ];
        let response = versions_html_response("requests", &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let html = String::from_utf8(bytes.to_vec()).unwrap();

        assert!(
            html.contains("http://nora:4000/simple/requests/requests-2.31.0.tar.gz"),
            "HTML must contain NORA URL for tarball"
        );
        assert!(
            html.contains("http://nora:4000/simple/requests/requests-2.31.0-py3-none-any.whl"),
            "HTML must contain NORA URL for wheel"
        );
        // No upstream host leak
        assert!(
            !html.contains("pypi.org") && !html.contains("pythonhosted"),
            "HTML must not contain upstream URLs"
        );
    }

    /// Trailing slash on base_url must not produce double-slash in URLs (#387).
    #[test]
    fn test_pep691_trailing_slash_handling() {
        let files = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".into(),
            sha256: Some("abc".into()),
        }];
        let response = versions_json_response("pkg", &files, "http://nora:4000/");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        let url = json["files"][0]["url"].as_str().unwrap();
        assert!(
            !url.contains("//simple"),
            "trailing slash on base_url must not produce double-slash: {url}"
        );
        assert!(
            url.starts_with("http://nora:4000/"),
            "URL must start with base: {url}"
        );
    }

    /// Empty file list produces valid response with no file URLs (#387).
    #[test]
    fn test_pep691_no_files_clean_response() {
        let files: Vec<FileEntry> = vec![];
        let response = versions_json_response("empty-pkg", &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["files"].as_array().unwrap().len(), 0);
        assert_eq!(json["name"], "empty-pkg");
    }

    /// Upstream HTML with no matching package links → empty file list (#387).
    #[test]
    fn test_parse_upstream_no_package_links_yields_empty() {
        let html = r#"<html><body>
            <a href="https://example.com/page">Not a package</a>
            <a href="/about">About</a>
        </body></html>"#;
        let files = parse_upstream_files(html);
        assert!(
            files.is_empty(),
            "HTML without package links should yield empty list"
        );
    }

    /// PEP 691 response must be valid JSON and deserializable back to typed struct.
    #[test]
    fn test_pep691_response_round_trip() {
        let files = vec![FileEntry {
            filename: "pkg-1.0.tar.gz".into(),
            sha256: Some("abc123".into()),
        }];
        let response = versions_json_response("pkg", &files, "http://nora:4000");
        let bytes =
            futures::executor::block_on(axum::body::to_bytes(response.into_body(), 1024 * 1024))
                .unwrap();

        // Must parse as valid JSON with expected top-level keys
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(json.get("meta").is_some(), "missing 'meta' key");
        assert!(json.get("name").is_some(), "missing 'name' key");
        assert!(json.get("files").is_some(), "missing 'files' key");

        // Snapshot the structure
        insta::assert_json_snapshot!("pypi_pep691_response_structure", json);
    }
}