zlayer-registry 0.14.3

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

use crate::error::{CacheError, RegistryError, Result};
use flate2::read::GzDecoder;
use std::collections::HashSet;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Cursor, Read};
use std::path::{Path, PathBuf};
use tar::Archive;

/// OCI layer media types
pub mod media_types {
    /// Uncompressed tar layer
    pub const TAR: &str = "application/vnd.oci.image.layer.v1.tar";
    /// Gzip compressed tar layer
    pub const TAR_GZIP: &str = "application/vnd.oci.image.layer.v1.tar+gzip";
    /// Zstd compressed tar layer
    pub const TAR_ZSTD: &str = "application/vnd.oci.image.layer.v1.tar+zstd";
    /// Docker gzip compressed layer (legacy)
    pub const DOCKER_TAR_GZIP: &str = "application/vnd.docker.image.rootfs.diff.tar.gzip";

    // Windows container layer media types.
    //
    // Windows base-OS layers are published as "foreign" / "nondistributable"
    // blobs hosted on mcr.microsoft.com. Unpacking them requires the
    // Windows-specific pipeline (wclayer / backup-stream / HCS) which lives in
    // `zlayer-agent`, *not* the Linux overlayfs+whiteouts flow in this module.
    // The constants are declared here so the rest of the registry can
    // recognize and classify them; see [`is_windows_layer`] for the matcher.

    /// Legacy Docker foreign-layer (gzip) — Windows base OS layers on MCR.
    pub const DOCKER_FOREIGN_TAR_GZIP: &str =
        "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip";
    /// OCI nondistributable layer, uncompressed tar (Windows).
    pub const OCI_NONDISTRIBUTABLE_TAR: &str =
        "application/vnd.oci.image.layer.nondistributable.v1.tar";
    /// OCI nondistributable layer, gzip compressed (Windows).
    pub const OCI_NONDISTRIBUTABLE_TAR_GZIP: &str =
        "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip";
    /// OCI nondistributable layer, zstd compressed (Windows).
    pub const OCI_NONDISTRIBUTABLE_TAR_ZSTD: &str =
        "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd";
}

/// Returns `true` if a layer media type is a recognized Linux tar layer
/// (overlayfs + whiteouts pipeline).
///
/// This covers both the modern OCI types and the legacy Docker v2.2 type.
/// It does *not* include Windows nondistributable/foreign layer types —
/// see [`is_windows_layer`] for that classification.
#[must_use]
pub fn is_linux_layer(media_type: &str) -> bool {
    matches!(
        media_type,
        media_types::TAR
            | media_types::TAR_GZIP
            | media_types::TAR_ZSTD
            | media_types::DOCKER_TAR_GZIP
    )
}

/// Returns `true` if a layer media type indicates a Windows container layer
/// (nondistributable / foreign).
///
/// Windows layers require a different unpack path (wclayer / backup-stream /
/// HCS) than the standard Linux tar+overlayfs flow this module implements.
/// Callers that receive a `true` here should route the blob to the
/// Windows-specific unpacker in `zlayer-agent` rather than invoking
/// [`LayerUnpacker::unpack_layer`].
#[must_use]
pub fn is_windows_layer(media_type: &str) -> bool {
    matches!(
        media_type,
        media_types::DOCKER_FOREIGN_TAR_GZIP
            | media_types::OCI_NONDISTRIBUTABLE_TAR
            | media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP
            | media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD
    )
}

/// Whiteout file prefix for deletions
const WHITEOUT_PREFIX: &str = ".wh.";
/// Opaque whiteout marker (delete entire directory contents)
const OPAQUE_WHITEOUT: &str = ".wh..wh..opq";

/// How the unpacker handles OCI whiteout entries.
///
/// OCI layers encode deletions as `.wh.<name>` (delete `<name>`) and
/// `.wh..wh..opq` (mark the containing dir opaque). The two unpack targets need
/// opposite behaviour:
///
/// - [`WhiteoutMode::Collapse`] — the legacy single-merged-tree path. All layers
///   are extracted into ONE directory, so a whiteout is applied immediately by
///   deleting the lower file from the merged tree. The merged tree is what a
///   container's full-copy rootfs has always been.
/// - [`WhiteoutMode::Preserve`] — the per-layer overlayfs lowerdir path. Each
///   layer is extracted into ITS OWN directory, so a whiteout must be PRESERVED
///   as an overlayfs whiteout (a `0:0` char device for a regular whiteout, the
///   `trusted.overlay.opaque="y"` xattr for an opaque one) for the kernel's
///   overlay driver to interpret at mount time — there is no lower file to
///   delete in a single-layer dir.
/// - [`WhiteoutMode::PreserveRootless`] — the per-layer lowerdir path for the
///   ROOTLESS `fuse-overlayfs` backend, which needs neither `CAP_MKNOD` nor
///   `CAP_SYS_ADMIN`. fuse-overlayfs reads two whiteout forms on every layer
///   (verified against `containers/fuse-overlayfs` 1.16 `src/overlay.rs` /
///   `src/whiteout.rs` / `src/xattr.rs`): a regular `.wh.<name>` file marks
///   `<name>` deleted, and the `user.overlay.opaque="y"` xattr (its
///   `UNPRIVILEGED_OPAQUE_XATTR`) marks a directory opaque. Both are settable by
///   an unprivileged process. So this mode writes a plain `.wh.<name>` file for
///   a regular whiteout and the `user.overlay.opaque` xattr for an opaque one,
///   instead of the privileged char-dev / `trusted.overlay.opaque` markers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WhiteoutMode {
    /// Apply whiteouts immediately by deleting from the merged tree.
    Collapse,
    /// Preserve whiteouts as kernel-overlay char-dev / `trusted.*`-opaque
    /// markers (needs `CAP_MKNOD` + `CAP_SYS_ADMIN`).
    Preserve,
    /// Preserve whiteouts the rootless `fuse-overlayfs` way: `.wh.<name>` files
    /// and the `user.overlay.opaque` xattr (no privilege required).
    PreserveRootless,
}

/// Compression type detection
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionType {
    /// No compression (plain tar)
    None,
    /// Gzip compression
    Gzip,
    /// Zstd compression
    Zstd,
}

impl CompressionType {
    /// Detect compression type from media type string
    /// Returns None if media type is unrecognized (caller should use magic bytes)
    #[must_use]
    pub fn from_media_type(media_type: &str) -> Option<Self> {
        match media_type {
            media_types::TAR_GZIP | media_types::DOCKER_TAR_GZIP => Some(Self::Gzip),
            media_types::TAR_ZSTD => Some(Self::Zstd),
            media_types::TAR => Some(Self::None),
            _ => None, // Unknown - caller should use detect() with actual data
        }
    }

    /// Detect compression type from magic bytes
    pub fn from_magic_bytes(data: &[u8]) -> Self {
        if data.len() < 4 {
            tracing::warn!(
                data_len = data.len(),
                "insufficient data for magic byte detection, assuming uncompressed tar"
            );
            return Self::None;
        }

        // Gzip magic: 0x1f 0x8b
        if data[0] == 0x1f && data[1] == 0x8b {
            return Self::Gzip;
        }

        // Zstd magic: 0x28 0xb5 0x2f 0xfd
        if data.len() >= 4
            && data[0] == 0x28
            && data[1] == 0xb5
            && data[2] == 0x2f
            && data[3] == 0xfd
        {
            return Self::Zstd;
        }

        Self::None
    }

    /// Detect compression, preferring media type but falling back to magic bytes
    pub fn detect(media_type: &str, data: &[u8]) -> Self {
        // First try media type
        if let Some(compression) = Self::from_media_type(media_type) {
            return compression;
        }
        // Fall back to magic bytes for unknown media types
        tracing::debug!(
            media_type = %media_type,
            "unrecognized media type, detecting compression from magic bytes"
        );
        Self::from_magic_bytes(data)
    }
}

/// Layer unpacker for extracting OCI layers to a rootfs
pub struct LayerUnpacker {
    /// Root filesystem directory
    rootfs_dir: PathBuf,
    /// Track deleted paths from whiteouts
    deleted_paths: HashSet<PathBuf>,
    /// Hard links whose target didn't exist yet when their entry was
    /// reached, retried after the rest of the layer has been extracted.
    /// Layer tars are NOT guaranteed to place a hard link's target before
    /// the link entry (buildah emits alphabetical ordering, so Fedora's
    /// `etc/pki/ca-trust/extracted/openssl/... -> .../pem/...` link comes
    /// FIRST) — failing immediately truncated the whole rootfs.
    /// `(link_path, link_target)` pairs, both absolute under `rootfs_dir`.
    pending_hardlinks: Vec<(PathBuf, PathBuf)>,
    /// Directory modes deferred until the end of the layer. A directory may
    /// be archived read-only (e.g. Fedora's `etc/pki/ca-trust/extracted`
    /// arrives mode `0o555`) yet still contain entries (symlinks, files,
    /// forward-referenced hard links) that appear LATER in the tar. Applying
    /// the archived mode immediately would make the dir unwritable and the
    /// child entries fail with `EACCES`. So directories are created `0o700`
    /// up front and their real mode is recorded here, then re-applied
    /// deepest-first by [`restore_dir_modes`] once everything is populated.
    /// `(dir_path, archived_mode)`, the path absolute under `rootfs_dir`.
    pending_dir_modes: Vec<(std::path::PathBuf, u32)>,
    /// Whether whiteouts collapse into the merged tree (legacy single-tree
    /// rootfs) or are preserved as overlayfs markers (per-layer lowerdir).
    whiteout_mode: WhiteoutMode,
}

impl LayerUnpacker {
    /// Create a new layer unpacker targeting the specified rootfs directory.
    ///
    /// Uses [`WhiteoutMode::Collapse`] — the legacy single-merged-tree
    /// behaviour where whiteouts delete from the merged rootfs. For the
    /// per-layer overlayfs lowerdir path use [`LayerUnpacker::new_for_overlay`].
    #[must_use]
    pub fn new(rootfs_dir: PathBuf) -> Self {
        Self::with_whiteout_mode(rootfs_dir, WhiteoutMode::Collapse)
    }

    /// Create a layer unpacker that PRESERVES whiteouts as overlayfs markers,
    /// for extracting a single layer into its own overlay `lowerdir`.
    ///
    /// See [`WhiteoutMode::Preserve`] and
    /// [`LayerUnpacker::unpack_layer_to_overlay_dir`].
    #[must_use]
    pub fn new_for_overlay(layer_dir: PathBuf) -> Self {
        Self::with_whiteout_mode(layer_dir, WhiteoutMode::Preserve)
    }

    /// Create a layer unpacker that PRESERVES whiteouts the ROOTLESS
    /// `fuse-overlayfs` way (`.wh.<name>` files + `user.overlay.opaque` xattr),
    /// for extracting a single layer into its own fuse-overlay `lowerdir`
    /// without `CAP_MKNOD` / `CAP_SYS_ADMIN`.
    ///
    /// See [`WhiteoutMode::PreserveRootless`] and
    /// [`LayerUnpacker::unpack_layer_to_overlay_dir_rootless`].
    #[must_use]
    pub fn new_for_overlay_rootless(layer_dir: PathBuf) -> Self {
        Self::with_whiteout_mode(layer_dir, WhiteoutMode::PreserveRootless)
    }

    /// Construct with an explicit [`WhiteoutMode`].
    #[must_use]
    pub fn with_whiteout_mode(rootfs_dir: PathBuf, whiteout_mode: WhiteoutMode) -> Self {
        Self {
            rootfs_dir,
            deleted_paths: HashSet::new(),
            pending_hardlinks: Vec::new(),
            pending_dir_modes: Vec::new(),
            whiteout_mode,
        }
    }

    /// Get the rootfs directory
    #[must_use]
    pub fn rootfs_dir(&self) -> &Path {
        &self.rootfs_dir
    }

    /// Unpack a single layer to the rootfs
    ///
    /// # Arguments
    /// * `layer_data` - The compressed or uncompressed layer data
    /// * `media_type` - The OCI media type of the layer
    ///
    /// # Errors
    /// Returns an error if decompression or extraction fails
    #[allow(clippy::unused_async)]
    pub async fn unpack_layer(&mut self, layer_data: &[u8], media_type: &str) -> Result<()> {
        // Ensure rootfs directory exists
        fs::create_dir_all(&self.rootfs_dir).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!("failed to create rootfs directory: {e}"),
            )))
        })?;

        // Detect compression type
        let compression = CompressionType::detect(media_type, layer_data);

        // Decompress and extract
        match compression {
            CompressionType::Gzip => self.unpack_gzip(layer_data),
            CompressionType::Zstd => self.unpack_zstd(layer_data),
            CompressionType::None => self.unpack_tar(layer_data),
        }
    }

    /// Unpack a single layer from a streaming reader, without buffering the
    /// whole (compressed) layer in memory.
    ///
    /// Compression is taken from `media_type` when recognized; otherwise the
    /// first bytes are peeked (via the internal [`BufReader`]) for magic-byte
    /// detection — no full read. The decompressed tar is streamed straight into
    /// the rootfs, so a multi-GB layer extracts with bounded RAM.
    ///
    /// # Errors
    /// Returns an error if the rootfs cannot be created, or decompression /
    /// extraction fails.
    pub fn unpack_layer_reader<R: Read>(&mut self, reader: R, media_type: &str) -> Result<()> {
        fs::create_dir_all(&self.rootfs_dir).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!("failed to create rootfs directory: {e}"),
            )))
        })?;

        let mut buffered = BufReader::new(reader);
        let compression = if let Some(c) = CompressionType::from_media_type(media_type) {
            c
        } else {
            // Peek the first bytes without consuming them.
            let magic = buffered.fill_buf().map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to read layer magic bytes: {e}"),
                )))
            })?;
            CompressionType::from_magic_bytes(magic)
        };

        self.extract_compressed(buffered, compression)
    }

    /// Extract ONE on-disk layer file into this unpacker's directory for use as
    /// an overlayfs `lowerdir`, PRESERVING whiteouts as overlay markers.
    ///
    /// Unlike [`unpack_layer_reader`] / [`unpack_layers_from_files`] (which merge
    /// a stack of layers into one tree and COLLAPSE whiteouts), this extracts a
    /// single layer in isolation: `.wh.<name>` becomes a `0:0` char device and
    /// `.wh..wh..opq` becomes the `trusted.overlay.opaque` xattr, so the kernel
    /// overlay driver — not this unpacker — resolves deletions at mount time.
    ///
    /// The unpacker MUST have been built with [`LayerUnpacker::new_for_overlay`]
    /// (i.e. [`WhiteoutMode::Preserve`]); a [`WhiteoutMode::Collapse`] unpacker
    /// is rejected, since collapsing into a single-layer dir would silently drop
    /// the deletion (no lower file exists to delete) and produce a wrong
    /// lowerdir. All of the merged path's safety still applies: the
    /// `var/run -> /run` relativization, `materialize_real_parent`, and
    /// `lremove_if_symlink` host-escape guards run identically here.
    ///
    /// File xattrs/capabilities the tar carries (e.g. `security.capability` set
    /// by `setcap`) are NOT preserved — only the file mode is applied, the same
    /// known gap the legacy full-copy merged path has had, so this is not a
    /// regression. Wave 2 / a follow-up can add full xattr passthrough in
    /// [`extract_file`] for both paths at once.
    ///
    /// Compression is taken from `media_type` (gzip/zstd/plain), falling back to
    /// magic-byte detection for unrecognized types. Linux-only (mknod + the
    /// `trusted.*` xattr need root / `CAP_MKNOD` + `CAP_SYS_ADMIN`).
    ///
    /// # Errors
    ///
    /// Returns an error if the unpacker is in collapse mode, the layer file
    /// cannot be opened or is empty, decompression / extraction fails, or a
    /// whiteout marker cannot be written (e.g. missing `CAP_MKNOD`).
    pub fn unpack_layer_to_overlay_dir(
        &mut self,
        layer_file: &Path,
        media_type: &str,
    ) -> Result<()> {
        if self.whiteout_mode != WhiteoutMode::Preserve {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "unpack_layer_to_overlay_dir requires a Preserve-mode unpacker \
                 (use LayerUnpacker::new_for_overlay)"
                    .to_string(),
            )));
        }

        let file = File::open(layer_file).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to open overlay layer file {}: {e}",
                    layer_file.display()
                ),
            )))
        })?;
        let len = file.metadata().map_or(0, |m| m.len());
        if len == 0 {
            return Err(RegistryError::Cache(CacheError::Corrupted(format!(
                "overlay layer file {} is empty",
                layer_file.display()
            ))));
        }

        // Reuse the streaming + safety pipeline; whiteout handling diverges via
        // `whiteout_mode` inside `extract_archive`.
        self.unpack_layer_reader(file, media_type)
    }

    /// Extract ONE on-disk layer file into this unpacker's directory for use as
    /// a ROOTLESS `fuse-overlayfs` `lowerdir`, preserving whiteouts the way
    /// fuse-overlayfs reads them WITHOUT privilege.
    ///
    /// Unlike [`unpack_layer_to_overlay_dir`](Self::unpack_layer_to_overlay_dir)
    /// (which needs `CAP_MKNOD` + `CAP_SYS_ADMIN` to write `0:0` char devices and
    /// the `trusted.overlay.opaque` xattr), this writes a plain `.wh.<name>`
    /// regular file for a regular whiteout and the `user.overlay.opaque="y"`
    /// xattr for an opaque directory — both settable by an unprivileged process,
    /// and both recognised by `fuse-overlayfs` on every layer (its
    /// `src/overlay.rs` scans for `.wh.<name>` files and `is_directory_opaque`
    /// checks `trusted.overlay.opaque` / `user.overlay.opaque` /
    /// `user.fuseoverlayfs.opaque` plus the `.wh..wh..opq` sentinel).
    ///
    /// The unpacker MUST have been built with
    /// [`LayerUnpacker::new_for_overlay_rootless`] (i.e.
    /// [`WhiteoutMode::PreserveRootless`]). All of the merged path's safety still
    /// applies identically: the `var/run -> /run` relativization,
    /// `materialize_real_parent`, and `lremove_if_symlink` host-escape guards.
    ///
    /// File xattrs/capabilities the tar carries are NOT preserved (same known gap
    /// as the kernel `Preserve` and legacy full-copy paths). Compression is taken
    /// from `media_type`, falling back to magic-byte detection.
    ///
    /// # Errors
    ///
    /// Returns an error if the unpacker is not in `PreserveRootless` mode, the
    /// layer file cannot be opened or is empty, decompression / extraction fails,
    /// or a whiteout marker cannot be written.
    pub fn unpack_layer_to_overlay_dir_rootless(
        &mut self,
        layer_file: &Path,
        media_type: &str,
    ) -> Result<()> {
        if self.whiteout_mode != WhiteoutMode::PreserveRootless {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "unpack_layer_to_overlay_dir_rootless requires a PreserveRootless-mode \
                 unpacker (use LayerUnpacker::new_for_overlay_rootless)"
                    .to_string(),
            )));
        }

        let file = File::open(layer_file).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to open rootless overlay layer file {}: {e}",
                    layer_file.display()
                ),
            )))
        })?;
        let len = file.metadata().map_or(0, |m| m.len());
        if len == 0 {
            return Err(RegistryError::Cache(CacheError::Corrupted(format!(
                "rootless overlay layer file {} is empty",
                layer_file.display()
            ))));
        }

        // Reuse the streaming + safety pipeline; whiteout handling diverges via
        // `whiteout_mode` inside `extract_archive`.
        self.unpack_layer_reader(file, media_type)
    }

    /// Unpack multiple on-disk layer files in order (base layer first),
    /// streaming each file so no layer is ever fully held in RAM.
    ///
    /// # Errors
    ///
    /// Returns an error if a layer file cannot be opened, a layer is empty,
    /// decompression fails, extraction fails, or the rootfs ends up empty.
    #[allow(clippy::unused_async)]
    pub async fn unpack_layers_from_files(&mut self, layers: &[(PathBuf, String)]) -> Result<()> {
        if layers.is_empty() {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "no layers to unpack".to_string(),
            )));
        }

        for (i, (path, media_type)) in layers.iter().enumerate() {
            let file = File::open(path).map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to open layer {i} file {}: {e}", path.display()),
                )))
            })?;

            // Validate layer is not empty (mirrors the in-memory path).
            let len = file.metadata().map_or(0, |m| m.len());
            if len == 0 {
                return Err(RegistryError::Cache(CacheError::Corrupted(format!(
                    "layer {i} is empty"
                ))));
            }

            tracing::debug!(
                layer = i,
                media_type = %media_type,
                size = len,
                "unpacking layer (streamed from file)"
            );
            self.unpack_layer_reader(file, media_type)?;
        }

        // Validate rootfs has content after all layers.
        if !self.rootfs_has_content() {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "rootfs empty after unpacking all layers".to_string(),
            )));
        }

        Ok(())
    }

    /// Unpack multiple layers in order (base layer first)
    ///
    /// # Errors
    ///
    /// Returns an error if any layer is empty, decompression fails, or extraction fails.
    pub async fn unpack_layers(&mut self, layers: &[(Vec<u8>, String)]) -> Result<()> {
        if layers.is_empty() {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "no layers to unpack".to_string(),
            )));
        }

        for (i, (data, media_type)) in layers.iter().enumerate() {
            // Validate layer data is not empty
            if data.is_empty() {
                return Err(RegistryError::Cache(CacheError::Corrupted(format!(
                    "layer {i} is empty"
                ))));
            }

            tracing::debug!(
                layer = i,
                media_type = %media_type,
                size = data.len(),
                "unpacking layer"
            );
            self.unpack_layer(data, media_type).await?;
        }

        // Validate rootfs has content after all layers
        if !self.rootfs_has_content() {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "rootfs empty after unpacking all layers".to_string(),
            )));
        }

        Ok(())
    }

    /// Check if the rootfs directory has any content
    fn rootfs_has_content(&self) -> bool {
        if let Ok(mut entries) = std::fs::read_dir(&self.rootfs_dir) {
            return entries.next().is_some();
        }
        false
    }

    /// Unpack a gzip-compressed tar archive
    fn unpack_gzip(&mut self, data: &[u8]) -> Result<()> {
        self.extract_compressed(Cursor::new(data), CompressionType::Gzip)
    }

    /// Unpack a zstd-compressed tar archive
    fn unpack_zstd(&mut self, data: &[u8]) -> Result<()> {
        self.extract_compressed(Cursor::new(data), CompressionType::Zstd)
    }

    /// Unpack an uncompressed tar archive
    fn unpack_tar(&mut self, data: &[u8]) -> Result<()> {
        self.extract_compressed(Cursor::new(data), CompressionType::None)
    }

    /// Decompress a tar stream per `compression` and extract it into the rootfs.
    /// Shared by the in-memory (`&[u8]`) and streaming (`impl Read`) paths.
    fn extract_compressed<R: Read>(
        &mut self,
        reader: R,
        compression: CompressionType,
    ) -> Result<()> {
        match compression {
            CompressionType::Gzip => {
                let mut archive = Archive::new(GzDecoder::new(reader));
                self.extract_archive(&mut archive)
            }
            CompressionType::Zstd => {
                let decoder = zstd::stream::Decoder::new(reader).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("zstd decompression failed: {e}"),
                    )))
                })?;
                let mut archive = Archive::new(decoder);
                self.extract_archive(&mut archive)
            }
            CompressionType::None => {
                let mut archive = Archive::new(reader);
                self.extract_archive(&mut archive)
            }
        }
    }

    /// Extract files from a tar archive, handling whiteouts
    fn extract_archive<R: Read>(&mut self, archive: &mut Archive<R>) -> Result<()> {
        let entries = archive.entries().map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!("failed to read tar entries: {e}"),
            )))
        })?;

        for entry in entries {
            let mut entry = entry.map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to read tar entry: {e}"),
                )))
            })?;

            let path = entry.path().map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to get entry path: {e}"),
                )))
            })?;
            let path = path.to_path_buf();

            // Security: Validate path doesn't escape rootfs
            if !self.is_safe_path(&path) {
                tracing::warn!(path = %path.display(), "skipping potentially unsafe path");
                continue;
            }

            let file_name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or_default();

            // Handle opaque whiteout.
            if file_name == OPAQUE_WHITEOUT {
                if let Some(parent) = path.parent() {
                    match self.whiteout_mode {
                        WhiteoutMode::Collapse => self.apply_opaque_whiteout(parent)?,
                        WhiteoutMode::Preserve => self.preserve_opaque_whiteout(parent)?,
                        WhiteoutMode::PreserveRootless => {
                            self.preserve_opaque_whiteout_rootless(parent)?;
                        }
                    }
                }
                continue;
            }

            // Handle regular whiteout `.wh.<name>`.
            if let Some(target_name) = file_name.strip_prefix(WHITEOUT_PREFIX) {
                if let Some(parent) = path.parent() {
                    match self.whiteout_mode {
                        WhiteoutMode::Collapse => {
                            let target_path = parent.join(target_name);
                            self.apply_whiteout(&target_path)?;
                        }
                        WhiteoutMode::Preserve => {
                            self.preserve_whiteout(parent, target_name)?;
                        }
                        WhiteoutMode::PreserveRootless => {
                            self.preserve_whiteout_rootless(parent, target_name)?;
                        }
                    }
                }
                continue;
            }

            // Skip if this path was deleted by a whiteout
            let full_path = self.rootfs_dir.join(&path);
            if self.is_deleted(&path) {
                continue;
            }

            // Extract the entry
            self.extract_entry(&mut entry, &full_path)?;
        }

        self.resolve_pending_hardlinks()?;
        // Re-apply deferred (possibly read-only) directory modes LAST, after
        // every file / symlink / hard link inside them has been written.
        self.restore_dir_modes()
    }

    /// Retry hard links whose target hadn't been extracted yet when their
    /// entry was reached. A target that STILL doesn't exist after the whole
    /// layer is on disk is a hard error — silently skipping is how a
    /// truncated rootfs used to masquerade as a successful unpack.
    fn resolve_pending_hardlinks(&mut self) -> Result<()> {
        for (link_path, target_full) in std::mem::take(&mut self.pending_hardlinks) {
            fs::hard_link(&target_full, &link_path).map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!(
                        "failed to create deferred hard link {} -> {} \
                         (target absent after full layer extraction): {}",
                        link_path.display(),
                        target_full.display(),
                        e
                    ),
                )))
            })?;
        }
        Ok(())
    }

    /// Re-apply directory modes that were deferred during extraction.
    ///
    /// Directories are created `0o700` so their (possibly later) children can
    /// be written; their archived mode — which may be read-only, e.g. Fedora's
    /// `0o555` ca-trust dirs — is recorded and re-applied here, after the
    /// whole layer is on disk. Modes are applied DEEPEST-FIRST (longest path
    /// component count first): restoring a parent to read-only must never
    /// block writing a still-pending child, and since this runs after all
    /// entries are extracted, going deepest-first keeps each parent writable
    /// until its descendants are sealed.
    ///
    /// The `Result<()>`/no-op shape mirrors [`set_permissions`]: load-bearing
    /// on Unix, a pure no-op on non-Unix.
    #[allow(clippy::unnecessary_wraps)]
    fn restore_dir_modes(&mut self) -> Result<()> {
        let mut pending = std::mem::take(&mut self.pending_dir_modes);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            // Deepest-first: more path components => applied earlier.
            pending.sort_by_key(|b| std::cmp::Reverse(b.0.components().count()));

            for (dir_path, mode) in pending {
                let permissions = fs::Permissions::from_mode(mode);
                fs::set_permissions(&dir_path, permissions).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!(
                            "failed to restore deferred directory mode {:o} on {}: {}",
                            mode,
                            dir_path.display(),
                            e
                        ),
                    )))
                })?;
            }
        }

        #[cfg(not(unix))]
        {
            let _ = &mut pending;
        }

        Ok(())
    }

    /// Validate that a path doesn't escape the rootfs directory
    #[allow(clippy::unused_self)]
    fn is_safe_path(&self, path: &Path) -> bool {
        use std::path::Component;

        // Reject platform-absolute paths (drive-letter on Windows, `/` on Unix).
        if path.is_absolute() {
            return false;
        }

        // Reject POSIX root-prefixed paths even on Windows — container tar
        // layers carry `/etc/passwd`-style paths, and those must still be
        // treated as root-escaping regardless of the host path semantics.
        let mut components = path.components();
        if matches!(
            components.next(),
            Some(Component::RootDir | Component::Prefix(_))
        ) {
            return false;
        }

        // Reject paths with .. components anywhere.
        for component in path.components() {
            if matches!(component, Component::ParentDir) {
                return false;
            }
        }

        true
    }

    /// Check if a path has been marked as deleted
    fn is_deleted(&self, path: &Path) -> bool {
        // Check if this exact path or any parent is deleted
        let mut current = path.to_path_buf();
        loop {
            if self.deleted_paths.contains(&current) {
                return true;
            }
            if !current.pop() {
                break;
            }
        }
        false
    }

    /// Apply a regular whiteout (delete a specific file or directory)
    fn apply_whiteout(&mut self, path: &Path) -> Result<()> {
        let full_path = self.rootfs_dir.join(path);
        self.deleted_paths.insert(path.to_path_buf());

        // Symlink-safe delete: a whiteout of `var/run` (a `-> /run` symlink) must
        // unlink the LINK, never `remove_dir_all` through it into the host. The
        // old `is_dir()` branch followed symlinks; `remove_path_no_follow` lstats.
        zlayer_paths::safe_fs::remove_path_no_follow(&full_path).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to remove whiteout target {}: {}",
                    full_path.display(),
                    e
                ),
            )))
        })?;

        Ok(())
    }

    /// Apply an opaque whiteout (delete all contents in a directory)
    fn apply_opaque_whiteout(&mut self, dir_path: &Path) -> Result<()> {
        let full_path = self.rootfs_dir.join(dir_path);

        // Only enumerate a REAL directory. If `full_path` is a symlink, `is_dir()`
        // would follow it and we'd `read_dir`/delete inside the link target (the
        // host). `lstat` (symlink_metadata) keeps us inside the rootfs.
        let is_real_dir = std::fs::symlink_metadata(&full_path).is_ok_and(|md| md.is_dir());
        if is_real_dir {
            // Remove all contents but keep the directory
            for entry in fs::read_dir(&full_path).map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to read directory {}: {}", full_path.display(), e),
                )))
            })? {
                let entry = entry.map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to read directory entry: {e}"),
                    )))
                })?;
                let entry_path = entry.path();
                let relative = entry_path
                    .strip_prefix(&self.rootfs_dir)
                    .unwrap_or(&entry_path);
                self.deleted_paths.insert(relative.to_path_buf());

                // Symlink-safe: unlink a symlinked child, never traverse it.
                zlayer_paths::safe_fs::remove_path_no_follow(&entry_path).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to remove {}: {}", entry_path.display(), e),
                    )))
                })?;
            }
        }

        Ok(())
    }

    /// Preserve a regular whiteout `.wh.<name>` as an overlayfs whiteout: a
    /// `0:0` character device named `<name>` in the (real, in-rootfs) parent.
    ///
    /// This is the per-layer-lowerdir counterpart of [`apply_whiteout`]: there
    /// is no merged lower file to delete in a single-layer dir, so the deletion
    /// is recorded the way the kernel's overlay driver reads it — an opaque
    /// `0:0` char device at the whited-out name shadows whatever a lower layer
    /// provides at the same path. Requires `CAP_MKNOD` (root); Linux-only.
    #[cfg(target_os = "linux")]
    fn preserve_whiteout(&mut self, parent: &Path, target_name: &str) -> Result<()> {
        use nix::sys::stat::{makedev, mknod, Mode, SFlag};

        let parent_full = self.rootfs_dir.join(parent);
        // The parent dir of the whiteout may not have been created yet in this
        // single layer (e.g. a tar that only deletes `foo/bar` ships only the
        // `.wh.bar` entry under `foo/`). Materialize a real in-rootfs parent so
        // the char device cannot be created through an escaping symlink.
        let target_full = parent_full.join(target_name);
        zlayer_paths::safe_fs::materialize_real_parent(&self.rootfs_dir, &target_full).map_err(
            |e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!(
                        "failed to materialize parent for whiteout {}: {}",
                        target_full.display(),
                        e
                    ),
                )))
            },
        )?;
        // Drop any pre-existing entry (file/dir/symlink) at the whiteout name so
        // the char device replaces it. lstat-based, never follows a symlink out.
        zlayer_paths::safe_fs::remove_path_no_follow(&target_full).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to clear whiteout target {}: {}",
                    target_full.display(),
                    e
                ),
            )))
        })?;

        mknod(&target_full, SFlag::S_IFCHR, Mode::empty(), makedev(0, 0)).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::other(format!(
                "failed to mknod overlay whiteout 0:0 char device at {} (needs CAP_MKNOD): {}",
                target_full.display(),
                e
            ))))
        })?;

        Ok(())
    }

    /// Preserve a regular whiteout — non-Linux stub. mknod of a `0:0` char
    /// device is a Linux+root operation; the overlay rootfs path only runs on
    /// Linux, so this is unreachable elsewhere and errors loudly if hit.
    #[cfg(not(target_os = "linux"))]
    #[allow(clippy::unused_self)] // `&mut self` kept for parity with the cfg(linux) variant
    fn preserve_whiteout(&mut self, _parent: &Path, _target_name: &str) -> Result<()> {
        Err(RegistryError::Cache(CacheError::Corrupted(
            "overlay whiteout preservation is only supported on Linux".to_string(),
        )))
    }

    /// Preserve an opaque whiteout `.wh..wh..opq` as the overlayfs
    /// `trusted.overlay.opaque="y"` xattr on the containing directory.
    ///
    /// The per-layer-lowerdir counterpart of [`apply_opaque_whiteout`]: instead
    /// of emptying a merged dir, set the xattr the kernel reads to mean "this
    /// dir fully masks all lower layers' versions of the same dir". Setting a
    /// `trusted.*` xattr requires `CAP_SYS_ADMIN` (root); Linux-only.
    #[cfg(target_os = "linux")]
    fn preserve_opaque_whiteout(&mut self, dir_path: &Path) -> Result<()> {
        let full_path = self.rootfs_dir.join(dir_path);
        // Ensure the directory the opaque marker applies to actually exists as a
        // real dir inside the rootfs (a layer can ship `<dir>/.wh..wh..opq`
        // without a separate `<dir>/` entry).
        fs::create_dir_all(&full_path).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to create opaque-whiteout dir {}: {}",
                    full_path.display(),
                    e
                ),
            )))
        })?;

        xattr::set(&full_path, "trusted.overlay.opaque", b"y").map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to set trusted.overlay.opaque on {} (needs CAP_SYS_ADMIN): {}",
                    full_path.display(),
                    e
                ),
            )))
        })?;

        Ok(())
    }

    /// Preserve an opaque whiteout — non-Linux stub (see [`preserve_whiteout`]).
    #[cfg(not(target_os = "linux"))]
    #[allow(clippy::unused_self)] // `&mut self` kept for parity with the cfg(linux) variant
    fn preserve_opaque_whiteout(&mut self, _dir_path: &Path) -> Result<()> {
        Err(RegistryError::Cache(CacheError::Corrupted(
            "overlay opaque-whiteout preservation is only supported on Linux".to_string(),
        )))
    }

    /// Preserve a regular whiteout `.wh.<name>` the ROOTLESS way: write a plain
    /// empty `.wh.<name>` regular file in the (real, in-rootfs) parent.
    ///
    /// The unprivileged counterpart of [`preserve_whiteout`](Self::preserve_whiteout):
    /// `fuse-overlayfs` recognises a `.wh.<name>` regular file on a lower layer
    /// as a deletion of `<name>` (its `src/overlay.rs` checks for exactly this
    /// file during readdir), so no `mknod`/`CAP_MKNOD` is needed. The same
    /// host-escape guards as the privileged path run first: a real in-rootfs
    /// parent is materialized (replacing any escaping symlink component) and any
    /// pre-existing entry at the whiteout name is lstat-removed.
    fn preserve_whiteout_rootless(&mut self, parent: &Path, target_name: &str) -> Result<()> {
        let parent_full = self.rootfs_dir.join(parent);
        let target_full = parent_full.join(target_name);
        // Materialize a real in-rootfs parent so the `.wh.` file cannot be
        // created through an escaping symlink.
        zlayer_paths::safe_fs::materialize_real_parent(&self.rootfs_dir, &target_full).map_err(
            |e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!(
                        "failed to materialize parent for rootless whiteout {}: {}",
                        target_full.display(),
                        e
                    ),
                )))
            },
        )?;
        // Drop any pre-existing entry (file/dir/symlink) at the whiteout name so
        // the `.wh.` marker is unambiguous. lstat-based, never follows a symlink.
        zlayer_paths::safe_fs::remove_path_no_follow(&target_full).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to clear rootless whiteout target {}: {}",
                    target_full.display(),
                    e
                ),
            )))
        })?;

        // The `.wh.<name>` marker is a sibling of `<name>` in the same parent.
        let wh_name = format!("{WHITEOUT_PREFIX}{target_name}");
        let wh_full = parent_full.join(&wh_name);
        File::create(&wh_full).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to create rootless .wh. whiteout file {}: {}",
                    wh_full.display(),
                    e
                ),
            )))
        })?;

        Ok(())
    }

    /// Preserve an opaque whiteout `.wh..wh..opq` the ROOTLESS way: set the
    /// `user.overlay.opaque="y"` xattr on the containing directory.
    ///
    /// The unprivileged counterpart of
    /// [`preserve_opaque_whiteout`](Self::preserve_opaque_whiteout): instead of
    /// the `CAP_SYS_ADMIN`-only `trusted.overlay.opaque`, set fuse-overlayfs's
    /// `UNPRIVILEGED_OPAQUE_XATTR` (`user.overlay.opaque`), which lives in the
    /// user xattr namespace and so is settable without privilege.
    /// fuse-overlayfs's `is_directory_opaque` checks this name. Also drops a
    /// `.wh..wh..opq` sentinel file as a belt-and-suspenders fallback (the same
    /// sentinel fuse-overlayfs falls back to when no opaque xattr is present),
    /// so the marker survives even on a backing filesystem that silently rejects
    /// `user.*` xattrs.
    fn preserve_opaque_whiteout_rootless(&mut self, dir_path: &Path) -> Result<()> {
        let full_path = self.rootfs_dir.join(dir_path);
        fs::create_dir_all(&full_path).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!(
                    "failed to create rootless opaque-whiteout dir {}: {}",
                    full_path.display(),
                    e
                ),
            )))
        })?;

        // Primary marker: the user-namespace opaque xattr fuse-overlayfs reads.
        // The `xattr` crate is a Linux-only dependency and fuse-overlayfs is
        // itself Linux-only, so on other targets we skip the xattr and rely
        // solely on the `.wh..wh..opq` sentinel file written below.
        #[cfg(target_os = "linux")]
        let xattr_ok = xattr::set(&full_path, "user.overlay.opaque", b"y").is_ok();
        #[cfg(not(target_os = "linux"))]
        let xattr_ok = false;

        // Fallback marker: the OCI `.wh..wh..opq` sentinel file. fuse-overlayfs
        // treats a directory containing this file as opaque too, so writing it
        // keeps the deletion correct even when the backing fs drops user xattrs.
        let sentinel = full_path.join(OPAQUE_WHITEOUT);
        let sentinel_ok = File::create(&sentinel).is_ok();

        if xattr_ok || sentinel_ok {
            Ok(())
        } else {
            Err(RegistryError::Cache(CacheError::Io(std::io::Error::other(
                format!(
                    "failed to mark rootless opaque whiteout on {} \
                     (both user.overlay.opaque xattr and .wh..wh..opq sentinel failed)",
                    full_path.display()
                ),
            ))))
        }
    }

    /// Extract a single tar entry to the filesystem
    #[allow(clippy::too_many_lines)]
    fn extract_entry<R: Read>(
        &mut self,
        entry: &mut tar::Entry<'_, R>,
        full_path: &Path,
    ) -> Result<()> {
        let entry_type = entry.header().entry_type();

        // SECURITY (host-escape via rootfs symlink): `is_safe_path` only checks
        // the LOGICAL tar path for `..`/absolute — it does NOT resolve symlinks
        // already written to disk. A layer can ship the standard
        // `var/run -> /run` symlink and then an entry under `var/run/...`; the
        // create/write/chmod below would then follow the link onto the HOST's
        // `/run` and (e.g.) chmod `/run/sshd` group-writable, wedging sshd.
        // Force every parent component to be a real directory INSIDE the rootfs
        // (replacing any symlinked component), and drop a pre-existing symlink at
        // the target itself so the write/chmod can't traverse it.
        zlayer_paths::safe_fs::materialize_real_parent(&self.rootfs_dir, full_path).map_err(
            |e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!(
                        "failed to materialize safe parent for {}: {}",
                        full_path.display(),
                        e
                    ),
                )))
            },
        )?;
        zlayer_paths::safe_fs::lremove_if_symlink(full_path).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!("failed to clear symlink at {}: {}", full_path.display(), e),
            )))
        })?;

        match entry_type {
            tar::EntryType::Regular | tar::EntryType::Continuous => {
                self.extract_file(entry, full_path)?;
            }
            tar::EntryType::Directory => {
                fs::create_dir_all(full_path).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to create directory {}: {}", full_path.display(), e),
                    )))
                })?;
                // DEFER the archived mode. A directory may be archived
                // read-only (Fedora's `etc/pki/ca-trust/...` arrives `0o555`)
                // yet still hold child entries that appear later in the tar.
                // Force it to a permissive `0o700` now so those children can
                // be written, and record the real mode to re-apply at the end
                // via `restore_dir_modes`. Idempotent across layers: an
                // earlier layer may have already created and left this dir at
                // `0o555`, so unconditionally force it back to `0o700`.
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;

                    let writable = fs::Permissions::from_mode(0o700);
                    fs::set_permissions(full_path, writable).map_err(|e| {
                        RegistryError::Cache(CacheError::Io(std::io::Error::new(
                            e.kind(),
                            format!(
                                "failed to make directory writable {}: {}",
                                full_path.display(),
                                e
                            ),
                        )))
                    })?;

                    if let Ok(archived_mode) = entry.header().mode() {
                        self.pending_dir_modes
                            .push((full_path.to_path_buf(), archived_mode));
                    }
                }
                #[cfg(not(unix))]
                {
                    self.set_permissions(entry, full_path)?;
                }
            }
            tar::EntryType::Symlink => {
                if let Ok(Some(target)) = entry.link_name() {
                    // Remove existing file/link if present
                    let _ = fs::remove_file(full_path);
                    #[cfg(unix)]
                    {
                        // Relativize an ABSOLUTE target so the unpacked rootfs
                        // stays self-contained. The standard `var/run -> /run`
                        // (absolute) lets any host-context filesystem op — a
                        // pre-pivot permissions/dir walk, the runtime's mount
                        // setup — follow the link onto the HOST's `/run`,
                        // chmod'ing host `/run`/`/run/sshd` (locks out
                        // systemd-resolved/-networkd, wedges host SSH). A
                        // relative `../run` resolves identically inside the
                        // container (post-pivot `/` IS the rootfs) but can
                        // never escape the rootfs. See
                        // `zlayer_paths::safe_fs::relativize_abs_symlink`.
                        let link_target: PathBuf = if target.is_absolute() {
                            full_path
                                .strip_prefix(&self.rootfs_dir)
                                .ok()
                                .and_then(|rel| {
                                    zlayer_paths::safe_fs::relativize_abs_symlink(rel, &target)
                                })
                                .unwrap_or_else(|| target.to_path_buf())
                        } else {
                            target.to_path_buf()
                        };
                        std::os::unix::fs::symlink(&link_target, full_path).map_err(|e| {
                            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                                e.kind(),
                                format!(
                                    "failed to create symlink {} -> {}: {}",
                                    full_path.display(),
                                    link_target.display(),
                                    e
                                ),
                            )))
                        })?;
                    }
                    #[cfg(not(unix))]
                    {
                        // On non-Unix, try to copy the file or create a placeholder
                        tracing::warn!(
                            path = %full_path.display(),
                            target = %target.display(),
                            "symlinks not fully supported on this platform"
                        );
                    }
                }
            }
            tar::EntryType::Link => {
                if let Ok(Some(target)) = entry.link_name() {
                    let target_full = self.rootfs_dir.join(&*target);
                    // Remove existing file if present
                    let _ = fs::remove_file(full_path);
                    if target_full.exists() {
                        fs::hard_link(&target_full, full_path).map_err(|e| {
                            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                                e.kind(),
                                format!(
                                    "failed to create hard link {} -> {}: {}",
                                    full_path.display(),
                                    target_full.display(),
                                    e
                                ),
                            )))
                        })?;
                    } else {
                        // Forward reference: the link's target appears later
                        // in this layer (tar entry order is not guaranteed).
                        // Defer and retry once the whole layer is extracted.
                        self.pending_hardlinks
                            .push((full_path.to_path_buf(), target_full));
                    }
                }
            }
            tar::EntryType::Char | tar::EntryType::Block | tar::EntryType::Fifo => {
                // Device nodes and FIFOs require special handling and usually root
                tracing::debug!(
                    path = %full_path.display(),
                    entry_type = ?entry_type,
                    "skipping special file (requires privileges)"
                );
            }
            _ => {
                tracing::trace!(
                    path = %full_path.display(),
                    entry_type = ?entry_type,
                    "skipping unknown entry type"
                );
            }
        }

        Ok(())
    }

    /// Extract a regular file
    fn extract_file<R: Read>(&self, entry: &mut tar::Entry<'_, R>, full_path: &Path) -> Result<()> {
        // Remove existing file if present (might be a different type)
        let _ = fs::remove_file(full_path);

        let mut file = File::create(full_path).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!("failed to create file {}: {}", full_path.display(), e),
            )))
        })?;

        std::io::copy(entry, &mut file).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                e.kind(),
                format!("failed to write file {}: {}", full_path.display(), e),
            )))
        })?;

        self.set_permissions(entry, full_path)?;

        Ok(())
    }

    /// Set file permissions from tar entry.
    ///
    /// The `Result<()>` return is load-bearing on Unix (where we can fail to
    /// apply the mode from the tar header); the Windows branch is a no-op
    /// and cannot fail, so clippy's `unnecessary_wraps` is allowed here.
    #[allow(clippy::unused_self, clippy::unnecessary_wraps)]
    fn set_permissions<R: Read>(&self, entry: &tar::Entry<'_, R>, full_path: &Path) -> Result<()> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            if let Ok(mode) = entry.header().mode() {
                let permissions = fs::Permissions::from_mode(mode);
                fs::set_permissions(full_path, permissions).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!(
                            "failed to set permissions on {}: {}",
                            full_path.display(),
                            e
                        ),
                    )))
                })?;
            }
        }

        #[cfg(not(unix))]
        {
            let _ = entry;
            let _ = full_path;
        }

        Ok(())
    }

    /// Clear the deleted paths tracking (useful between image extractions)
    pub fn reset(&mut self) {
        self.deleted_paths.clear();
        self.pending_hardlinks.clear();
        self.pending_dir_modes.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    fn create_tar_gz(files: &[(&str, &[u8])]) -> Vec<u8> {
        let mut builder = tar::Builder::new(Vec::new());

        for (path, content) in files {
            let mut header = tar::Header::new_gnu();
            header.set_path(path).unwrap();
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder.append(&header, *content).unwrap();
        }

        let tar_data = builder.into_inner().unwrap();

        // Compress with gzip
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        encoder.finish().unwrap()
    }

    fn create_tar_zstd(files: &[(&str, &[u8])]) -> Vec<u8> {
        let mut builder = tar::Builder::new(Vec::new());

        for (path, content) in files {
            let mut header = tar::Header::new_gnu();
            header.set_path(path).unwrap();
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder.append(&header, *content).unwrap();
        }

        let tar_data = builder.into_inner().unwrap();

        // Compress with zstd
        zstd::encode_all(std::io::Cursor::new(tar_data), 3).unwrap()
    }

    /// Streaming a layer from a file produces the same rootfs as the in-memory
    /// path, for both gzip and zstd, including by-magic-bytes detection when the
    /// media type is unrecognized.
    #[tokio::test]
    async fn unpack_from_files_matches_unpack_layers() {
        let files: &[(&str, &[u8])] = &[
            ("etc/hostname", b"host\n"),
            ("usr/bin/app", b"\x7fELF binary-ish payload"),
            ("var/data/blob", &[42u8; 4096]),
        ];
        let gz = create_tar_gz(files);
        let zst = create_tar_zstd(files);

        // Reference: in-memory unpack.
        let ref_dir = TempDir::new().unwrap();
        let ref_rootfs = ref_dir.path().join("rootfs");
        let mut ref_unpacker = LayerUnpacker::new(ref_rootfs.clone());
        ref_unpacker
            .unpack_layers(&[
                (gz.clone(), media_types::TAR_GZIP.to_string()),
                (zst.clone(), media_types::TAR_ZSTD.to_string()),
            ])
            .await
            .unwrap();

        // Streamed: write layers to files, unpack from disk. Use an UNKNOWN
        // media type for the gzip layer to exercise magic-byte detection.
        let layer_dir = TempDir::new().unwrap();
        let gz_path = layer_dir.path().join("layer0.tar.gz");
        let zst_path = layer_dir.path().join("layer1.tar.zst");
        tokio::fs::write(&gz_path, &gz).await.unwrap();
        tokio::fs::write(&zst_path, &zst).await.unwrap();

        let stream_dir = TempDir::new().unwrap();
        let stream_rootfs = stream_dir.path().join("rootfs");
        let mut stream_unpacker = LayerUnpacker::new(stream_rootfs.clone());
        stream_unpacker
            .unpack_layers_from_files(&[
                (gz_path, "application/octet-stream".to_string()), // unknown → magic bytes
                (zst_path, media_types::TAR_ZSTD.to_string()),
            ])
            .await
            .unwrap();

        for (path, content) in files {
            let a = fs::read(ref_rootfs.join(path)).unwrap();
            let b = fs::read(stream_rootfs.join(path)).unwrap();
            assert_eq!(a, b, "mismatch for {path}");
            assert_eq!(a, *content, "content mismatch for {path}");
        }
    }

    /// A hard-link entry whose TARGET appears later in the same layer tar
    /// (buildah emits alphabetical entry order, so Fedora's ca-trust tree
    /// links `extracted/openssl/... -> extracted/pem/...` forward). The
    /// unpacker must defer the link, not die — an immediate failure used to
    /// truncate the whole VZ rootfs at that point.
    #[tokio::test]
    async fn test_unpack_forward_referencing_hardlink() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let mut builder = tar::Builder::new(Vec::new());
        // 1. The LINK entry first (forward reference).
        let mut link_header = tar::Header::new_gnu();
        link_header.set_entry_type(tar::EntryType::Link);
        link_header.set_size(0);
        link_header.set_mode(0o644);
        builder
            .append_link(&mut link_header, "dir/a-link.txt", "dir/z-target.txt")
            .unwrap();
        // 2. The target file afterwards.
        let mut file_header = tar::Header::new_gnu();
        file_header.set_path("dir/z-target.txt").unwrap();
        file_header.set_size(12);
        file_header.set_mode(0o644);
        file_header.set_cksum();
        builder.append(&file_header, &b"link content"[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let layer = encoder.finish().unwrap();

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer, media_types::TAR_GZIP)
            .await
            .unwrap();

        assert_eq!(
            fs::read_to_string(rootfs.join("dir/z-target.txt")).unwrap(),
            "link content"
        );
        assert_eq!(
            fs::read_to_string(rootfs.join("dir/a-link.txt")).unwrap(),
            "link content",
            "forward-referencing hard link must resolve after the layer"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            assert_eq!(
                fs::metadata(rootfs.join("dir/a-link.txt")).unwrap().ino(),
                fs::metadata(rootfs.join("dir/z-target.txt")).unwrap().ino(),
                "must be a hard link, not a copy"
            );
        }
    }

    /// A hard link whose target never appears must be a LOUD error — the
    /// silent-skip behavior is what let truncated rootfs unpacks masquerade
    /// as success.
    #[tokio::test]
    async fn test_unpack_dangling_hardlink_errors() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let mut builder = tar::Builder::new(Vec::new());
        let mut link_header = tar::Header::new_gnu();
        link_header.set_entry_type(tar::EntryType::Link);
        link_header.set_size(0);
        link_header.set_mode(0o644);
        builder
            .append_link(&mut link_header, "orphan-link.txt", "never-exists.txt")
            .unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let layer = encoder.finish().unwrap();

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        let err = unpacker
            .unpack_layer(&layer, media_types::TAR_GZIP)
            .await
            .expect_err("dangling hard link must fail the unpack");
        assert!(
            err.to_string().contains("deferred hard link"),
            "error should name the deferred-link failure: {err}"
        );
    }

    /// The exact Fedora ca-trust case: a DIRECTORY entry archived mode `0o555`
    /// (read-only) appears BEFORE the symlink entries whose paths live inside
    /// it. Applying `0o555` to the dir before writing the symlinks would fail
    /// with `EACCES`. The unpacker must defer the dir mode, write the
    /// symlinks, then seal the dir back to `0o555`.
    #[tokio::test]
    async fn test_unpack_readonly_dir_with_symlinks_inside() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let mut builder = tar::Builder::new(Vec::new());
        // 1. The read-only directory entry FIRST.
        let mut dir_header = tar::Header::new_gnu();
        dir_header.set_entry_type(tar::EntryType::Directory);
        dir_header.set_path("ca-trust/").unwrap();
        dir_header.set_size(0);
        dir_header.set_mode(0o555);
        dir_header.set_cksum();
        builder.append(&dir_header, std::io::empty()).unwrap();
        // 2. Symlink entries INSIDE that read-only dir afterwards.
        let mut link1 = tar::Header::new_gnu();
        link1.set_entry_type(tar::EntryType::Symlink);
        link1.set_size(0);
        link1.set_mode(0o777);
        builder
            .append_link(&mut link1, "ca-trust/cert.pem", "../actual/cert.pem")
            .unwrap();
        let mut link2 = tar::Header::new_gnu();
        link2.set_entry_type(tar::EntryType::Symlink);
        link2.set_size(0);
        link2.set_mode(0o777);
        builder
            .append_link(&mut link2, "ca-trust/bundle.pem", "../actual/bundle.pem")
            .unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let layer = encoder.finish().unwrap();

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer, media_types::TAR_GZIP)
            .await
            .expect("read-only dir holding later symlinks must unpack");

        assert!(
            fs::symlink_metadata(rootfs.join("ca-trust/cert.pem"))
                .unwrap()
                .file_type()
                .is_symlink(),
            "symlink inside the read-only dir must exist"
        );
        assert!(
            fs::symlink_metadata(rootfs.join("ca-trust/bundle.pem"))
                .unwrap()
                .file_type()
                .is_symlink(),
            "second symlink inside the read-only dir must exist"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(rootfs.join("ca-trust"))
                .unwrap()
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(
                mode, 0o555,
                "the directory's FINAL mode must be the archived read-only 0o555"
            );
        }
    }

    /// A read-only (`0o555`) directory holding a forward-referenced hard link:
    /// the link entry inside the dir precedes its target, and the dir mode
    /// must be deferred so both the link and its target can be written before
    /// the dir is sealed read-only.
    #[tokio::test]
    async fn test_unpack_readonly_dir_with_hardlink_target_inside() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let mut builder = tar::Builder::new(Vec::new());
        // 1. Read-only directory entry FIRST.
        let mut dir_header = tar::Header::new_gnu();
        dir_header.set_entry_type(tar::EntryType::Directory);
        dir_header.set_path("ro/").unwrap();
        dir_header.set_size(0);
        dir_header.set_mode(0o555);
        dir_header.set_cksum();
        builder.append(&dir_header, std::io::empty()).unwrap();
        // 2. Forward-referencing hard link INSIDE the dir.
        let mut link_header = tar::Header::new_gnu();
        link_header.set_entry_type(tar::EntryType::Link);
        link_header.set_size(0);
        link_header.set_mode(0o644);
        builder
            .append_link(&mut link_header, "ro/a-link.txt", "ro/z-target.txt")
            .unwrap();
        // 3. The hard link's target, also inside the read-only dir.
        let mut file_header = tar::Header::new_gnu();
        file_header.set_path("ro/z-target.txt").unwrap();
        file_header.set_size(12);
        file_header.set_mode(0o644);
        file_header.set_cksum();
        builder.append(&file_header, &b"link content"[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let layer = encoder.finish().unwrap();

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer, media_types::TAR_GZIP)
            .await
            .expect("read-only dir with forward hard link must unpack");

        assert_eq!(
            fs::read_to_string(rootfs.join("ro/z-target.txt")).unwrap(),
            "link content"
        );
        assert_eq!(
            fs::read_to_string(rootfs.join("ro/a-link.txt")).unwrap(),
            "link content",
            "forward hard link inside the read-only dir must resolve"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::{MetadataExt, PermissionsExt};
            assert_eq!(
                fs::metadata(rootfs.join("ro/a-link.txt")).unwrap().ino(),
                fs::metadata(rootfs.join("ro/z-target.txt")).unwrap().ino(),
                "must be a hard link, not a copy"
            );
            let mode = fs::metadata(rootfs.join("ro"))
                .unwrap()
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(
                mode, 0o555,
                "the directory's FINAL mode must be the archived read-only 0o555"
            );
        }
    }

    #[tokio::test]
    async fn test_unpack_gzip_layer() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let layer_data = create_tar_gz(&[
            ("file.txt", b"hello world"),
            ("subdir/nested.txt", b"nested content"),
        ]);

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer_data, media_types::TAR_GZIP)
            .await
            .unwrap();

        assert!(rootfs.join("file.txt").exists());
        assert_eq!(
            fs::read_to_string(rootfs.join("file.txt")).unwrap(),
            "hello world"
        );
        assert!(rootfs.join("subdir/nested.txt").exists());
        assert_eq!(
            fs::read_to_string(rootfs.join("subdir/nested.txt")).unwrap(),
            "nested content"
        );
    }

    #[tokio::test]
    async fn test_unpack_zstd_layer() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let layer_data = create_tar_zstd(&[("zstd_file.txt", b"zstd compressed")]);

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer_data, media_types::TAR_ZSTD)
            .await
            .unwrap();

        assert!(rootfs.join("zstd_file.txt").exists());
        assert_eq!(
            fs::read_to_string(rootfs.join("zstd_file.txt")).unwrap(),
            "zstd compressed"
        );
    }

    #[tokio::test]
    async fn test_compression_detection_magic_bytes() {
        // Gzip magic bytes
        let gzip_data = vec![0x1f, 0x8b, 0x08, 0x00];
        assert_eq!(
            CompressionType::from_magic_bytes(&gzip_data),
            CompressionType::Gzip
        );

        // Zstd magic bytes
        let zstd_data = vec![0x28, 0xb5, 0x2f, 0xfd];
        assert_eq!(
            CompressionType::from_magic_bytes(&zstd_data),
            CompressionType::Zstd
        );

        // No compression
        let tar_data = vec![0x00, 0x00, 0x00, 0x00];
        assert_eq!(
            CompressionType::from_magic_bytes(&tar_data),
            CompressionType::None
        );
    }

    #[tokio::test]
    async fn test_whiteout_file_deletion() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        // First layer: create files - one to delete and one to keep
        let layer1 = create_tar_gz(&[
            ("to_delete.txt", b"will be deleted"),
            ("keep_me.txt", b"this file stays"),
        ]);

        // Second layer: whiteout file to delete the specific file
        let layer2 = create_tar_gz(&[(".wh.to_delete.txt", b"")]);

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layers(&[
                (layer1, media_types::TAR_GZIP.to_string()),
                (layer2, media_types::TAR_GZIP.to_string()),
            ])
            .await
            .unwrap();

        // The whiteout target should be deleted
        assert!(!rootfs.join("to_delete.txt").exists());
        // The other file should still exist
        assert!(rootfs.join("keep_me.txt").exists());
        assert_eq!(
            fs::read_to_string(rootfs.join("keep_me.txt")).unwrap(),
            "this file stays"
        );
    }

    #[tokio::test]
    async fn test_path_traversal_prevention() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let unpacker = LayerUnpacker::new(rootfs);

        // These paths should be rejected
        assert!(!unpacker.is_safe_path(Path::new("/etc/passwd")));
        assert!(!unpacker.is_safe_path(Path::new("../../../etc/passwd")));
        assert!(!unpacker.is_safe_path(Path::new("foo/../../../etc/passwd")));

        // These paths should be accepted
        assert!(unpacker.is_safe_path(Path::new("normal/path/file.txt")));
        assert!(unpacker.is_safe_path(Path::new("file.txt")));
    }

    #[tokio::test]
    async fn test_layer_ordering() {
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        // First layer: create a file
        let layer1 = create_tar_gz(&[("file.txt", b"original")]);

        // Second layer: modify the file
        let layer2 = create_tar_gz(&[("file.txt", b"modified")]);

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layers(&[
                (layer1, media_types::TAR_GZIP.to_string()),
                (layer2, media_types::TAR_GZIP.to_string()),
            ])
            .await
            .unwrap();

        // Should have the modified content
        assert_eq!(
            fs::read_to_string(rootfs.join("file.txt")).unwrap(),
            "modified"
        );
    }

    #[test]
    fn test_is_linux_layer_classifier() {
        assert!(is_linux_layer(media_types::TAR));
        assert!(is_linux_layer(media_types::TAR_GZIP));
        assert!(is_linux_layer(media_types::TAR_ZSTD));
        assert!(is_linux_layer(media_types::DOCKER_TAR_GZIP));

        // Windows types must NOT be classified as Linux.
        assert!(!is_linux_layer(media_types::DOCKER_FOREIGN_TAR_GZIP));
        assert!(!is_linux_layer(media_types::OCI_NONDISTRIBUTABLE_TAR));
        assert!(!is_linux_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP));
        assert!(!is_linux_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD));

        assert!(!is_linux_layer("application/vnd.oci.image.config.v1+json"));
        assert!(!is_linux_layer("application/unknown"));
    }

    #[test]
    fn test_is_windows_layer_classifier() {
        assert!(is_windows_layer(media_types::DOCKER_FOREIGN_TAR_GZIP));
        assert!(is_windows_layer(media_types::OCI_NONDISTRIBUTABLE_TAR));
        assert!(is_windows_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP));
        assert!(is_windows_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD));

        // Linux types must NOT be classified as Windows.
        assert!(!is_windows_layer(media_types::TAR));
        assert!(!is_windows_layer(media_types::TAR_GZIP));
        assert!(!is_windows_layer(media_types::TAR_ZSTD));
        assert!(!is_windows_layer(media_types::DOCKER_TAR_GZIP));

        assert!(!is_windows_layer(
            "application/vnd.oci.image.config.v1+json"
        ));
        assert!(!is_windows_layer("application/unknown"));
    }

    #[test]
    fn test_linux_and_windows_classifiers_are_disjoint() {
        // Every supported media type must classify as exactly one of
        // Linux or Windows (never both, never neither).
        let all = [
            media_types::TAR,
            media_types::TAR_GZIP,
            media_types::TAR_ZSTD,
            media_types::DOCKER_TAR_GZIP,
            media_types::DOCKER_FOREIGN_TAR_GZIP,
            media_types::OCI_NONDISTRIBUTABLE_TAR,
            media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP,
            media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD,
        ];
        for mt in all {
            assert!(
                is_linux_layer(mt) ^ is_windows_layer(mt),
                "media type {mt} must be exactly one of linux/windows"
            );
        }
    }

    #[test]
    fn test_media_type_detection() {
        assert_eq!(
            CompressionType::from_media_type(media_types::TAR_GZIP),
            Some(CompressionType::Gzip)
        );
        assert_eq!(
            CompressionType::from_media_type(media_types::DOCKER_TAR_GZIP),
            Some(CompressionType::Gzip)
        );
        assert_eq!(
            CompressionType::from_media_type(media_types::TAR_ZSTD),
            Some(CompressionType::Zstd)
        );
        assert_eq!(
            CompressionType::from_media_type(media_types::TAR),
            Some(CompressionType::None)
        );
        // Unknown media type returns None
        assert_eq!(
            CompressionType::from_media_type("application/unknown"),
            None
        );
    }

    /// HOST-ESCAPE REGRESSION (the `/run/sshd` SSH-wedge bug): a layer that ships
    /// the standard `var/run -> /run` symlink followed by an entry under
    /// `var/run/...` must NOT write or chmod through the link onto the host. The
    /// unpacker must replace the symlinked parent with a real dir inside the
    /// rootfs and keep the write contained. Fails pre-fix (would clobber the host
    /// sentinel), passes post-fix.
    #[cfg(unix)]
    #[tokio::test]
    async fn unpack_never_writes_through_rootfs_symlink_to_host() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().unwrap();
        // A sentinel standing in for the HOST's /run (the symlink target),
        // OUTSIDE the rootfs, with a protected file standing in for /run/sshd.
        let host_run = temp_dir.path().join("host_run");
        fs::create_dir_all(&host_run).unwrap();
        let host_sshd = host_run.join("sshd");
        fs::write(&host_sshd, b"HOST sshd runtime dir must NOT be touched").unwrap();
        fs::set_permissions(&host_sshd, fs::Permissions::from_mode(0o600)).unwrap();

        let rootfs = temp_dir.path().join("rootfs");

        let mut builder = tar::Builder::new(Vec::new());
        // 1. `var/run -> <host_run>` absolute symlink (like a real `var/run -> /run`).
        let mut link = tar::Header::new_gnu();
        link.set_entry_type(tar::EntryType::Symlink);
        link.set_size(0);
        link.set_mode(0o777);
        builder
            .append_link(&mut link, "var/run", host_run.to_str().unwrap())
            .unwrap();
        // 2. A file UNDER the symlinked dir — the escape vector.
        let mut file = tar::Header::new_gnu();
        file.set_path("var/run/sshd").unwrap();
        file.set_size(7);
        file.set_mode(0o666);
        file.set_cksum();
        builder.append(&file, &b"PAYLOAD"[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let layer = encoder.finish().unwrap();

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer, media_types::TAR_GZIP)
            .await
            .expect("layer must unpack without escaping the rootfs");

        // The host sentinel must be byte-for-byte and mode-for-mode untouched.
        assert_eq!(
            fs::read(&host_sshd).unwrap(),
            b"HOST sshd runtime dir must NOT be touched",
            "the host /run/sshd stand-in must NOT have been overwritten"
        );
        assert_eq!(
            fs::metadata(&host_sshd).unwrap().permissions().mode() & 0o777,
            0o600,
            "the host /run/sshd stand-in must NOT have been chmod'd (the sshd-wedge bug)"
        );
        assert_eq!(
            fs::read_dir(&host_run).unwrap().count(),
            1,
            "no extra files may be created in the host dir via the symlink"
        );

        // The write must have been contained: var/run is now a REAL dir in the
        // rootfs with the payload inside it.
        let run_md = fs::symlink_metadata(rootfs.join("var/run")).unwrap();
        assert!(
            run_md.is_dir() && !run_md.file_type().is_symlink(),
            "rootfs/var/run must be a real directory, not the escaping symlink"
        );
        assert_eq!(
            fs::read(rootfs.join("var/run/sshd")).unwrap(),
            b"PAYLOAD",
            "the entry must land inside the rootfs"
        );
    }

    /// Root-gated helper: skip a test (printing why) when not uid 0, since the
    /// overlay per-layer path needs `CAP_MKNOD` (mknod) and `CAP_SYS_ADMIN`
    /// (`trusted.*` xattr).
    #[cfg(target_os = "linux")]
    fn require_root_or_skip(test: &str) -> bool {
        if zlayer_paths::is_root() {
            return true;
        }
        eprintln!("skipping {test}: requires root (CAP_MKNOD / CAP_SYS_ADMIN)");
        false
    }

    /// PRESERVE mode: a `.wh.foo` whiteout must become a `0:0` character device
    /// named `foo` (an overlayfs whiteout), NOT delete-from-merged.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn overlay_layer_preserves_regular_whiteout_as_chardev() {
        use std::os::unix::fs::{FileTypeExt, MetadataExt};
        if !require_root_or_skip("overlay_layer_preserves_regular_whiteout_as_chardev") {
            return;
        }

        let temp_dir = TempDir::new().unwrap();
        let layer_dir = temp_dir.path().join("fs");
        let layer = create_tar_gz(&[(".wh.foo", b"")]);
        let layer_path = temp_dir.path().join("layer.tar.gz");
        std::fs::write(&layer_path, &layer).unwrap();

        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
        unpacker
            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
            .expect("overlay whiteout extraction must succeed as root");

        let wh = layer_dir.join("foo");
        let md = std::fs::symlink_metadata(&wh).expect("whiteout char dev must exist");
        assert!(
            md.file_type().is_char_device(),
            "regular whiteout must be a character device, got {:?}",
            md.file_type()
        );
        assert_eq!(md.rdev(), 0, "overlayfs whiteout must be device 0:0");
        // The `.wh.foo` marker file itself must NOT be present.
        assert!(
            !layer_dir.join(".wh.foo").exists(),
            "the .wh. marker must be consumed, not left on disk"
        );
    }

    /// PRESERVE mode: a `.wh..wh..opq` opaque whiteout must set the
    /// `trusted.overlay.opaque="y"` xattr on the containing directory.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn overlay_layer_preserves_opaque_whiteout_as_xattr() {
        if !require_root_or_skip("overlay_layer_preserves_opaque_whiteout_as_xattr") {
            return;
        }
        let temp_dir = TempDir::new().unwrap();
        let layer_dir = temp_dir.path().join("fs");
        // A dir entry plus its opaque marker (.wh..wh..opq).
        let mut builder = tar::Builder::new(Vec::new());
        let mut dh = tar::Header::new_gnu();
        dh.set_entry_type(tar::EntryType::Directory);
        dh.set_path("etc/").unwrap();
        dh.set_size(0);
        dh.set_mode(0o755);
        dh.set_cksum();
        builder.append(&dh, std::io::empty()).unwrap();
        let mut oh = tar::Header::new_gnu();
        oh.set_path("etc/.wh..wh..opq").unwrap();
        oh.set_size(0);
        oh.set_mode(0o644);
        oh.set_cksum();
        builder.append(&oh, std::io::empty()).unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        enc.write_all(&tar_data).unwrap();
        let layer = enc.finish().unwrap();
        let layer_path = temp_dir.path().join("layer.tar.gz");
        std::fs::write(&layer_path, &layer).unwrap();

        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
        unpacker
            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
            .expect("opaque whiteout extraction must succeed as root");

        let val = xattr::get(layer_dir.join("etc"), "trusted.overlay.opaque")
            .expect("xattr read must succeed")
            .expect("trusted.overlay.opaque must be set on the dir");
        assert_eq!(val, b"y", "opaque marker value must be \"y\"");
    }

    /// PRESERVE mode: a normal file extracts with the archived mode (the
    /// non-whiteout path must behave like the merged extractor).
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn overlay_layer_extracts_normal_file_with_mode() {
        use std::os::unix::fs::PermissionsExt;
        if !require_root_or_skip("overlay_layer_extracts_normal_file_with_mode") {
            return;
        }

        let temp_dir = TempDir::new().unwrap();
        let layer_dir = temp_dir.path().join("fs");
        let mut builder = tar::Builder::new(Vec::new());
        let mut h = tar::Header::new_gnu();
        h.set_path("usr/bin/app").unwrap();
        h.set_size(5);
        h.set_mode(0o755);
        h.set_cksum();
        builder.append(&h, &b"hello"[..]).unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        enc.write_all(&tar_data).unwrap();
        let layer = enc.finish().unwrap();
        let layer_path = temp_dir.path().join("layer.tar.gz");
        std::fs::write(&layer_path, &layer).unwrap();

        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
        unpacker
            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
            .expect("normal file extraction must succeed");

        let f = layer_dir.join("usr/bin/app");
        assert_eq!(std::fs::read(&f).unwrap(), b"hello");
        assert_eq!(
            std::fs::metadata(&f).unwrap().permissions().mode() & 0o777,
            0o755,
            "archived file mode must be applied in the overlay path too"
        );
    }

    /// PRESERVE mode: the `var/run -> /run` absolute symlink must still be
    /// relativized to `../run` in the per-layer overlay path (the host-escape
    /// guard is not dropped when whiteouts are preserved).
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn overlay_layer_relativizes_absolute_rootfs_symlink() {
        if !require_root_or_skip("overlay_layer_relativizes_absolute_rootfs_symlink") {
            return;
        }
        let temp_dir = TempDir::new().unwrap();
        let layer_dir = temp_dir.path().join("fs");

        let mut builder = tar::Builder::new(Vec::new());
        let mut run_dir = tar::Header::new_gnu();
        run_dir.set_entry_type(tar::EntryType::Directory);
        run_dir.set_path("run/").unwrap();
        run_dir.set_size(0);
        run_dir.set_mode(0o700);
        run_dir.set_cksum();
        builder.append(&run_dir, std::io::empty()).unwrap();
        let mut link = tar::Header::new_gnu();
        link.set_entry_type(tar::EntryType::Symlink);
        link.set_size(0);
        link.set_mode(0o777);
        builder.append_link(&mut link, "var/run", "/run").unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        enc.write_all(&tar_data).unwrap();
        let layer = enc.finish().unwrap();
        let layer_path = temp_dir.path().join("layer.tar.gz");
        std::fs::write(&layer_path, &layer).unwrap();

        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
        unpacker
            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
            .expect("layer must unpack");

        let vr = layer_dir.join("var/run");
        let md = std::fs::symlink_metadata(&vr).unwrap();
        assert!(md.file_type().is_symlink(), "var/run must remain a symlink");
        assert_eq!(
            std::fs::read_link(&vr).unwrap(),
            std::path::PathBuf::from("../run"),
            "var/run must be relativized to ../run in the overlay path too"
        );
    }

    /// A Collapse-mode unpacker must reject `unpack_layer_to_overlay_dir` (using
    /// the wrong mode would silently drop deletions). Runs without root.
    #[tokio::test]
    async fn overlay_dir_rejects_collapse_mode_unpacker() {
        let temp_dir = TempDir::new().unwrap();
        let layer = create_tar_gz(&[("x", b"y")]);
        let layer_path = temp_dir.path().join("layer.tar.gz");
        std::fs::write(&layer_path, &layer).unwrap();

        let mut unpacker = LayerUnpacker::new(temp_dir.path().join("fs"));
        let err = unpacker
            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
            .expect_err("collapse-mode unpacker must be rejected");
        assert!(
            err.to_string().contains("Preserve-mode"),
            "error must explain the mode requirement: {err}"
        );
    }

    /// HOST-ESCAPE REGRESSION (the host `/run` 0700 corruption / DNS+networkd
    /// wedge): the exact `zql-ci-base` shape — an image ships the standard
    /// ABSOLUTE `var/run -> /run` symlink and its own real `/run` dir (mode
    /// 0700) but NO entry *under* `var/run` (so `materialize_real_parent` never
    /// fires). At container run-time a host-context op that resolves
    /// `<rootfs>/var/run` would then follow the absolute link onto the HOST's
    /// `/run` and chmod it. The unpacker must store the link RELATIVE
    /// (`../run`) so it can never escape the rootfs. Fails pre-fix (link stays
    /// absolute), passes post-fix.
    #[cfg(unix)]
    #[tokio::test]
    async fn unpack_relativizes_absolute_rootfs_symlink() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path().join("rootfs");

        let mut builder = tar::Builder::new(Vec::new());
        // 1. The image's own `/run` directory, mode 0700 (like zql-ci-base).
        let mut run_dir = tar::Header::new_gnu();
        run_dir.set_entry_type(tar::EntryType::Directory);
        run_dir.set_path("run/").unwrap();
        run_dir.set_size(0);
        run_dir.set_mode(0o700);
        run_dir.set_cksum();
        builder.append(&run_dir, std::io::empty()).unwrap();
        // 2. The standard ABSOLUTE `var/run -> /run` symlink, no child entries.
        let mut link = tar::Header::new_gnu();
        link.set_entry_type(tar::EntryType::Symlink);
        link.set_size(0);
        link.set_mode(0o777);
        builder.append_link(&mut link, "var/run", "/run").unwrap();
        let tar_data = builder.into_inner().unwrap();
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_data).unwrap();
        let layer = encoder.finish().unwrap();

        let mut unpacker = LayerUnpacker::new(rootfs.clone());
        unpacker
            .unpack_layer(&layer, media_types::TAR_GZIP)
            .await
            .expect("layer must unpack");

        // `var/run` is still a symlink, but now RELATIVE and confined.
        let vr = rootfs.join("var/run");
        let md = fs::symlink_metadata(&vr).unwrap();
        assert!(
            md.file_type().is_symlink(),
            "var/run must remain a symlink (container semantics preserved)"
        );
        let target = fs::read_link(&vr).unwrap();
        assert!(
            target.is_relative(),
            "var/run must be relativized so it cannot escape the rootfs; got {target:?}"
        );
        assert_eq!(
            target,
            std::path::PathBuf::from("../run"),
            "var/run must resolve to the rootfs's own /run"
        );
        // It resolves to the rootfs's own /run, not anywhere outside.
        assert_eq!(
            fs::canonicalize(&vr).unwrap(),
            fs::canonicalize(rootfs.join("run")).unwrap(),
            "var/run must resolve inside the rootfs"
        );
        // The image's own /run dir landed correctly (mode restored to 0700).
        assert_eq!(
            fs::metadata(rootfs.join("run"))
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o700
        );
    }

    /// Build a plain (uncompressed) layer tar with arbitrary entry types.
    /// Returns the raw tar bytes (media type `media_types::TAR`).
    fn tar_with(headers: impl FnOnce(&mut tar::Builder<Vec<u8>>)) -> Vec<u8> {
        let mut builder = tar::Builder::new(Vec::new());
        headers(&mut builder);
        builder.into_inner().unwrap()
    }

    /// ROOTLESS overlay extract: a regular whiteout `.wh.<name>` must be
    /// PRESERVED as a plain `.wh.<name>` regular file (NOT a char device), and
    /// an opaque whiteout `.wh..wh..opq` must set the `user.overlay.opaque`
    /// xattr on the dir — exactly the markers fuse-overlayfs reads rootless. No
    /// privilege required, so this test is NOT root-gated.
    #[tokio::test]
    async fn rootless_overlay_extract_writes_wh_file_and_user_opaque_xattr() {
        let tmp = TempDir::new().unwrap();
        let layer_dir = tmp.path().join("fs-fuse");

        // A layer that: ships a real file, whites out `gone.txt` via
        // `.wh.gone.txt`, and marks `opq/` opaque via `opq/.wh..wh..opq`.
        let layer = tar_with(|b| {
            let mut h = tar::Header::new_gnu();
            h.set_path("keep.txt").unwrap();
            h.set_size(5);
            h.set_mode(0o644);
            h.set_cksum();
            b.append(&h, &b"keep\n"[..]).unwrap();

            let mut wh = tar::Header::new_gnu();
            wh.set_path(".wh.gone.txt").unwrap();
            wh.set_size(0);
            wh.set_mode(0o644);
            wh.set_cksum();
            b.append(&wh, std::io::empty()).unwrap();

            let mut opq = tar::Header::new_gnu();
            opq.set_path("opq/.wh..wh..opq").unwrap();
            opq.set_size(0);
            opq.set_mode(0o644);
            opq.set_cksum();
            b.append(&opq, std::io::empty()).unwrap();
        });
        let layer_file = tmp.path().join("layer.tar");
        fs::write(&layer_file, &layer).unwrap();

        let mut unpacker = LayerUnpacker::new_for_overlay_rootless(layer_dir.clone());
        unpacker
            .unpack_layer_to_overlay_dir_rootless(&layer_file, media_types::TAR)
            .expect("rootless overlay extract");

        // Real file extracted.
        assert_eq!(
            fs::read_to_string(layer_dir.join("keep.txt")).unwrap(),
            "keep\n"
        );

        // Regular whiteout: a PLAIN `.wh.gone.txt` file, NOT a char device.
        let wh = layer_dir.join(".wh.gone.txt");
        let md = fs::symlink_metadata(&wh).expect(".wh.gone.txt must exist");
        assert!(
            md.file_type().is_file(),
            ".wh. whiteout must be a regular file in rootless mode (got {:?})",
            md.file_type()
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::FileTypeExt;
            assert!(
                !md.file_type().is_char_device(),
                "rootless whiteout must NOT be a char device (that needs CAP_MKNOD)"
            );
        }

        // Opaque whiteout: the `user.overlay.opaque` xattr is set to "y" on the
        // dir. (Backing fs must support user xattrs; tmpfs/ext4 do. If it does
        // not, the extract still wrote the `.wh..wh..opq` sentinel fallback.)
        let opq_dir = layer_dir.join("opq");
        assert!(opq_dir.is_dir(), "opaque dir must exist");
        #[cfg(target_os = "linux")]
        match xattr::get(&opq_dir, "user.overlay.opaque") {
            Ok(Some(v)) => assert_eq!(
                v, b"y",
                "user.overlay.opaque must be \"y\" (fuse-overlayfs opaque marker)"
            ),
            Ok(None) | Err(_) => {
                // Fallback path: the sentinel file must be present instead.
                assert!(
                    opq_dir.join(".wh..wh..opq").exists(),
                    "without the user.overlay.opaque xattr the .wh..wh..opq sentinel \
                     fallback must be present"
                );
            }
        }
        // On non-Linux the `xattr` crate is unavailable; the rootless extract
        // still writes the `.wh..wh..opq` sentinel, so assert that directly.
        #[cfg(not(target_os = "linux"))]
        assert!(
            opq_dir.join(".wh..wh..opq").exists(),
            "rootless opaque whiteout must write the .wh..wh..opq sentinel on non-Linux"
        );
    }

    /// The rootless entrypoint must REJECT a non-`PreserveRootless` unpacker —
    /// using a collapse/preserve unpacker would write the wrong whiteout form.
    #[tokio::test]
    async fn rootless_overlay_extract_rejects_wrong_mode() {
        let tmp = TempDir::new().unwrap();
        let layer_file = tmp.path().join("layer.tar");
        fs::write(
            &layer_file,
            tar_with(|b| {
                let mut h = tar::Header::new_gnu();
                h.set_path("f").unwrap();
                h.set_size(1);
                h.set_mode(0o644);
                h.set_cksum();
                b.append(&h, &b"x"[..]).unwrap();
            }),
        )
        .unwrap();

        // A Collapse-mode unpacker must be rejected by the rootless entrypoint.
        let mut wrong = LayerUnpacker::new(tmp.path().join("out"));
        let err = wrong
            .unpack_layer_to_overlay_dir_rootless(&layer_file, media_types::TAR)
            .expect_err("non-PreserveRootless unpacker must be rejected");
        assert!(
            err.to_string().contains("PreserveRootless"),
            "error should name the required mode: {err}"
        );
    }
}