sui-store 0.1.10

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

// TODO(scope): NarInfo lives in sui-compat — add `impl FromStr for NarInfo`
// there so callers can use `"...".parse::<NarInfo>()` instead of `NarInfo::parse()`.
use sui_compat::narinfo::{NarInfo, NarInfoError};
use sui_compat::store_path::StorePath;

use crate::http::{HttpClient, HttpError, ReqwestHttpClient};
use crate::traits::{PathInfo, Store, StoreError, StoreResult};

/// Typed errors for binary cache operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BinaryCacheError {
    /// HTTP client returned an error (network, DNS, TLS, etc.).
    #[error("http client error: {0}")]
    HttpClient(#[from] HttpError),
    /// Server returned an unexpected (non-2xx, non-404) HTTP status.
    #[error("unexpected HTTP status {status} for {url}")]
    UnexpectedStatus {
        /// The HTTP status code received.
        status: u16,
        /// The URL that was requested.
        url: String,
    },
    /// The NarInfo response body could not be parsed.
    #[error("narinfo parse error: {0}")]
    NarInfoParse(#[from] NarInfoError),
}

impl From<BinaryCacheError> for StoreError {
    fn from(e: BinaryCacheError) -> Self {
        match &e {
            BinaryCacheError::HttpClient(_) | BinaryCacheError::UnexpectedStatus { .. } => {
                StoreError::Http(e.to_string())
            }
            BinaryCacheError::NarInfoParse(_) => StoreError::NarInfo(e.to_string()),
        }
    }
}

/// A read-only binary cache store accessed over HTTP.
pub struct BinaryCacheStore {
    client: Box<dyn HttpClient>,
    /// Base URL (e.g., `https://cache.nixos.org`).
    base_url: String,
    /// Trusted public keys for signature verification (`keyname:base64pubkey`).
    trusted_keys: Vec<String>,
    /// Optional authorization header (`("Bearer", "<token>")` or `("Basic", "<creds>")`).
    auth_header: Option<(String, String)>,
}

/// Builder for [`BinaryCacheStore`].
pub struct BinaryCacheStoreBuilder {
    base_url: String,
    trusted_keys: Vec<String>,
    client: Option<Box<dyn HttpClient>>,
    auth_header: Option<(String, String)>,
}

impl BinaryCacheStoreBuilder {
    /// Set the trusted public keys for signature verification.
    #[must_use]
    pub fn trusted_keys(mut self, keys: Vec<String>) -> Self {
        self.trusted_keys = keys;
        self
    }

    /// Use a custom HTTP client implementation (e.g., for testing).
    #[must_use]
    pub fn http_client(mut self, client: Box<dyn HttpClient>) -> Self {
        self.client = Some(client);
        self
    }

    /// Set an authorization header (e.g., `("Bearer", "<token>")` for Attic).
    #[must_use]
    pub fn auth_header(mut self, scheme: &str, credentials: &str) -> Self {
        self.auth_header = Some((scheme.to_string(), credentials.to_string()));
        self
    }

    /// Build the [`BinaryCacheStore`].
    #[must_use]
    pub fn build(self) -> BinaryCacheStore {
        BinaryCacheStore {
            client: self.client.unwrap_or_else(|| Box::new(ReqwestHttpClient::new())),
            base_url: self.base_url,
            trusted_keys: self.trusted_keys,
            auth_header: self.auth_header,
        }
    }
}

impl BinaryCacheStore {
    /// Create a builder for a binary cache store with the given base URL.
    #[must_use]
    pub fn builder(base_url: &str) -> BinaryCacheStoreBuilder {
        BinaryCacheStoreBuilder {
            base_url: base_url.trim_end_matches('/').to_string(),
            trusted_keys: Vec::new(),
            client: None,
            auth_header: None,
        }
    }

    /// Create a new binary cache client with default HTTP backend.
    #[must_use]
    pub fn new(base_url: &str, trusted_keys: Vec<String>) -> Self {
        Self::builder(base_url).trusted_keys(trusted_keys).build()
    }

    /// Create a new binary cache client with a custom HTTP backend.
    #[must_use]
    pub fn with_http_client(
        base_url: &str,
        trusted_keys: Vec<String>,
        client: Box<dyn HttpClient>,
    ) -> Self {
        Self::builder(base_url)
            .trusted_keys(trusted_keys)
            .http_client(client)
            .build()
    }

    /// Build the request headers, including auth if configured.
    fn request_headers(&self, extra: &[(&str, &str)]) -> Vec<(String, String)> {
        let mut headers: Vec<(String, String)> = extra
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        if let Some((scheme, creds)) = &self.auth_header {
            headers.push(("Authorization".to_string(), format!("{scheme} {creds}")));
        }
        headers
    }

    /// Fetch NarInfo for a store path hash.
    pub async fn fetch_narinfo(&self, hash: &str) -> StoreResult<Option<NarInfo>> {
        let url = format!("{}/{hash}.narinfo", self.base_url);
        let headers = self.request_headers(&[("Accept", "text/x-nix-narinfo")]);
        let header_refs: Vec<(&str, &str)> = headers.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();

        let response = self
            .client
            .get(&url, &header_refs)
            .await
            .map_err(BinaryCacheError::from)?;

        if response.status == 404 {
            return Ok(None);
        }

        if !response.is_success() {
            return Err(BinaryCacheError::UnexpectedStatus {
                status: response.status,
                url,
            }
            .into());
        }

        let info = NarInfo::parse(&response.body).map_err(BinaryCacheError::from)?;

        Ok(Some(info))
    }

    /// Return the base URL of this binary cache (without trailing slash).
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Return the trusted public keys used for signature verification.
    #[must_use]
    pub fn trusted_keys(&self) -> &[String] {
        &self.trusted_keys
    }

    /// Return the configured authorization header, if any.
    #[must_use]
    pub fn auth_header(&self) -> Option<(&str, &str)> {
        self.auth_header.as_ref().map(|(s, c)| (s.as_str(), c.as_str()))
    }

    /// Download a NAR file from the cache.
    pub async fn fetch_nar(&self, url_path: &str) -> StoreResult<Vec<u8>> {
        let url = format!("{}/{url_path}", self.base_url);

        self.client
            .get_bytes(&url)
            .await
            .map_err(BinaryCacheError::from)
            .map_err(StoreError::from)
    }

    /// Convert a NarInfo to our PathInfo type.
    ///
    /// Delegates to the [`From<&NarInfo>`](PathInfo::from) impl.
    #[cfg(test)]
    fn narinfo_to_path_info(info: &NarInfo) -> PathInfo {
        PathInfo::from(info)
    }

    /// Get the store path hash (first 32 chars of the basename).
    fn store_path_hash(path: &StorePath) -> String {
        let basename = path.to_basename();
        basename[..32.min(basename.len())].to_string()
    }

    /// Verify that a NarInfo has at least one valid signature from the trusted keys.
    ///
    /// The NarInfo fingerprint is: `1;{storePath};{narHash};{narSize};{sortedReferences}`.
    /// Each signature in the NarInfo is in `keyname:base64sig` format. Each trusted key
    /// is in `keyname:base64pubkey` format.
    ///
    /// Returns `Ok(true)` if at least one signature matches a trusted key,
    /// `Ok(false)` if no trusted keys are provided or no signatures match.
    pub fn verify_narinfo_signatures(
        narinfo: &NarInfo,
        trusted_keys: &[String],
    ) -> StoreResult<bool> {
        use sui_compat::signature::{StorePathSignature, compute_fingerprint};
        use sui_compat::hash::base64_decode;

        if trusted_keys.is_empty() {
            return Ok(false);
        }

        // Build the sorted references for the fingerprint.
        let mut sorted_refs: Vec<String> = narinfo.references.clone();
        sorted_refs.sort();

        let fingerprint = compute_fingerprint(
            &narinfo.store_path,
            &narinfo.nar_hash,
            narinfo.nar_size,
            &sorted_refs,
        );

        // Build a map of key_name -> public_key_bytes from trusted keys.
        let mut key_map: std::collections::HashMap<String, Vec<u8>> =
            std::collections::HashMap::new();
        for key_str in trusted_keys {
            if let Some((name, b64_pubkey)) = key_str.split_once(':')
                && let Ok(pubkey_bytes) = base64_decode(b64_pubkey) {
                    key_map.insert(name.to_string(), pubkey_bytes);
                }
        }

        // Check each signature against the matching trusted key.
        for sig_str in &narinfo.signatures {
            let parsed = match StorePathSignature::parse(sig_str) {
                Ok(s) => s,
                Err(_) => continue,
            };

            if let Some(pubkey_bytes) = key_map.get(&parsed.key_name)
                && pubkey_bytes.len() == 32 {
                    let pubkey: [u8; 32] = pubkey_bytes
                        .as_slice()
                        .try_into()
                        .expect("length checked");
                    if parsed.verify(&fingerprint, &pubkey).is_ok() {
                        return Ok(true);
                    }
                }
        }

        Ok(false)
    }
}

#[async_trait::async_trait]
impl Store for BinaryCacheStore {
    async fn query_path_info(&self, path: &StorePath) -> StoreResult<Option<PathInfo>> {
        let hash = Self::store_path_hash(path);
        Ok(self
            .fetch_narinfo(&hash)
            .await?
            .as_ref()
            .map(PathInfo::from))
    }

    async fn is_valid_path(&self, path: &StorePath) -> StoreResult<bool> {
        let hash = Self::store_path_hash(path);
        Ok(self.fetch_narinfo(&hash).await?.is_some())
    }

    async fn query_all_valid_paths(&self) -> StoreResult<Vec<StorePath>> {
        Err(StoreError::NotSupported(
            "binary cache does not support listing all paths".to_string(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::{HttpError, HttpResponse};

    #[test]
    fn store_path_hash_extraction() {
        let path = StorePath::from_absolute_path(
            "/nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1",
        )
        .unwrap();
        let hash = BinaryCacheStore::store_path_hash(&path);
        assert_eq!(hash, "sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6");
    }

    #[test]
    fn narinfo_to_path_info_conversion() {
        // NarInfo references are bare basenames; the PathInfo conversion
        // must prefix them with the store directory.
        let narinfo = sui_compat::narinfo::NarInfo {
            store_path: "/nix/store/abc-hello".to_string(),
            url: "nar/abc.nar.xz".to_string(),
            compression: "xz".to_string(),
            file_hash: "sha256:aaa".to_string(),
            file_size: 1000,
            nar_hash: "sha256:bbb".to_string(),
            nar_size: 5000,
            references: vec![
                "3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8".to_string(),
            ],
            deriver: Some("abc.drv".to_string()),
            signatures: vec!["key:sig".to_string()],
            ca: None,
        };
        let info = BinaryCacheStore::narinfo_to_path_info(&narinfo);
        assert_eq!(info.path, "/nix/store/abc-hello");
        assert_eq!(info.nar_size, 5000);
        assert_eq!(info.references.len(), 1);
        assert_eq!(
            info.references[0],
            "/nix/store/3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8"
        );
    }

    #[test]
    fn with_http_client_constructor() {
        let client = Box::new(ReqwestHttpClient::new());
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org/",
            vec![],
            client,
        );
        assert_eq!(store.base_url, "https://cache.nixos.org");
    }

    #[test]
    fn base_url_accessor() {
        let store = BinaryCacheStore::new("https://cache.nixos.org/", vec![]);
        assert_eq!(store.base_url(), "https://cache.nixos.org");
    }

    #[test]
    fn trusted_keys_accessor_returns_keys() {
        let keys = vec![
            "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=".to_string(),
        ];
        let store = BinaryCacheStore::new("https://cache.nixos.org", keys.clone());
        assert_eq!(store.trusted_keys(), &keys[..]);
    }

    #[test]
    fn trusted_keys_accessor_empty() {
        let store = BinaryCacheStore::new("https://cache.nixos.org", vec![]);
        assert!(store.trusted_keys().is_empty());
    }

    // ── MockHttpClient (local to binary_cache tests) ─────────

    struct MockHttpClient {
        responses: std::collections::HashMap<String, HttpResponse>,
    }

    impl MockHttpClient {
        fn new() -> Self {
            Self {
                responses: std::collections::HashMap::new(),
            }
        }
        fn with_response(mut self, url: &str, resp: HttpResponse) -> Self {
            self.responses.insert(url.to_string(), resp);
            self
        }
    }

    #[async_trait::async_trait]
    impl HttpClient for MockHttpClient {
        async fn get(
            &self,
            url: &str,
            _h: &[(&str, &str)],
        ) -> Result<HttpResponse, HttpError> {
            self.responses
                .get(url)
                .cloned()
                .ok_or_else(|| HttpError::Request(format!("no mock: {url}")))
        }
        async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, HttpError> {
            Ok(self.get(url, &[]).await?.body.into_bytes())
        }
    }

    // Valid NarInfo text for mock responses.
    const MOCK_NARINFO: &str = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References: 3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8
Deriver: abc.drv
Sig: cache.nixos.org-1:sig==
";

    fn hello_store_path() -> StorePath {
        StorePath::from_absolute_path(
            "/nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1",
        )
        .unwrap()
    }

    // ── fetch_narinfo with valid response ────────────────────

    #[tokio::test]
    async fn fetch_narinfo_valid_response() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: MOCK_NARINFO.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let narinfo = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap();
        assert!(narinfo.is_some());
        let info = narinfo.unwrap();
        assert_eq!(info.nar_size, 5000);
        assert_eq!(info.references.len(), 1);
        assert!(info
            .store_path
            .contains("hello-2.12.1"));
    }

    // ── fetch_narinfo with 404 ──────────────────────────────

    #[tokio::test]
    async fn fetch_narinfo_404_returns_none() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/nonexistenthash000000000000000000.narinfo",
            HttpResponse {
                status: 404,
                body: "not found".to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let narinfo = store
            .fetch_narinfo("nonexistenthash000000000000000000")
            .await
            .unwrap();
        assert!(narinfo.is_none());
    }

    // ── fetch_narinfo with HTTP error status ────────────────

    #[tokio::test]
    async fn fetch_narinfo_500_returns_error() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 500,
                body: "server error".to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store
            .fetch_narinfo("abc00000000000000000000000000000")
            .await;
        assert!(result.is_err());
    }

    // ── query_path_info through Store trait ──────────────────

    #[tokio::test]
    async fn query_path_info_via_store_trait() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: MOCK_NARINFO.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let path_info = store
            .query_path_info(&hello_store_path())
            .await
            .unwrap();
        assert!(path_info.is_some());
        let info = path_info.unwrap();
        assert_eq!(info.path, "/nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1");
        assert_eq!(info.nar_hash, "sha256:bbb");
        assert_eq!(info.nar_size, 5000);
        assert_eq!(info.signatures, vec!["cache.nixos.org-1:sig=="]);
    }

    // ── is_valid_path through Store trait ─────────────────────

    #[tokio::test]
    async fn is_valid_path_true_when_exists() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: MOCK_NARINFO.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        assert!(store.is_valid_path(&hello_store_path()).await.unwrap());
    }

    #[tokio::test]
    async fn is_valid_path_false_when_missing() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 404,
                body: String::new(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        assert!(!store.is_valid_path(&hello_store_path()).await.unwrap());
    }

    // ── query_all_valid_paths is unsupported ─────────────────

    #[tokio::test]
    async fn query_all_valid_paths_unsupported() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store.query_all_valid_paths().await;
        assert!(result.is_err());
    }

    // ── narinfo_to_path_info preserves content_address ───────

    #[test]
    fn narinfo_to_path_info_preserves_ca() {
        let narinfo = NarInfo {
            store_path: "/nix/store/abc-src.tar.gz".to_string(),
            url: "nar/abc.nar".to_string(),
            compression: "none".to_string(),
            file_hash: "sha256:fff".to_string(),
            file_size: 500,
            nar_hash: "sha256:eee".to_string(),
            nar_size: 1000,
            references: vec![],
            deriver: None,
            signatures: vec![],
            ca: Some("fixed:out:r:sha256:deadbeef".to_string()),
        };
        let info = BinaryCacheStore::narinfo_to_path_info(&narinfo);
        assert_eq!(
            info.content_address,
            Some("fixed:out:r:sha256:deadbeef".to_string())
        );
        assert_eq!(info.registration_time, 0);
    }

    // ── store_path_hash with short basename ──────────────────

    #[test]
    fn store_path_hash_extracts_exactly_32_chars() {
        let path = StorePath::from_absolute_path(
            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-hierarchical-0.1.0.1",
        )
        .unwrap();
        let hash = BinaryCacheStore::store_path_hash(&path);
        assert_eq!(hash.len(), 32);
        assert_eq!(hash, "00bgd045z0d4icpbc2yyz4gx48ak44la");
    }

    // ── base_url trailing slash normalization ─────────────────

    #[test]
    fn base_url_trailing_slashes_stripped() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org///",
            vec![],
            Box::new(client),
        );
        // Only one trailing slash should be stripped by trim_end_matches
        // but the URL should not have a trailing slash
        assert!(!store.base_url.ends_with('/'));
    }

    // ── fetch_nar with MockHttpClient ───────────────────────

    #[tokio::test]
    async fn fetch_nar_returns_bytes() {
        let nar_content = b"fake-nar-content-with-binary-data\x00\xff\xfe";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/nar/abc.nar.xz",
            HttpResponse {
                status: 200,
                body: String::from_utf8_lossy(nar_content).to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let data = store.fetch_nar("nar/abc.nar.xz").await.unwrap();
        assert!(!data.is_empty());
    }

    #[tokio::test]
    async fn fetch_nar_http_error() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store.fetch_nar("nar/missing.nar.xz").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_nar_empty_body() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/nar/empty.nar",
            HttpResponse {
                status: 200,
                body: String::new(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let data = store.fetch_nar("nar/empty.nar").await.unwrap();
        assert!(data.is_empty());
    }

    // ── fetch_narinfo edge cases ──────────────────────────────

    #[tokio::test]
    async fn fetch_narinfo_unknown_fields_ignored() {
        let narinfo_with_extra = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References: 3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8
Deriver: abc.drv
Sig: cache.nixos.org-1:sig==
FutureField: should-be-ignored
AnotherUnknown: 42
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: narinfo_with_extra.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let narinfo = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap();
        assert!(narinfo.is_some());
        assert_eq!(narinfo.unwrap().nar_size, 5000);
    }

    #[tokio::test]
    async fn fetch_narinfo_malformed_body_returns_error() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 200,
                body: "this is not valid narinfo content at all".to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store
            .fetch_narinfo("abc00000000000000000000000000000")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_missing_required_field() {
        let incomplete_narinfo = "\
StorePath: /nix/store/abc-hello
Compression: xz
NarHash: sha256:bbb
NarSize: 5000
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 200,
                body: incomplete_narinfo.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store
            .fetch_narinfo("abc00000000000000000000000000000")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_whitespace_in_body() {
        let narinfo_with_whitespace = "\
  StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
  URL: nar/abc.nar.xz
  Compression: xz
  FileHash: sha256:aaa
  FileSize: 1000
  NarHash: sha256:bbb
  NarSize: 5000
  References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: narinfo_with_whitespace.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let narinfo = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap();
        assert!(narinfo.is_some());
    }

    #[tokio::test]
    async fn fetch_narinfo_http_client_error() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store
            .fetch_narinfo("nonexistent0000000000000000000000")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_302_redirect_returns_error() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 302,
                body: String::new(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let result = store
            .fetch_narinfo("abc00000000000000000000000000000")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_no_signatures() {
        let narinfo_no_sigs = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: narinfo_no_sigs.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let narinfo = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert!(narinfo.signatures.is_empty());
        assert!(narinfo.references.is_empty());
    }

    #[tokio::test]
    async fn fetch_narinfo_multiple_signatures() {
        let narinfo_multi_sigs = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
Sig: key1:aaa==
Sig: key2:bbb==
Sig: key3:ccc==
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: narinfo_multi_sigs.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let narinfo = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(narinfo.signatures.len(), 3);
        assert_eq!(narinfo.signatures[0], "key1:aaa==");
        assert_eq!(narinfo.signatures[2], "key3:ccc==");
    }

    // ── Store trait with dyn Store (Arc<dyn Store> pattern) ──

    #[tokio::test]
    async fn dyn_store_query_path_info() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: MOCK_NARINFO.to_string(),
            },
        );
        let store: std::sync::Arc<dyn Store> = std::sync::Arc::new(
            BinaryCacheStore::with_http_client(
                "https://cache.nixos.org",
                vec![],
                Box::new(client),
            ),
        );

        let info = store.query_path_info(&hello_store_path()).await.unwrap();
        assert!(info.is_some());
        assert_eq!(info.unwrap().nar_size, 5000);
    }

    #[tokio::test]
    async fn dyn_store_is_valid_path() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: MOCK_NARINFO.to_string(),
            },
        );
        let store: std::sync::Arc<dyn Store> = std::sync::Arc::new(
            BinaryCacheStore::with_http_client(
                "https://cache.nixos.org",
                vec![],
                Box::new(client),
            ),
        );

        assert!(store.is_valid_path(&hello_store_path()).await.unwrap());
    }

    #[tokio::test]
    async fn dyn_store_query_all_valid_paths_unsupported() {
        let client = MockHttpClient::new();
        let store: std::sync::Arc<dyn Store> = std::sync::Arc::new(
            BinaryCacheStore::with_http_client(
                "https://cache.nixos.org",
                vec![],
                Box::new(client),
            ),
        );

        let result = store.query_all_valid_paths().await;
        assert!(result.is_err());
    }


    // ── BinaryCacheError → StoreError conversion ─────────────

    #[test]
    fn binary_cache_error_http_client_converts_to_store_http() {
        let http_err = HttpError::Request("dns failure".to_string());
        let bc_err: BinaryCacheError = http_err.into();
        let store_err: StoreError = bc_err.into();
        match store_err {
            StoreError::Http(msg) => assert!(msg.contains("dns failure")),
            other => panic!("expected Http, got {other:?}"),
        }
    }

    #[test]
    fn binary_cache_error_unexpected_status_converts_to_store_http() {
        let bc_err = BinaryCacheError::UnexpectedStatus {
            status: 503,
            url: "https://cache.test/abc.narinfo".to_string(),
        };
        let store_err: StoreError = bc_err.into();
        match store_err {
            StoreError::Http(msg) => {
                assert!(msg.contains("503"));
                assert!(msg.contains("cache.test"));
            }
            other => panic!("expected Http, got {other:?}"),
        }
    }

    #[test]
    fn binary_cache_error_narinfo_parse_converts_to_store_narinfo() {
        let parse_err = sui_compat::narinfo::NarInfoError::MissingField("StorePath".to_string());
        let bc_err: BinaryCacheError = parse_err.into();
        let store_err: StoreError = bc_err.into();
        match store_err {
            StoreError::NarInfo(msg) => {
                assert!(msg.contains("StorePath") || msg.contains("missing"));
            }
            other => panic!("expected NarInfo, got {other:?}"),
        }
    }

    #[test]
    fn binary_cache_error_display_unexpected_status() {
        let err = BinaryCacheError::UnexpectedStatus {
            status: 418,
            url: "https://teapot.test/x.narinfo".to_string(),
        };
        let s = err.to_string();
        assert!(s.contains("418"));
        assert!(s.contains("teapot.test"));
    }

    #[test]
    fn binary_cache_error_debug_format() {
        let err = BinaryCacheError::UnexpectedStatus {
            status: 500,
            url: "x".to_string(),
        };
        let debug = format!("{err:?}");
        assert!(debug.contains("UnexpectedStatus"));
        assert!(debug.contains("500"));
    }

    // ── Builder pattern ─────────────────────────────────────

    #[test]
    fn builder_default_is_reqwest_client() {
        let store = BinaryCacheStore::builder("https://cache.nixos.org").build();
        assert_eq!(store.base_url(), "https://cache.nixos.org");
        assert!(store.trusted_keys().is_empty());
    }

    #[test]
    fn builder_with_trusted_keys() {
        let keys = vec!["k1:abc==".to_string(), "k2:def==".to_string()];
        let store = BinaryCacheStore::builder("https://cache.nixos.org")
            .trusted_keys(keys.clone())
            .build();
        assert_eq!(store.trusted_keys().len(), 2);
        assert_eq!(store.trusted_keys()[0], "k1:abc==");
    }

    #[test]
    fn builder_chaining_order_independent() {
        let client = Box::new(MockHttpClient::new());
        let keys = vec!["k:s".to_string()];
        let store = BinaryCacheStore::builder("https://cache.nixos.org")
            .http_client(client)
            .trusted_keys(keys.clone())
            .build();
        assert_eq!(store.trusted_keys(), &keys[..]);
        assert_eq!(store.base_url(), "https://cache.nixos.org");
    }

    #[test]
    fn builder_strips_trailing_slash() {
        let store = BinaryCacheStore::builder("https://cache.nixos.org/").build();
        assert_eq!(store.base_url(), "https://cache.nixos.org");
    }

    #[test]
    fn builder_strips_multiple_trailing_slashes() {
        let store = BinaryCacheStore::builder("https://cache.nixos.org////").build();
        assert!(!store.base_url().ends_with('/'));
    }

    // ── store_path_hash edge cases ──────────────────────────

    #[test]
    fn store_path_hash_for_drv_path() {
        let path = StorePath::from_absolute_path(
            "/nix/store/xb4y5iklhya4blk42k1cfkb8k07dpp4n-hello-2.12.1.drv",
        )
        .unwrap();
        let hash = BinaryCacheStore::store_path_hash(&path);
        assert_eq!(hash, "xb4y5iklhya4blk42k1cfkb8k07dpp4n");
        assert_eq!(hash.len(), 32);
    }

    // ── narinfo with different compression algorithms ────────

    #[tokio::test]
    async fn fetch_narinfo_zstd_compression() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.zst
Compression: zstd
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(info.compression, "zstd");
    }

    #[tokio::test]
    async fn fetch_narinfo_no_compression() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar
Compression: none
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(info.compression, "none");
    }

    #[tokio::test]
    async fn fetch_narinfo_bzip2_compression() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.bz2
Compression: bzip2
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(info.compression, "bzip2");
    }

    // ── narinfo with content-address (CA) field ──────────────

    #[tokio::test]
    async fn fetch_narinfo_with_ca_field() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-source.tar.gz
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
CA: fixed:out:r:sha256:cafebabedeadbeef
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            info.ca,
            Some("fixed:out:r:sha256:cafebabedeadbeef".to_string())
        );
        // Ensure conversion to PathInfo carries CA
        let path_info = PathInfo::from(&info);
        assert_eq!(
            path_info.content_address,
            Some("fixed:out:r:sha256:cafebabedeadbeef".to_string())
        );
    }

    // ── narinfo with many references on a single line ───────

    #[tokio::test]
    async fn fetch_narinfo_many_references_on_one_line() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References: dep1 dep2 dep3 dep4 dep5 dep6 dep7 dep8 dep9 dep10
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(info.references.len(), 10);
        assert_eq!(info.references[0], "dep1");
        assert_eq!(info.references[9], "dep10");
    }

    // ── narinfo without optional Deriver field ───────────────

    #[tokio::test]
    async fn fetch_narinfo_no_deriver() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert!(info.deriver.is_none());
    }

    // ── narinfo with empty Deriver value ─────────────────────

    #[tokio::test]
    async fn fetch_narinfo_empty_deriver_treated_as_none() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
Deriver:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap()
            .unwrap();
        assert!(info.deriver.is_none());
    }

    // ── HTTP status code variations ──────────────────────────

    #[tokio::test]
    async fn fetch_narinfo_503_returns_error() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 503,
                body: "service unavailable".to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store.fetch_narinfo("abc00000000000000000000000000000").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_403_returns_error() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 403,
                body: "forbidden".to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store.fetch_narinfo("abc00000000000000000000000000000").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_301_redirect_returns_error() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/abc00000000000000000000000000000.narinfo",
            HttpResponse {
                status: 301,
                body: String::new(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store.fetch_narinfo("abc00000000000000000000000000000").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn fetch_narinfo_201_created_treated_as_success() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 201,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = store
            .fetch_narinfo("sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6")
            .await
            .unwrap();
        assert!(info.is_some());
    }

    // ── fetch_nar 4xx/5xx errors ─────────────────────────────

    #[tokio::test]
    async fn fetch_nar_returns_correct_url_path() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/nar/some/nested/path.nar.xz",
            HttpResponse {
                status: 200,
                body: "data".to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let bytes = store.fetch_nar("nar/some/nested/path.nar.xz").await.unwrap();
        assert_eq!(bytes, b"data");
    }

    // ── Default trait methods on BinaryCacheStore ────────────

    #[tokio::test]
    async fn binary_cache_collect_garbage_unsupported() {
        use crate::traits::GcOptions;
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store.collect_garbage(&GcOptions::default()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn binary_cache_add_to_store_unsupported() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store.add_to_store("hello", b"data", &[]).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn binary_cache_register_path_unsupported() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let info = PathInfo::new("/nix/store/abc-x", "sha256:aaa");
        let result = store.register_path(&info).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn binary_cache_query_referrers_unsupported() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store.query_referrers(&hello_store_path()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn binary_cache_add_signatures_unsupported() {
        let client = MockHttpClient::new();
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        let result = store
            .add_signatures(&hello_store_path(), &["sig".to_string()])
            .await;
        assert!(result.is_err());
    }

    // ── query_references via BinaryCacheStore ────────────────
    //
    // BinaryCacheStore.query_path_info populates PathInfo.references with
    // absolute store paths (bare NarInfo basenames are prefixed with
    // /nix/store/ at conversion time). The default query_references in the
    // Store trait then parses each entry via StorePath::from_absolute_path,
    // so the full reference list flows through end to end.

    #[tokio::test]
    async fn binary_cache_query_references_round_trip() {
        let body = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References: 3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37 00bgd045z0d4icpbc2yyz4gx48ak44la-bash-5.2
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: body.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );
        // PathInfo.references are absolute store paths after the conversion.
        let info = store.query_path_info(&hello_store_path()).await.unwrap().unwrap();
        assert_eq!(info.references.len(), 2);
        assert_eq!(
            info.references[0],
            "/nix/store/3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37"
        );

        // query_references parses those absolute paths back into StorePaths,
        // yielding the full reference list.
        let refs = store.query_references(&hello_store_path()).await.unwrap();
        assert_eq!(refs.len(), 2);
    }

    // ── Box<dyn Store> dispatch ──────────────────────────────

    #[tokio::test]
    async fn box_dyn_binary_cache_store_query_path_info() {
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: MOCK_NARINFO.to_string(),
            },
        );
        let store: Box<dyn Store> = Box::new(BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        ));
        let info = store.query_path_info(&hello_store_path()).await.unwrap();
        assert!(info.is_some());
    }

    // ── Reference-prefix gap fix regression tests ────────────

    /// Round-trip a NarInfo with multiple bare-basename references through
    /// `BinaryCacheStore::query_path_info` and verify every reference comes
    /// out as a `/nix/store/`-prefixed absolute store path.
    #[tokio::test]
    async fn query_path_info_references_are_absolute_store_paths() {
        let narinfo_multi_refs = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References: 3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8 00bgd045z0d4icpbc2yyz4gx48ak44la-bash-5.2 sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
Deriver: abc.drv
Sig: cache.nixos.org-1:sig==
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: narinfo_multi_refs.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let info = store
            .query_path_info(&hello_store_path())
            .await
            .unwrap()
            .expect("path info should be present");

        assert_eq!(info.references.len(), 3);
        for r in &info.references {
            assert!(
                r.starts_with("/nix/store/"),
                "reference should be absolute store path, got {r:?}"
            );
        }
        assert_eq!(
            info.references[0],
            "/nix/store/3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8"
        );
        assert_eq!(
            info.references[1],
            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-bash-5.2"
        );
        assert_eq!(
            info.references[2],
            "/nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1"
        );
    }

    /// `Store::query_references` (the default trait method) must return a
    /// non-empty Vec when the underlying NarInfo had references — proving
    /// the silent-drop bug is fixed end to end.
    #[tokio::test]
    async fn query_references_via_store_returns_full_prefixed_paths() {
        // Tiny in-memory mock store that returns a fixed PathInfo whose
        // references already came from a NarInfo round-trip.
        struct MockStore {
            info: PathInfo,
        }

        #[async_trait::async_trait]
        impl Store for MockStore {
            async fn query_path_info(
                &self,
                _path: &StorePath,
            ) -> StoreResult<Option<PathInfo>> {
                Ok(Some(self.info.clone()))
            }
            async fn is_valid_path(&self, _path: &StorePath) -> StoreResult<bool> {
                Ok(true)
            }
            async fn query_all_valid_paths(&self) -> StoreResult<Vec<StorePath>> {
                Ok(vec![])
            }
        }

        let narinfo = NarInfo {
            store_path: "/nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1".to_string(),
            url: "nar/abc.nar.xz".to_string(),
            compression: "xz".to_string(),
            file_hash: "sha256:aaa".to_string(),
            file_size: 1000,
            nar_hash: "sha256:bbb".to_string(),
            nar_size: 5000,
            references: vec![
                "3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8".to_string(),
                "00bgd045z0d4icpbc2yyz4gx48ak44la-bash-5.2".to_string(),
            ],
            deriver: None,
            signatures: vec![],
            ca: None,
        };
        let mock = MockStore {
            info: PathInfo::from(&narinfo),
        };

        let refs = mock.query_references(&hello_store_path()).await.unwrap();
        assert_eq!(
            refs.len(),
            2,
            "default query_references must yield both NarInfo references"
        );
        let absolute: Vec<String> = refs.iter().map(StorePath::to_absolute_path).collect();
        assert!(absolute.contains(
            &"/nix/store/3n58xw4373jp0ljirf06d8077j15pc4j-glibc-2.37-8".to_string()
        ));
        assert!(absolute.contains(
            &"/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-bash-5.2".to_string()
        ));
    }

    /// A NarInfo whose `References:` line is empty must produce an empty
    /// `PathInfo.references` vec (no spurious entries from prefixing logic).
    #[tokio::test]
    async fn query_path_info_empty_references_yields_empty_vec() {
        let narinfo_no_refs = "\
StorePath: /nix/store/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6-hello-2.12.1
URL: nar/abc.nar.xz
Compression: xz
FileHash: sha256:aaa
FileSize: 1000
NarHash: sha256:bbb
NarSize: 5000
References:
";
        let client = MockHttpClient::new().with_response(
            "https://cache.nixos.org/sn5lbjwwmkbzj7cx0hfnlwf4sh16cll6.narinfo",
            HttpResponse {
                status: 200,
                body: narinfo_no_refs.to_string(),
            },
        );
        let store = BinaryCacheStore::with_http_client(
            "https://cache.nixos.org",
            vec![],
            Box::new(client),
        );

        let info = store
            .query_path_info(&hello_store_path())
            .await
            .unwrap()
            .expect("path info should be present");
        assert!(info.references.is_empty());
    }

    // ── verify_narinfo_signatures ──────────────────────────────

    fn make_signed_narinfo() -> (NarInfo, String) {
        use ed25519_dalek::{Signer, SigningKey};
        use sui_compat::hash::base64_encode;
        use sui_compat::signature::compute_fingerprint;

        let signing_key = SigningKey::from_bytes(&[42u8; 32]);
        let verifying_key = signing_key.verifying_key();

        let narinfo = NarInfo {
            store_path: "/nix/store/abc-hello".to_string(),
            url: "nar/abc.nar.xz".to_string(),
            compression: "xz".to_string(),
            file_hash: "sha256:aaa".to_string(),
            file_size: 1000,
            nar_hash: "sha256:bbb".to_string(),
            nar_size: 5000,
            references: vec![],
            deriver: None,
            signatures: vec![],
            ca: None,
        };

        let fingerprint = compute_fingerprint(
            &narinfo.store_path,
            &narinfo.nar_hash,
            narinfo.nar_size,
            &narinfo.references,
        );
        let sig = signing_key.sign(fingerprint.as_bytes());
        let sig_str = format!(
            "test-key:{}",
            base64_encode(&sig.to_bytes())
        );
        let trusted_key = format!(
            "test-key:{}",
            base64_encode(verifying_key.as_bytes())
        );

        let mut signed = narinfo;
        signed.signatures = vec![sig_str];

        (signed, trusted_key)
    }

    #[test]
    fn verify_narinfo_signatures_valid() {
        let (narinfo, trusted_key) = make_signed_narinfo();
        let result = BinaryCacheStore::verify_narinfo_signatures(
            &narinfo,
            &[trusted_key],
        )
        .unwrap();
        assert!(result);
    }

    #[test]
    fn verify_narinfo_signatures_invalid_key() {
        use sui_compat::hash::base64_encode;

        let (narinfo, _) = make_signed_narinfo();
        // Use a different key — should fail.
        let wrong_key = format!(
            "test-key:{}",
            base64_encode(&[99u8; 32])
        );
        let result = BinaryCacheStore::verify_narinfo_signatures(
            &narinfo,
            &[wrong_key],
        )
        .unwrap();
        assert!(!result);
    }

    #[test]
    fn verify_narinfo_signatures_empty_trusted_keys_returns_false() {
        let (narinfo, _) = make_signed_narinfo();
        let result = BinaryCacheStore::verify_narinfo_signatures(
            &narinfo,
            &[],
        )
        .unwrap();
        assert!(!result);
    }

    #[test]
    fn verify_narinfo_signatures_no_matching_key_name() {
        use sui_compat::hash::base64_encode;

        let (narinfo, _) = make_signed_narinfo();
        // Trusted key has a different name.
        let wrong_name_key = format!(
            "other-key:{}",
            base64_encode(&[42u8; 32])
        );
        let result = BinaryCacheStore::verify_narinfo_signatures(
            &narinfo,
            &[wrong_name_key],
        )
        .unwrap();
        assert!(!result);
    }

    #[test]
    fn verify_narinfo_signatures_unsigned_narinfo() {
        let narinfo = NarInfo {
            store_path: "/nix/store/abc-hello".to_string(),
            url: "nar/abc.nar.xz".to_string(),
            compression: "xz".to_string(),
            file_hash: "sha256:aaa".to_string(),
            file_size: 1000,
            nar_hash: "sha256:bbb".to_string(),
            nar_size: 5000,
            references: vec![],
            deriver: None,
            signatures: vec![],
            ca: None,
        };
        let result = BinaryCacheStore::verify_narinfo_signatures(
            &narinfo,
            &["key:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".to_string()],
        )
        .unwrap();
        assert!(!result);
    }

    #[test]
    fn verify_narinfo_signatures_with_references() {
        use ed25519_dalek::{Signer, SigningKey};
        use sui_compat::hash::base64_encode;
        use sui_compat::signature::compute_fingerprint;

        let signing_key = SigningKey::from_bytes(&[10u8; 32]);
        let verifying_key = signing_key.verifying_key();

        let refs = vec![
            "dep-b".to_string(),
            "dep-a".to_string(),
        ];

        let narinfo = NarInfo {
            store_path: "/nix/store/xyz-pkg".to_string(),
            url: "nar/xyz.nar".to_string(),
            compression: "none".to_string(),
            file_hash: "sha256:fff".to_string(),
            file_size: 2000,
            nar_hash: "sha256:eee".to_string(),
            nar_size: 3000,
            references: refs.clone(),
            deriver: None,
            signatures: vec![],
            ca: None,
        };

        // The verify method sorts references, so we must sign with sorted refs.
        let mut sorted_refs = refs;
        sorted_refs.sort();
        let fingerprint = compute_fingerprint(
            &narinfo.store_path,
            &narinfo.nar_hash,
            narinfo.nar_size,
            &sorted_refs,
        );
        let sig = signing_key.sign(fingerprint.as_bytes());
        let sig_str = format!("k:{}", base64_encode(&sig.to_bytes()));
        let trusted_key = format!("k:{}", base64_encode(verifying_key.as_bytes()));

        let mut signed = narinfo;
        signed.signatures = vec![sig_str];

        let result = BinaryCacheStore::verify_narinfo_signatures(
            &signed,
            &[trusted_key],
        )
        .unwrap();
        assert!(result);
    }

    // ── Auth header tests ────────────────────────────────────────

    #[test]
    fn builder_auth_header_none_by_default() {
        let store = BinaryCacheStore::builder("https://cache.example.com").build();
        assert!(store.auth_header().is_none());
    }

    #[test]
    fn builder_auth_header_set() {
        let store = BinaryCacheStore::builder("https://cache.example.com")
            .auth_header("Bearer", "my-token-123")
            .build();
        let (scheme, creds) = store.auth_header().unwrap();
        assert_eq!(scheme, "Bearer");
        assert_eq!(creds, "my-token-123");
    }

    #[test]
    fn request_headers_without_auth() {
        let store = BinaryCacheStore::builder("https://cache.example.com").build();
        let headers = store.request_headers(&[("Accept", "text/plain")]);
        assert_eq!(headers.len(), 1);
        assert_eq!(headers[0], ("Accept".to_string(), "text/plain".to_string()));
    }

    #[test]
    fn request_headers_with_auth() {
        let store = BinaryCacheStore::builder("https://cache.example.com")
            .auth_header("Bearer", "token123")
            .build();
        let headers = store.request_headers(&[("Accept", "text/plain")]);
        assert_eq!(headers.len(), 2);
        assert_eq!(headers[1], ("Authorization".to_string(), "Bearer token123".to_string()));
    }

    #[test]
    fn new_constructor_has_no_auth() {
        let store = BinaryCacheStore::new("https://cache.example.com", vec![]);
        assert!(store.auth_header().is_none());
    }
}