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

//! Ansible Galaxy collection proxy (API v3).
//!
//! Implements a caching proxy for galaxy.ansible.com:
//!   GET /ansible/                                         — API discovery
//!   GET /ansible/v3/collections/                          — collection list (short path)
//!   GET /ansible/v3/collections/{ns}/{name}/              — collection detail
//!   GET /ansible/v3/collections/{ns}/{name}/versions/     — version list
//!   GET /ansible/v3/collections/{ns}/{name}/versions/{ver}/ — version detail
//!   GET /ansible/download/{ns}-{name}-{ver}.tar.gz        — tarball (immutable)
//!   GET /ansible/api/v3/.../artifacts/{file}              — tarball alias (Galaxy format)
//!
//! Also supports full Pulp-style paths under /ansible/api/v3/plugin/ansible/...
//!
//! Namespace and collection names follow Galaxy spec: [a-z0-9_]+ (no hyphens).
//!
//! Client config:
//!   ansible-galaxy collection install community.general -s http://nora:4000/ansible/

use crate::activity_log::{ActionType, ActivityEntry};
use crate::audit::AuditEntry;
use crate::registry::{
    circuit_open_response, nora_base_url, proxy_fetch, proxy_fetch_conditional, read_validators,
    write_validators, ProxyError, Revalidation, Validators,
};
use crate::registry_type::RegistryType;
use crate::secrets::expose_opt;
use crate::AppState;
use axum::{
    body::Bytes,
    extract::{Path, RawQuery, State},
    http::{header, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::time::Duration;

const UPSTREAM_DEFAULT: &str = "https://galaxy.ansible.com";

/// Storage prefix and file suffix for repo index scanning.
pub const INDEX_PATTERN: (&str, &str) = ("ansible/", ".tar.gz");
const API_PREFIX: &str = "/api/v3/plugin/ansible/content/published/collections/index";

pub fn routes() -> Router<AppState> {
    Router::new()
        // Galaxy API discovery (ansible-galaxy CLI hits this first)
        .route("/ansible/", get(api_discovery))
        .route("/ansible/api/", get(api_discovery))
        // Short v3 paths (ansible-galaxy --api-version 3 format)
        .route("/ansible/v3/collections/", get(collection_list))
        .route(
            "/ansible/v3/collections/{ns}/{name}/",
            get(collection_detail),
        )
        .route(
            "/ansible/v3/collections/{ns}/{name}/versions/",
            get(version_list),
        )
        .route(
            "/ansible/v3/collections/{ns}/{name}/versions/{ver}/",
            get(version_detail),
        )
        // Full pulp-style paths (direct API access)
        .route(
            "/ansible/api/v3/plugin/ansible/content/published/collections/index/",
            get(collection_list),
        )
        .route(
            "/ansible/api/v3/plugin/ansible/content/published/collections/index/{ns}/{name}/",
            get(collection_detail),
        )
        .route(
            "/ansible/api/v3/plugin/ansible/content/published/collections/index/{ns}/{name}/versions/",
            get(version_list),
        )
        .route(
            "/ansible/api/v3/plugin/ansible/content/published/collections/index/{ns}/{name}/versions/{ver}/",
            get(version_detail),
        )
        // Collection tarball download (immutable)
        .route("/ansible/download/{filename}", get(download_tarball))
        // Artifact path alias — upstream Galaxy serves tarballs here too (#438)
        .route(
            "/ansible/api/v3/plugin/ansible/content/published/collections/artifacts/{filename}",
            get(download_tarball),
        )
}

// ── API discovery ─────────────────────────────────────────────────────

async fn api_discovery() -> Response {
    let body = r#"{"available_versions":{"v3":"v3/"}}"#;
    (
        StatusCode::OK,
        [(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        )],
        body,
    )
        .into_response()
}

// ── Collection list ────────────────────────────────────────────────────

async fn collection_list(State(state): State<AppState>, RawQuery(raw_query): RawQuery) -> Response {
    let proxy_url = upstream_url(&state);
    let base = format!("{}{}/", proxy_url.trim_end_matches('/'), API_PREFIX);
    let url = append_query(&base, raw_query.as_deref());

    let cache_key = match extract_page_param(raw_query.as_deref()) {
        Some(page) => format!("ansible/metadata/collections-page-{}.json", page),
        None => "ansible/metadata/collections.json".to_string(),
    };

    proxy_json(&state, &url, "ansible-collections", &cache_key, None).await
}

// ── Collection detail ──────────────────────────────────────────────────

async fn collection_detail(
    State(state): State<AppState>,
    Path((ns, name)): Path<(String, String)>,
) -> Response {
    if !is_valid_name(&ns) || !is_valid_name(&name) {
        return StatusCode::BAD_REQUEST.into_response();
    }

    let proxy_url = upstream_url(&state);
    let url = format!(
        "{}{}/{}/{}/",
        proxy_url.trim_end_matches('/'),
        API_PREFIX,
        ns,
        name
    );

    let cache_key = format!("ansible/metadata/{}/{}.json", ns, name);
    proxy_json(
        &state,
        &url,
        &format!("{}.{}", ns, name),
        &cache_key,
        Some(&format!("{}.{}", ns, name)),
    )
    .await
}

// ── Version listing ────────────────────────────────────────────────────

async fn version_list(
    State(state): State<AppState>,
    Path((ns, name)): Path<(String, String)>,
    RawQuery(raw_query): RawQuery,
) -> Response {
    if !is_valid_name(&ns) || !is_valid_name(&name) {
        return StatusCode::BAD_REQUEST.into_response();
    }

    let proxy_url = upstream_url(&state);
    let base = format!(
        "{}{}/{}/{}/versions/",
        proxy_url.trim_end_matches('/'),
        API_PREFIX,
        ns,
        name
    );
    let url = append_query(&base, raw_query.as_deref());

    let cache_key = match extract_page_param(raw_query.as_deref()) {
        Some(page) => format!(
            "ansible/metadata/{}/{}/versions-page-{}.json",
            ns, name, page
        ),
        None => format!("ansible/metadata/{}/{}/versions.json", ns, name),
    };

    proxy_json(
        &state,
        &url,
        &format!("{}.{}/versions", ns, name),
        &cache_key,
        Some(&format!("{}.{}", ns, name)),
    )
    .await
}

// ── Version detail ─────────────────────────────────────────────────────

async fn version_detail(
    State(state): State<AppState>,
    headers: axum::http::HeaderMap,
    Path((ns, name, ver)): Path<(String, String, String)>,
) -> Response {
    if !is_valid_name(&ns) || !is_valid_name(&name) || !is_valid_version(&ver) {
        return StatusCode::BAD_REQUEST.into_response();
    }

    // Curation check. #733: an internal-namespace collection is operator-owned — skip curation;
    // proxy_json below already serves any local copy and blocks the upstream branch for internal.
    if !crate::curation::is_internal_namespace(
        &state.curation().curation_engine,
        crate::curation::RegistryType::Ansible,
        &format!("{}.{}", ns, name),
    ) {
        if let Some(response) = crate::curation::check_download(
            &state.curation().curation_engine,
            state.bypass_token().as_deref(),
            &headers,
            crate::curation::RegistryType::Ansible,
            &format!("{}.{}", ns, name),
            Some(&ver),
            None,
        ) {
            return response;
        }
    }

    let proxy_url = upstream_url(&state);
    let url = format!(
        "{}{}/{}/{}/versions/{}/",
        proxy_url.trim_end_matches('/'),
        API_PREFIX,
        ns,
        name,
        ver
    );

    let cache_key = format!("ansible/metadata/{}/{}/{}.json", ns, name, ver);
    proxy_json(
        &state,
        &url,
        &format!("{}.{} v{}", ns, name, ver),
        &cache_key,
        Some(&format!("{}.{}", ns, name)),
    )
    .await
}

/// Per-version `created_at` from cached Galaxy metadata (#748/#750).
///
/// Prefers the per-version detail JSON (`{ver}.json`, cached when the client
/// fetches version metadata immediately before download) — it carries the exact
/// version's `created_at` at top level with no pagination concern. Falls back to
/// the first page of the versions listing (`versions.json`), which only holds the
/// most recent versions for large collections (Galaxy paginates). Any miss →
/// `None` (the quarantine falls back to NORA's own first-seen clock).
async fn extract_ansible_publish_date(
    storage: &crate::storage::Storage,
    ns: &str,
    name: &str,
    ver: &str,
) -> Option<i64> {
    // Per-version detail (top-level created_at; works for any version).
    let ver_key = format!("ansible/metadata/{}/{}/{}.json", ns, name, ver);
    if let Ok(data) = storage.get(&ver_key).await {
        if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&data) {
            if let Some(date_str) = json
                .get("created_at")
                .or_else(|| json.get("created"))
                .and_then(|v| v.as_str())
            {
                if let Some(ts) = crate::curation::parse_iso8601_to_unix(date_str) {
                    return Some(ts);
                }
            }
        }
    }

    // First-page versions listing (data[]; recent versions only).
    let key = format!("ansible/metadata/{}/{}/versions.json", ns, name);
    let data = storage.get(&key).await.ok()?;
    let json: serde_json::Value = serde_json::from_slice(&data).ok()?;
    let entries = json.get("data").and_then(|d| d.as_array())?;
    let entry = entries
        .iter()
        .find(|e| e.get("version").and_then(|v| v.as_str()) == Some(ver))?;
    let date_str = entry
        .get("created_at")
        .or_else(|| entry.get("created"))?
        .as_str()?;
    crate::curation::parse_iso8601_to_unix(date_str)
}

// ── Tarball download (immutable) ───────────────────────────────────────

async fn download_tarball(
    State(state): State<AppState>,
    headers: axum::http::HeaderMap,
    Path(filename): Path<String>,
) -> Response {
    // filename = "namespace-name-version.tar.gz"
    if !filename.ends_with(".tar.gz") || !is_safe_filename(&filename) {
        return StatusCode::BAD_REQUEST.into_response();
    }

    // Parse namespace, name, version from filename
    let stem = filename.strip_suffix(".tar.gz").unwrap_or(&filename);
    let parts: Vec<&str> = stem.splitn(3, '-').collect();
    if parts.len() < 3 {
        return StatusCode::BAD_REQUEST.into_response();
    }
    let (ns, name, ver) = (parts[0], parts[1], parts[2]);

    if !is_valid_name(ns) || !is_valid_name(name) || !is_valid_version(ver) {
        return StatusCode::BAD_REQUEST.into_response();
    }

    let storage_key = format!("ansible/download/{}", filename);

    // Release date for the digest-quarantine first-seen clock (#748/#750): the
    // Galaxy versions metadata (cached by version_list) carries per-version
    // created_at. Hosted-only uses mtime.
    let publish_date = if state.config.ansible.proxy.is_none() {
        crate::curation::extract_mtime_as_publish_date(&state.storage, &storage_key).await
    } else if state.config.server.trust_upstream_dates {
        extract_ansible_publish_date(&state.storage, ns, name, ver).await
    } else {
        None
    };

    // Curation check. #733 serve-local: an internal-namespace collection is operator-owned — skip
    // curation and serve any local copy below; block the upstream branch separately.
    let internal = crate::curation::is_internal_namespace(
        &state.curation().curation_engine,
        crate::curation::RegistryType::Ansible,
        &format!("{}.{}", ns, name),
    );
    if !internal {
        if let Some(response) = crate::curation::check_download(
            &state.curation().curation_engine,
            state.bypass_token().as_deref(),
            &headers,
            crate::curation::RegistryType::Ansible,
            &format!("{}.{}", ns, name),
            Some(ver),
            publish_date,
        ) {
            return response;
        }
    }

    // Immutable cache. get_verified discharges the integrity witness at serve
    // (compile-time guarantee — see crate::verified).
    if let Ok(outcome) = state.storage.get_verified(&storage_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(),
        };
        // Integrity check
        if let Some(response) = crate::curation::verify_integrity(
            &state.curation().curation_engine,
            crate::curation::RegistryType::Ansible,
            &format!("{}.{}", ns, name),
            Some(ver),
            &data,
        ) {
            return response;
        }

        let (q_mode, q_secs) = crate::digest_quarantine::resolve_global(
            state.config.curation.ansible.quarantine.as_ref().or(state
                .config
                .curation
                .quarantine
                .as_ref()),
            state
                .config
                .curation
                .ansible
                .quarantine_ttl
                .as_deref()
                .or(state.config.curation.quarantine_ttl.as_deref()),
        );
        if let Some(resp) = crate::digest_quarantine::proxy_gate_dated(
            &state.digest_store,
            "ansible",
            &data,
            &q_mode,
            q_secs,
            "cache",
            publish_date,
        ) {
            return resp;
        }

        // Range request: 206 Partial Content, or 416 when the client asks past the
        // end. The gates above ran on the whole object; the partial body itself
        // cannot be rehashed, so the client's own checksum covers it (#657).
        if let Some(response) = crate::registry::range::range_response(
            &state.storage,
            &[&storage_key],
            &headers,
            data.len() as u64,
            "application/gzip",
            &[],
        )
        .await
        {
            if response.status() == StatusCode::PARTIAL_CONTENT {
                state.metrics.record_download("ansible");
                state.metrics.record_cache_hit("ansible");
            }
            return response;
        }

        state.metrics.record_download("ansible");
        state.metrics.record_cache_hit("ansible");
        state.activity.push(ActivityEntry::new(
            ActionType::CacheHit,
            filename,
            crate::registry_type::RegistryType::Ansible,
            "CACHE",
        ));
        return with_binary(data.to_vec());
    }

    // #733: an internal-namespace collection with no local copy is never proxied upstream.
    if internal {
        return crate::curation::check_namespace_isolation(
            &state.curation().curation_engine,
            crate::curation::RegistryType::Ansible,
            &format!("{}.{}", ns, name),
        )
        .unwrap_or_else(|| StatusCode::NOT_FOUND.into_response());
    }

    // Fetch from upstream
    let proxy_url = upstream_url(&state);
    let url = format!(
        "{}/download/{}-{}-{}.tar.gz",
        proxy_url.trim_end_matches('/'),
        ns,
        name,
        ver
    );

    match proxy_fetch(
        &state.http_client,
        &url,
        Duration::from_secs(state.config.ansible.proxy_timeout),
        expose_opt(&state.config.ansible.proxy_auth),
        &state.circuit_breaker,
        RegistryType::Ansible,
    )
    .await
    {
        Ok(bytes) => {
            state.metrics.record_download("ansible");
            state.metrics.record_cache_miss("ansible");
            state.activity.push(ActivityEntry::new(
                ActionType::ProxyFetch,
                filename,
                crate::registry_type::RegistryType::Ansible,
                "PROXY",
            ));
            state
                .audit
                .log(AuditEntry::new("proxy_fetch", "api", "", "ansible", ""));

            state.spawn_cache_immutable("ansible", storage_key, Bytes::from(bytes.clone()));
            let (q_mode, q_secs) = crate::digest_quarantine::resolve_global(
                state.config.curation.ansible.quarantine.as_ref().or(state
                    .config
                    .curation
                    .quarantine
                    .as_ref()),
                state
                    .config
                    .curation
                    .ansible
                    .quarantine_ttl
                    .as_deref()
                    .or(state.config.curation.quarantine_ttl.as_deref()),
            );
            if let Some(resp) = crate::digest_quarantine::proxy_gate_dated(
                &state.digest_store,
                "ansible",
                &bytes,
                &q_mode,
                q_secs,
                &url,
                publish_date,
            ) {
                return resp;
            }
            with_binary(bytes)
        }
        Err(ProxyError::NotFound) => StatusCode::NOT_FOUND.into_response(),
        Err(ProxyError::CircuitOpen(reg)) => circuit_open_response(&reg),
        Err(e) => {
            tracing::debug!(error = ?e, "Ansible Galaxy download error");
            StatusCode::BAD_GATEWAY.into_response()
        }
    }
}

// ── Generic JSON proxy with metadata caching ─────────────────────────

/// Proxy a Galaxy API JSON request with metadata caching and serve-stale.
///
/// `cache_key` is the storage path for the cached response (e.g.
/// `ansible/metadata/community/general.json`).
async fn proxy_json(
    state: &AppState,
    url: &str,
    artifact_name: &str,
    cache_key: &str,
    package_name: Option<&str>,
) -> Response {
    let base_url = nora_base_url(state);
    let upstream = upstream_url(state);

    // Read cache eagerly so stale data is available on upstream failure.
    let cached_data = state.storage.get(cache_key).await.ok();

    // TTL check — serve fresh cache without hitting upstream.
    if let Some(ref data) = cached_data {
        if let Some(meta) = state.storage.stat(cache_key).await {
            if crate::cache_ttl::is_within_ttl(meta.modified, state.config.ansible.metadata_ttl) {
                state.metrics.record_download("ansible");
                state.metrics.record_cache_hit("ansible");
                let text = String::from_utf8_lossy(data);
                let rewritten = rewrite_ansible_urls(&text, &upstream, &base_url);
                return with_json(rewritten.into_bytes());
            }
        }
    }

    // #68 namespace isolation: an internal-namespace collection's metadata must never
    // be fetched upstream (dependency confusion). Serve any local copy (fresh path
    // returned above), else block — never proxy. (collection_list passes None: the
    // catalog index has no single package name to gate.)
    if let Some(pkg) = package_name {
        if crate::curation::is_internal_namespace(
            &state.curation().curation_engine,
            crate::curation::RegistryType::Ansible,
            pkg,
        ) {
            if let Some(ref data) = cached_data {
                state.metrics.record_download("ansible");
                state.metrics.record_cache_hit("ansible");
                let text = String::from_utf8_lossy(data);
                let rewritten = rewrite_ansible_urls(&text, &upstream, &base_url);
                return with_json(rewritten.into_bytes());
            }
            return crate::curation::check_namespace_isolation(
                &state.curation().curation_engine,
                crate::curation::RegistryType::Ansible,
                pkg,
            )
            .unwrap_or_else(|| StatusCode::NOT_FOUND.into_response());
        }
    }

    // Cache miss or stale — revalidate with a conditional request when enabled
    // (a cheap 304 when the upstream sends validators) and fall back to a full
    // fetch otherwise. Empty validators ⇒ no conditional headers ⇒ always a 200,
    // which is also how the first fetch captures validators for next time.
    let validators = if state.config.ansible.revalidate {
        read_validators(&state.storage, cache_key)
            .await
            .unwrap_or_default()
    } else {
        Validators::default()
    };
    let had_validators = validators.is_some();

    match proxy_fetch_conditional(
        &state.http_client,
        url,
        Duration::from_secs(state.config.ansible.proxy_timeout),
        expose_opt(&state.config.ansible.proxy_auth),
        &validators,
        &state.circuit_breaker,
        RegistryType::Ansible,
    )
    .await
    {
        // Upstream unchanged — serve the cached body (rewritten at read time) and
        // bump its freshness so we don't revalidate again until the next TTL
        // window. No body was downloaded.
        Ok(Revalidation::NotModified) => {
            let Ok(cached) = state.storage.get(cache_key).await else {
                // Body vanished under us — fall back to serve-stale / 502.
                return serve_stale_or_bad_gateway(
                    state,
                    cached_data,
                    cache_key,
                    &upstream,
                    &base_url,
                );
            };
            crate::metrics::PROXY_UPSTREAM_304_TOTAL
                .with_label_values(&["ansible"])
                .inc();
            crate::metrics::PROXY_REVALIDATION_BYTES_SAVED_TOTAL
                .with_label_values(&["ansible"])
                .inc_by(cached.len() as u64);
            state.metrics.record_download("ansible");
            state.metrics.record_cache_hit("ansible");
            // Re-put bumps the file mtime (the freshness source) without download.
            let storage = state.storage.clone();
            let key_clone = cache_key.to_string();
            let body = cached.clone();
            tokio::spawn(async move {
                let _ = storage.put(&key_clone, &body).await;
            });
            let text = String::from_utf8_lossy(&cached);
            let rewritten = rewrite_ansible_urls(&text, &upstream, &base_url);
            with_json(rewritten.into_bytes())
        }
        // New body — cache the raw bytes first, then persist the fresh validators.
        Ok(Revalidation::Modified { body, validators }) => {
            state.metrics.record_download("ansible");
            state.metrics.record_cache_miss("ansible");
            state.activity.push(ActivityEntry::new(
                ActionType::ProxyFetch,
                artifact_name.to_string(),
                crate::registry_type::RegistryType::Ansible,
                "PROXY",
            ));
            state
                .audit
                .log(AuditEntry::new("proxy_fetch", "api", "", "ansible", ""));

            // Cache raw response (before URL rewriting) for serve-stale; the
            // validator sidecar is written AFTER the body so it never advertises
            // freshness for a body that is not there.
            let raw = Bytes::from(body);
            let storage = state.storage.clone();
            let key_clone = cache_key.to_string();
            let raw_for_cache = raw.clone();
            tokio::spawn(async move {
                if let Err(e) = storage.put(&key_clone, &raw_for_cache).await {
                    tracing::warn!(key = %key_clone, error = ?e, "ansible proxy: failed to cache metadata");
                    return;
                }
                write_validators(&storage, &key_clone, &validators).await;
            });

            let text = String::from_utf8_lossy(&raw);
            let rewritten = rewrite_ansible_urls(&text, &upstream, &base_url);
            state.repo_index.invalidate("ansible");
            with_json(rewritten.into_bytes())
        }
        Err(ProxyError::NotFound) => StatusCode::NOT_FOUND.into_response(),
        Err(ProxyError::CircuitOpen(reg)) => circuit_open_response(&reg),
        Err(e) => {
            if had_validators {
                crate::metrics::PROXY_REVALIDATION_ERRORS_TOTAL
                    .with_label_values(&["ansible"])
                    .inc();
            }
            tracing::debug!(error = ?e, "Ansible Galaxy upstream error");
            serve_stale_or_bad_gateway(state, cached_data, cache_key, &upstream, &base_url)
        }
    }
}

/// Serve stale cached metadata when upstream is unreachable, or 502 if no cache.
fn serve_stale_or_bad_gateway(
    state: &AppState,
    cached: Option<Bytes>,
    label: &str,
    upstream: &str,
    base_url: &str,
) -> Response {
    if let Some(data) = cached {
        if state.config.ansible.serve_stale {
            tracing::warn!(
                registry = "ansible",
                endpoint = label,
                "Upstream unreachable, serving stale cached metadata"
            );
            let text = String::from_utf8_lossy(&data);
            let rewritten = rewrite_ansible_urls(&text, upstream, base_url);
            return (
                StatusCode::OK,
                [
                    (
                        header::CONTENT_TYPE,
                        HeaderValue::from_static("application/json"),
                    ),
                    (
                        header::CACHE_CONTROL,
                        HeaderValue::from_static("public, max-age=0, must-revalidate"),
                    ),
                    (
                        axum::http::header::HeaderName::from_static("x-nora-stale"),
                        axum::http::header::HeaderValue::from_static("true"),
                    ),
                ],
                rewritten.into_bytes(),
            )
                .into_response();
        }
    }
    StatusCode::BAD_GATEWAY.into_response()
}

// ── URL rewriting ─────────────────────────────────────────────────────

/// Rewrite upstream Galaxy URLs in JSON responses to point through NORA.
///
/// Replacements are applied most-specific-first to avoid double-rewriting:
/// 1. `{upstream}/download/` → `{base}/ansible/download/`
/// 2. `{upstream}/.../artifacts/` → `{base}/ansible/download/` (#438)
/// 3. `{upstream}{API_PREFIX}/` → `{base}/ansible/v3/collections/`
/// 4. `{upstream}` (remaining) → `{base}/ansible`
fn rewrite_ansible_urls(json_text: &str, upstream_url: &str, base_url: &str) -> String {
    let upstream = upstream_url.trim_end_matches('/');
    let base = base_url.trim_end_matches('/');
    let nora_ansible = format!("{}/ansible", base);
    // Each mapping is escape-aware (plain + `\/`-escaped) so a slash-escaped upstream
    // URL cannot survive and leak the host to the client (#385).
    use super::replace_url_escape_aware as rw;

    // Most specific first: download URLs
    let s = rw(
        json_text,
        &format!("{}/download/", upstream),
        &format!("{}/download/", nora_ansible),
    );
    // Artifact URLs → download path (#438)
    let s = rw(
        &s,
        &format!(
            "{}/api/v3/plugin/ansible/content/published/collections/artifacts/",
            upstream
        ),
        &format!("{}/download/", nora_ansible),
    );
    // Pulp-style API paths → short v3 paths
    let s = rw(
        &s,
        &format!("{}{}/", upstream, API_PREFIX),
        &format!("{}/v3/collections/", nora_ansible),
    );
    // Catch-all: any remaining upstream references
    let s = rw(&s, upstream, &nora_ansible);

    // Root-relative pagination links (#851-followup): galaxy_ng emits
    // `links.next`/`first`/`last` as host-relative paths (no scheme/host), e.g.
    // `/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=100`.
    // The absolute rewrites above never match these, so without this the client
    // resolves them against NORA's host root — dropping the `/ansible` mount —
    // and every collection with >100 versions (e.g. community.docker) 404s on page 2.
    // Rewrite to root-relative NORA paths so the client's relative-link
    // resolution keeps them under `/ansible`.
    //
    // These needles are anchored on the opening `"` of the JSON string value
    // (the escape-aware `rw` also matches the `\"`…`\/`-escaped form). Unlike the
    // absolute rules above — pinned by a full `scheme://host` — a bare path is a
    // weak anchor, so without the quote it would also rewrite the middle of a
    // *different* host's URL or a literal path in free text (`docs_blob`). The
    // pagination links are whole string values, so the quote is always adjacent.
    let nora_ansible_path = format!("{}/ansible", crate::config::url_path_component(base));
    let s = rw(
        &s,
        "\"/api/v3/plugin/ansible/content/published/collections/artifacts/",
        &format!("\"{}/download/", nora_ansible_path),
    );
    rw(
        &s,
        &format!("\"{}/", API_PREFIX),
        &format!("\"{}/v3/collections/", nora_ansible_path),
    )
}

// ── Helpers ────────────────────────────────────────────────────────────

/// Append query string to a URL, rejecting oversized or malformed values.
fn append_query(base_url: &str, raw_query: Option<&str>) -> String {
    match raw_query {
        Some(q) if !q.is_empty() && q.len() <= 256 && !q.contains('#') && !q.contains('\0') => {
            format!("{}?{}", base_url, q)
        }
        _ => base_url.to_string(),
    }
}

/// Extract `page` or `offset` parameter from a query string for cache key differentiation.
fn extract_page_param(raw_query: Option<&str>) -> Option<String> {
    let q = raw_query?;
    for pair in q.split('&') {
        if let Some(val) = pair
            .strip_prefix("page=")
            .or_else(|| pair.strip_prefix("offset="))
        {
            if !val.is_empty() && val.len() <= 10 && val.chars().all(|c| c.is_ascii_digit()) {
                return Some(val.to_string());
            }
        }
    }
    None
}

fn upstream_url(state: &AppState) -> String {
    state
        .config
        .ansible
        .proxy
        .clone()
        .unwrap_or_else(|| UPSTREAM_DEFAULT.to_string())
}

fn with_json(data: Vec<u8>) -> Response {
    (
        StatusCode::OK,
        [
            (
                header::CONTENT_TYPE,
                HeaderValue::from_static("application/json"),
            ),
            (
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=60, must-revalidate"),
            ),
        ],
        data,
    )
        .into_response()
}

fn with_binary(data: Vec<u8>) -> Response {
    (
        StatusCode::OK,
        [
            (
                header::CONTENT_TYPE,
                HeaderValue::from_static("application/gzip"),
            ),
            (
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=31536000, immutable"),
            ),
            (header::ACCEPT_RANGES, HeaderValue::from_static("bytes")),
        ],
        data,
    )
        .into_response()
}

fn is_valid_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 256
        && !name.contains('/')
        && !name.contains('\0')
        && !name.contains("..")
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn is_valid_version(version: &str) -> bool {
    !version.is_empty()
        && version.len() <= 128
        && !version.contains('/')
        && !version.contains('\0')
        && !version.contains("..")
        && version
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')
}

fn is_safe_filename(name: &str) -> bool {
    !name.contains("..")
        && !name.contains('/')
        && !name.contains('\0')
        && !name.is_empty()
        && name.len() <= 512
}

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

    /// #385: a slash-escaped upstream URL (`https:\/\/host` — valid JSON many
    /// origins emit) must not survive the raw-text rewrite and leak the host.
    #[test]
    fn rewrite_ansible_drops_upstream_host_plain_and_escaped() {
        const HOST: &str = "galaxy.ansible.com";
        let upstream = "https://galaxy.ansible.com";
        let base = "http://nora.test";

        let plain = rewrite_ansible_urls(
            r#"{"download_url":"https://galaxy.ansible.com/download/x/a.tar.gz"}"#,
            upstream,
            base,
        );
        assert!(!plain.contains(HOST), "plain upstream host leaked: {plain}");

        let escaped = rewrite_ansible_urls(
            r#"{"download_url":"https:\/\/galaxy.ansible.com\/download\/x\/a.tar.gz"}"#,
            upstream,
            base,
        );
        assert!(
            !escaped.contains(HOST),
            "slash-escaped upstream host leaked (#385): {escaped}"
        );
        assert!(
            escaped.contains("nora.test"),
            "escaped url not rewritten to nora base: {escaped}"
        );
    }

    #[test]
    fn test_valid_names() {
        assert!(is_valid_name("community"));
        assert!(is_valid_name("ansible"));
        assert!(is_valid_name("cloud_common"));
    }

    #[test]
    fn test_invalid_names() {
        assert!(!is_valid_name(""));
        assert!(!is_valid_name("../evil"));
        assert!(!is_valid_name("foo/bar"));
        // Galaxy spec: namespaces/names use underscores, not hyphens
        assert!(!is_valid_name("cloud-common"));
    }

    #[test]
    fn test_valid_version() {
        assert!(is_valid_version("7.0.0"));
        assert!(is_valid_version("1.2.3"));
        assert!(!is_valid_version(""));
        assert!(!is_valid_version("../evil"));
        assert!(!is_valid_version("foo/bar"));
    }

    #[test]
    fn test_safe_filename() {
        assert!(is_safe_filename("community-general-7.0.0.tar.gz"));
        assert!(!is_safe_filename("../evil.tar.gz"));
        assert!(!is_safe_filename("evil/path.tar.gz"));
    }

    #[test]
    fn test_rewrite_ansible_urls_download() {
        let input = r#"{"download_url":"https://galaxy.ansible.com/download/community-general-7.0.0.tar.gz"}"#;
        let result = rewrite_ansible_urls(input, "https://galaxy.ansible.com", "http://nora:4000");
        assert!(result.contains("http://nora:4000/ansible/download/community-general-7.0.0.tar.gz"));
        assert!(!result.contains("galaxy.ansible.com"));
    }

    #[test]
    fn test_rewrite_ansible_urls_href_and_pagination() {
        let input = r#"{"data":[{"href":"https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/index/community/general/"}],"links":{"next":"https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/index/?page=2"}}"#;
        let result = rewrite_ansible_urls(
            input,
            "https://galaxy.ansible.com",
            "https://registry.local",
        );
        assert!(result.contains("https://registry.local/ansible/v3/collections/community/general/"));
        assert!(result.contains("https://registry.local/ansible/v3/collections/?page=2"));
        assert!(!result.contains("galaxy.ansible.com"));
    }

    #[test]
    fn test_rewrite_ansible_urls_versions_url() {
        let input = r#"{"versions_url":"https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/index/community/general/versions/"}"#;
        let result = rewrite_ansible_urls(input, "https://galaxy.ansible.com", "http://nora:4000");
        assert!(
            result.contains("http://nora:4000/ansible/v3/collections/community/general/versions/")
        );
        assert!(!result.contains("galaxy.ansible.com"));
    }

    #[test]
    fn test_append_query_basic() {
        let base = "https://galaxy.ansible.com/api/v3/versions/";
        assert_eq!(
            append_query(base, Some("limit=10&offset=20")),
            "https://galaxy.ansible.com/api/v3/versions/?limit=10&offset=20"
        );
    }

    #[test]
    fn test_append_query_empty() {
        let base = "https://galaxy.ansible.com/api/v3/versions/";
        assert_eq!(append_query(base, None), base);
        assert_eq!(append_query(base, Some("")), base);
    }

    #[test]
    fn test_append_query_rejects_oversized() {
        let base = "https://galaxy.ansible.com/api/v3/versions/";
        let huge = "a".repeat(257);
        assert_eq!(append_query(base, Some(&huge)), base);
    }

    #[test]
    fn test_append_query_rejects_fragment() {
        let base = "https://galaxy.ansible.com/api/v3/versions/";
        assert_eq!(append_query(base, Some("page=1#evil")), base);
    }

    #[test]
    fn test_append_query_rejects_null_byte() {
        let base = "https://galaxy.ansible.com/api/v3/versions/";
        assert_eq!(append_query(base, Some("page=1\0")), base);
    }

    #[test]
    fn test_extract_page_param() {
        assert_eq!(extract_page_param(Some("page=2")), Some("2".to_string()));
        assert_eq!(
            extract_page_param(Some("limit=10&offset=20")),
            Some("20".to_string())
        );
        assert_eq!(extract_page_param(Some("limit=10")), None);
        assert_eq!(extract_page_param(None), None);
        assert_eq!(extract_page_param(Some("")), None);
        // Reject non-numeric
        assert_eq!(extract_page_param(Some("page=abc")), None);
    }

    #[test]
    fn test_rewrite_preserves_pagination_query_params() {
        let input = r#"{"links":{"next":"https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/index/community/general/versions/?limit=10&offset=20"}}"#;
        let result = rewrite_ansible_urls(input, "https://galaxy.ansible.com", "http://nora:4000");
        assert!(result.contains("http://nora:4000/ansible/v3/collections/community/general/versions/?limit=10&offset=20"));
        assert!(!result.contains("galaxy.ansible.com"));
    }

    #[test]
    fn test_rewrite_ansible_urls_artifacts_path() {
        // Upstream Galaxy returns download_url with artifacts path (#438)
        let input = r#"{"download_url":"https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/artifacts/community-general-12.2.0.tar.gz"}"#;
        let result = rewrite_ansible_urls(input, "https://galaxy.ansible.com", "http://nora:4000");
        assert!(
            result.contains("http://nora:4000/ansible/download/community-general-12.2.0.tar.gz"),
            "artifacts path should rewrite to /ansible/download/: {}",
            result
        );
        assert!(!result.contains("galaxy.ansible.com"));
    }

    #[test]
    fn test_rewrite_relative_pagination_next_link() {
        // galaxy_ng emits root-relative pagination links (no scheme/host). The
        // absolute rewrites don't touch them; they must still land under /ansible
        // so the client's relative-link resolution stays on the mount. Regression
        // for community.docker (148 versions) 404ing on page 2.
        let input = r#"{"links":{"next":"/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=100","first":"/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=0"}}"#;
        let result = rewrite_ansible_urls(
            input,
            "https://galaxy.ansible.com",
            "https://nora.nuc.m8g.dev",
        );
        assert!(
            result.contains(
                "\"next\":\"/ansible/v3/collections/community/docker/versions/?limit=100&offset=100\""
            ),
            "relative next link not rewritten to /ansible path: {result}"
        );
        assert!(
            result.contains(
                "\"first\":\"/ansible/v3/collections/community/docker/versions/?limit=100&offset=0\""
            ),
            "relative first link not rewritten: {result}"
        );
        // No bare /api/v3/plugin path may survive (would drop the /ansible mount).
        assert!(
            !result.contains("\"/api/v3/plugin/"),
            "a root-relative pulp path leaked: {result}"
        );

        // Same link in the `\/`-escaped JSON form many origins emit (#385 class):
        // must be rewritten too, or the pulp path survives once the client
        // unescapes it.
        let escaped = r#"{"links":{"next":"\/api\/v3\/plugin\/ansible\/content\/published\/collections\/index\/community\/docker\/versions\/?limit=100&offset=100"}}"#;
        let result = rewrite_ansible_urls(
            escaped,
            "https://galaxy.ansible.com",
            "https://nora.nuc.m8g.dev",
        );
        assert!(
            result.contains(
                "\"next\":\"\\/ansible\\/v3\\/collections\\/community\\/docker\\/versions\\/?limit=100&offset=100\""
            ),
            "escaped relative next link not rewritten: {result}"
        );
        assert!(
            !result.contains("plugin"),
            "an escaped pulp path leaked: {result}"
        );
    }

    #[test]
    fn test_rewrite_relative_pagination_subpath_mount() {
        // NORA mounted under a sub-path (reverse proxy): the relative link must
        // carry the prefix so the client resolves it under `/prefix/ansible`, not
        // the host root. Exercises `url_path_component` inside the rewriter — the
        // reason it exists — which `test_url_path_component` only covers in isolation.
        let input = r#"{"links":{"next":"/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=100"}}"#;
        let result = rewrite_ansible_urls(
            input,
            "https://galaxy.ansible.com",
            "https://nora.test/prefix",
        );
        assert!(
            result.contains(
                "\"next\":\"/prefix/ansible/v3/collections/community/docker/versions/?limit=100&offset=100\""
            ),
            "relative link did not carry the sub-path mount prefix: {result}"
        );
    }

    #[test]
    fn test_relative_rewrite_is_quote_anchored() {
        // The relative rules match a bare path only at the start of a JSON string
        // value (anchored on the opening quote). A pulp-looking path in the middle
        // of a *different* host's absolute URL, or in free text, must be left
        // untouched — otherwise the weakly-anchored rule mangles unrelated content.
        let foreign = r#"{"x":"https://mirror.example/api/v3/plugin/ansible/content/published/collections/index/foo/bar/"}"#;
        assert_eq!(
            rewrite_ansible_urls(foreign, "https://galaxy.ansible.com", "https://nora.test"),
            foreign,
            "a non-upstream absolute URL was mangled mid-path"
        );
        let prose = r#"{"description":"see /api/v3/plugin/ansible/content/published/collections/index/ here"}"#;
        assert_eq!(
            rewrite_ansible_urls(prose, "https://galaxy.ansible.com", "https://nora.test"),
            prose,
            "a literal path in free text was mangled"
        );
    }

    #[test]
    fn test_url_path_component() {
        use crate::config::url_path_component;
        assert_eq!(url_path_component("https://nora.nuc.m8g.dev"), "");
        assert_eq!(url_path_component("https://nora.test/prefix"), "/prefix");
        assert_eq!(url_path_component("http://nora:4000"), "");
        assert_eq!(url_path_component("/already/a/path"), "/already/a/path");
    }

    #[test]
    fn test_rewrite_ansible_urls_no_upstream_unchanged() {
        let input = r#"{"name":"community.general","version":"7.0.0"}"#;
        let result = rewrite_ansible_urls(input, "https://galaxy.ansible.com", "http://nora:4000");
        assert_eq!(input, result);
    }

    #[test]
    fn test_rewrite_ansible_urls_custom_upstream() {
        let input =
            r#"{"download_url":"https://hub.example.com/download/my-collection-1.0.0.tar.gz"}"#;
        let result = rewrite_ansible_urls(input, "https://hub.example.com", "http://nora:4000");
        assert!(result.contains("http://nora:4000/ansible/download/my-collection-1.0.0.tar.gz"));
        assert!(!result.contains("hub.example.com"));
    }
}

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

    #[tokio::test]
    async fn test_ansible_disabled_returns_404() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = false;
        });
        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/api/v3/plugin/ansible/content/published/collections/index/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_ansible_cached_tarball() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
        });

        ctx.state
            .storage
            .put(
                "ansible/download/community-general-7.0.0.tar.gz",
                b"tarball-data",
            )
            .await
            .unwrap();

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/download/community-general-7.0.0.tar.gz",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_bytes(resp).await;
        assert_eq!(&body[..], b"tarball-data");
    }

    /// Resume support on a cached collection tarball: 206 for a byte range, 416
    /// past the end, `Accept-Ranges` on the full 200.
    #[tokio::test]
    async fn test_ansible_tarball_range_request() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
        });
        let url = "/ansible/download/community-general-7.0.1.tar.gz";
        ctx.state
            .storage
            .put(
                "ansible/download/community-general-7.0.1.tar.gz",
                b"0123456789",
            )
            .await
            .unwrap();

        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("content-range")
                .unwrap()
                .to_str()
                .unwrap(),
            "bytes 2-5/10"
        );
        assert_eq!(
            resp.headers()
                .get("accept-ranges")
                .unwrap()
                .to_str()
                .unwrap(),
            "bytes"
        );
        assert_eq!(&body_bytes(resp).await[..], b"2345");

        let resp =
            send_with_headers(&ctx.app, Method::GET, url, vec![("range", "bytes=10-")], "").await;
        assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
        assert_eq!(
            resp.headers()
                .get("content-range")
                .unwrap()
                .to_str()
                .unwrap(),
            "bytes */10"
        );

        let resp = send(&ctx.app, Method::GET, url, "").await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get("accept-ranges")
                .unwrap()
                .to_str()
                .unwrap(),
            "bytes"
        );
    }

    #[tokio::test]
    async fn test_ansible_unreachable_proxy() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some("http://127.0.0.1:1".to_string());
            cfg.ansible.proxy_timeout = 1;
        });
        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/api/v3/plugin/ansible/content/published/collections/index/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
    }

    #[tokio::test]
    async fn test_ansible_api_discovery() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
        });
        // /ansible/ discovery
        let resp = send(&ctx.app, Method::GET, "/ansible/", "").await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_bytes(resp).await;
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["available_versions"]["v3"], "v3/");

        // /ansible/api/ discovery
        let resp = send(&ctx.app, Method::GET, "/ansible/api/", "").await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_bytes(resp).await;
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["available_versions"]["v3"], "v3/");
    }

    #[tokio::test]
    async fn test_ansible_short_v3_path_tarball() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
        });
        ctx.state
            .storage
            .put(
                "ansible/download/community-general-7.0.0.tar.gz",
                b"tarball-v3",
            )
            .await
            .unwrap();

        // Short v3 path should still serve downloads
        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/download/community-general-7.0.0.tar.gz",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_bytes(resp).await;
        assert_eq!(&body[..], b"tarball-v3");
    }

    #[tokio::test]
    async fn test_ansible_download_rejects_invalid_name_parts() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
        });

        // Path traversal in namespace
        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/download/..%2F-name-1.0.0.tar.gz",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        // Empty name part (double-hyphen)
        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/download/community--1.0.0.tar.gz",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// Stale cache + unreachable upstream + serve_stale=true → 200 with X-Nora-Stale header (#466)
    #[tokio::test]
    async fn test_serve_stale_collection_detail() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some("http://127.0.0.1:1".to_string());
            cfg.ansible.proxy_timeout = 1;
            cfg.ansible.metadata_ttl = 0; // force TTL expiry → always stale
            cfg.ansible.serve_stale = true;
        });

        // Pre-populate cache
        ctx.state
            .storage
            .put(
                "ansible/metadata/community/general.json",
                br#"{"name":"community.general","namespace":{"name":"community"}}"#,
            )
            .await
            .unwrap();

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/v3/collections/community/general/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers().get("x-nora-stale").map(|v| v.as_bytes()),
            Some(b"true".as_ref()),
        );
        let body = body_bytes(resp).await;
        assert!(String::from_utf8_lossy(&body).contains("community.general"));
    }

    /// Stale cache + unreachable upstream + serve_stale=false → 502 (#466)
    #[tokio::test]
    async fn test_serve_stale_disabled_returns_502() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some("http://127.0.0.1:1".to_string());
            cfg.ansible.proxy_timeout = 1;
            cfg.ansible.metadata_ttl = 0;
            cfg.ansible.serve_stale = false;
        });

        ctx.state
            .storage
            .put(
                "ansible/metadata/community/general.json",
                br#"{"name":"community.general"}"#,
            )
            .await
            .unwrap();

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/v3/collections/community/general/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
        assert!(resp.headers().get("x-nora-stale").is_none());
    }

    /// Fresh cache (within TTL) → 200 without upstream request (#466)
    #[tokio::test]
    async fn test_fresh_cache_served_without_upstream() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some("http://127.0.0.1:1".to_string());
            cfg.ansible.proxy_timeout = 1;
            cfg.ansible.metadata_ttl = -1; // cache forever
        });

        ctx.state
            .storage
            .put(
                "ansible/metadata/community/general.json",
                br#"{"name":"community.general","cached":true}"#,
            )
            .await
            .unwrap();

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/v3/collections/community/general/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        // No stale header — cache is fresh
        assert!(resp.headers().get("x-nora-stale").is_none());
        let body = body_bytes(resp).await;
        assert!(String::from_utf8_lossy(&body).contains("community.general"));
    }

    /// No cache + unreachable upstream → 502 (not stale, just unavailable)
    #[tokio::test]
    async fn test_no_cache_unreachable_returns_502() {
        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some("http://127.0.0.1:1".to_string());
            cfg.ansible.proxy_timeout = 1;
            cfg.ansible.serve_stale = true;
        });

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/v3/collections/community/general/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
    }

    /// #52 acceptance: with a cached versions-list body + stored validators, a
    /// stale request revalidates with `If-None-Match`; on upstream 304 the cached
    /// body is served and NO 200-with-body is ever fetched. Drives the real
    /// handler. (Self-hosted Galaxy NG sends no validators, but a fronting CDN
    /// like galaxy.ansible.com does — this proves NORA uses them when present.)
    #[tokio::test]
    async fn test_ansible_revalidation_304_serves_cache_no_body_download() {
        use crate::registry::{write_validators, Validators};
        use wiremock::matchers::{header_exists, method};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let upstream = MockServer::start().await;
        // Conditional request (has If-None-Match) → 304. A request WITHOUT it
        // would 404 (no other mount), so any full fetch would visibly fail —
        // proving the 304 path served from cache.
        Mock::given(method("GET"))
            .and(header_exists("if-none-match"))
            .respond_with(ResponseTemplate::new(304))
            .mount(&upstream)
            .await;

        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some(upstream.uri());
            cfg.ansible.metadata_ttl = 0; // always stale → always revalidate
            cfg.ansible.revalidate = true;
            cfg.ansible.serve_stale = false;
        });

        // Pre-seed the cached versions body + validator sidecar (as a prior 200
        // would have).
        let key = "ansible/metadata/community/general/versions.json";
        ctx.state
            .storage
            .put(key, br#"{"data":[{"version":"1.0.0"}]}"#)
            .await
            .unwrap();
        write_validators(
            &ctx.state.storage,
            key,
            &Validators {
                etag: Some("\"v1\"".to_string()),
                last_modified: None,
            },
        )
        .await;

        let before = crate::metrics::PROXY_UPSTREAM_304_TOTAL
            .with_label_values(&["ansible"])
            .get();

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/v3/collections/community/general/versions/",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_bytes(resp).await;
        assert!(
            String::from_utf8_lossy(&body).contains("1.0.0"),
            "must serve the cached versions body"
        );

        let after = crate::metrics::PROXY_UPSTREAM_304_TOTAL
            .with_label_values(&["ansible"])
            .get();
        assert!(after > before, "a 304 revalidation must be recorded");
    }

    /// Regression: galaxy_ng emits `links.next` as a *host-relative* path
    /// (no scheme/host). Driven through the real `version_list` handler, the
    /// rewritten body must land the pagination link under `/ansible` so the
    /// client stays on the mount — otherwise a >100-version collection (e.g.
    /// community.docker, 148 versions) 404s on page 2 with `cmd_arg` HTTP 404.
    #[tokio::test]
    async fn test_version_list_rewrites_relative_next_link() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let upstream = MockServer::start().await;
        // Page 1 body carries galaxy_ng's root-relative pagination pointers.
        let page1 = r#"{"meta":{"count":148},"links":{"first":"/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=0","previous":null,"next":"/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=100","last":"/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/?limit=100&offset=48"},"data":[{"version":"4.4.0"}]}"#;
        Mock::given(method("GET"))
            .and(path(
                "/api/v3/plugin/ansible/content/published/collections/index/community/docker/versions/",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_raw(page1, "application/json"))
            .mount(&upstream)
            .await;

        let ctx = create_test_context_with_config(|cfg| {
            cfg.ansible.enabled = true;
            cfg.ansible.proxy = Some(upstream.uri());
            cfg.ansible.metadata_ttl = 0; // force an upstream fetch (no fresh cache)
            cfg.ansible.revalidate = false; // no validators → plain 200 full fetch
        });

        let resp = send(
            &ctx.app,
            Method::GET,
            "/ansible/v3/collections/community/docker/versions/?limit=100",
            "",
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_bytes(resp).await;
        let text = String::from_utf8_lossy(&body);

        // Relative pagination links now point under /ansible (path-only, so the
        // client's relative-link resolution keeps the mount prefix).
        assert!(
            text.contains(
                "\"next\":\"/ansible/v3/collections/community/docker/versions/?limit=100&offset=100\""
            ),
            "next link not rewritten under /ansible: {text}"
        );
        assert!(
            text.contains(
                "\"first\":\"/ansible/v3/collections/community/docker/versions/?limit=100&offset=0\""
            ),
            "first link not rewritten under /ansible: {text}"
        );
        // No bare pulp path may survive — that is exactly what dropped the mount.
        assert!(
            !text.contains("/api/v3/plugin/"),
            "a root-relative pulp path leaked to the client: {text}"
        );
        // Payload is otherwise passed through untouched.
        assert!(text.contains("\"version\":\"4.4.0\""), "data lost: {text}");
    }
}