atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
//! Blob addressing and verified fetching.
//!
//! # The URI
//!
//! ```text
//! atpmcp://public/blob/{did}/{cid}
//! ```
//!
//! `atpmcp` names *this server*, which is what the URI is actually scoped to:
//! nothing outside this process can resolve one, and `atproto:` is not a
//! scheme the AT Protocol project defines, so taking it would be squatting a
//! name the ecosystem may still want.
//!
//! `public` is the authority and names the **trust half**: no credential is
//! used, so the result carries `cacheScope: "public"`. It reserves
//! `atpmcp://private/blob/{did}/{cid}` for an authenticated read, which would
//! be `"private"` and cached per account. Putting the trust half in the URI
//! rather than in a flag means the two can never share a cache entry.
//!
//! The DID is a DID and never a handle. Handles are mutable aliases, and a
//! resource URI whose meaning changes when someone moves their domain is a
//! cache-poisoning primitive. Tools accept handles and resolve them; the URI
//! they hand back is canonical.
//!
//! `did:plc:abc` inside a path segment is legal per RFC 3986 — `:` is in
//! `pchar` and is only special in the first segment of a relative-path
//! reference — so no percent-encoding is needed and the URI stays greppable.
//!
//! # Why the bytes are always verified
//!
//! Resolving a DID to a PDS means reading a `serviceEndpoint` that the DID's
//! own subject published. That host is attacker-controlled. Two things make it
//! safe to fetch from anyway: the request carries no credential, so nothing
//! leaks to whoever answers; and the bytes are hashed and compared against the
//! CID before they are returned or cached, so a hostile host can refuse or
//! stall but cannot substitute content.
//!
//! # Streamed, not buffered
//!
//! A fresh fetch writes the response straight to a temporary file while
//! feeding an incremental SHA-256 hasher ([`atproto_dasl::cid::RawCidHasher`]),
//! so the whole blob is never resident in memory at once. A cache hit is
//! verified the same way, reading the file through the hasher a chunk at a
//! time. Only a 2xx answer is the blob: any other status is reported with the
//! start of its body, and nothing is written or hashed. Three properties hold
//! regardless:
//!
//! - **Verify before publish.** The temporary file is renamed to the cache's
//!   real path — the only name [`crate::cache::BlobCache::get`] ever looks
//!   up — only after the hash matches. Nothing else can observe the bytes at
//!   that name before that, so a cache hit is always content that already
//!   passed the check.
//! - **Delete on mismatch.** Any failure — a hash mismatch, an oversize body,
//!   a transport error — removes the temporary file before returning.
//! - **A hard size bound.** `max_bytes` is checked against the running total
//!   after every chunk, not trusted from a peer-supplied `Content-Length`
//!   (used only to refuse an obviously oversize body early). A hostile
//!   endpoint can make a fetch fail; it cannot make one fill the disk. A
//!   cache hit is held to the same bound.
//!
//! The handle the bytes were verified through stays open in the
//! [`VerifiedBlob`], and an inline reply reads them back through it and hashes
//! them again ([`VerifiedBlob::bytes`]). A cache entry is a plain file that an
//! eviction pass can unlink and anything with the user's access can replace,
//! so reading `path` again would read whatever is there by then.
//!
//! # What the blob reference adds
//!
//! -04 §11.7 has a client verify a fetched blob's "content hash and size",
//! and "the media type declared in the blob metadata". The hash needs only the
//! CID. The rest needs the reference, which a caller passes as an
//! [`Expected`]: a blob of another size is refused, fetched or cached, and the
//! declared type is checked against the served one and the bytes, a
//! disagreement reported rather than refused. A host may serve any blob as
//! `application/octet-stream` (§11.8), so that answer is not taken as the
//! blob's type: the declared or the sniffed type stands in for it, and is what
//! the cache records ([`crate::mime::resolve_served`]).

use std::path::{Path, PathBuf};
use std::sync::Arc;

use atproto_dasl::cid::{CidCore, RAW_CODEC, RawCidHasher, SHA256_CODE};
use atproto_identity::validation::{is_valid_did_method_plc, is_valid_did_method_web};
use futures::StreamExt;
use tokio::io::AsyncWriteExt;

use crate::context::ServerContext;
use crate::errors::{ResourceError, ToolError};
use crate::proto::serve::RequestCtx;

/// The URI scheme this server addresses its resources under.
pub const SCHEME: &str = "atpmcp";

/// The authority naming the unauthenticated half of the namespace.
pub const NAMESPACE_PUBLIC: &str = "public";

/// The RFC 6570 template advertised by `resources/templates/list`.
///
/// `{+did}` and not `{did}`: simple string expansion percent-encodes reserved
/// characters and would yield `did%3Aplc%3Aabc`, which is not the URI the
/// tools return. Reserved expansion keeps the colons literal.
pub const URI_TEMPLATE: &str = "atpmcp://public/blob/{+did}/{cid}";

/// A parsed blob resource URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobUri {
    /// The repository DID holding the blob.
    pub did: String,
    /// The blob's content address.
    pub cid: String,
}

impl BlobUri {
    /// Build a URI from a DID and CID that are already known good.
    #[must_use]
    pub fn new(did: impl Into<String>, cid: impl Into<String>) -> Self {
        Self {
            did: did.into(),
            cid: cid.into(),
        }
    }

    /// Render the canonical URI.
    #[must_use]
    pub fn to_uri(&self) -> String {
        format!(
            "{SCHEME}://{NAMESPACE_PUBLIC}/blob/{}/{}",
            self.did, self.cid
        )
    }

    /// Parse and validate a blob resource URI.
    ///
    /// Everything is checked rather than assumed: the scheme, the authority,
    /// the segment count, the absence of a query or fragment, the DID's
    /// method-specific syntax, and the CID's profile. A trailing segment is
    /// rejected rather than ignored, so one blob has exactly one URI and the
    /// cache key is unambiguous.
    ///
    /// # Errors
    ///
    /// Returns [`ResourceError::UnsupportedScheme`] when the scheme or
    /// authority is not ours, and [`ResourceError::MalformedUri`] for
    /// everything else.
    pub fn parse(uri: &str) -> Result<Self, ResourceError> {
        let malformed = |reason: &str| ResourceError::MalformedUri {
            uri: uri.to_string(),
            reason: reason.to_string(),
        };

        if uri.contains('?') {
            return Err(malformed("a blob URI carries no query string"));
        }
        if uri.contains('#') {
            return Err(malformed("a blob URI carries no fragment"));
        }

        let prefix = format!("{SCHEME}://");
        let Some(rest) = uri.strip_prefix(&prefix) else {
            return Err(ResourceError::UnsupportedScheme {
                uri: uri.to_string(),
            });
        };

        let segments: Vec<&str> = rest.split('/').collect();
        let [namespace, kind, did, cid] = segments.as_slice() else {
            return Err(malformed(
                "expected exactly atpmcp://public/blob/{did}/{cid}",
            ));
        };

        if *namespace != NAMESPACE_PUBLIC {
            return Err(ResourceError::UnsupportedScheme {
                uri: uri.to_string(),
            });
        }
        if *kind != "blob" {
            return Err(ResourceError::UnsupportedScheme {
                uri: uri.to_string(),
            });
        }

        if !is_supported_did(did) {
            return Err(malformed("the DID is not a valid did:plc or did:web"));
        }

        validate_blob_cid(cid).map_err(|reason| malformed(&reason))?;

        Ok(Self::new(*did, *cid))
    }
}

/// Whether a DID is one of the methods this server can resolve.
#[must_use]
pub fn is_supported_did(did: &str) -> bool {
    is_valid_did_method_plc(did) || is_valid_did_method_web(did, false)
}

/// Check that a string is a CID a blob can legitimately be addressed by.
///
/// The strict profile: CIDv1, `raw` codec, SHA-256, 32-byte digest. A
/// `dag-cbor` CID here is a *record* CID and a caller mistake worth naming
/// rather than passing to a PDS that will simply 404.
///
/// # Errors
///
/// Returns a human-readable reason when the CID does not fit the profile.
pub fn validate_blob_cid(cid: &str) -> Result<(), String> {
    let parsed: CidCore = cid.parse().map_err(|error| format!("not a CID: {error}"))?;

    if parsed.version() != atproto_dasl::CidVersion::V1 {
        return Err("a blob CID must be CIDv1".to_string());
    }
    if parsed.codec() != RAW_CODEC {
        return Err(format!(
            "a blob CID must use the raw codec (0x55), got 0x{:x}; a dag-cbor CID addresses a record, not a blob",
            parsed.codec()
        ));
    }
    let hash = parsed.hash();
    if hash.code() != SHA256_CODE {
        return Err("a blob CID must use SHA-256".to_string());
    }
    if hash.digest().len() != 32 {
        return Err("a blob CID must carry a 32-byte digest".to_string());
    }

    // The canonical rendering must round-trip, so that one blob has one key.
    if parsed.to_string() != cid {
        return Err("the CID is not in its canonical base32 form".to_string());
    }

    Ok(())
}

/// A blob that has been fetched and verified.
///
/// It names the verified file and never holds the bytes: `path` is where they
/// live and `size` is known without reading them back. A cache hit used to
/// carry them in a `data` field, read whole to be hashed, so a hit held an
/// entire blob in memory that a fresh fetch never did. It does hold the open
/// handle the bytes were verified through, which [`Self::bytes`] reads.
#[derive(Debug)]
pub struct VerifiedBlob {
    /// Where the verified bytes live on disk. Always populated, and always
    /// exists at the moment this value is returned.
    pub path: PathBuf,
    /// Size in bytes.
    pub size: u64,
    /// The content type it is reported as: the one the repository served,
    /// or the cache recorded, unless that was generic or missing, when it is
    /// the declared or the sniffed type ([`crate::mime::resolve_served`]).
    pub mime_type: String,
    /// Set when the declared content type disagrees with the served type or
    /// the bytes.
    pub mime_disagreement: Option<String>,
    /// Whether the bytes came from the local cache rather than the network.
    pub cached: bool,
    /// The CID the bytes were verified against.
    cid: String,
    /// The handle the bytes were written or hashed through, still open.
    /// `None` only once [`Drop`] has closed it.
    file: Option<tokio::fs::File>,
    /// Whether `path` is a private scratch file with no life beyond this
    /// call -- true only when the persistent cache is disabled, the blob is
    /// larger than the cache's whole budget, or a streamed write could not
    /// be published into it and was moved out instead. Deleted when this value is dropped, so an early
    /// return can never leak it, unless [`Self::keep`] was called.
    ephemeral: bool,
}

impl VerifiedBlob {
    /// The bytes, read back and verified again.
    ///
    /// Only meant for a caller that already knows the size is small, such as
    /// an inline reply capped well below the transfer ceiling: `size` can be
    /// as large as `max_bytes` allowed the fetch to be.
    ///
    /// They are read through the handle they were verified through, not by
    /// opening `path` again, and at most `size` bytes of them. An open handle
    /// goes on reading the same file after an eviction unlinks `path` or a
    /// rename replaces it -- on Unix, where this matters -- so neither turns a
    /// verified fetch into an error or into different bytes. What is read is
    /// hashed again, which catches the one change a handle does see, the file
    /// rewritten in place. So the bytes returned are always ones hashed
    /// against the CID in the same read.
    ///
    /// This read `path` with `tokio::fs::read`, unbounded and unchecked,
    /// after a check on `size` alone.
    ///
    /// # Errors
    ///
    /// [`ToolError::BlobReadBackFailed`] when the read fails, or finds a
    /// different length or bytes that no longer hash to the CID.
    pub async fn bytes(&mut self) -> Result<Vec<u8>, ToolError> {
        use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};

        let failed = |reason: String| ToolError::BlobReadBackFailed {
            path: self.path.display().to_string(),
            reason,
        };
        let Some(file) = self.file.as_mut() else {
            return Err(failed("the verified file is already closed".to_string()));
        };

        file.rewind()
            .await
            .map_err(|error| failed(error.to_string()))?;
        // One byte past the verified size, so a file that grew is caught
        // without reading any more of it.
        let capacity = usize::try_from(self.size).unwrap_or(usize::MAX);
        let mut data = Vec::with_capacity(capacity);
        file.take(self.size.saturating_add(1))
            .read_to_end(&mut data)
            .await
            .map_err(|error| failed(error.to_string()))?;

        if data.len() as u64 != self.size {
            return Err(failed(format!(
                "it no longer holds the {} bytes that were verified; it was changed after it \
                 was verified",
                self.size
            )));
        }
        let computed = atproto_dasl::compute_raw_cid(&data).to_string();
        if computed != self.cid {
            tracing::warn!(
                path = %self.path.display(),
                expected = %self.cid,
                computed = %computed,
                "A verified blob changed on disk before it was read back."
            );
            return Err(failed(format!(
                "it now hashes to {computed}, not {}; it was changed after it was verified",
                self.cid
            )));
        }
        Ok(data)
    }

    /// Keep `path` after this value is dropped, and return it.
    ///
    /// For a caller that hands the path to someone else, rather than reading
    /// it here: without this, an ephemeral path stops existing once this
    /// value is dropped. A cached blob is
    /// already kept. An ephemeral one is a scratch file in the system temp
    /// directory under a name unique to this call, created exclusively, so
    /// keeping it hands out a file nothing else could have put there -- and
    /// the operating system's own temp-directory cleanup, not this process,
    /// is what eventually removes it.
    pub fn keep(&mut self) -> PathBuf {
        self.ephemeral = false;
        self.path.clone()
    }
}

impl Drop for VerifiedBlob {
    fn drop(&mut self) {
        // Closed first: a platform that refuses to delete an open file would
        // otherwise leave the scratch file behind.
        self.file = None;
        if self.ephemeral {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

/// What the caller's blob reference says about a blob, to check it against.
///
/// Both are optional, since a caller may hold only a CID, and a resource URI
/// carries nothing else.
#[derive(Debug, Clone, Default)]
pub struct Expected {
    /// The reference's `size`. A blob of another size is refused.
    pub size: Option<u64>,
    /// The reference's `mimeType`. Checked against the served type and the
    /// bytes, and used in place of a generic served type.
    pub mime_type: Option<String>,
}

/// Where to look for a blob.
#[derive(Debug, Clone)]
pub struct Locator {
    /// The repository DID.
    pub did: String,
    /// The blob CID.
    pub cid: String,
    /// An explicit endpoint, bypassing DID-document resolution.
    pub endpoint: Option<String>,
}

/// Fetch a blob, serving it from cache when possible and verifying it always.
///
/// The bytes are always verified against the CID, and against
/// `expected.size` when one is given (-04 §11.7, "content hash and size").
/// The content type is decided by [`crate::mime::resolve_served`].
///
/// # Errors
///
/// Returns a [`ToolError`] naming the failure: a CID mismatch, a size refusal
/// or mismatch, an unresolvable identity, or an upstream error.
pub async fn fetch(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    locator: &Locator,
    expected: &Expected,
    max_bytes: u64,
) -> Result<VerifiedBlob, ToolError> {
    // A blob the reference says is over the limit is refused before anything
    // is read: either the reference is right and the blob is too large, or it
    // is wrong and the size check would refuse the blob anyway.
    if let Some(size) = expected.size
        && size > max_bytes
    {
        return Err(ToolError::BlobTooLarge {
            size,
            limit: max_bytes,
        });
    }

    // The cache is consulted first, and its contents are re-hashed on read, so
    // a hit is proven rather than trusted.
    if let Some(mut cached) = ctx.cache.get(&locator.cid).await {
        // A hit is held to `max_bytes` as a fresh fetch is. It was returned
        // before the limit was looked at, so a caller asking for at most
        // 1 KiB, or an operator who had lowered the download ceiling, got a
        // multi-megabyte blob whenever it happened to be cached -- and
        // `upload_blob` seeds the cache under the *upload* ceiling, so an
        // entry can be larger than the download ceiling without anyone having
        // lowered anything. Refused rather than refetched: the CID fixes the
        // bytes, so the network would answer with the same size.
        if cached.size > max_bytes {
            return Err(ToolError::BlobTooLarge {
                size: cached.size,
                limit: max_bytes,
            });
        }
        // Not evicted: the bytes are the CID's, and it is the reference that
        // disagrees with them.
        if let Some(declared) = expected.size
            && declared != cached.size
        {
            return Err(ToolError::BlobSizeMismatch {
                declared,
                actual: cached.size,
                at_least: false,
            });
        }
        // The recorded type is resolved as a served one is, so an entry that
        // recorded a generic type, as one written before types were resolved
        // may have, is reported by the reference or the bytes.
        let decided = decide_type(
            cached.mime_type.as_deref(),
            expected.mime_type.as_deref(),
            &mut cached.file,
        )
        .await;
        tracing::debug!(cid = %locator.cid, "Serving a blob from cache.");
        return Ok(VerifiedBlob {
            path: cached.path,
            size: cached.size,
            mime_type: decided.value,
            mime_disagreement: decided.disagreement,
            cached: true,
            cid: locator.cid.clone(),
            file: Some(cached.file),
            ephemeral: false,
        });
    }

    if rctx.cancel.is_cancelled() {
        return Err(ToolError::BlobDownloadFailed {
            reason: "cancelled".to_string(),
        });
    }

    let endpoint = match locator.endpoint.as_deref() {
        Some(endpoint) => endpoint.to_string(),
        None => resolve_endpoint(ctx, &locator.did).await?,
    };

    rctx.report_progress(0, &format!("Fetching {} from {endpoint}", locator.cid));

    let streamed = tokio::select! {
        biased;
        () = rctx.cancel.cancelled() => {
            return Err(ToolError::BlobDownloadFailed { reason: "cancelled".to_string() });
        }
        result = stream_and_verify(ctx, &endpoint, &locator.did, &locator.cid, expected, max_bytes) => result?,
    };

    rctx.set_progress_total(Some(streamed.size));
    rctx.finish_progress(streamed.size, &format!("Fetched {} bytes", streamed.size));

    Ok(VerifiedBlob {
        path: streamed.path,
        size: streamed.size,
        mime_type: streamed.mime_type.value,
        mime_disagreement: streamed.mime_type.disagreement,
        cached: false,
        cid: locator.cid.clone(),
        file: Some(streamed.file),
        ephemeral: streamed.ephemeral,
    })
}

/// How much of a blob is read to sniff its content type. `infer` looks at
/// far less for every format a blob is likely to be.
const SNIFF_BYTES: u64 = 8 * 1024;

/// Decide a verified blob's content type, reading the start of `file` only
/// when the decision can use it ([`crate::mime::wants_sniff`]).
///
/// The read goes through the handle the bytes were verified through, and
/// leaves it at an arbitrary position: every later read of it rewinds first.
/// A file that cannot be read for this is treated as unrecognised, since the
/// type is a label and the bytes were already verified.
async fn decide_type(
    served: Option<&str>,
    declared: Option<&str>,
    file: &mut tokio::fs::File,
) -> crate::mime::ServedType {
    use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};

    let mut sniffed = None;
    if crate::mime::wants_sniff(served, declared) {
        let mut prefix = Vec::new();
        let read = async {
            file.rewind().await?;
            (&mut *file)
                .take(SNIFF_BYTES)
                .read_to_end(&mut prefix)
                .await
        }
        .await;
        if read.is_ok() {
            sniffed = crate::mime::sniff(&prefix);
        }
    }
    crate::mime::resolve_served(served, declared, sniffed)
}

/// The outcome of a streamed, verified fetch.
struct StreamedBlob {
    path: PathBuf,
    size: u64,
    /// The decided type, which is also what the cache recorded.
    mime_type: crate::mime::ServedType,
    ephemeral: bool,
    /// The handle the bytes were written through, still open.
    file: tokio::fs::File,
}

/// Stream a blob from `endpoint`, hashing it as it arrives and writing it
/// straight to disk -- inside the cache directory when one is configured,
/// otherwise a private scratch file -- so that verifying it against `cid`
/// never requires holding more than one chunk in memory at a time. See the
/// module docs for the three safety properties this preserves.
///
/// With `expected.size`, the read stops at the chunk that passes it rather
/// than at `max_bytes`, which [`fetch`] has already checked it against, and a blob of
/// any other size is refused and discarded like a CID mismatch. The content
/// type recorded in the cache is the decided one, so a host's
/// `application/octet-stream` is never recorded over a declared or sniffed
/// type.
async fn stream_and_verify(
    ctx: &Arc<ServerContext>,
    endpoint: &str,
    did: &str,
    cid: &str,
    expected: &Expected,
    max_bytes: u64,
) -> Result<StreamedBlob, ToolError> {
    // A size beyond the declared one is a mismatch, not a blob too large.
    let limit = expected.size.map_or(max_bytes, |size| size.min(max_bytes));
    let mismatch = |error: ToolError| match (error, expected.size) {
        (ToolError::BlobDownloadTooLarge { size, .. }, Some(declared)) if declared <= max_bytes => {
            ToolError::BlobSizeMismatch {
                declared,
                actual: size,
                at_least: true,
            }
        }
        (error, _) => error,
    };

    let url = atproto_identity::url::build_url(
        endpoint,
        "/xrpc/com.atproto.sync.getBlob",
        [("did", did), ("cid", cid)],
    )
    .map_err(|error| ToolError::BlobDownloadFailed {
        reason: format!("could not build a request URL for {endpoint}: {error}"),
    })?;

    let response = ctx
        .blob_client
        .get(url.as_str())
        .send()
        .await
        .map_err(|error| ToolError::BlobDownloadFailed {
            reason: format!("request to {endpoint} failed: {error}"),
        })?;

    // The status first: an error answer is not the blob. Hashing it made a
    // `400 {"error":"BlobNotFound"}` -- the commonest failure there is -- read
    // as a CID mismatch, the alarm for a repository serving the wrong bytes,
    // and an error body over the limit read as a blob too large to fetch.
    let status = response.status();
    if !status.is_success() {
        return Err(ToolError::BlobErrorResponse {
            endpoint: endpoint.to_string(),
            status: status.as_u16(),
            body: error_body(response).await,
        });
    }

    let served_type = response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .map(str::to_string);

    // A hint, never a bound: used only to refuse an obviously oversize body
    // before spending a write on it. The running total in `write_hashed`
    // below is what actually stops the read, so a peer that omits or
    // under-declares this gains nothing.
    // Refused as a lower bound, not a size: the declaration is the peer's and
    // is never checked.
    let declared = response.content_length();
    if let Some(declared) = declared
        && declared > limit
    {
        return Err(mismatch(ToolError::BlobDownloadTooLarge {
            size: declared,
            limit,
        }));
    }

    // A declared size larger than the whole cache keeps the blob out of it,
    // since committing it would evict everything else and then the blob
    // itself. It goes to scratch, as with no cache. A response that declares
    // no length is written in the cache's directory, and its size is checked
    // once it is known, below.
    let (temp_path, final_target) = match ctx.cache.prepare_write(cid, declared).await {
        Ok(Some(target)) => (target.temp_path.clone(), Some(target)),
        Ok(None) => (scratch_path(cid), None),
        Err(error) => {
            tracing::warn!(
                error = ?error,
                "Could not prepare the cache for a streamed blob; using scratch space."
            );
            (scratch_path(cid), None)
        }
    };

    let write_result = write_hashed(&temp_path, response.bytes_stream(), limit).await;

    let (size, computed, mut file) = match write_result {
        Ok(written) => written,
        Err(error) => {
            discard_temp(ctx, &temp_path, final_target.as_ref()).await;
            return Err(mismatch(error));
        }
    };

    if computed != cid {
        tracing::warn!(
            requested = %cid,
            computed = %computed,
            endpoint = %endpoint,
            "A repository served bytes that do not match the requested CID."
        );
        discard_temp(ctx, &temp_path, final_target.as_ref()).await;
        return Err(ToolError::BlobCidMismatch {
            requested: cid.to_string(),
            computed,
        });
    }

    // Shorter than declared; a longer one stopped above. The bytes are the
    // CID's, so it is the reference that is wrong, but the call asked for
    // this reference's blob, and a refused call leaves nothing behind.
    if let Some(declared) = expected.size
        && declared != size
    {
        discard_temp(ctx, &temp_path, final_target.as_ref()).await;
        return Err(ToolError::BlobSizeMismatch {
            declared,
            actual: size,
            at_least: false,
        });
    }

    let mime_type = decide_type(
        served_type.as_deref(),
        expected.mime_type.as_deref(),
        &mut file,
    )
    .await;

    let (path, file, ephemeral) = match final_target {
        // A response that declared no length is known to fit only now. One
        // larger than the whole budget is not committed, because its commit
        // would evict every other entry and still be over budget. It moves
        // out to scratch, where a declared one would have gone.
        Some(target) if !ctx.cache.admits(size) => {
            tracing::debug!(
                cid = %cid,
                size,
                "A blob that declared no length is larger than the cache; keeping it as a scratch file."
            );
            let (path, file) = move_to_scratch(ctx, &target, cid, file).await?;
            (path, file, true)
        }
        Some(target) => match ctx
            .cache
            .commit_write(&target, Some(&mime_type.value))
            .await
        {
            Ok(()) => (target.final_path, file, false),
            // Moved out, not used in place: in place is the `.partial` temp
            // file, which `download_blob` would keep in the cache directory
            // under a name the cache neither counts nor evicts.
            Err(error) => {
                tracing::warn!(
                    error = ?error,
                    "Failed to publish a streamed blob into the cache; keeping it as a scratch file."
                );
                let (path, file) = move_to_scratch(ctx, &target, cid, file).await?;
                (path, file, true)
            }
        },
        None => (temp_path, file, true),
    };

    Ok(StreamedBlob {
        path,
        size,
        mime_type,
        ephemeral,
        file,
    })
}

/// Stream `chunks` to a new file at `path`, hashing them as they arrive.
///
/// Returns the total size written, the resulting raw CID and the handle the
/// file was written through, opened for reading too, once the stream ends
/// normally. Returns [`ToolError::BlobDownloadTooLarge`] the instant the
/// running total would exceed `max_bytes` -- dropping `chunks` at that point
/// drops the underlying connection, so a peer that intends to keep sending
/// stops being read. Either way, this function only ever creates `path`; the
/// caller deletes it on any `Err`.
///
/// `path` must not exist yet, and the open refuses one that does rather than
/// truncating it. A scratch path lives in the system temp directory, which is
/// shared between users on many systems, and a plain create would follow a
/// symlink someone else planted at a predictable name and write the blob
/// wherever it pointed. Both callers' names are unique per process and call,
/// so an existing file there is never one this process made.
async fn write_hashed(
    path: &Path,
    mut chunks: impl futures::Stream<Item = reqwest::Result<bytes::Bytes>> + Unpin,
    max_bytes: u64,
) -> Result<(u64, String, tokio::fs::File), ToolError> {
    let mut file = tokio::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .open(path)
        .await
        .map_err(|error| ToolError::BlobDownloadFailed {
            reason: format!("could not create {}: {error}", path.display()),
        })?;

    let mut hasher = RawCidHasher::new();
    let mut written: u64 = 0;

    while let Some(chunk) = chunks.next().await {
        let chunk = chunk.map_err(|error| ToolError::BlobDownloadFailed {
            reason: format!("reading the response body failed: {error}"),
        })?;

        written += chunk.len() as u64;
        if written > max_bytes {
            // What has arrived so far, which the blob is at least: the read
            // stops here, so its real size is never learned.
            return Err(ToolError::BlobDownloadTooLarge {
                size: written,
                limit: max_bytes,
            });
        }

        hasher.update(&chunk);
        file.write_all(&chunk)
            .await
            .map_err(|error| ToolError::BlobDownloadFailed {
                reason: format!("writing {}: {error}", path.display()),
            })?;
    }

    file.flush()
        .await
        .map_err(|error| ToolError::BlobDownloadFailed {
            reason: format!("flushing {}: {error}", path.display()),
        })?;

    Ok((written, hasher.finalize().to_string(), file))
}

/// The most of an error answer's body that a tool error quotes.
const ERROR_BODY_LIMIT: usize = 1024;

/// What a repository said when it answered a blob fetch with an error.
///
/// The body is quoted, not trusted and not kept: at most [`ERROR_BODY_LIMIT`]
/// bytes are read, since a proxy's error page can be any size and none of it
/// is worth putting in front of a model past the first kilobyte. An XRPC
/// error's `{"error", "message"}` fits whole and is quoted as compact JSON. A
/// redirect is named rather than quoted, because this client follows none and
/// its body usually says nothing.
async fn error_body(response: reqwest::Response) -> String {
    if response.status().is_redirection() {
        let location = response
            .headers()
            .get(reqwest::header::LOCATION)
            .and_then(|value| value.to_str().ok())
            .map(|location| format!(" to {location}"))
            .unwrap_or_default();
        return format!("a redirect{location}, which is not followed for a blob");
    }

    let mut chunks = response.bytes_stream();
    let mut collected: Vec<u8> = Vec::new();
    let mut truncated = false;
    while let Some(Ok(chunk)) = chunks.next().await {
        let room = ERROR_BODY_LIMIT - collected.len();
        if chunk.len() > room {
            collected.extend_from_slice(&chunk[..room]);
            truncated = true;
            break;
        }
        collected.extend_from_slice(&chunk);
    }

    if collected.is_empty() {
        return "(no body)".to_string();
    }
    if !truncated && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&collected) {
        return value.to_string();
    }
    let mut text = String::from_utf8_lossy(&collected).into_owned();
    if truncated {
        text.push_str(&format!(" … (truncated at {ERROR_BODY_LIMIT} bytes)"));
    }
    text
}

/// Delete a temp file that failed to write or did not verify.
///
/// Routed through [`crate::cache::BlobCache::abort_write`] when it is
/// cache-backed, so the cache's own bookkeeping for that path -- there is
/// none beyond the file today, but this is the one call site that must not
/// forget it if that changes -- stays in one place.
async fn discard_temp(
    ctx: &Arc<ServerContext>,
    temp_path: &Path,
    target: Option<&crate::cache::WriteTarget>,
) {
    match target {
        Some(target) => ctx.cache.abort_write(target).await,
        None => {
            let _ = tokio::fs::remove_file(temp_path).await;
        }
    }
}

/// Move a verified blob the cache will not keep out of the cache directory,
/// to a new [`scratch_path`], and return that path with a handle to it.
///
/// The temp file is renamed when it can be, and `file` goes on reading it. A
/// cache directory on another filesystem than the temp directory refuses a
/// rename, and then the bytes are copied through `file` into a new file,
/// hashed again on the way ([`copy_verified`]). The temp file is gone when
/// this returns, whatever happened: a blob is never handed out from inside
/// the cache directory under a name the cache neither counts nor evicts.
///
/// # Errors
///
/// [`ToolError::BlobDownloadFailed`] when neither the rename nor the copy
/// works, as when a fetch with no cache cannot create its scratch file.
async fn move_to_scratch(
    ctx: &Arc<ServerContext>,
    target: &crate::cache::WriteTarget,
    cid: &str,
    file: tokio::fs::File,
) -> Result<(PathBuf, tokio::fs::File), ToolError> {
    let scratch = scratch_path(cid);
    let renamed = match tokio::fs::rename(&target.temp_path, &scratch).await {
        Ok(()) => return Ok((scratch, file)),
        Err(error) => error,
    };
    let copied = copy_verified(file, &scratch, cid).await;
    ctx.cache.abort_write(target).await;
    match copied {
        Ok(file) => Ok((scratch, file)),
        Err(reason) => Err(ToolError::BlobDownloadFailed {
            reason: format!(
                "could not move the verified blob out of the cache to {}: renaming it failed \
                 ({renamed}), and so did copying it ({reason})",
                scratch.display()
            ),
        }),
    }
}

/// Copy the verified blob `from` into a new file at `to`, hashing it again as
/// it goes, and return a handle to the copy.
///
/// `to` is created exclusively, as [`write_hashed`] creates a scratch file,
/// and deleted again if the copy fails or no longer hashes to `cid`.
async fn copy_verified(
    mut from: tokio::fs::File,
    to: &Path,
    cid: &str,
) -> Result<tokio::fs::File, String> {
    use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};

    let mut out = tokio::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create_new(true)
        .open(to)
        .await
        .map_err(|error| format!("could not create {}: {error}", to.display()))?;

    let copied = async {
        from.rewind().await?;
        let mut hasher = RawCidHasher::new();
        let mut buffer = vec![0u8; 64 * 1024];
        loop {
            let read = from.read(&mut buffer).await?;
            if read == 0 {
                break;
            }
            hasher.update(&buffer[..read]);
            out.write_all(&buffer[..read]).await?;
        }
        out.flush().await?;
        Ok::<_, std::io::Error>(hasher.finalize().to_string())
    }
    .await;

    let failure = match copied {
        Ok(computed) if computed == cid => return Ok(out),
        Ok(computed) => format!("the copy hashes to {computed}, not {cid}"),
        Err(error) => format!("copying into {}: {error}", to.display()),
    };
    drop(out);
    let _ = tokio::fs::remove_file(to).await;
    Err(failure)
}

/// A private, uniquely-named path for a blob the persistent cache will not
/// hold: streamed here when there is no cache or the blob declared a size over
/// its budget, and moved here ([`move_to_scratch`]) when it turns out to be
/// over budget once written or its commit fails. Unique per call, so nothing
/// else -- another fetch of the same CID, a leftover from a previous run --
/// ever shares this name.
///
/// No `.partial` suffix: `download_blob` hands this path out once the bytes
/// are verified (see [`VerifiedBlob::keep`]), and by then it is complete.
fn scratch_path(cid: &str) -> PathBuf {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    std::env::temp_dir().join(format!(
        "atpmcp-blob-{cid}-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ))
}

/// Resolve a DID to a PDS endpoint that is safe to fetch from.
async fn resolve_endpoint(ctx: &Arc<ServerContext>, did: &str) -> Result<String, ToolError> {
    let document =
        ctx.resolver
            .resolve(did)
            .await
            .map_err(|error| ToolError::BlobDownloadFailed {
                reason: format!("failed to resolve {did}: {error:#}"),
            })?;

    // Validated, not raw, and never waived: the endpoint comes from a document
    // the DID's subject publishes, and the validated form rejects non-https,
    // address literals, embedded credentials and non-default ports. Using the
    // raw list here would make this an SSRF primitive reachable from a model
    // prompt. See `host_policy` for why the waiver does not reach it.
    crate::host_policy::pds_endpoint(&document, false).map_err(|unusable| {
        ToolError::BlobDownloadFailed {
            reason: unusable.tool_reason(did, Some("endpoint")),
        }
    })
}

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

    const DID: &str = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";

    fn blob_cid() -> String {
        atproto_dasl::compute_raw_cid(b"some blob bytes").to_string()
    }

    fn record_cid() -> String {
        atproto_dasl::compute_cid_for(&serde_json::json!({ "a": 1 }))
            .unwrap()
            .to_string()
    }

    #[test]
    fn round_trips_a_uri() {
        let cid = blob_cid();
        let uri = BlobUri::new(DID, &cid);
        let text = uri.to_uri();
        assert_eq!(text, format!("atpmcp://public/blob/{DID}/{cid}"));
        assert_eq!(BlobUri::parse(&text).unwrap(), uri);
    }

    #[test]
    fn a_did_keeps_its_colons_unescaped() {
        let uri = BlobUri::new(DID, blob_cid()).to_uri();
        assert!(uri.contains("did:plc:"), "colons must stay literal: {uri}");
        assert!(!uri.contains("%3A"));
    }

    #[test]
    fn the_template_uses_reserved_expansion_for_the_did() {
        // The regression test for the RFC 6570 trap: `{did}` would
        // percent-encode the colons and produce a URI that never matches what
        // the tools return.
        assert!(URI_TEMPLATE.contains("{+did}"));
        assert!(!URI_TEMPLATE.contains("{did}"));

        // Expanding the template by hand must equal the canonical rendering.
        let cid = blob_cid();
        let expanded = URI_TEMPLATE.replace("{+did}", DID).replace("{cid}", &cid);
        assert_eq!(expanded, BlobUri::new(DID, &cid).to_uri());
    }

    #[test]
    fn rejects_a_foreign_scheme() {
        let cid = blob_cid();
        for uri in [
            format!("atproto://public/blob/{DID}/{cid}"),
            format!("https://public/blob/{DID}/{cid}"),
            format!("at://{DID}/blob/{cid}"),
        ] {
            assert!(
                matches!(
                    BlobUri::parse(&uri),
                    Err(ResourceError::UnsupportedScheme { .. })
                ),
                "should reject {uri}"
            );
        }
    }

    #[test]
    fn rejects_a_foreign_namespace_or_kind() {
        let cid = blob_cid();
        for uri in [
            format!("atpmcp://private/blob/{DID}/{cid}"),
            format!("atpmcp://public/record/{DID}/{cid}"),
        ] {
            assert!(matches!(
                BlobUri::parse(&uri),
                Err(ResourceError::UnsupportedScheme { .. })
            ));
        }
    }

    #[test]
    fn rejects_extra_or_missing_segments() {
        let cid = blob_cid();
        for uri in [
            format!("atpmcp://public/blob/{DID}"),
            format!("atpmcp://public/blob/{DID}/{cid}/extra"),
            "atpmcp://public/blob".to_string(),
        ] {
            assert!(BlobUri::parse(&uri).is_err(), "should reject {uri}");
        }
    }

    #[test]
    fn rejects_a_query_or_fragment() {
        let cid = blob_cid();
        for uri in [
            format!("atpmcp://public/blob/{DID}/{cid}?download=1"),
            format!("atpmcp://public/blob/{DID}/{cid}#top"),
        ] {
            assert!(matches!(
                BlobUri::parse(&uri),
                Err(ResourceError::MalformedUri { .. })
            ));
        }
    }

    #[test]
    fn rejects_an_invalid_did() {
        let cid = blob_cid();
        for did in ["not-a-did", "did:unknown:abc", "alice.bsky.social"] {
            let uri = format!("atpmcp://public/blob/{did}/{cid}");
            assert!(BlobUri::parse(&uri).is_err(), "should reject did {did}");
        }
    }

    #[test]
    fn rejects_a_record_cid() {
        let uri = format!("atpmcp://public/blob/{DID}/{}", record_cid());
        let error = BlobUri::parse(&uri).expect_err("a dag-cbor CID is not a blob CID");
        assert!(error.to_string().contains("raw codec"));
    }

    #[test]
    fn rejects_a_cidv0() {
        // The canonical v0 form is base58 and starts with Qm.
        let uri =
            format!("atpmcp://public/blob/{DID}/QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR");
        assert!(BlobUri::parse(&uri).is_err());
    }

    #[test]
    fn rejects_a_non_canonical_cid_rendering() {
        // Upper-case base32 parses but is not the canonical form, and letting
        // it through would give one blob two cache keys.
        let cid = blob_cid().to_uppercase();
        let uri = format!("atpmcp://public/blob/{DID}/{cid}");
        assert!(BlobUri::parse(&uri).is_err());
    }

    #[test]
    fn errors_carry_the_uri_and_the_right_code() {
        let error = BlobUri::parse("atpmcp://public/blob/bad").unwrap_err();
        assert_eq!(error.code(), crate::proto::INVALID_PARAMS);
        assert_eq!(error.uri(), Some("atpmcp://public/blob/bad"));
    }

    #[test]
    fn supported_did_methods() {
        assert!(is_supported_did(DID));
        assert!(is_supported_did("did:web:example.com"));
        assert!(!is_supported_did("did:key:z6Mk"));
        assert!(!is_supported_did(""));
    }

    // -- Streamed, verified fetch: the three safety properties ----------

    use crate::tools::test_support::{
        one_shot_server, test_context, test_context_with_cache, test_request,
    };

    /// Everything currently in `dir`, for asserting a temp or final file was
    /// (or was not) left behind. A missing directory counts as empty.
    fn dir_entries(dir: &Path) -> Vec<String> {
        std::fs::read_dir(dir)
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .map(|entry| entry.file_name().to_string_lossy().to_string())
                    .collect()
            })
            .unwrap_or_default()
    }

    #[tokio::test]
    async fn a_fresh_fetch_streams_to_its_cache_path() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let body = b"a freshly fetched blob, never held in one buffer".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();
        let base_url = one_shot_server(200, body.clone(), true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid: cid.clone(),
            endpoint: Some(base_url),
        };

        let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect("fetch succeeds");

        assert!(!blob.cached);
        assert!(
            !blob.ephemeral,
            "a working cache should land the blob at its real path, not scratch"
        );
        assert_eq!(blob.size, body.len() as u64);
        assert_eq!(blob.path, ctx.cache.path_for(&cid).unwrap());
        assert_eq!(std::fs::read(&blob.path).unwrap(), body);

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// The finding: a cache hit was returned before `max_bytes` was looked
    /// at. The endpoint is unroutable, so the refusal cannot have come from a
    /// fetch: it is the hit itself that is held to the limit.
    #[tokio::test]
    async fn a_cache_hit_over_max_bytes_is_refused_like_a_fetch() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let body = vec![4u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();
        ctx.cache.put(&cid, &body, None).await.unwrap();

        let locator = Locator {
            did: DID.to_string(),
            cid: cid.clone(),
            endpoint: Some("https://127.0.0.1:1".to_string()),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("a hit over max_bytes must be refused");
        assert!(
            matches!(
                error,
                ToolError::BlobTooLarge {
                    size: 4096,
                    limit: 1024
                }
            ),
            "expected the exact size and the limit, got {error}"
        );

        // Refused, not evicted: the entry is still good for a caller whose
        // limit it fits.
        let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 4096)
            .await
            .expect("a hit within max_bytes is served");
        assert!(blob.cached);
        assert_eq!(blob.size, 4096);

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// Safety property: a mismatch deletes the partial file rather than
    /// leaving it, and the cache never gains an entry for it.
    #[tokio::test]
    async fn a_cid_mismatch_deletes_the_partial_file_and_leaves_no_cache_entry() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let served = b"bytes the server actually sends".to_vec();
        // A CID for different content, so whatever is served cannot match.
        let requested_cid =
            atproto_dasl::compute_raw_cid(b"a completely different blob").to_string();
        let base_url = one_shot_server(200, served, true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid: requested_cid.clone(),
            endpoint: Some(base_url),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("a mismatch must fail the fetch");
        assert!(
            matches!(error, ToolError::BlobCidMismatch { .. }),
            "expected BlobCidMismatch, got {error}"
        );

        let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
        assert_eq!(
            dir_entries(&dir),
            Vec::<String>::new(),
            "no partial or final file may survive a CID mismatch"
        );
        assert!(ctx.cache.get(&requested_cid).await.is_none());

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Safety property: the size bound is enforced against the running
    /// total, not merely against a peer-supplied `Content-Length` -- this
    /// server sends none, so only the write loop's own counter can catch it
    /// -- and tripping it deletes the partial file rather than filling the
    /// disk.
    #[tokio::test]
    async fn an_oversize_body_is_refused_on_the_running_total_and_leaves_no_partial_file() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let body = vec![7u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();
        let base_url = one_shot_server(200, body, false).await;

        let locator = Locator {
            did: DID.to_string(),
            cid,
            endpoint: Some(base_url),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("a body over max_bytes must be refused");
        // A lower bound, and said to be one: the read stopped at the chunk
        // that crossed the limit, so the blob's size was never learned. It
        // was `tool-13` with this count given as the size, so a caller could
        // retry with `max_bytes` set to it and be refused again.
        let message = error.to_string();
        match error {
            ToolError::BlobDownloadTooLarge { size, limit } => {
                assert_eq!(limit, 1024);
                assert!(size > limit, "the reported size must exceed the limit");
                assert!(size <= 4096, "and cannot exceed what was sent");
            }
            other => panic!("expected BlobDownloadTooLarge, got {other}"),
        }
        assert!(message.starts_with("error-atpmcp-tool-20 "), "{message}");
        assert!(message.contains("at least"), "{message}");

        let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
        assert_eq!(
            dir_entries(&dir),
            Vec::<String>::new(),
            "a size refusal must not leave a partial file behind to fill the disk"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The finding: a `400 {"error":"BlobNotFound"}` was hashed like a blob
    /// and reported as a CID mismatch, the alarm for a repository serving the
    /// wrong bytes. It is the status and the body now, and nothing is
    /// written.
    #[tokio::test]
    async fn an_error_status_is_reported_as_the_answer_and_never_hashed() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let cid = blob_cid();
        let base_url = one_shot_server(
            400,
            br#"{"error":"BlobNotFound","message":"Blob not found"}"#.to_vec(),
            true,
        )
        .await;

        let locator = Locator {
            did: DID.to_string(),
            cid: cid.clone(),
            endpoint: Some(base_url.clone()),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("an error answer is not the blob");
        match &error {
            ToolError::BlobErrorResponse {
                endpoint,
                status,
                body,
            } => {
                assert_eq!(endpoint, &base_url);
                assert_eq!(*status, 400);
                assert_eq!(
                    body,
                    r#"{"error":"BlobNotFound","message":"Blob not found"}"#
                );
            }
            other => panic!("expected BlobErrorResponse, got {other}"),
        }
        let message = error.to_string();
        assert!(message.starts_with("error-atpmcp-tool-19 "), "{message}");
        assert!(!message.contains("mismatch"), "{message}");

        let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
        assert_eq!(dir_entries(&dir), Vec::<String>::new());
        assert!(ctx.cache.get(&cid).await.is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A redirect comes back as the response, since the blob client follows
    /// none, and it was hashed like any other body. It is named instead.
    #[tokio::test]
    async fn a_redirect_is_named_and_never_hashed() {
        let ctx = test_context();
        let mut rctx = test_request();
        let base_url = one_shot_server(302, Vec::new(), true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid: blob_cid(),
            endpoint: Some(base_url),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("a redirect is not the blob");
        let ToolError::BlobErrorResponse { status, body, .. } = &error else {
            panic!("expected BlobErrorResponse, got {error}");
        };
        assert_eq!(*status, 302);
        assert!(body.contains("redirect"), "{body}");
        assert!(body.contains("not followed"), "{body}");
    }

    /// An error page larger than the transfer limit is still an error
    /// answer, not a blob too large to fetch, and only its start is quoted.
    #[tokio::test]
    async fn a_large_error_page_is_an_error_answer_quoted_in_part() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let mut page = b"<html><body>Bad Gateway".to_vec();
        page.resize(8192, b'x');
        let base_url = one_shot_server(502, page, true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid: blob_cid(),
            endpoint: Some(base_url),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("a 502 is not the blob");
        let ToolError::BlobErrorResponse { status, body, .. } = &error else {
            panic!("expected BlobErrorResponse, got {error}");
        };
        assert_eq!(*status, 502);
        assert!(body.starts_with("<html><body>Bad Gateway"), "{body}");
        assert!(body.ends_with("(truncated at 1024 bytes)"), "{body}");
        assert!(body.len() < 1024 + 64, "{} bytes quoted", body.len());

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// The companion case: a `Content-Length` that already exceeds the bound
    /// is refused before any file is created at all.
    #[tokio::test]
    async fn an_oversize_declared_content_length_is_refused_before_writing_anything() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let body = vec![9u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();
        let base_url = one_shot_server(200, body, true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid,
            endpoint: Some(base_url),
        };

        let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect_err("an over-declared Content-Length must be refused");
        // The peer's declaration, never verified: reported as a lower bound,
        // not as the blob's size.
        assert!(
            matches!(
                error,
                ToolError::BlobDownloadTooLarge {
                    size: 4096,
                    limit: 1024
                }
            ),
            "expected BlobDownloadTooLarge, got {error}"
        );
        assert!(error.to_string().contains("at least 4096 bytes"), "{error}");

        let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
        assert_eq!(dir_entries(&dir), Vec::<String>::new());
        let _ = std::fs::remove_dir_all(&dir);
    }

    // -- What the blob reference says: size and type (-04 §11.7, §11.8) ---

    /// A PNG long enough to be one, for the sniff.
    fn png() -> Vec<u8> {
        let mut data = vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52,
        ];
        data.extend_from_slice(&[1u8; 64]);
        data
    }

    fn expecting(size: Option<u64>, mime_type: Option<&str>) -> Expected {
        Expected {
            size,
            mime_type: mime_type.map(str::to_string),
        }
    }

    /// Fetch `body` from a one-shot server answering with `content_type`.
    async fn fetch_served(
        ctx: &Arc<ServerContext>,
        body: &[u8],
        declare_length: bool,
        content_type: Option<&str>,
        expected: &Expected,
    ) -> Result<VerifiedBlob, ToolError> {
        let base_url = crate::tools::test_support::one_shot_server_typed(
            200,
            body.to_vec(),
            declare_length,
            content_type,
        )
        .await;
        let locator = Locator {
            did: DID.to_string(),
            cid: atproto_dasl::compute_raw_cid(body).to_string(),
            endpoint: Some(base_url),
        };
        fetch(ctx, &mut test_request(), &locator, expected, 1024).await
    }

    /// The finding: an octet-stream answer was the blob's type, and was
    /// cached as it, so a PNG was not an image. It is sniffed now, and the
    /// sniffed type is what the cache records.
    #[tokio::test]
    async fn an_octet_stream_png_is_a_png_and_is_cached_as_one() {
        let ctx = test_context_with_cache();
        let data = png();
        let blob = fetch_served(
            &ctx,
            &data,
            true,
            Some("application/octet-stream"),
            &Expected::default(),
        )
        .await
        .expect("fetch succeeds");
        assert_eq!(blob.mime_type, "image/png");
        assert!(blob.mime_disagreement.is_none());
        drop(blob);

        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        let cached = ctx.cache.get(&cid).await.expect("cached");
        assert_eq!(cached.mime_type.as_deref(), Some("image/png"));

        let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
    }

    /// Bytes with no magic: the reference's type is the one used and cached,
    /// over the host's octet-stream, and over no Content-Type at all.
    #[tokio::test]
    async fn a_declared_type_is_used_and_cached_over_a_generic_one() {
        for served in [Some("application/octet-stream"), None] {
            let ctx = test_context_with_cache();
            let data = format!("plain text, served as {served:?}").into_bytes();
            let blob = fetch_served(
                &ctx,
                &data,
                true,
                served,
                &expecting(None, Some("text/plain")),
            )
            .await
            .expect("fetch succeeds");
            assert_eq!(blob.mime_type, "text/plain", "{served:?}");
            drop(blob);

            let cid = atproto_dasl::compute_raw_cid(&data).to_string();
            let cached = ctx.cache.get(&cid).await.expect("cached");
            assert_eq!(
                cached.mime_type.as_deref(),
                Some("text/plain"),
                "{served:?}"
            );
            let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
        }
    }

    /// A type the host names stands, and a declared one that disagrees is
    /// reported rather than refused.
    #[tokio::test]
    async fn a_specific_served_type_stands_and_a_disagreement_is_reported() {
        let ctx = test_context();
        let blob = fetch_served(
            &ctx,
            &png(),
            true,
            Some("image/webp"),
            &expecting(None, Some("image/png")),
        )
        .await
        .expect("a disagreement is not a refusal");
        assert_eq!(blob.mime_type, "image/webp");
        let note = blob.mime_disagreement.as_deref().expect("reported");
        assert!(note.contains("the host served 'image/webp'"), "{note}");
    }

    /// A cache entry that recorded octet-stream, as entries written before
    /// this did, is resolved as a served octet-stream is.
    #[tokio::test]
    async fn a_hit_that_recorded_octet_stream_is_sniffed() {
        let ctx = test_context_with_cache();
        let data = png();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache
            .put(&cid, &data, Some("application/octet-stream"))
            .await
            .unwrap();
        let locator = Locator {
            did: DID.to_string(),
            cid,
            endpoint: Some("https://127.0.0.1:1".to_string()),
        };
        let blob = fetch(
            &ctx,
            &mut test_request(),
            &locator,
            &Expected::default(),
            1024,
        )
        .await
        .expect("a hit");
        assert!(blob.cached);
        assert_eq!(blob.mime_type, "image/png");
        drop(blob);
        let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
    }

    /// A whole, verified blob shorter than the reference says is refused,
    /// and nothing of it is kept.
    #[tokio::test]
    async fn a_blob_shorter_than_its_declared_size_is_refused_and_discarded() {
        let ctx = test_context_with_cache();
        let data = b"forty-odd bytes of a blob with a wrong size".to_vec();
        let declared = data.len() as u64 + 10;
        let error = fetch_served(&ctx, &data, true, None, &expecting(Some(declared), None))
            .await
            .expect_err("a size mismatch is refused");
        match &error {
            ToolError::BlobSizeMismatch {
                declared: said,
                actual,
                at_least,
            } => {
                assert_eq!(*said, declared);
                assert_eq!(*actual, data.len() as u64);
                assert!(!at_least);
            }
            other => panic!("expected BlobSizeMismatch, got {other}"),
        }
        let message = error.to_string();
        assert!(message.starts_with("error-atpmcp-tool-22 "), "{message}");
        assert!(
            message.contains(&format!("the blob is {}", data.len())),
            "{message}"
        );

        let dir = ctx.cache.dir().unwrap().to_path_buf();
        assert_eq!(dir_entries(&dir), Vec::<String>::new());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Longer than declared: the read stops past the declared size, well
    /// under `max_bytes`, whether or not a `Content-Length` gave it away.
    #[tokio::test]
    async fn a_blob_longer_than_its_declared_size_is_refused_at_that_size() {
        for declare_length in [true, false] {
            let ctx = test_context_with_cache();
            let data = vec![5u8; 900];
            let error = fetch_served(
                &ctx,
                &data,
                declare_length,
                None,
                &expecting(Some(100), None),
            )
            .await
            .expect_err("a size mismatch is refused");
            let message = error.to_string();
            match error {
                ToolError::BlobSizeMismatch {
                    declared,
                    actual,
                    at_least,
                } => {
                    assert_eq!(declared, 100);
                    assert!(actual > 100, "{actual}");
                    assert!(at_least, "{declare_length}");
                }
                other => panic!("expected BlobSizeMismatch, got {other}"),
            }
            assert!(message.contains("the host sent at least"), "{message}");

            let dir = ctx.cache.dir().unwrap().to_path_buf();
            assert_eq!(dir_entries(&dir), Vec::<String>::new());
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    /// A blob of exactly the declared size is served.
    #[tokio::test]
    async fn a_blob_of_its_declared_size_is_served() {
        let ctx = test_context();
        let data = png();
        let blob = fetch_served(
            &ctx,
            &data,
            false,
            Some("image/png"),
            &expecting(Some(data.len() as u64), Some("image/png")),
        )
        .await
        .expect("fetch succeeds");
        assert_eq!(blob.size, data.len() as u64);
        assert!(blob.mime_disagreement.is_none());
    }

    /// A reference that declares more than `max_bytes` is refused before
    /// anything connects: the endpoint is unroutable.
    #[tokio::test]
    async fn a_declared_size_over_max_bytes_is_refused_before_fetching() {
        let ctx = test_context();
        let locator = Locator {
            did: DID.to_string(),
            cid: blob_cid(),
            endpoint: Some("https://127.0.0.1:1".to_string()),
        };
        let error = fetch(
            &ctx,
            &mut test_request(),
            &locator,
            &expecting(Some(4096), None),
            1024,
        )
        .await
        .expect_err("refused");
        assert!(
            matches!(
                error,
                ToolError::BlobTooLarge {
                    size: 4096,
                    limit: 1024
                }
            ),
            "{error}"
        );
    }

    /// A hit is held to the declared size too, and kept: its bytes are the
    /// CID's.
    #[tokio::test]
    async fn a_hit_of_another_size_is_refused_and_kept() {
        let ctx = test_context_with_cache();
        let data = vec![6u8; 64];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache.put(&cid, &data, None).await.unwrap();
        let locator = Locator {
            did: DID.to_string(),
            cid: cid.clone(),
            endpoint: Some("https://127.0.0.1:1".to_string()),
        };
        let error = fetch(
            &ctx,
            &mut test_request(),
            &locator,
            &expecting(Some(65), None),
            1024,
        )
        .await
        .expect_err("refused");
        assert!(
            matches!(
                error,
                ToolError::BlobSizeMismatch {
                    declared: 65,
                    actual: 64,
                    at_least: false
                }
            ),
            "{error}"
        );
        assert!(ctx.cache.get(&cid).await.is_some(), "the entry is kept");
        let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
    }

    /// A cache hit for `data`, as `fetch` returns it: verified, with the
    /// handle it was hashed through still open.
    async fn a_verified_hit(data: &[u8]) -> (Arc<ServerContext>, VerifiedBlob) {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();
        let cid = atproto_dasl::compute_raw_cid(data).to_string();
        ctx.cache.put(&cid, data, None).await.unwrap();
        let locator = Locator {
            did: DID.to_string(),
            cid,
            endpoint: Some("https://127.0.0.1:1".to_string()),
        };
        let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024 * 1024)
            .await
            .expect("a cache hit");
        assert!(blob.cached);
        (ctx, blob)
    }

    fn remove_cache(ctx: &Arc<ServerContext>) {
        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// The finding: the inline read opened `path` again, so a file replaced
    /// between verification and the read was inlined unverified. It reads
    /// through the verified handle now, which a rename does not redirect.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_file_replaced_after_verification_reads_back_as_the_verified_bytes() {
        let original = b"the bytes that were verified".to_vec();
        let (ctx, mut blob) = a_verified_hit(&original).await;

        let impostor = blob.path.with_extension("impostor");
        std::fs::write(&impostor, b"the bytes put there afterwards").unwrap();
        std::fs::rename(&impostor, &blob.path).unwrap();

        let data = blob.bytes().await.expect("the verified file is still open");
        assert_eq!(data, original, "never the bytes that replaced it");
        drop(blob);
        remove_cache(&ctx);
    }

    /// An eviction pass unlinks the oldest entries, which can include the one
    /// just verified. That turned a verified fetch into a read-back error; the
    /// open handle still reads it.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_file_removed_after_verification_still_reads_back() {
        let original = b"evicted between verification and the inline read".to_vec();
        let (ctx, mut blob) = a_verified_hit(&original).await;

        std::fs::remove_file(&blob.path).unwrap();

        let data = blob.bytes().await.expect("the verified file is still open");
        assert_eq!(data, original);
        drop(blob);
        remove_cache(&ctx);
    }

    /// The one change an open handle does see is the file rewritten in
    /// place. The read-back hashes what it read, so that is refused rather
    /// than inlined.
    #[tokio::test]
    async fn a_file_rewritten_in_place_after_verification_is_refused() {
        use std::io::Write as _;

        let original = b"the bytes that were verified".to_vec();
        let (ctx, mut blob) = a_verified_hit(&original).await;

        let mut tampered = original.clone();
        tampered[4] ^= 0x20;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .open(&blob.path)
            .unwrap();
        file.write_all(&tampered).unwrap();
        drop(file);

        let error = blob.bytes().await.expect_err("changed bytes are refused");
        assert!(
            matches!(&error, ToolError::BlobReadBackFailed { reason, .. } if reason.contains("hashes to")),
            "{error}"
        );
        assert!(
            error.to_string().starts_with("error-atpmcp-tool-21 "),
            "{error}"
        );
        drop(blob);
        remove_cache(&ctx);
    }

    /// Bytes appended in place are refused too, after reading one byte past
    /// the verified size rather than all of them: the read-back is bounded
    /// by what was verified, not by what the file has become.
    #[tokio::test]
    async fn a_file_grown_after_verification_is_refused_without_reading_it_all() {
        use std::io::Write as _;

        let original = b"the bytes that were verified".to_vec();
        let (ctx, mut blob) = a_verified_hit(&original).await;

        let mut file = std::fs::OpenOptions::new()
            .append(true)
            .open(&blob.path)
            .unwrap();
        file.write_all(&vec![0u8; 1024 * 1024]).unwrap();
        drop(file);

        let error = blob.bytes().await.expect_err("a grown file is refused");
        assert!(
            matches!(&error, ToolError::BlobReadBackFailed { reason, .. }
                if reason.contains(&format!("{} bytes", original.len()))),
            "{error}"
        );
        drop(blob);
        remove_cache(&ctx);
    }

    #[tokio::test]
    async fn a_disabled_cache_streams_to_a_scratch_file_cleaned_up_on_drop() {
        let ctx = test_context(); // cache disabled
        let mut rctx = test_request();
        let body = b"scratch-only blob".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();
        let base_url = one_shot_server(200, body.clone(), true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid,
            endpoint: Some(base_url),
        };

        let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect("fetch succeeds even with no persistent cache");
        assert!(blob.ephemeral);
        let path = blob.path.clone();
        assert!(
            path.exists(),
            "the scratch file exists while `blob` is alive"
        );
        assert_eq!(std::fs::read(&path).unwrap(), body);

        drop(blob);
        assert!(
            !path.exists(),
            "an ephemeral scratch file must not outlive its VerifiedBlob"
        );
    }

    /// `keep` is how `download_blob` reports a path with no cache to put the
    /// blob in: the verified scratch file outlives the value.
    #[tokio::test]
    async fn a_kept_scratch_file_outlives_its_verified_blob() {
        let ctx = test_context(); // cache disabled
        let mut rctx = test_request();
        let body = b"kept scratch blob".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();
        let base_url = one_shot_server(200, body.clone(), true).await;

        let locator = Locator {
            did: DID.to_string(),
            cid,
            endpoint: Some(base_url),
        };

        let mut blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
            .await
            .expect("fetch succeeds even with no persistent cache");
        assert!(blob.ephemeral);
        let path = blob.keep();
        assert!(!blob.ephemeral);
        drop(blob);

        assert_eq!(
            std::fs::read(&path).unwrap(),
            body,
            "a kept scratch file survives the drop with the verified bytes"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// A verified temp file in `ctx`'s cache directory holding `data`, and
    /// the open handle it was written through, as `stream_and_verify` has
    /// them once the hash matches.
    async fn a_verified_temp_file(
        ctx: &Arc<ServerContext>,
        data: &[u8],
    ) -> (String, crate::cache::WriteTarget, tokio::fs::File) {
        let cid = atproto_dasl::compute_raw_cid(data).to_string();
        let target = ctx
            .cache
            .prepare_write(&cid, None)
            .await
            .unwrap()
            .expect("a cache to write into");
        let chunks = futures::stream::iter(vec![Ok(bytes::Bytes::copy_from_slice(data))]);
        let (_, computed, file) = write_hashed(&target.temp_path, chunks, 1024 * 1024)
            .await
            .unwrap();
        assert_eq!(computed, cid);
        (cid, target, file)
    }

    /// A blob the cache will not keep moves out of the cache directory, and
    /// the handle it was verified through still reads it.
    #[tokio::test]
    async fn a_blob_moved_to_scratch_leaves_nothing_in_the_cache() {
        let ctx = test_context_with_cache();
        let data = b"moved out of the cache directory".to_vec();
        let (cid, target, file) = a_verified_temp_file(&ctx, &data).await;

        let (path, file) = move_to_scratch(&ctx, &target, &cid, file)
            .await
            .expect("moved");
        let dir = ctx.cache.dir().unwrap().to_path_buf();
        assert!(!path.starts_with(&dir), "{}", path.display());
        assert_eq!(std::fs::read(&path).unwrap(), data);
        assert_eq!(dir_entries(&dir), Vec::<String>::new());

        let mut blob = VerifiedBlob {
            path: path.clone(),
            size: data.len() as u64,
            mime_type: crate::mime::OCTET_STREAM.to_string(),
            mime_disagreement: None,
            cached: false,
            cid,
            file: Some(file),
            ephemeral: true,
        };
        assert_eq!(blob.bytes().await.unwrap(), data);
        drop(blob);
        assert!(
            !path.exists(),
            "an ephemeral scratch file goes with its value"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// When the rename fails, as it does across filesystems, the bytes are
    /// copied through the verified handle instead. Here the rename fails
    /// because the temp file has already been unlinked, which the open handle
    /// survives on Unix.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_blob_that_cannot_be_renamed_to_scratch_is_copied_through_its_handle() {
        let ctx = test_context_with_cache();
        let data = vec![3u8; 200_000];
        let (cid, target, file) = a_verified_temp_file(&ctx, &data).await;
        std::fs::remove_file(&target.temp_path).unwrap();

        let (path, mut file) = move_to_scratch(&ctx, &target, &cid, file)
            .await
            .expect("copied");
        assert_eq!(std::fs::read(&path).unwrap(), data);

        use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};
        let mut through_handle = Vec::new();
        file.rewind().await.unwrap();
        file.read_to_end(&mut through_handle).await.unwrap();
        assert_eq!(through_handle, data, "the handle returned is the copy's");

        let _ = std::fs::remove_file(&path);
        remove_cache(&ctx);
    }

    /// The copy is created exclusively, and a copy that does not hash to the
    /// CID is not kept.
    #[tokio::test]
    async fn a_copy_refuses_an_existing_path_and_one_that_does_not_verify() {
        let ctx = test_context_with_cache();
        let data = b"copied and hashed again".to_vec();
        let (cid, target, file) = a_verified_temp_file(&ctx, &data).await;

        let existing = scratch_path(&cid);
        std::fs::write(&existing, b"someone else's file").unwrap();
        let error = copy_verified(file, &existing, &cid)
            .await
            .expect_err("an existing path is refused");
        assert!(error.contains("could not create"), "{error}");
        assert_eq!(std::fs::read(&existing).unwrap(), b"someone else's file");
        let _ = std::fs::remove_file(&existing);

        let file = tokio::fs::File::open(&target.temp_path).await.unwrap();
        let other = atproto_dasl::compute_raw_cid(b"different bytes").to_string();
        let to = scratch_path(&other);
        let error = copy_verified(file, &to, &other)
            .await
            .expect_err("a copy that does not verify is refused");
        assert!(error.contains("hashes to"), "{error}");
        assert!(!to.exists(), "and deleted");
        remove_cache(&ctx);
    }

    /// The streamed write refuses a file already at its path instead of
    /// truncating it or following a symlink placed there.
    #[tokio::test]
    async fn a_streamed_write_refuses_an_existing_path() {
        let path = std::env::temp_dir().join(format!(
            "atpmcp-existing-{}-{}",
            std::process::id(),
            line!()
        ));
        std::fs::write(&path, b"someone else's file").unwrap();

        let chunks = futures::stream::iter(vec![Ok(bytes::Bytes::from_static(b"blob bytes"))]);
        let result = write_hashed(&path, chunks, 1024).await;

        assert!(result.is_err(), "an existing path must be refused");
        assert_eq!(
            std::fs::read(&path).unwrap(),
            b"someone else's file",
            "and left exactly as it was"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// Safety property, demonstrated directly rather than inferred: while a
    /// fetch is still streaming, nothing can read its bytes back from the
    /// cache's real path, because the rename into that name only happens
    /// after the hash is checked.
    #[tokio::test]
    async fn a_verified_fetch_is_not_visible_at_its_cache_path_before_it_completes() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let ctx = test_context_with_cache();
        let body = vec![5u8; 65536];
        let cid = atproto_dasl::compute_raw_cid(&body).to_string();

        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("addr");
        let server_body = body.clone();
        tokio::spawn(async move {
            let Ok((mut socket, _)) = listener.accept().await else {
                return;
            };
            let mut raw = Vec::new();
            let mut buffer = [0u8; 4096];
            loop {
                let Ok(read) = socket.read(&mut buffer).await else {
                    return;
                };
                if read == 0 {
                    break;
                }
                raw.extend_from_slice(&buffer[..read]);
                if raw.windows(4).any(|w| w == b"\r\n\r\n") {
                    break;
                }
            }
            let mut response = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n",
                server_body.len()
            );
            response.push_str("Connection: close\r\n\r\n");
            let _ = socket.write_all(response.as_bytes()).await;
            let (first, second) = server_body.split_at(server_body.len() / 2);
            let _ = socket.write_all(first).await;
            // A long stall relative to the check below, so ordinary
            // scheduling jitter cannot turn this into a false pass.
            tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
            let _ = socket.write_all(second).await;
            let _ = socket.shutdown().await;
        });

        let locator = Locator {
            did: DID.to_string(),
            cid: cid.clone(),
            endpoint: Some(format!("http://{addr}")),
        };

        let ctx_bg = Arc::clone(&ctx);
        let locator_bg = locator.clone();
        let handle = tokio::spawn(async move {
            let mut rctx = test_request();
            fetch(
                &ctx_bg,
                &mut rctx,
                &locator_bg,
                &Expected::default(),
                1024 * 1024,
            )
            .await
        });

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        assert!(
            ctx.cache
                .path_for(&cid)
                .filter(|path| path.exists())
                .is_none(),
            "an in-flight fetch must not be visible at its final cache path yet"
        );

        let result = handle.await.unwrap();
        assert!(
            result.is_ok(),
            "fetch should eventually succeed: {result:?}"
        );
        assert!(
            ctx.cache
                .path_for(&cid)
                .filter(|path| path.exists())
                .is_some(),
            "once complete, the verified blob must be at its real cache path"
        );

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}