mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
//! Sole mise-internal bridge to the `mise-sigstore` crate.
//!
//! Every call mise makes into `mise_sigstore` goes through this module. Callers never
//! touch the underlying crate directly and never pass a GitHub token — the token is resolved
//! internally via [`crate::github::resolve_token_for_api_url`], which walks the full chain
//! (env vars → `credential_command` → `github_tokens.toml` → gh CLI → git credential fill).
//!
//! ## Why this exists
//!
//! Before this module, three sigstore call sites (`src/backend/aqua.rs`,
//! `src/plugins/core/python.rs`, `src/plugins/core/ruby.rs`) passed
//! `crate::env::GITHUB_TOKEN.as_deref()` — env vars only — while the github backend used the
//! full chain. That asymmetry left `mise lock` issuing unauthenticated attestation requests,
//! which hit GitHub's 60/hour IP rate limit after the second run.
//!
//! Concentrating the `mise_sigstore` surface here makes the asymmetry
//! structurally impossible: wrapper signatures omit the token argument, so callers cannot
//! re-introduce the bug without first editing this file.
//!
//! ## Default API URL
//!
//! Functions that accept `api_url: Option<&str>` fall back to [`crate::github::API_URL`]
//! (`"https://api.github.com"`) when `None` is passed. The default must be a full URL so
//! [`crate::github::resolve_token_for_api_url`] can parse the host correctly; a bare hostname
//! would be silently misrouted for GitHub Enterprise Server tenants. After token resolution,
//! the API URL is routed through [`crate::http::apply_url_replacements`] so attestation
//! requests follow the same trusted proxy/cache replacements as normal mise HTTP requests. A
//! replacement that changes the host drops the token, which was resolved for the original host.

use std::path::Path;

use mise_sigstore::sources::github::GitHubSource;
use mise_sigstore::{ArtifactRef, AttestationClient, AttestationSource, FetchParams, RetryConfig};

pub use mise_sigstore::{
    Attestation, AttestationError, CosignIdentity, SlsaArtifact, SlsaSignerIdentity,
};

/// Result alias that matches `mise_sigstore`'s internal convention.
type AttestationResult<T> = std::result::Result<T, AttestationError>;

type VerificationCell = std::sync::Arc<tokio::sync::OnceCell<bool>>;
static INVOCATION_VERIFICATIONS: std::sync::LazyLock<
    std::sync::Mutex<std::collections::HashMap<String, VerificationCell>>,
> = std::sync::LazyLock::new(Default::default);

async fn shared_verification(
    key: String,
    verification: impl std::future::Future<Output = AttestationResult<bool>>,
) -> AttestationResult<bool> {
    let settings = mise_settings::Settings::get();
    if !settings.generate_lockfiles() || settings.force_provenance_verify() {
        return verification.await;
    }
    let cell = INVOCATION_VERIFICATIONS
        .lock()
        .unwrap()
        .entry(key)
        .or_default()
        .clone();
    cell.get_or_try_init(|| verification).await.copied()
}

#[derive(Debug)]
enum CachedAttestationVerification {
    /// These repositories (`owner/repo`) made attestations that verified.
    Verified(Vec<String>),
    Retry(Option<AttestationError>),
}

fn classify_cached_attestation_verification(
    result: AttestationResult<Vec<String>>,
) -> CachedAttestationVerification {
    match result {
        Ok(sources) if !sources.is_empty() => CachedAttestationVerification::Verified(sources),
        Ok(_) => CachedAttestationVerification::Retry(None),
        Err(err) => CachedAttestationVerification::Retry(Some(err)),
    }
}

/// Resolve a GitHub token for an optional API base URL, defaulting to [`crate::github::API_URL`].
fn resolve_token_for_wrapper(api_url: Option<&str>) -> Option<String> {
    let url = api_url.unwrap_or(crate::github::API_URL);
    crate::github::resolve_token_for_api_url(url)
}

/// Apply `url_replacements` to the attestation API base URL with the credential rules
/// [`crate::http`] applies to any rewritten request: credentials resolved for the original
/// host are dropped when the rule changes the host, then an HTTPS-to-HTTP downgrade is
/// refused for whatever credentials are left.
///
/// `token` is the token resolved for `api_url`. Returns the URL to use and the token that
/// may still be sent to it.
fn routed_api_url(
    api_url: &str,
    token: Option<String>,
) -> AttestationResult<(String, Option<String>)> {
    let Ok(mut url) = url::Url::parse(api_url) else {
        debug!("invalid GitHub attestation API URL, skipping url_replacements: {api_url}");
        return Ok((api_url.to_string(), token));
    };
    let original = url.clone();
    crate::http::apply_url_replacements(&mut url);
    // mise-sigstore builds the Authorization header itself, so the token is scoped here;
    // `clear_cross_host_credentials` only has inherited userinfo left to strip.
    let token = token.filter(|_| url.host() == original.host());
    crate::http::clear_cross_host_credentials(
        &mut reqwest::header::HeaderMap::new(),
        &original,
        &mut url,
    );
    crate::http::ensure_secure_url_replacement(&original, &url, token.is_some())
        .map_err(|err| AttestationError::Verification(err.to_string()))?;
    if url == original {
        Ok((api_url.to_string(), token))
    } else {
        Ok((url.to_string(), token))
    }
}

/// Apply mise's `url_replacements` to the Sigstore public-good TUF URL.
///
/// Returns `Some(replaced)` only when a replacement actually changed the URL,
/// otherwise `None` (meaning: keep the sigstore crate's default behavior). The
/// result is pushed into `mise-sigstore` via [`mise_sigstore::set_tuf_url`] so
/// the TUF root fetch follows the same mirror as the rest of mise's traffic.
fn routed_tuf_url() -> Option<String> {
    let Ok(mut url) = url::Url::parse(mise_sigstore::DEFAULT_TUF_URL) else {
        debug!(
            "invalid Sigstore TUF URL, skipping url_replacements: {}",
            mise_sigstore::DEFAULT_TUF_URL
        );
        return None;
    };
    let original = url.clone();
    crate::http::apply_url_replacements(&mut url);
    if let Err(err) = crate::http::ensure_secure_url_replacement(&original, &url, false) {
        warn!("{err}; ignoring insecure Sigstore TUF URL replacement");
        return None;
    }
    (url != original).then(|| url.to_string())
}

/// Build a [`RetryConfig`] from mise's HTTP settings so attestation requests
/// retry and time out exactly like the rest of mise's HTTP traffic rather than
/// using a policy hardcoded in the `mise-sigstore` crate.
fn mise_retry_config() -> RetryConfig {
    let settings = mise_settings::Settings::get();
    RetryConfig {
        timeout: crate::network::http_timeout(&settings),
        retries: crate::network::http_retries(&settings).max(0) as usize,
        ..RetryConfig::default()
    }
}

fn attestation_client(api_url: &str) -> AttestationResult<AttestationClient> {
    let (base_url, token) = routed_api_url(api_url, resolve_token_for_wrapper(Some(api_url)))?;
    let mut builder = AttestationClient::builder()
        .base_url(&base_url)
        .retry_config(mise_retry_config());
    if let Some(token) = token.as_deref() {
        builder = builder.github_token(token);
    }
    builder.build()
}

/// Verify a GitHub artifact attestation for a file on disk.
///
/// Applies configured URL replacements to the API base URL before dispatching to
/// [`mise_sigstore::verify_github_attestation_with_base_url`].
pub async fn verify_attestation(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    expected_workflow: Option<&str>,
    api_url: Option<&str>,
    use_versions_host: bool,
) -> AttestationResult<bool> {
    if !mise_settings::Settings::get().generate_lockfiles() {
        return verify_attestation_uncached(
            artifact_path,
            owner,
            repo,
            expected_workflow,
            api_url,
            use_versions_host,
        )
        .await;
    }
    let digest = mise_sigstore::calculate_file_digest(artifact_path).await?;
    let key = format!(
        "github:{owner}/{repo}:{digest}:{expected_workflow:?}:{api_url:?}:{use_versions_host}"
    );
    shared_verification(
        key,
        verify_attestation_uncached(
            artifact_path,
            owner,
            repo,
            expected_workflow,
            api_url,
            use_versions_host,
        ),
    )
    .await
}

async fn verify_attestation_uncached(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    expected_workflow: Option<&str>,
    api_url: Option<&str>,
    use_versions_host: bool,
) -> AttestationResult<bool> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    let mut digest = None;
    let mut mirror_err = None;
    if use_versions_host_for_attestations(api_url, use_versions_host) {
        let artifact_digest = mise_sigstore::calculate_file_digest(artifact_path).await?;
        match verify_with_mirror(
            artifact_path,
            owner,
            repo,
            expected_workflow,
            None,
            &artifact_digest,
        )
        .await
        {
            MirrorVerdict::Done(result) => return result,
            MirrorVerdict::AskGithub => {}
            MirrorVerdict::RetryGithub(err) => mirror_err = Some(err),
        }
        digest = Some(artifact_digest);
    }

    let (base_url, token) = routed_api_url(
        api_url.unwrap_or(crate::github::API_URL),
        resolve_token_for_wrapper(api_url),
    )?;
    let result = if let Some(digest) = digest {
        mise_sigstore::verify_github_attestation_with_base_url_and_digest(
            mise_sigstore::GithubAttestationRequest {
                artifact_path,
                owner,
                repo,
                token: token.as_deref(),
                signer_workflow: expected_workflow,
                base_url: Some(&base_url),
                digest: Some(&digest),
                retry_config: mise_retry_config(),
            },
        )
        .await
    } else {
        mise_sigstore::verify_github_attestation_with_base_url(
            artifact_path,
            owner,
            repo,
            token.as_deref(),
            expected_workflow,
            &base_url,
            mise_retry_config(),
        )
        .await
    };
    accept_renamed_repository(owner, repo, api_url, result)
        .await
        .map_err(|err| after_mirror_failure(err, owner, repo, mirror_err.as_ref()))
}

/// Attestations name the repository as it was when they were made, so after
/// a rename or transfer GitHub lists some under a name that was not
/// requested. Accept those when GitHub confirms both names are one
/// repository. [`crate::github::canonical_repo`] refuses to answer when
/// `url_replacements` reroutes the API: the host that picked the
/// attestations must not also vouch for the rename.
async fn accept_renamed_repository(
    owner: &str,
    repo: &str,
    api_url: Option<&str>,
    result: AttestationResult<bool>,
) -> AttestationResult<bool> {
    let on_github = api_url.is_none_or(|url| url.trim_end_matches('/') == crate::github::API_URL);
    match result {
        Err(AttestationError::RepositoryMismatch { found, .. })
            if on_github && crate::github::attested_by_repository(owner, repo, &found).await =>
        {
            Ok(true)
        }
        result => result,
    }
}

/// Verify a GitHub artifact attestation filtered by predicate type.
///
/// mise-versions serves every attestation for a digest, so the filter is
/// applied here, the way GitHub's `predicate_type` parameter applies it.
pub async fn verify_attestation_with_predicate_type(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    expected_workflow: Option<&str>,
    predicate_type: Option<&str>,
    api_url: Option<&str>,
    use_versions_host: bool,
) -> AttestationResult<bool> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    let Some(predicate_type) = predicate_type else {
        return verify_attestation(
            artifact_path,
            owner,
            repo,
            expected_workflow,
            api_url,
            use_versions_host,
        )
        .await;
    };

    let artifact_digest = mise_sigstore::calculate_file_digest(artifact_path).await?;
    let mut mirror_err = None;
    if use_versions_host_for_attestations(api_url, use_versions_host) {
        match verify_with_mirror(
            artifact_path,
            owner,
            repo,
            expected_workflow,
            Some(predicate_type),
            &artifact_digest,
        )
        .await
        {
            MirrorVerdict::Done(result) => return result,
            MirrorVerdict::AskGithub => {}
            MirrorVerdict::RetryGithub(err) => mirror_err = Some(err),
        }
    }
    let client = attestation_client(api_url.unwrap_or(crate::github::API_URL))?;
    let attestations = client
        .fetch_attestations(FetchParams {
            owner: owner.to_string(),
            repo: Some(format!("{owner}/{repo}")),
            digest: format!("sha256:{artifact_digest}"),
            limit: 30,
            predicate_type: Some(predicate_type.to_string()),
        })
        .await
        .map_err(|err| after_mirror_failure(err, owner, repo, mirror_err.as_ref()))?;
    let result = mise_sigstore::verify_github_attestation_with_attestations(
        artifact_path,
        &attestations,
        owner,
        repo,
        expected_workflow,
    )
    .await;
    accept_renamed_repository(owner, repo, api_url, result).await
}

/// Reason the pre-download attestation probe could not complete.
///
/// Preserved as two variants so callers can log distinct warnings for a misconfigured
/// endpoint (source creation) versus an API/network error (fetch). The original inline
/// pre-wrapper code at `src/backend/github.rs` emitted different messages for each; the
/// wrapper keeps that signal instead of flattening both into one error string.
#[derive(Debug)]
pub enum DetectError {
    /// Attestation source/client construction rejected the base URL.
    SourceCreation(AttestationError),
    /// The attestations endpoint returned an error (403 rate-limit, 5xx, network failure).
    Fetch(AttestationError),
}

impl std::fmt::Display for DetectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DetectError::SourceCreation(e) => write!(f, "{e}"),
            DetectError::Fetch(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for DetectError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            DetectError::SourceCreation(e) => Some(e),
            DetectError::Fetch(e) => Some(e),
        }
    }
}

/// Probe the GitHub attestation API for the given digest without downloading the artifact.
///
/// Returns `Ok(true)` if any attestations exist for the digest. Used at lock time to decide
/// whether `ProvenanceType::GithubAttestations` should be recorded before committing to a
/// full download + verify.
pub async fn detect_attestations(
    owner: &str,
    repo: &str,
    api_url: &str,
    digest: &str,
    use_versions_host: bool,
) -> Result<bool, DetectError> {
    let mut mirror_err = None;
    if use_versions_host_for_attestations(Some(api_url), use_versions_host) {
        match detect_with_mirror(owner, repo, digest, None).await {
            MirrorVerdict::Done(found) => return found,
            MirrorVerdict::AskGithub => {}
            MirrorVerdict::RetryGithub(err) => mirror_err = Some(err),
        }
    }

    let (base_url, token) = routed_api_url(api_url, resolve_token_for_wrapper(Some(api_url)))
        .map_err(DetectError::SourceCreation)?;
    let source = GitHubSource::with_base_url(owner, repo, token.as_deref(), &base_url)
        .map_err(DetectError::SourceCreation)?;
    let artifact_ref = ArtifactRef::from_digest(digest);
    let attestations = source
        .fetch_attestations(&artifact_ref)
        .await
        .map_err(|err| {
            DetectError::Fetch(after_mirror_failure(err, owner, repo, mirror_err.as_ref()))
        })?;
    Ok(!attestations.is_empty())
}

/// Probe the GitHub attestation API for the given digest and predicate type.
/// From mise-versions, filtered here, as in
/// [`verify_attestation_with_predicate_type`].
pub async fn detect_attestations_with_predicate_type(
    owner: &str,
    repo: &str,
    api_url: &str,
    digest: &str,
    predicate_type: Option<&str>,
    use_versions_host: bool,
) -> Result<bool, DetectError> {
    let Some(predicate_type) = predicate_type else {
        return detect_attestations(owner, repo, api_url, digest, use_versions_host).await;
    };
    let mut mirror_err = None;
    if use_versions_host_for_attestations(Some(api_url), use_versions_host) {
        match detect_with_mirror(owner, repo, digest, Some(predicate_type)).await {
            MirrorVerdict::Done(found) => return found,
            MirrorVerdict::AskGithub => {}
            MirrorVerdict::RetryGithub(err) => mirror_err = Some(err),
        }
    }

    let client = attestation_client(api_url).map_err(DetectError::SourceCreation)?;
    let digest = if digest.contains(':') {
        digest.to_string()
    } else {
        format!("sha256:{digest}")
    };
    let attestations = client
        .fetch_attestations(FetchParams {
            owner: owner.to_string(),
            repo: Some(format!("{owner}/{repo}")),
            digest,
            limit: 30,
            predicate_type: Some(predicate_type.to_string()),
        })
        .await
        .map_err(|err| {
            DetectError::Fetch(after_mirror_failure(err, owner, repo, mirror_err.as_ref()))
        })?;
    Ok(!attestations.is_empty())
}

/// Whether mise-versions saying an artifact has no attestations is taken as
/// final. A wrong "none" skips verification, and a lockfile written after it
/// records no provenance, so paranoid mode confirms it with GitHub instead,
/// at the cost of one API call per unattested artifact. "Yes" needs no
/// confirmation: it only leads to verification.
/// How long a set of attestations from mise-versions is kept on disk.
const MIRRORED_ATTESTATIONS_TTL: std::time::Duration =
    std::time::Duration::from_secs(7 * 24 * 60 * 60);

type MirroredAttestations = Option<Vec<mise_sigstore::Attestation>>;
type MirroredAttestationsCell = std::sync::Arc<tokio::sync::OnceCell<MirroredAttestations>>;
static MIRRORED_ATTESTATIONS: std::sync::LazyLock<
    std::sync::Mutex<std::collections::HashMap<String, MirroredAttestationsCell>>,
> = std::sync::LazyLock::new(Default::default);

/// mise-versions' attestations for `repo` at `digest`, asked for once per
/// command and kept in the cache dir.
///
/// The set for a digest only grows, and every caller verifies what it gets
/// against the artifact and asks GitHub when that fails, so a kept set
/// answers as well as a fresh one. `mise lock` asks for one digest to detect
/// provenance and again to verify it, and again for every platform sharing
/// the artifact; reinstalling a build asks again. Within a command every
/// answer is shared; only a non-empty set is written to disk, since an empty
/// one may predate the attestation. Paranoid mode always asks.
///
/// Routing is checked before either cache is read: once `url_replacements`
/// sends this repository's endpoints elsewhere, that replacement is the only
/// source, and a set kept from mise-versions earlier must not answer for it.
async fn mirrored_attestations(repo: &str, digest: &str) -> eyre::Result<MirroredAttestations> {
    if !crate::versions_host::enabled_for_github_repo(repo) {
        return Ok(None);
    }
    if mise_settings::Settings::get().paranoid.provenance() {
        return crate::versions_host::github_attestations(repo, digest).await;
    }
    let key = mirrored_attestations_key(repo, digest);
    let cell = MIRRORED_ATTESTATIONS
        .lock()
        .unwrap()
        .entry(key.clone())
        .or_default()
        .clone();
    cell.get_or_try_init(async || {
        mirrored_attestations_cache(&key)
            .get_or_try_init_async_if(
                || crate::versions_host::github_attestations(repo, digest),
                keep_mirrored_attestations,
            )
            .await
    })
    .await
    .cloned()
}

fn mirrored_attestations_key(repo: &str, digest: &str) -> String {
    format!(
        "attestations-{}",
        crate::hash::hash_to_str(&(repo.to_ascii_lowercase(), digest))
    )
}

fn mirrored_attestations_cache(key: &str) -> crate::cache::CacheManager<MirroredAttestations> {
    crate::cache::CacheManagerBuilder::new(
        crate::dirs::CACHE
            .join("github")
            .join(format!("{key}.msgpack.z")),
    )
    .with_fresh_duration(Some(MIRRORED_ATTESTATIONS_TTL))
    .build()
}

/// Only a complete set is kept: one missing a bundle is asked for again next
/// time rather than failing for a week.
fn keep_mirrored_attestations(attestations: &MirroredAttestations) -> bool {
    attestations
        .as_ref()
        .is_some_and(|a| !a.is_empty() && a.iter().all(|a| a.has_inline_bundle()))
}

/// mise-versions' attestations for `repo` at `digest`, asked for again past
/// the copy [`mirrored_attestations`] keeps, which may predate one GitHub
/// added since. A complete answer replaces that copy, on disk and for the
/// rest of this command, so later checks don't ask again.
async fn refreshed_mirrored_attestations(
    repo: &str,
    digest: &str,
) -> eyre::Result<MirroredAttestations> {
    let fresh = crate::versions_host::github_attestations(repo, digest).await?;
    if keep_mirrored_attestations(&fresh) && !mise_settings::Settings::get().paranoid.provenance() {
        let key = mirrored_attestations_key(repo, digest);
        if let Err(err) = mirrored_attestations_cache(&key).write(&fresh) {
            debug!("failed to keep refreshed attestations for {repo}: {err:#}");
        }
        MIRRORED_ATTESTATIONS.lock().unwrap().insert(
            key,
            std::sync::Arc::new(tokio::sync::OnceCell::new_with(Some(fresh.clone()))),
        );
    }
    Ok(fresh)
}

/// What mise-versions settled about an artifact's attestations: `T` is a
/// verification's result, or a probe's.
enum MirrorVerdict<T = AttestationResult<bool>> {
    /// The answer: verified, or why not.
    Done(T),
    /// GitHub has to answer: paranoid mode confirming what mise-versions
    /// said, or a repository mise-versions doesn't know (a private one) while
    /// the user has a token to read it with.
    AskGithub,
    /// mise-versions failed in a way GitHub is asked to make up for (see
    /// [`crate::github::MirrorAnswer`]). GitHub answers, and when its
    /// lookup fails too, the error names both failures; whether that fails
    /// the install is `provenance_api_failures_fatal`'s to say, as for any
    /// failed lookup.
    RetryGithub(eyre::Report),
}

/// The verdict once mise-versions failed to answer for `full`.
fn mirror_error_verdict(full: &str, err: eyre::Report) -> MirrorVerdict {
    if crate::versions_host::retries_on_github(&err) {
        return MirrorVerdict::RetryGithub(err);
    }
    MirrorVerdict::Done(Err(mirror_failure(full, &err)))
}

/// GitHub's attestation `err` for `owner/repo`, after mise-versions failed
/// with `mirror_err`: a failed lookup names both failures and stays a lookup
/// failure ([`is_api_failure`]); anything else, such as an attestation that
/// doesn't verify, is GitHub's answer alone.
fn after_mirror_failure(
    err: AttestationError,
    owner: &str,
    repo: &str,
    mirror_err: Option<&eyre::Report>,
) -> AttestationError {
    match mirror_err {
        Some(mirror_err) if is_api_failure(&err) => {
            let failed = crate::versions_host::GithubRetryFailed::new(
                &format!("GitHub attestations of {owner}/{repo}"),
                mirror_err,
                eyre::Report::new(err),
            );
            AttestationError::Api(format!("{:#}", eyre::Report::new(failed)))
        }
        _ => err,
    }
}

/// Verify `artifact_path` against mise-versions' attestations for `owner/repo`,
/// keeping only those of `predicate_type` when it is set.
///
/// Normal usage asks api.github.com, whose rate limit is 60 requests an hour
/// without a token, only when mise-versions errors
/// ([`MirrorVerdict::RetryGithub`]). A set kept from an earlier command may
/// predate an attestation GitHub added since, so one that doesn't verify is
/// asked for again before the failure stands; mise-versions refreshes its own
/// copy within half an hour of a release.
async fn verify_with_mirror(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    expected_workflow: Option<&str>,
    predicate_type: Option<&str>,
    artifact_digest: &str,
) -> MirrorVerdict {
    let full = format!("{owner}/{repo}");
    if !crate::versions_host::enabled_for_github_repo(&full) {
        // url_replacements reroutes this repository's attestations; the
        // replacement answers, not mise-versions.
        return MirrorVerdict::AskGithub;
    }
    let digest = format!("sha256:{artifact_digest}");
    for fresh in [false, true] {
        let found = if fresh {
            refreshed_mirrored_attestations(&full, &digest).await
        } else {
            mirrored_attestations(&full, &digest).await
        };
        let attestations = match found {
            Ok(Some(attestations)) => attestations,
            Ok(None) => {
                return verdict_after_attestation_404(
                    &full,
                    repo_listing(&full).await,
                    !mirror_may_answer_none(),
                    || resolve_token_for_wrapper(None).is_some(),
                );
            }
            // Paranoid mode has GitHub confirm mise-versions anyway, so it
            // asks GitHub when mise-versions can't answer.
            Err(_) if !mirror_may_answer_none() => return MirrorVerdict::AskGithub,
            Err(err) => return mirror_error_verdict(&full, err),
        };
        trace!(
            "got {} GitHub attestations for {full}@{digest} from mise-versions",
            attestations.len()
        );
        if attestations.is_empty() {
            // Not kept on disk, so already as fresh as mise-versions has it.
            return no_attestations_verdict(&full);
        }
        // Before the predicate filter, which can't read a missing bundle and
        // would pass it off as "no attestations".
        if attestations.iter().any(|a| !a.has_inline_bundle()) {
            if !fresh {
                continue;
            }
            if !mirror_may_answer_none() {
                return MirrorVerdict::AskGithub;
            }
            return MirrorVerdict::Done(Err(AttestationError::Api(format!(
                "mise-versions returned attestations for {full} without their bundles"
            ))));
        }
        let selected: Vec<_> = attestations
            .into_iter()
            .filter(|a| predicate_type.is_none_or(|p| a.matches_predicate_type(p)))
            .collect();
        if selected.is_empty() {
            if fresh {
                return no_attestations_verdict(&full);
            }
            continue;
        }
        match classify_cached_attestation_verification(
            mise_sigstore::verify_github_attestation_sources(
                artifact_path,
                &selected,
                expected_workflow,
            )
            .await,
        ) {
            // Anyone can attest any digest from their own repository;
            // GitHub's API only lists the requested repository's, but a
            // mirror could list anyone's.
            CachedAttestationVerification::Verified(sources)
                if crate::github::attested_by_repository(owner, repo, &sources).await =>
            {
                return MirrorVerdict::Done(Ok(true));
            }
            CachedAttestationVerification::Verified(sources) => {
                let made_by = sources.join(", ");
                if !mirror_may_answer_none() {
                    warn!(
                        "mise-versions returned attestations for {full} made by {made_by}; verifying with GitHub instead"
                    );
                    return MirrorVerdict::AskGithub;
                }
                return MirrorVerdict::Done(Err(AttestationError::Verification(format!(
                    "the attestations mise-versions has for {full} were made by {made_by}"
                ))));
            }
            CachedAttestationVerification::Retry(err) if fresh => {
                if !mirror_may_answer_none() {
                    debug!(
                        "mise-versions GitHub attestations did not verify for {full}; paranoid mode asks GitHub"
                    );
                    return MirrorVerdict::AskGithub;
                }
                return MirrorVerdict::Done(Err(err.unwrap_or_else(|| {
                    AttestationError::Verification(format!(
                        "no attestation mise-versions has for {full} verified this artifact"
                    ))
                })));
            }
            CachedAttestationVerification::Retry(_) => debug!(
                "GitHub attestations kept for {full} did not verify; asking mise-versions again"
            ),
        }
    }
    unreachable!("the second pass always returns")
}

/// Whether mise-versions' attestations for `owner/repo` at `digest` include
/// any of `predicate_type` (any at all when `None`), with the same verdicts
/// as [`verify_with_mirror`].
async fn detect_with_mirror(
    owner: &str,
    repo: &str,
    digest: &str,
    predicate_type: Option<&str>,
) -> MirrorVerdict<Result<bool, DetectError>> {
    let full = format!("{owner}/{repo}");
    if !crate::versions_host::enabled_for_github_repo(&full) {
        // Rerouted by url_replacements, as in `verify_with_mirror`.
        return MirrorVerdict::AskGithub;
    }
    let digest = if digest.contains(':') {
        digest.to_string()
    } else {
        format!("sha256:{digest}")
    };
    // As in `verify_with_mirror`: a set kept from earlier may predate the
    // attestation looked for, so a miss is asked of mise-versions again.
    for fresh in [false, true] {
        let found = if fresh {
            refreshed_mirrored_attestations(&full, &digest).await
        } else {
            mirrored_attestations(&full, &digest).await
        };
        let attestations = match found {
            Ok(Some(attestations)) => attestations,
            Ok(None) => {
                return detect_verdict(verdict_after_attestation_404(
                    &full,
                    repo_listing(&full).await,
                    !mirror_may_answer_none(),
                    || resolve_token_for_wrapper(None).is_some(),
                ));
            }
            Err(_) if !mirror_may_answer_none() => return MirrorVerdict::AskGithub,
            Err(err) => return detect_verdict(mirror_error_verdict(&full, err)),
        };
        trace!(
            "got {} GitHub attestation probes for {full}@{digest} from mise-versions",
            attestations.len()
        );
        // Only a predicate filter reads the bundles; whether any attestation
        // exists doesn't depend on them.
        if predicate_type.is_some() && attestations.iter().any(|a| !a.has_inline_bundle()) {
            if !fresh {
                continue;
            }
            if !mirror_may_answer_none() {
                return MirrorVerdict::AskGithub;
            }
            return MirrorVerdict::Done(Err(DetectError::Fetch(AttestationError::Api(format!(
                "mise-versions returned attestations for {full} without their bundles"
            )))));
        }
        let found = attestations
            .iter()
            .any(|a| predicate_type.is_none_or(|p| a.matches_predicate_type(p)));
        // An empty set is never kept on disk, so it is already fresh.
        if found || attestations.is_empty() || fresh {
            if !found && !mirror_may_answer_none() {
                debug!(
                    "mise-versions has no attestations for {full}@{digest}; paranoid mode asks GitHub"
                );
                return MirrorVerdict::AskGithub;
            }
            return MirrorVerdict::Done(Ok(found));
        }
    }
    unreachable!("the second pass always returns")
}

fn no_attestations_verdict(full: &str) -> MirrorVerdict {
    if mirror_may_answer_none() {
        MirrorVerdict::Done(Err(AttestationError::NoAttestations))
    } else {
        debug!("mise-versions has no GitHub attestations for {full}; paranoid mode asks GitHub");
        MirrorVerdict::AskGithub
    }
}

/// What mise-versions' release listing says about a repository whose
/// attestations it answered 404 for.
enum RepoListing {
    /// It lists the repository: a public one with no attestations for that
    /// digest.
    Listed,
    /// A 404 here too: the repository is private or gone.
    Unknown,
    /// The listing failed, so mise can't tell which.
    Failed(eyre::Report),
}

async fn repo_listing(full: &str) -> RepoListing {
    match crate::versions_host::github_releases(full, 1).await {
        Ok(Some(_)) => RepoListing::Listed,
        Ok(None) => RepoListing::Unknown,
        Err(err) => RepoListing::Failed(err),
    }
}

/// The verdict after mise-versions answered 404 for `full`'s attestations.
/// A failed listing is a failed lookup, not "no attestations": that would
/// let the install go on unchecked. It is retried on GitHub when
/// mise-versions errored ([`mirror_error_verdict`]), and
/// `provenance_api_failures_fatal` decides what a failed lookup does.
/// Paranoid mode asks GitHub instead.
fn verdict_after_attestation_404(
    full: &str,
    listing: RepoListing,
    paranoid: bool,
    has_token: impl FnOnce() -> bool,
) -> MirrorVerdict {
    match listing {
        RepoListing::Listed if paranoid => MirrorVerdict::AskGithub,
        RepoListing::Listed => MirrorVerdict::Done(Err(AttestationError::NoAttestations)),
        // Only here is a token needed, so only here is it resolved: that
        // may run the user's credential helper.
        // Paranoid mode has GitHub confirm what mise-versions can't settle.
        RepoListing::Unknown if paranoid => MirrorVerdict::AskGithub,
        RepoListing::Unknown => unknown_repo_verdict(full, has_token()),
        RepoListing::Failed(_) if paranoid => MirrorVerdict::AskGithub,
        RepoListing::Failed(err) => mirror_error_verdict(full, err),
    }
}

/// A verification's verdict for a probe: no attestations is `Ok(false)` and
/// any other failure a fetch error.
fn detect_verdict(verdict: MirrorVerdict) -> MirrorVerdict<Result<bool, DetectError>> {
    match verdict {
        MirrorVerdict::AskGithub => MirrorVerdict::AskGithub,
        MirrorVerdict::RetryGithub(err) => MirrorVerdict::RetryGithub(err),
        MirrorVerdict::Done(Err(AttestationError::NoAttestations)) => {
            MirrorVerdict::Done(Ok(false))
        }
        MirrorVerdict::Done(Err(err)) => MirrorVerdict::Done(Err(DetectError::Fetch(err))),
        MirrorVerdict::Done(Ok(found)) => MirrorVerdict::Done(Ok(found)),
    }
}

/// mise-versions doesn't serve `full`, which is private or gone. Only the
/// user's token can read a private repository's attestations; the
/// attestation client sends a token, not netrc credentials.
fn unknown_repo_verdict(full: &str, has_token: bool) -> MirrorVerdict {
    if has_token {
        debug!("mise-versions does not know {full}; asking GitHub, which may hold it privately");
        return MirrorVerdict::AskGithub;
    }
    MirrorVerdict::Done(Err(AttestationError::Api(format!(
        "GitHub repository {full} not found (404 from mise-versions.jdx.dev, which mise asks \
         before api.github.com). If the repository is private, set GITHUB_TOKEN; to ask \
         GitHub directly, set use_versions_host = false."
    ))))
}

fn mirror_failure(full: &str, err: &eyre::Report) -> AttestationError {
    AttestationError::Api(format!(
        "{} {err:#}",
        crate::github::versions_host_failure(&format!("GitHub attestations of {full}"))
    ))
}

fn mirror_may_answer_none() -> bool {
    !mise_settings::Settings::get().paranoid.provenance()
}

fn use_versions_host_for_attestations(api_url: Option<&str>, use_versions_host: bool) -> bool {
    if !use_versions_host || !crate::versions_host::enabled_for_github_metadata() {
        return false;
    }

    api_url
        .unwrap_or(crate::github::API_URL)
        .trim_end_matches('/')
        == crate::github::API_URL
}

/// Verify SLSA provenance for an already-downloaded artifact. Passthrough — no token needed.
pub async fn verify_slsa_provenance(
    artifact_path: &Path,
    provenance_path: &Path,
    min_level: u8,
    signer: SlsaSignerIdentity<'_>,
) -> AttestationResult<bool> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    let verify = async {
        let result = mise_sigstore::verify_slsa_provenance(
            artifact_path,
            provenance_path,
            min_level,
            signer,
        )
        .await;
        match renamed_slsa_source(&result, provenance_path, signer, None).await {
            Some(renamed) => {
                mise_sigstore::verify_slsa_provenance(
                    artifact_path,
                    provenance_path,
                    min_level,
                    SlsaSignerIdentity {
                        source_repository: Some(&renamed),
                        ..signer
                    },
                )
                .await
            }
            None => result,
        }
    };
    if !mise_settings::Settings::get().generate_lockfiles() {
        return verify.await;
    }
    let artifact_digest = mise_sigstore::calculate_file_digest(artifact_path).await?;
    let provenance_digest = mise_sigstore::calculate_file_digest(provenance_path).await?;
    let key = format!(
        "slsa:{artifact_digest}:{provenance_digest}:{min_level}:{}:{}:{:?}:{:?}",
        signer.identity, signer.issuer, signer.source_repository, signer.source_tag
    );
    shared_verification(key, verify).await
}

pub async fn verify_slsa_provenance_artifacts(
    provenance_path: &Path,
    artifacts: &[SlsaArtifact],
    min_level: u8,
    signer: SlsaSignerIdentity<'_>,
) -> AttestationResult<bool> {
    verify_slsa_provenance_artifacts_with(provenance_path, artifacts, min_level, signer, None).await
}

/// Stands in for GitHub's answer to "are these one repository?" in tests.
type ConfirmRename<'a> = Option<&'a (dyn Fn(&str, &str, &str) -> bool + Sync)>;

async fn verify_slsa_provenance_artifacts_with(
    provenance_path: &Path,
    artifacts: &[SlsaArtifact],
    min_level: u8,
    signer: SlsaSignerIdentity<'_>,
    confirm: ConfirmRename<'_>,
) -> AttestationResult<bool> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    let result = mise_sigstore::verify_slsa_provenance_artifacts(
        provenance_path,
        artifacts,
        min_level,
        signer,
    )
    .await;
    match renamed_slsa_source(&result, provenance_path, signer, confirm).await {
        Some(renamed) => {
            mise_sigstore::verify_slsa_provenance_artifacts(
                provenance_path,
                artifacts,
                min_level,
                SlsaSignerIdentity {
                    source_repository: Some(&renamed),
                    ..signer
                },
            )
            .await
        }
        None => result,
    }
}

/// When `result` failed because the provenance was built in a repository
/// `signer` doesn't accept, the name `signer.source_repository` had when it
/// was built, if GitHub confirms that both names are one repository (renamed
/// or transferred since). Provenance names the repository as it was when it
/// was signed. The caller verifies again in full with that name.
///
/// Only api.github.com itself can confirm a rename:
/// [`crate::github::canonical_repo`] refuses when `url_replacements`
/// reroutes it, since that host may have served the provenance.
async fn renamed_slsa_source(
    result: &AttestationResult<bool>,
    provenance_path: &Path,
    signer: SlsaSignerIdentity<'_>,
    confirm: ConfirmRename<'_>,
) -> Option<String> {
    if result.is_ok() {
        return None;
    }
    let (owner, repo) = signer
        .source_repository
        .and_then(mise_sigstore::normalize_github_repository)?
        .split_once('/')?;
    let unaccepted =
        mise_sigstore::slsa_provenance_unaccepted_source_repositories(provenance_path, signer)
            .await
            .ok()?;
    // A handful at most; each one costs GitHub API requests.
    for other in unaccepted.into_iter().take(3) {
        let confirmed = match confirm {
            Some(confirm) => confirm(owner, repo, &other),
            None => {
                crate::github::attested_by_repository(owner, repo, std::slice::from_ref(&other))
                    .await
            }
        };
        if confirmed {
            debug!("SLSA provenance for {owner}/{repo} was built in {other}, its former name");
            return Some(other);
        }
    }
    None
}

pub fn is_slsa_subject_mismatch(error: &AttestationError) -> bool {
    mise_sigstore::is_slsa_subject_mismatch(error)
}

pub fn is_api_failure(error: &AttestationError) -> bool {
    matches!(error, AttestationError::Api(_) | AttestationError::Http(_))
}

/// Verify a keyless Cosign signature or bundle against the expected signer
/// identity. Passthrough — no token needed.
pub async fn verify_cosign_signature(
    artifact_path: &Path,
    sig_or_bundle_path: &Path,
    identity: &CosignIdentity,
) -> AttestationResult<bool> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    if !mise_settings::Settings::get().generate_lockfiles() {
        return mise_sigstore::verify_cosign_signature(artifact_path, sig_or_bundle_path, identity)
            .await;
    }
    let artifact_digest = mise_sigstore::calculate_file_digest(artifact_path).await?;
    let signature_digest = mise_sigstore::calculate_file_digest(sig_or_bundle_path).await?;
    // The identity is part of the key: a result shared across callers must
    // not let a verification with weaker constraints satisfy a stricter one.
    let key = format!("cosign:{artifact_digest}:{signature_digest}:{identity:?}");
    shared_verification(
        key,
        mise_sigstore::verify_cosign_signature(artifact_path, sig_or_bundle_path, identity),
    )
    .await
}

/// Verify a Cosign signature against a public key. Passthrough — no token needed.
pub async fn verify_cosign_signature_with_key(
    artifact_path: &Path,
    sig_or_bundle_path: &Path,
    public_key_path: &Path,
) -> AttestationResult<bool> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    mise_sigstore::verify_cosign_signature_with_key(
        artifact_path,
        sig_or_bundle_path,
        public_key_path,
    )
    .await
}

/// Verify attestations against a sha512 digest and return the `owner/repo`
/// each verified one was built from. Passthrough — no token needed, but the TUF
/// root follows `url_replacements` like every other check here.
pub async fn verify_github_attestation_sources_for_sha512(
    sha512: &[u8],
    attestations: &[Attestation],
    signer_workflow: Option<&str>,
) -> AttestationResult<Vec<String>> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    mise_sigstore::verify_github_attestation_sources_for_sha512(
        sha512,
        attestations,
        signer_workflow,
    )
    .await
}

/// [`verify_github_attestation_sources_for_sha512`] for GitHub Actions or
/// gitlab.com CI provenance; each source is `github.com/owner/repo` or
/// `gitlab.com/group/project`.
pub async fn verify_forge_attestation_sources_for_sha512(
    sha512: &[u8],
    attestations: &[Attestation],
) -> AttestationResult<Vec<String>> {
    mise_sigstore::set_tuf_url(routed_tuf_url());
    mise_sigstore::verify_forge_attestation_sources_for_sha512(sha512, attestations).await
}

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

    fn listed() -> RepoListing {
        RepoListing::Listed
    }
    fn unknown() -> RepoListing {
        RepoListing::Unknown
    }
    /// A listing that failed with `status` (`None`: no connection).
    fn failed_with(status: Option<u16>) -> RepoListing {
        RepoListing::Failed(
            crate::versions_host::VersionsHostUnavailable {
                status,
                message: format!("HTTP {status:?}"),
            }
            .into(),
        )
    }
    fn failed() -> RepoListing {
        failed_with(Some(503))
    }

    #[test]
    fn test_attestation_404_verdict_by_listing() {
        let verdict = |listing, paranoid, has_token| {
            verdict_after_attestation_404("o/r", listing, paranoid, || has_token)
        };
        // Listed: a public repository without attestations for the digest.
        assert!(matches!(
            verdict(listed(), false, false),
            MirrorVerdict::Done(Err(AttestationError::NoAttestations))
        ));
        // Unknown: private or gone; GitHub only with a token.
        assert!(matches!(
            verdict(unknown(), false, false),
            MirrorVerdict::Done(Err(AttestationError::Api(_)))
        ));
        assert!(matches!(
            verdict(unknown(), false, true),
            MirrorVerdict::AskGithub
        ));
        // Failed listing: never "no attestations". mise-versions erroring
        // (no connection, 429, 5xx) retries the lookup on GitHub, token or
        // not; a 403 (the mirror disabled) is a failed lookup.
        for listing in [failed(), failed_with(None), failed_with(Some(429))] {
            assert!(matches!(
                verdict(listing, false, false),
                MirrorVerdict::RetryGithub(_)
            ));
        }
        assert!(matches!(
            verdict(failed(), false, true),
            MirrorVerdict::RetryGithub(_)
        ));
        assert!(matches!(
            verdict(failed_with(Some(403)), false, false),
            MirrorVerdict::Done(Err(AttestationError::Api(_)))
        ));
        // Paranoid mode asks GitHub whenever mise-versions can't settle it.
        assert!(matches!(
            verdict(listed(), true, false),
            MirrorVerdict::AskGithub
        ));
        // An unlisted repository without a token: paranoid mode still asks GitHub.
        assert!(matches!(
            verdict(unknown(), true, false),
            MirrorVerdict::AskGithub
        ));
        assert!(matches!(
            verdict(failed(), true, false),
            MirrorVerdict::AskGithub
        ));
    }

    #[test]
    fn test_attestation_404_resolves_a_token_only_for_an_unknown_repo() {
        // Resolving a token may run a credential helper; a listed repository
        // or a failed listing never needs one.
        for listing in [listed(), failed()] {
            let _ = verdict_after_attestation_404("o/r", listing, false, || {
                panic!("token resolved for a repository mise-versions can answer for")
            });
        }
    }

    #[test]
    fn test_attestation_404_probe_by_listing() {
        let probe = |listing, paranoid, has_token| {
            detect_verdict(verdict_after_attestation_404(
                "o/r",
                listing,
                paranoid,
                || has_token,
            ))
        };
        assert!(matches!(
            probe(listed(), false, false),
            MirrorVerdict::Done(Ok(false))
        ));
        assert!(matches!(
            probe(unknown(), false, false),
            MirrorVerdict::Done(Err(DetectError::Fetch(AttestationError::Api(_))))
        ));
        assert!(matches!(
            probe(unknown(), false, true),
            MirrorVerdict::AskGithub
        ));
        assert!(matches!(
            probe(failed(), false, false),
            MirrorVerdict::RetryGithub(_)
        ));
        assert!(matches!(
            probe(failed_with(Some(403)), false, false),
            MirrorVerdict::Done(Err(DetectError::Fetch(AttestationError::Api(_))))
        ));
        assert!(matches!(
            probe(listed(), true, false),
            MirrorVerdict::AskGithub
        ));
        assert!(matches!(
            probe(failed(), true, false),
            MirrorVerdict::AskGithub
        ));
    }

    #[test]
    fn test_github_failure_after_mirror_failure_names_both() {
        let mirror_err: eyre::Report = crate::versions_host::VersionsHostUnavailable {
            status: Some(503),
            message: "HTTP status server error (503 Service Unavailable)".to_string(),
        }
        .into();
        let err = after_mirror_failure(
            AttestationError::Api("HTTP 403 rate limit exceeded".to_string()),
            "o",
            "r",
            Some(&mirror_err),
        );
        // Still a failed lookup, for provenance_api_failures_fatal.
        assert!(is_api_failure(&err));
        let message = err.to_string();
        assert!(message.contains("mise-versions.jdx.dev"), "{message}");
        assert!(message.contains("503 Service Unavailable"), "{message}");
        assert!(message.contains("api.github.com"), "{message}");
        assert!(message.contains("rate limit exceeded"), "{message}");
        // GitHub's own answer stands alone.
        assert!(matches!(
            after_mirror_failure(
                AttestationError::NoAttestations,
                "o",
                "r",
                Some(&mirror_err)
            ),
            AttestationError::NoAttestations
        ));
        assert!(matches!(
            after_mirror_failure(AttestationError::Api("x".into()), "o", "r", None),
            AttestationError::Api(m) if m == "x"
        ));
    }
    use crate::env as mise_env;
    use confique::Layer;

    const TOKEN_ENV_VARS: &[&str] = &[
        "MISE_GITHUB_TOKEN",
        "GITHUB_API_TOKEN",
        "GITHUB_TOKEN",
        "MISE_GITHUB_ENTERPRISE_TOKEN",
    ];

    struct SettingsGuard {
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl SettingsGuard {
        fn new(replacements: Option<indexmap::IndexMap<String, String>>) -> Self {
            Self::with_versions_host(replacements, None)
        }

        fn with_versions_host(
            replacements: Option<indexmap::IndexMap<String, String>>,
            use_versions_host: Option<bool>,
        ) -> Self {
            let lock = crate::testing::lock_ignoring_poison(&crate::testing::SETTINGS_LOCK);
            let mut settings = mise_settings::SettingsPartial::empty();
            settings.url_replacements = replacements;
            settings.use_versions_host = use_versions_host;
            crate::testing::reset_settings(Some(settings));
            Self { _lock: lock }
        }
    }

    impl Drop for SettingsGuard {
        fn drop(&mut self) {
            crate::testing::reset_settings(None);
        }
    }

    /// RAII guard: snapshots the tracked token env vars on construction, clears them for the
    /// test body, and restores the original values on drop — including when a test panics.
    struct TokenEnvGuard {
        saved: Vec<(&'static str, Option<String>)>,
    }

    impl TokenEnvGuard {
        fn new() -> Self {
            let saved: Vec<_> = TOKEN_ENV_VARS
                .iter()
                .map(|name| (*name, std::env::var(name).ok()))
                .collect();
            for name in TOKEN_ENV_VARS {
                mise_env::remove_var(name);
            }
            Self { saved }
        }
    }

    impl Drop for TokenEnvGuard {
        fn drop(&mut self) {
            for (name, value) in std::mem::take(&mut self.saved) {
                match value {
                    Some(v) => mise_env::set_var(name, v),
                    None => mise_env::remove_var(name),
                }
            }
        }
    }

    #[test]
    fn test_resolve_token_wrapper_uses_env_var_with_default_url() {
        let _lock = crate::testing::lock_ignoring_poison(&crate::github::TEST_ENV_LOCK);
        let _env = TokenEnvGuard::new();
        mise_env::set_var("GITHUB_TOKEN", "ghp_wrapper_default");

        let resolved = resolve_token_for_wrapper(None);
        assert_eq!(
            resolved.as_deref(),
            Some("ghp_wrapper_default"),
            "env var should flow through the wrapper with the default API URL"
        );
    }

    #[test]
    fn test_resolve_token_wrapper_uses_env_var_with_explicit_api_url() {
        let _lock = crate::testing::lock_ignoring_poison(&crate::github::TEST_ENV_LOCK);
        let _env = TokenEnvGuard::new();
        mise_env::set_var("MISE_GITHUB_TOKEN", "ghp_explicit_api");

        let resolved = resolve_token_for_wrapper(Some(crate::github::API_URL));
        assert_eq!(
            resolved.as_deref(),
            Some("ghp_explicit_api"),
            "explicit api.github.com URL should resolve identically to the default"
        );
    }

    #[test]
    fn test_resolve_token_wrapper_respects_enterprise_api_url() {
        let _lock = crate::testing::lock_ignoring_poison(&crate::github::TEST_ENV_LOCK);
        let _env = TokenEnvGuard::new();
        mise_env::set_var("GITHUB_TOKEN", "ghp_public_only");
        mise_env::set_var("MISE_GITHUB_ENTERPRISE_TOKEN", "ghp_enterprise_only");

        // An enterprise API URL must parse and route to the enterprise token, proving the
        // wrapper passes a full URL (not a bare hostname) to `resolve_token_for_api_url`.
        let resolved =
            resolve_token_for_wrapper(Some("https://github.enterprise.example.com/api/v3"));
        assert_eq!(
            resolved.as_deref(),
            Some("ghp_enterprise_only"),
            "enterprise api_url should resolve the enterprise token, not the public one"
        );

        // And the default (None) must still pick the public token.
        let resolved_default = resolve_token_for_wrapper(None);
        assert_eq!(
            resolved_default.as_deref(),
            Some("ghp_public_only"),
            "default api_url should still resolve the public token"
        );
    }

    /// Guard that seeds the `github_tokens.toml` test override and clears it on drop.
    struct TokensFileOverrideGuard;

    impl TokensFileOverrideGuard {
        fn set(host: &str, token: &str) -> Self {
            let mut map = std::collections::HashMap::new();
            map.insert(host.to_string(), token.to_string());
            *crate::github::test_support::TOKENS_FILE_OVERRIDE
                .write()
                .unwrap() = Some(map);
            Self
        }
    }

    impl Drop for TokensFileOverrideGuard {
        fn drop(&mut self) {
            *crate::github::test_support::TOKENS_FILE_OVERRIDE
                .write()
                .unwrap() = None;
        }
    }

    #[test]
    fn test_resolve_token_wrapper_uses_github_tokens_toml_source() {
        // Proves the wrapper delegates all the way through `resolve_token` to the
        // non-env-var sources — here, the `github_tokens.toml` path (source #4). Without
        // this, a future regression could short-circuit on env vars and silently pass all
        // prior tests.
        let _lock = crate::testing::lock_ignoring_poison(&crate::github::TEST_ENV_LOCK);
        let _env = TokenEnvGuard::new();
        let _tokens_file = TokensFileOverrideGuard::set("github.com", "ghp_from_tokens_file");

        let resolved = resolve_token_for_wrapper(None);
        assert_eq!(
            resolved.as_deref(),
            Some("ghp_from_tokens_file"),
            "wrapper should resolve tokens from github_tokens.toml when env vars are empty"
        );
    }

    #[test]
    fn test_is_api_failure_excludes_malformed_payloads() {
        assert!(is_api_failure(&AttestationError::Api(
            "rate limited".into()
        )));
        assert!(!is_api_failure(&AttestationError::Json(
            serde_json::from_str::<serde_json::Value>("{").unwrap_err()
        )));
    }

    #[tokio::test]
    async fn test_mirrored_attestations_survive_the_disk_cache() {
        // The bundle is arbitrary JSON; it has to come back out of the
        // msgpack cache file as the same value for verification to use it.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("attestations.msgpack.z");
        let bundle = serde_json::json!({
            "mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json",
            "verificationMaterial": {"tlogEntries": [{"logIndex": "1", "integratedTime": 2}]},
            "dsseEnvelope": {"payload": "e30=", "signatures": [{"sig": "AA=="}]},
        });
        let attestation: mise_sigstore::Attestation =
            serde_json::from_value(serde_json::json!({"bundle": bundle, "bundle_url": null}))
                .unwrap();
        let write = crate::cache::CacheManagerBuilder::new(&path)
            .with_fresh_duration(Some(MIRRORED_ATTESTATIONS_TTL))
            .build::<MirroredAttestations>();
        write.write(&Some(vec![attestation])).unwrap();

        let read = crate::cache::CacheManagerBuilder::new(&path)
            .with_fresh_duration(Some(MIRRORED_ATTESTATIONS_TTL))
            .build::<MirroredAttestations>();
        let cached = read
            .get_or_try_init_async_if(
                async || -> eyre::Result<MirroredAttestations> {
                    panic!("a fresh cached set must not be fetched again")
                },
                |a| a.as_ref().is_some_and(|a| !a.is_empty()),
            )
            .await
            .unwrap()
            .unwrap();
        assert_eq!(cached.len(), 1);
        assert!(cached[0].has_inline_bundle());
        assert_eq!(
            serde_json::to_value(&cached[0]).unwrap()["bundle"],
            bundle,
            "the bundle changed on its way through the cache"
        );
    }

    #[test]
    fn test_cached_attestation_verification_accepts_only_success() {
        assert!(matches!(
            classify_cached_attestation_verification(Ok(vec!["jdx/mise".to_string()])),
            CachedAttestationVerification::Verified(sources) if sources == ["jdx/mise"]
        ));
        assert!(matches!(
            classify_cached_attestation_verification(Ok(vec![])),
            CachedAttestationVerification::Retry(None)
        ));

        let outcome = classify_cached_attestation_verification(Err(
            AttestationError::WorkflowMismatch("stale cached signer".to_string()),
        ));
        assert!(matches!(
            outcome,
            CachedAttestationVerification::Retry(Some(AttestationError::WorkflowMismatch(_)))
        ));
    }

    /// slsa-github-generator provenance for sops v3.9.0, built in
    /// getsops/sops, which was mozilla/sops until its transfer.
    fn sops_provenance() -> &'static Path {
        Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../mise-sigstore/tests/fixtures/sops_v3_9_0.intoto.jsonl"
        ))
    }

    fn sops_artifact() -> SlsaArtifact {
        SlsaArtifact {
            name: "sops-v3.9.0.linux.amd64".to_string(),
            sha256: "0d65660fbe785647ff4f1764d7f69edf598f79d6d79ebbef4a501909b6ff6b82".to_string(),
        }
    }

    /// The generator's identity, expecting sops under its former name.
    const SOPS_SIGNER_BEFORE_TRANSFER: SlsaSignerIdentity<'static> = SlsaSignerIdentity {
        identity: "https://github.com/slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@refs/tags/v2.0.0",
        issuer: "https://token.actions.githubusercontent.com",
        source_repository: Some("mozilla/sops"),
        source_tag: None,
    };

    /// Verifies the sops provenance against `SOPS_SIGNER_BEFORE_TRANSFER`,
    /// with `confirm` standing in for api.github.com's answer to whether two
    /// names are one repository. Each verification is a full Sigstore check,
    /// so each test runs only one to stay within the per-test time limit.
    fn verify_sops_rename(
        confirm: &(dyn Fn(&str, &str, &str) -> bool + Sync),
    ) -> AttestationResult<bool> {
        let _settings = SettingsGuard::new(None);
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(verify_slsa_provenance_artifacts_with(
                sops_provenance(),
                &[sops_artifact()],
                1,
                SOPS_SIGNER_BEFORE_TRANSFER,
                Some(confirm),
            ))
    }

    #[test]
    fn test_slsa_refuses_a_rename_github_does_not_confirm() {
        // Without GitHub's word, provenance built in getsops/sops is not
        // mozilla/sops's.
        let err = verify_sops_rename(&|_, _, _| false).unwrap_err();
        assert!(err.to_string().contains("built in getsops/sops"), "{err}");
    }

    #[test]
    fn test_slsa_accepts_a_rename_github_confirms() {
        // api.github.com says getsops/sops is mozilla/sops, transferred.
        let confirmed = verify_sops_rename(&|owner, repo, other| {
            (owner, repo, other) == ("mozilla", "sops", "getsops/sops")
        });
        assert!(confirmed.unwrap());
    }

    fn verify_sops_v3_9_0_as(tag: &str) -> AttestationResult<bool> {
        let _settings = SettingsGuard::new(None);
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(verify_slsa_provenance_artifacts(
                sops_provenance(),
                &[sops_artifact()],
                1,
                SlsaSignerIdentity {
                    source_repository: Some("getsops/sops"),
                    source_tag: Some(tag),
                    ..SOPS_SIGNER_BEFORE_TRANSFER
                },
            ))
    }

    #[test]
    fn test_slsa_rejects_provenance_of_another_release() {
        // A host serving sops v3.9.0's genuine artifact and provenance as
        // v3.10.0: the generator signs every release with one identity.
        let err = verify_sops_v3_9_0_as("v3.10.0").unwrap_err();
        assert!(
            err.to_string()
                .contains("built from refs/tags/v3.9.0, expected refs/tags/v3.10.0"),
            "{err}"
        );
    }

    #[test]
    fn test_slsa_accepts_provenance_of_its_release() {
        assert!(verify_sops_v3_9_0_as("v3.9.0").unwrap());
    }

    #[test]
    fn test_slsa_rename_cannot_be_confirmed_by_a_mirror() {
        // A host standing in for api.github.com claims both names are one
        // repository. It must not get to vouch for the provenance it may
        // have served.
        let mut mirror = mockito::Server::new();
        let lookups = ["mozilla/sops", "getsops/sops"].map(|repo| {
            mirror
                .mock("GET", format!("/repos/{repo}").as_str())
                .with_header("content-type", "application/json")
                .with_body(r#"{"id": 1, "full_name": "getsops/sops"}"#)
                .expect(0)
                .create()
        });
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => mirror.url(),
        }));
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();

        let err = runtime
            .block_on(verify_slsa_provenance_artifacts(
                sops_provenance(),
                &[sops_artifact()],
                1,
                SOPS_SIGNER_BEFORE_TRANSFER,
            ))
            .unwrap_err();
        assert!(err.to_string().contains("built in getsops/sops"), "{err}");
        for lookup in lookups {
            lookup.assert();
        }
    }

    #[test]
    fn test_rerouted_api_cannot_confirm_a_rename() {
        // The host that stands in for api.github.com also picked the
        // attestations, so it must not get to say that the repository that
        // made them is the requested one under an older name.
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => "https://github-proxy.invalid".to_string(),
        }));
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();

        let err = runtime
            .block_on(crate::github::canonical_repo("erlang/rebar3"))
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("only GitHub can confirm a repository rename"),
            "{err}"
        );

        let result = runtime.block_on(accept_renamed_repository(
            "erlang",
            "rebar3",
            None,
            Err(AttestationError::RepositoryMismatch {
                expected: "erlang/rebar3".to_string(),
                found: vec!["jdx/mise".to_string()],
            }),
        ));
        assert!(
            matches!(result, Err(AttestationError::RepositoryMismatch { .. })),
            "{result:?}"
        );
    }

    fn original_host_token() -> Option<String> {
        Some("ghp_original_host".to_string())
    }

    #[test]
    fn test_routed_api_url_applies_simple_url_replacement() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => "https://github-proxy.example.com".to_string(),
        }));

        let (routed, token) =
            routed_api_url(crate::github::API_URL, original_host_token()).unwrap();

        assert_eq!(routed, "https://github-proxy.example.com/");
        // The token was resolved for api.github.com; the proxy does not get it.
        assert_eq!(token, None);
    }

    #[test]
    fn test_routed_api_url_applies_regex_url_replacement() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "regex:^https://api\\.github\\.com".to_string() => "https://github-proxy.example.com/api".to_string(),
        }));

        let (routed, token) =
            routed_api_url(crate::github::API_URL, original_host_token()).unwrap();

        assert_eq!(routed, "https://github-proxy.example.com/api/");
        assert_eq!(token, None);
    }

    #[test]
    fn test_routed_api_url_keeps_original_url_without_replacement() {
        let _settings = SettingsGuard::new(None);

        let (routed, token) =
            routed_api_url(crate::github::API_URL, original_host_token()).unwrap();

        assert_eq!(routed, crate::github::API_URL);
        assert_eq!(token, original_host_token());
    }

    #[test]
    fn test_routed_api_url_keeps_token_on_same_host_replacement() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => "https://api.github.com/proxy".to_string(),
        }));

        let (routed, token) =
            routed_api_url(crate::github::API_URL, original_host_token()).unwrap();

        assert_eq!(routed, "https://api.github.com/proxy/");
        assert_eq!(token, original_host_token());
    }

    #[test]
    fn test_routed_api_url_drops_inherited_userinfo_on_cross_host_replacement() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "regex:^https://(.*)ghe\\.example\\.com".to_string()
                => "https://${1}github-proxy.example.com".to_string(),
        }));

        let (routed, token) = routed_api_url(
            "https://user:password@ghe.example.com/api/v3",
            original_host_token(),
        )
        .unwrap();

        assert_eq!(routed, "https://github-proxy.example.com/api/v3");
        assert_eq!(token, None);
    }

    #[test]
    fn test_routed_api_url_rejects_credential_downgrade() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => "http://api.github.com".to_string(),
        }));

        let err = routed_api_url(crate::github::API_URL, original_host_token()).unwrap_err();

        assert!(err.to_string().contains("refusing to send credentials"));
        assert!(!is_api_failure(&err));
    }

    #[test]
    fn test_routed_api_url_drops_token_on_cross_host_downgrade() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => "http://github-proxy.example.com".to_string(),
        }));

        let (routed, token) =
            routed_api_url(crate::github::API_URL, original_host_token()).unwrap();

        assert_eq!(routed, "http://github-proxy.example.com/");
        assert_eq!(token, None);
    }

    #[test]
    fn test_routed_api_url_rejects_userinfo_downgrade_without_token() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string()
                => "http://user:password@github-proxy.example.com".to_string(),
        }));

        let err = routed_api_url(crate::github::API_URL, None).unwrap_err();

        assert!(err.to_string().contains("refusing to send credentials"));
        assert!(!err.to_string().contains("password"));
        assert!(!is_api_failure(&err));
    }

    #[test]
    fn test_routed_tuf_url_applies_url_replacement() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://tuf-repo-cdn.sigstore.dev".to_string()
                => "https://tuf-mirror.example.com".to_string(),
        }));

        let routed = routed_tuf_url();

        assert_eq!(routed.as_deref(), Some("https://tuf-mirror.example.com/"));
    }

    #[test]
    fn test_routed_tuf_url_none_without_replacement() {
        let _settings = SettingsGuard::new(None);

        assert_eq!(routed_tuf_url(), None);
    }

    #[test]
    fn test_routed_tuf_url_ignores_userinfo_downgrade() {
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://tuf-repo-cdn.sigstore.dev".to_string()
                => "http://user:password@tuf-mirror.example.com".to_string(),
        }));

        assert_eq!(routed_tuf_url(), None);
    }

    #[test]
    fn test_use_versions_host_for_attestations_respects_setting() {
        let _settings = SettingsGuard::with_versions_host(None, Some(false));

        assert!(!use_versions_host_for_attestations(
            Some(crate::github::API_URL),
            true
        ));
    }

    #[test]
    fn test_use_versions_host_for_attestations_defers_to_url_replacements() {
        // GitHub routed elsewhere (a proxy, a mirror, a fixture): the
        // replacement is the only source of GitHub data.
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com".to_string() => "https://github-proxy.example.com".to_string(),
        }));

        assert!(!use_versions_host_for_attestations(
            Some(crate::github::API_URL),
            true
        ));
    }

    #[tokio::test]
    async fn test_mirrored_attestations_defer_to_a_repository_url_replacement() {
        // A set this command already got from mise-versions, then a rule that
        // reroutes only this repository: the kept set must not answer for it.
        let repo = "acme/attested-tool";
        let digest = "sha256:0";
        let key = format!(
            "attestations-{}",
            crate::hash::hash_to_str(&(repo.to_ascii_lowercase(), digest))
        );
        let attestation: mise_sigstore::Attestation =
            serde_json::from_value(serde_json::json!({"bundle": {}, "bundle_url": null})).unwrap();
        let cell = MirroredAttestationsCell::default();
        cell.set(Some(vec![attestation])).unwrap();
        MIRRORED_ATTESTATIONS.lock().unwrap().insert(key, cell);

        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com/repos/acme/attested-tool/".to_string()
                => "https://github-proxy.example.com/repos/acme/attested-tool/".to_string(),
        }));
        assert!(mirrored_attestations(repo, digest).await.unwrap().is_none());
    }

    #[test]
    fn test_path_specific_url_replacements_are_detected_per_repository() {
        // A rule that only reroutes one repository's releases leaves the bare
        // GitHub URLs alone, but still takes that repository off mise-versions.
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com/repos/acme/tool/".to_string()
                => "https://github-proxy.example.com/repos/acme/tool/".to_string(),
        }));

        assert!(!crate::versions_host::github_is_url_replaced(None));
        assert!(crate::versions_host::github_is_url_replaced(Some(
            "acme/tool"
        )));
        assert!(!crate::versions_host::github_is_url_replaced(Some(
            "acme/other"
        )));
    }

    #[test]
    fn test_exact_release_url_replacements_are_honored() {
        // A rule for one release's API URL takes that release off mise-versions
        // and out of the mirrored cache entry, and leaves other tags alone.
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            "https://api.github.com/repos/acme/tool/releases/tags/v2.0.0".to_string()
                => "https://github-proxy.example.com/acme/tool/v2.0.0".to_string(),
        }));

        assert!(crate::versions_host::github_release_is_url_replaced(
            "acme/tool",
            "v2.0.0"
        ));
        assert!(!crate::versions_host::github_release_is_url_replaced(
            "acme/tool",
            "v1.0.0"
        ));
        assert!(
            crate::github::release_cache_key_for_test("acme/tool", "v2.0.0").ends_with("direct")
        );
        assert!(
            crate::github::release_cache_key_for_test("acme/tool", "v1.0.0").ends_with("hosted-2")
        );
    }

    #[test]
    fn test_download_only_url_replacements_keep_mise_versions() {
        // Mirroring release downloads (the documented Artifactory example)
        // doesn't change where release metadata comes from.
        let _settings = SettingsGuard::new(Some(indexmap::indexmap! {
            r"regex:^https://github\.com/([^/]+)/([^/]+)/releases/download/(.+)".to_string()
                => "https://hub.example.com/artifactory/github/$1/$2/$3".to_string(),
        }));

        assert!(!crate::versions_host::github_is_url_replaced(Some(
            "acme/tool"
        )));
    }

    #[test]
    fn test_use_versions_host_for_attestations_respects_caller_gate() {
        let _settings = SettingsGuard::with_versions_host(None, Some(true));

        assert!(!use_versions_host_for_attestations(
            Some(crate::github::API_URL),
            false
        ));
        assert!(use_versions_host_for_attestations(
            Some(crate::github::API_URL),
            true
        ));
    }
}