Skip to main content

zlayer_registry/
unpack.rs

1//! OCI layer unpacking and extraction
2//!
3//! This module handles extracting OCI image layers to a rootfs directory,
4//! supporting gzip, zstd, and uncompressed tar formats.
5
6use crate::error::{CacheError, RegistryError, Result};
7use flate2::read::GzDecoder;
8use std::collections::HashSet;
9use std::fs::{self, File};
10use std::io::{BufRead, BufReader, Cursor, Read};
11use std::path::{Path, PathBuf};
12use tar::Archive;
13
14/// OCI layer media types
15pub mod media_types {
16    /// Uncompressed tar layer
17    pub const TAR: &str = "application/vnd.oci.image.layer.v1.tar";
18    /// Gzip compressed tar layer
19    pub const TAR_GZIP: &str = "application/vnd.oci.image.layer.v1.tar+gzip";
20    /// Zstd compressed tar layer
21    pub const TAR_ZSTD: &str = "application/vnd.oci.image.layer.v1.tar+zstd";
22    /// Docker gzip compressed layer (legacy)
23    pub const DOCKER_TAR_GZIP: &str = "application/vnd.docker.image.rootfs.diff.tar.gzip";
24
25    // Windows container layer media types.
26    //
27    // Windows base-OS layers are published as "foreign" / "nondistributable"
28    // blobs hosted on mcr.microsoft.com. Unpacking them requires the
29    // Windows-specific pipeline (wclayer / backup-stream / HCS) which lives in
30    // `zlayer-agent`, *not* the Linux overlayfs+whiteouts flow in this module.
31    // The constants are declared here so the rest of the registry can
32    // recognize and classify them; see [`is_windows_layer`] for the matcher.
33
34    /// Legacy Docker foreign-layer (gzip) — Windows base OS layers on MCR.
35    pub const DOCKER_FOREIGN_TAR_GZIP: &str =
36        "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip";
37    /// OCI nondistributable layer, uncompressed tar (Windows).
38    pub const OCI_NONDISTRIBUTABLE_TAR: &str =
39        "application/vnd.oci.image.layer.nondistributable.v1.tar";
40    /// OCI nondistributable layer, gzip compressed (Windows).
41    pub const OCI_NONDISTRIBUTABLE_TAR_GZIP: &str =
42        "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip";
43    /// OCI nondistributable layer, zstd compressed (Windows).
44    pub const OCI_NONDISTRIBUTABLE_TAR_ZSTD: &str =
45        "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd";
46}
47
48/// Returns `true` if a layer media type is a recognized Linux tar layer
49/// (overlayfs + whiteouts pipeline).
50///
51/// This covers both the modern OCI types and the legacy Docker v2.2 type.
52/// It does *not* include Windows nondistributable/foreign layer types —
53/// see [`is_windows_layer`] for that classification.
54#[must_use]
55pub fn is_linux_layer(media_type: &str) -> bool {
56    matches!(
57        media_type,
58        media_types::TAR
59            | media_types::TAR_GZIP
60            | media_types::TAR_ZSTD
61            | media_types::DOCKER_TAR_GZIP
62    )
63}
64
65/// Returns `true` if a layer media type indicates a Windows container layer
66/// (nondistributable / foreign).
67///
68/// Windows layers require a different unpack path (wclayer / backup-stream /
69/// HCS) than the standard Linux tar+overlayfs flow this module implements.
70/// Callers that receive a `true` here should route the blob to the
71/// Windows-specific unpacker in `zlayer-agent` rather than invoking
72/// [`LayerUnpacker::unpack_layer`].
73#[must_use]
74pub fn is_windows_layer(media_type: &str) -> bool {
75    matches!(
76        media_type,
77        media_types::DOCKER_FOREIGN_TAR_GZIP
78            | media_types::OCI_NONDISTRIBUTABLE_TAR
79            | media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP
80            | media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD
81    )
82}
83
84/// Whiteout file prefix for deletions
85const WHITEOUT_PREFIX: &str = ".wh.";
86/// Opaque whiteout marker (delete entire directory contents)
87const OPAQUE_WHITEOUT: &str = ".wh..wh..opq";
88
89/// How the unpacker handles OCI whiteout entries.
90///
91/// OCI layers encode deletions as `.wh.<name>` (delete `<name>`) and
92/// `.wh..wh..opq` (mark the containing dir opaque). The two unpack targets need
93/// opposite behaviour:
94///
95/// - [`WhiteoutMode::Collapse`] — the legacy single-merged-tree path. All layers
96///   are extracted into ONE directory, so a whiteout is applied immediately by
97///   deleting the lower file from the merged tree. The merged tree is what a
98///   container's full-copy rootfs has always been.
99/// - [`WhiteoutMode::Preserve`] — the per-layer overlayfs lowerdir path. Each
100///   layer is extracted into ITS OWN directory, so a whiteout must be PRESERVED
101///   as an overlayfs whiteout (a `0:0` char device for a regular whiteout, the
102///   `trusted.overlay.opaque="y"` xattr for an opaque one) for the kernel's
103///   overlay driver to interpret at mount time — there is no lower file to
104///   delete in a single-layer dir.
105/// - [`WhiteoutMode::PreserveRootless`] — the per-layer lowerdir path for the
106///   ROOTLESS `fuse-overlayfs` backend, which needs neither `CAP_MKNOD` nor
107///   `CAP_SYS_ADMIN`. fuse-overlayfs reads two whiteout forms on every layer
108///   (verified against `containers/fuse-overlayfs` 1.16 `src/overlay.rs` /
109///   `src/whiteout.rs` / `src/xattr.rs`): a regular `.wh.<name>` file marks
110///   `<name>` deleted, and the `user.overlay.opaque="y"` xattr (its
111///   `UNPRIVILEGED_OPAQUE_XATTR`) marks a directory opaque. Both are settable by
112///   an unprivileged process. So this mode writes a plain `.wh.<name>` file for
113///   a regular whiteout and the `user.overlay.opaque` xattr for an opaque one,
114///   instead of the privileged char-dev / `trusted.overlay.opaque` markers.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum WhiteoutMode {
117    /// Apply whiteouts immediately by deleting from the merged tree.
118    Collapse,
119    /// Preserve whiteouts as kernel-overlay char-dev / `trusted.*`-opaque
120    /// markers (needs `CAP_MKNOD` + `CAP_SYS_ADMIN`).
121    Preserve,
122    /// Preserve whiteouts the rootless `fuse-overlayfs` way: `.wh.<name>` files
123    /// and the `user.overlay.opaque` xattr (no privilege required).
124    PreserveRootless,
125}
126
127/// Compression type detection
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum CompressionType {
130    /// No compression (plain tar)
131    None,
132    /// Gzip compression
133    Gzip,
134    /// Zstd compression
135    Zstd,
136}
137
138impl CompressionType {
139    /// Detect compression type from media type string
140    /// Returns None if media type is unrecognized (caller should use magic bytes)
141    #[must_use]
142    pub fn from_media_type(media_type: &str) -> Option<Self> {
143        match media_type {
144            media_types::TAR_GZIP | media_types::DOCKER_TAR_GZIP => Some(Self::Gzip),
145            media_types::TAR_ZSTD => Some(Self::Zstd),
146            media_types::TAR => Some(Self::None),
147            _ => None, // Unknown - caller should use detect() with actual data
148        }
149    }
150
151    /// Detect compression type from magic bytes
152    pub fn from_magic_bytes(data: &[u8]) -> Self {
153        if data.len() < 4 {
154            tracing::warn!(
155                data_len = data.len(),
156                "insufficient data for magic byte detection, assuming uncompressed tar"
157            );
158            return Self::None;
159        }
160
161        // Gzip magic: 0x1f 0x8b
162        if data[0] == 0x1f && data[1] == 0x8b {
163            return Self::Gzip;
164        }
165
166        // Zstd magic: 0x28 0xb5 0x2f 0xfd
167        if data.len() >= 4
168            && data[0] == 0x28
169            && data[1] == 0xb5
170            && data[2] == 0x2f
171            && data[3] == 0xfd
172        {
173            return Self::Zstd;
174        }
175
176        Self::None
177    }
178
179    /// Detect compression, preferring media type but falling back to magic bytes
180    pub fn detect(media_type: &str, data: &[u8]) -> Self {
181        // First try media type
182        if let Some(compression) = Self::from_media_type(media_type) {
183            return compression;
184        }
185        // Fall back to magic bytes for unknown media types
186        tracing::debug!(
187            media_type = %media_type,
188            "unrecognized media type, detecting compression from magic bytes"
189        );
190        Self::from_magic_bytes(data)
191    }
192}
193
194/// Layer unpacker for extracting OCI layers to a rootfs
195pub struct LayerUnpacker {
196    /// Root filesystem directory
197    rootfs_dir: PathBuf,
198    /// Track deleted paths from whiteouts
199    deleted_paths: HashSet<PathBuf>,
200    /// Hard links whose target didn't exist yet when their entry was
201    /// reached, retried after the rest of the layer has been extracted.
202    /// Layer tars are NOT guaranteed to place a hard link's target before
203    /// the link entry (buildah emits alphabetical ordering, so Fedora's
204    /// `etc/pki/ca-trust/extracted/openssl/... -> .../pem/...` link comes
205    /// FIRST) — failing immediately truncated the whole rootfs.
206    /// `(link_path, link_target)` pairs, both absolute under `rootfs_dir`.
207    pending_hardlinks: Vec<(PathBuf, PathBuf)>,
208    /// Directory modes deferred until the end of the layer. A directory may
209    /// be archived read-only (e.g. Fedora's `etc/pki/ca-trust/extracted`
210    /// arrives mode `0o555`) yet still contain entries (symlinks, files,
211    /// forward-referenced hard links) that appear LATER in the tar. Applying
212    /// the archived mode immediately would make the dir unwritable and the
213    /// child entries fail with `EACCES`. So directories are created `0o700`
214    /// up front and their real mode is recorded here, then re-applied
215    /// deepest-first by [`restore_dir_modes`] once everything is populated.
216    /// `(dir_path, archived_mode)`, the path absolute under `rootfs_dir`.
217    pending_dir_modes: Vec<(std::path::PathBuf, u32)>,
218    /// Whether whiteouts collapse into the merged tree (legacy single-tree
219    /// rootfs) or are preserved as overlayfs markers (per-layer lowerdir).
220    whiteout_mode: WhiteoutMode,
221}
222
223impl LayerUnpacker {
224    /// Create a new layer unpacker targeting the specified rootfs directory.
225    ///
226    /// Uses [`WhiteoutMode::Collapse`] — the legacy single-merged-tree
227    /// behaviour where whiteouts delete from the merged rootfs. For the
228    /// per-layer overlayfs lowerdir path use [`LayerUnpacker::new_for_overlay`].
229    #[must_use]
230    pub fn new(rootfs_dir: PathBuf) -> Self {
231        Self::with_whiteout_mode(rootfs_dir, WhiteoutMode::Collapse)
232    }
233
234    /// Create a layer unpacker that PRESERVES whiteouts as overlayfs markers,
235    /// for extracting a single layer into its own overlay `lowerdir`.
236    ///
237    /// See [`WhiteoutMode::Preserve`] and
238    /// [`LayerUnpacker::unpack_layer_to_overlay_dir`].
239    #[must_use]
240    pub fn new_for_overlay(layer_dir: PathBuf) -> Self {
241        Self::with_whiteout_mode(layer_dir, WhiteoutMode::Preserve)
242    }
243
244    /// Create a layer unpacker that PRESERVES whiteouts the ROOTLESS
245    /// `fuse-overlayfs` way (`.wh.<name>` files + `user.overlay.opaque` xattr),
246    /// for extracting a single layer into its own fuse-overlay `lowerdir`
247    /// without `CAP_MKNOD` / `CAP_SYS_ADMIN`.
248    ///
249    /// See [`WhiteoutMode::PreserveRootless`] and
250    /// [`LayerUnpacker::unpack_layer_to_overlay_dir_rootless`].
251    #[must_use]
252    pub fn new_for_overlay_rootless(layer_dir: PathBuf) -> Self {
253        Self::with_whiteout_mode(layer_dir, WhiteoutMode::PreserveRootless)
254    }
255
256    /// Construct with an explicit [`WhiteoutMode`].
257    #[must_use]
258    pub fn with_whiteout_mode(rootfs_dir: PathBuf, whiteout_mode: WhiteoutMode) -> Self {
259        Self {
260            rootfs_dir,
261            deleted_paths: HashSet::new(),
262            pending_hardlinks: Vec::new(),
263            pending_dir_modes: Vec::new(),
264            whiteout_mode,
265        }
266    }
267
268    /// Get the rootfs directory
269    #[must_use]
270    pub fn rootfs_dir(&self) -> &Path {
271        &self.rootfs_dir
272    }
273
274    /// Unpack a single layer to the rootfs
275    ///
276    /// # Arguments
277    /// * `layer_data` - The compressed or uncompressed layer data
278    /// * `media_type` - The OCI media type of the layer
279    ///
280    /// # Errors
281    /// Returns an error if decompression or extraction fails
282    #[allow(clippy::unused_async)]
283    pub async fn unpack_layer(&mut self, layer_data: &[u8], media_type: &str) -> Result<()> {
284        // Ensure rootfs directory exists
285        fs::create_dir_all(&self.rootfs_dir).map_err(|e| {
286            RegistryError::Cache(CacheError::Io(std::io::Error::new(
287                e.kind(),
288                format!("failed to create rootfs directory: {e}"),
289            )))
290        })?;
291
292        // Detect compression type
293        let compression = CompressionType::detect(media_type, layer_data);
294
295        // Decompress and extract
296        match compression {
297            CompressionType::Gzip => self.unpack_gzip(layer_data),
298            CompressionType::Zstd => self.unpack_zstd(layer_data),
299            CompressionType::None => self.unpack_tar(layer_data),
300        }
301    }
302
303    /// Unpack a single layer from a streaming reader, without buffering the
304    /// whole (compressed) layer in memory.
305    ///
306    /// Compression is taken from `media_type` when recognized; otherwise the
307    /// first bytes are peeked (via the internal [`BufReader`]) for magic-byte
308    /// detection — no full read. The decompressed tar is streamed straight into
309    /// the rootfs, so a multi-GB layer extracts with bounded RAM.
310    ///
311    /// # Errors
312    /// Returns an error if the rootfs cannot be created, or decompression /
313    /// extraction fails.
314    pub fn unpack_layer_reader<R: Read>(&mut self, reader: R, media_type: &str) -> Result<()> {
315        fs::create_dir_all(&self.rootfs_dir).map_err(|e| {
316            RegistryError::Cache(CacheError::Io(std::io::Error::new(
317                e.kind(),
318                format!("failed to create rootfs directory: {e}"),
319            )))
320        })?;
321
322        let mut buffered = BufReader::new(reader);
323        let compression = if let Some(c) = CompressionType::from_media_type(media_type) {
324            c
325        } else {
326            // Peek the first bytes without consuming them.
327            let magic = buffered.fill_buf().map_err(|e| {
328                RegistryError::Cache(CacheError::Io(std::io::Error::new(
329                    e.kind(),
330                    format!("failed to read layer magic bytes: {e}"),
331                )))
332            })?;
333            CompressionType::from_magic_bytes(magic)
334        };
335
336        self.extract_compressed(buffered, compression)
337    }
338
339    /// Extract ONE on-disk layer file into this unpacker's directory for use as
340    /// an overlayfs `lowerdir`, PRESERVING whiteouts as overlay markers.
341    ///
342    /// Unlike [`unpack_layer_reader`] / [`unpack_layers_from_files`] (which merge
343    /// a stack of layers into one tree and COLLAPSE whiteouts), this extracts a
344    /// single layer in isolation: `.wh.<name>` becomes a `0:0` char device and
345    /// `.wh..wh..opq` becomes the `trusted.overlay.opaque` xattr, so the kernel
346    /// overlay driver — not this unpacker — resolves deletions at mount time.
347    ///
348    /// The unpacker MUST have been built with [`LayerUnpacker::new_for_overlay`]
349    /// (i.e. [`WhiteoutMode::Preserve`]); a [`WhiteoutMode::Collapse`] unpacker
350    /// is rejected, since collapsing into a single-layer dir would silently drop
351    /// the deletion (no lower file exists to delete) and produce a wrong
352    /// lowerdir. All of the merged path's safety still applies: the
353    /// `var/run -> /run` relativization, `materialize_real_parent`, and
354    /// `lremove_if_symlink` host-escape guards run identically here.
355    ///
356    /// File xattrs/capabilities the tar carries (e.g. `security.capability` set
357    /// by `setcap`) are NOT preserved — only the file mode is applied, the same
358    /// known gap the legacy full-copy merged path has had, so this is not a
359    /// regression. Wave 2 / a follow-up can add full xattr passthrough in
360    /// [`extract_file`] for both paths at once.
361    ///
362    /// Compression is taken from `media_type` (gzip/zstd/plain), falling back to
363    /// magic-byte detection for unrecognized types. Linux-only (mknod + the
364    /// `trusted.*` xattr need root / `CAP_MKNOD` + `CAP_SYS_ADMIN`).
365    ///
366    /// # Errors
367    ///
368    /// Returns an error if the unpacker is in collapse mode, the layer file
369    /// cannot be opened or is empty, decompression / extraction fails, or a
370    /// whiteout marker cannot be written (e.g. missing `CAP_MKNOD`).
371    pub fn unpack_layer_to_overlay_dir(
372        &mut self,
373        layer_file: &Path,
374        media_type: &str,
375    ) -> Result<()> {
376        if self.whiteout_mode != WhiteoutMode::Preserve {
377            return Err(RegistryError::Cache(CacheError::Corrupted(
378                "unpack_layer_to_overlay_dir requires a Preserve-mode unpacker \
379                 (use LayerUnpacker::new_for_overlay)"
380                    .to_string(),
381            )));
382        }
383
384        let file = File::open(layer_file).map_err(|e| {
385            RegistryError::Cache(CacheError::Io(std::io::Error::new(
386                e.kind(),
387                format!(
388                    "failed to open overlay layer file {}: {e}",
389                    layer_file.display()
390                ),
391            )))
392        })?;
393        let len = file.metadata().map_or(0, |m| m.len());
394        if len == 0 {
395            return Err(RegistryError::Cache(CacheError::Corrupted(format!(
396                "overlay layer file {} is empty",
397                layer_file.display()
398            ))));
399        }
400
401        // Reuse the streaming + safety pipeline; whiteout handling diverges via
402        // `whiteout_mode` inside `extract_archive`.
403        self.unpack_layer_reader(file, media_type)
404    }
405
406    /// Extract ONE on-disk layer file into this unpacker's directory for use as
407    /// a ROOTLESS `fuse-overlayfs` `lowerdir`, preserving whiteouts the way
408    /// fuse-overlayfs reads them WITHOUT privilege.
409    ///
410    /// Unlike [`unpack_layer_to_overlay_dir`](Self::unpack_layer_to_overlay_dir)
411    /// (which needs `CAP_MKNOD` + `CAP_SYS_ADMIN` to write `0:0` char devices and
412    /// the `trusted.overlay.opaque` xattr), this writes a plain `.wh.<name>`
413    /// regular file for a regular whiteout and the `user.overlay.opaque="y"`
414    /// xattr for an opaque directory — both settable by an unprivileged process,
415    /// and both recognised by `fuse-overlayfs` on every layer (its
416    /// `src/overlay.rs` scans for `.wh.<name>` files and `is_directory_opaque`
417    /// checks `trusted.overlay.opaque` / `user.overlay.opaque` /
418    /// `user.fuseoverlayfs.opaque` plus the `.wh..wh..opq` sentinel).
419    ///
420    /// The unpacker MUST have been built with
421    /// [`LayerUnpacker::new_for_overlay_rootless`] (i.e.
422    /// [`WhiteoutMode::PreserveRootless`]). All of the merged path's safety still
423    /// applies identically: the `var/run -> /run` relativization,
424    /// `materialize_real_parent`, and `lremove_if_symlink` host-escape guards.
425    ///
426    /// File xattrs/capabilities the tar carries are NOT preserved (same known gap
427    /// as the kernel `Preserve` and legacy full-copy paths). Compression is taken
428    /// from `media_type`, falling back to magic-byte detection.
429    ///
430    /// # Errors
431    ///
432    /// Returns an error if the unpacker is not in `PreserveRootless` mode, the
433    /// layer file cannot be opened or is empty, decompression / extraction fails,
434    /// or a whiteout marker cannot be written.
435    pub fn unpack_layer_to_overlay_dir_rootless(
436        &mut self,
437        layer_file: &Path,
438        media_type: &str,
439    ) -> Result<()> {
440        if self.whiteout_mode != WhiteoutMode::PreserveRootless {
441            return Err(RegistryError::Cache(CacheError::Corrupted(
442                "unpack_layer_to_overlay_dir_rootless requires a PreserveRootless-mode \
443                 unpacker (use LayerUnpacker::new_for_overlay_rootless)"
444                    .to_string(),
445            )));
446        }
447
448        let file = File::open(layer_file).map_err(|e| {
449            RegistryError::Cache(CacheError::Io(std::io::Error::new(
450                e.kind(),
451                format!(
452                    "failed to open rootless overlay layer file {}: {e}",
453                    layer_file.display()
454                ),
455            )))
456        })?;
457        let len = file.metadata().map_or(0, |m| m.len());
458        if len == 0 {
459            return Err(RegistryError::Cache(CacheError::Corrupted(format!(
460                "rootless overlay layer file {} is empty",
461                layer_file.display()
462            ))));
463        }
464
465        // Reuse the streaming + safety pipeline; whiteout handling diverges via
466        // `whiteout_mode` inside `extract_archive`.
467        self.unpack_layer_reader(file, media_type)
468    }
469
470    /// Unpack multiple on-disk layer files in order (base layer first),
471    /// streaming each file so no layer is ever fully held in RAM.
472    ///
473    /// # Errors
474    ///
475    /// Returns an error if a layer file cannot be opened, a layer is empty,
476    /// decompression fails, extraction fails, or the rootfs ends up empty.
477    #[allow(clippy::unused_async)]
478    pub async fn unpack_layers_from_files(&mut self, layers: &[(PathBuf, String)]) -> Result<()> {
479        if layers.is_empty() {
480            return Err(RegistryError::Cache(CacheError::Corrupted(
481                "no layers to unpack".to_string(),
482            )));
483        }
484
485        for (i, (path, media_type)) in layers.iter().enumerate() {
486            let file = File::open(path).map_err(|e| {
487                RegistryError::Cache(CacheError::Io(std::io::Error::new(
488                    e.kind(),
489                    format!("failed to open layer {i} file {}: {e}", path.display()),
490                )))
491            })?;
492
493            // Validate layer is not empty (mirrors the in-memory path).
494            let len = file.metadata().map_or(0, |m| m.len());
495            if len == 0 {
496                return Err(RegistryError::Cache(CacheError::Corrupted(format!(
497                    "layer {i} is empty"
498                ))));
499            }
500
501            tracing::debug!(
502                layer = i,
503                media_type = %media_type,
504                size = len,
505                "unpacking layer (streamed from file)"
506            );
507            self.unpack_layer_reader(file, media_type)?;
508        }
509
510        // Validate rootfs has content after all layers.
511        if !self.rootfs_has_content() {
512            return Err(RegistryError::Cache(CacheError::Corrupted(
513                "rootfs empty after unpacking all layers".to_string(),
514            )));
515        }
516
517        Ok(())
518    }
519
520    /// Unpack multiple layers in order (base layer first)
521    ///
522    /// # Errors
523    ///
524    /// Returns an error if any layer is empty, decompression fails, or extraction fails.
525    pub async fn unpack_layers(&mut self, layers: &[(Vec<u8>, String)]) -> Result<()> {
526        if layers.is_empty() {
527            return Err(RegistryError::Cache(CacheError::Corrupted(
528                "no layers to unpack".to_string(),
529            )));
530        }
531
532        for (i, (data, media_type)) in layers.iter().enumerate() {
533            // Validate layer data is not empty
534            if data.is_empty() {
535                return Err(RegistryError::Cache(CacheError::Corrupted(format!(
536                    "layer {i} is empty"
537                ))));
538            }
539
540            tracing::debug!(
541                layer = i,
542                media_type = %media_type,
543                size = data.len(),
544                "unpacking layer"
545            );
546            self.unpack_layer(data, media_type).await?;
547        }
548
549        // Validate rootfs has content after all layers
550        if !self.rootfs_has_content() {
551            return Err(RegistryError::Cache(CacheError::Corrupted(
552                "rootfs empty after unpacking all layers".to_string(),
553            )));
554        }
555
556        Ok(())
557    }
558
559    /// Check if the rootfs directory has any content
560    fn rootfs_has_content(&self) -> bool {
561        if let Ok(mut entries) = std::fs::read_dir(&self.rootfs_dir) {
562            return entries.next().is_some();
563        }
564        false
565    }
566
567    /// Unpack a gzip-compressed tar archive
568    fn unpack_gzip(&mut self, data: &[u8]) -> Result<()> {
569        self.extract_compressed(Cursor::new(data), CompressionType::Gzip)
570    }
571
572    /// Unpack a zstd-compressed tar archive
573    fn unpack_zstd(&mut self, data: &[u8]) -> Result<()> {
574        self.extract_compressed(Cursor::new(data), CompressionType::Zstd)
575    }
576
577    /// Unpack an uncompressed tar archive
578    fn unpack_tar(&mut self, data: &[u8]) -> Result<()> {
579        self.extract_compressed(Cursor::new(data), CompressionType::None)
580    }
581
582    /// Decompress a tar stream per `compression` and extract it into the rootfs.
583    /// Shared by the in-memory (`&[u8]`) and streaming (`impl Read`) paths.
584    fn extract_compressed<R: Read>(
585        &mut self,
586        reader: R,
587        compression: CompressionType,
588    ) -> Result<()> {
589        match compression {
590            CompressionType::Gzip => {
591                let mut archive = Archive::new(GzDecoder::new(reader));
592                self.extract_archive(&mut archive)
593            }
594            CompressionType::Zstd => {
595                let decoder = zstd::stream::Decoder::new(reader).map_err(|e| {
596                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
597                        std::io::ErrorKind::InvalidData,
598                        format!("zstd decompression failed: {e}"),
599                    )))
600                })?;
601                let mut archive = Archive::new(decoder);
602                self.extract_archive(&mut archive)
603            }
604            CompressionType::None => {
605                let mut archive = Archive::new(reader);
606                self.extract_archive(&mut archive)
607            }
608        }
609    }
610
611    /// Extract files from a tar archive, handling whiteouts
612    fn extract_archive<R: Read>(&mut self, archive: &mut Archive<R>) -> Result<()> {
613        let entries = archive.entries().map_err(|e| {
614            RegistryError::Cache(CacheError::Io(std::io::Error::new(
615                e.kind(),
616                format!("failed to read tar entries: {e}"),
617            )))
618        })?;
619
620        for entry in entries {
621            let mut entry = entry.map_err(|e| {
622                RegistryError::Cache(CacheError::Io(std::io::Error::new(
623                    e.kind(),
624                    format!("failed to read tar entry: {e}"),
625                )))
626            })?;
627
628            let path = entry.path().map_err(|e| {
629                RegistryError::Cache(CacheError::Io(std::io::Error::new(
630                    e.kind(),
631                    format!("failed to get entry path: {e}"),
632                )))
633            })?;
634            let path = path.to_path_buf();
635
636            // Security: Validate path doesn't escape rootfs
637            if !self.is_safe_path(&path) {
638                tracing::warn!(path = %path.display(), "skipping potentially unsafe path");
639                continue;
640            }
641
642            let file_name = path
643                .file_name()
644                .and_then(|n| n.to_str())
645                .unwrap_or_default();
646
647            // Handle opaque whiteout.
648            if file_name == OPAQUE_WHITEOUT {
649                if let Some(parent) = path.parent() {
650                    match self.whiteout_mode {
651                        WhiteoutMode::Collapse => self.apply_opaque_whiteout(parent)?,
652                        WhiteoutMode::Preserve => self.preserve_opaque_whiteout(parent)?,
653                        WhiteoutMode::PreserveRootless => {
654                            self.preserve_opaque_whiteout_rootless(parent)?;
655                        }
656                    }
657                }
658                continue;
659            }
660
661            // Handle regular whiteout `.wh.<name>`.
662            if let Some(target_name) = file_name.strip_prefix(WHITEOUT_PREFIX) {
663                if let Some(parent) = path.parent() {
664                    match self.whiteout_mode {
665                        WhiteoutMode::Collapse => {
666                            let target_path = parent.join(target_name);
667                            self.apply_whiteout(&target_path)?;
668                        }
669                        WhiteoutMode::Preserve => {
670                            self.preserve_whiteout(parent, target_name)?;
671                        }
672                        WhiteoutMode::PreserveRootless => {
673                            self.preserve_whiteout_rootless(parent, target_name)?;
674                        }
675                    }
676                }
677                continue;
678            }
679
680            // Skip if this path was deleted by a whiteout
681            let full_path = self.rootfs_dir.join(&path);
682            if self.is_deleted(&path) {
683                continue;
684            }
685
686            // Extract the entry
687            self.extract_entry(&mut entry, &full_path)?;
688        }
689
690        self.resolve_pending_hardlinks()?;
691        // Re-apply deferred (possibly read-only) directory modes LAST, after
692        // every file / symlink / hard link inside them has been written.
693        self.restore_dir_modes()
694    }
695
696    /// Retry hard links whose target hadn't been extracted yet when their
697    /// entry was reached. A target that STILL doesn't exist after the whole
698    /// layer is on disk is a hard error — silently skipping is how a
699    /// truncated rootfs used to masquerade as a successful unpack.
700    fn resolve_pending_hardlinks(&mut self) -> Result<()> {
701        for (link_path, target_full) in std::mem::take(&mut self.pending_hardlinks) {
702            fs::hard_link(&target_full, &link_path).map_err(|e| {
703                RegistryError::Cache(CacheError::Io(std::io::Error::new(
704                    e.kind(),
705                    format!(
706                        "failed to create deferred hard link {} -> {} \
707                         (target absent after full layer extraction): {}",
708                        link_path.display(),
709                        target_full.display(),
710                        e
711                    ),
712                )))
713            })?;
714        }
715        Ok(())
716    }
717
718    /// Re-apply directory modes that were deferred during extraction.
719    ///
720    /// Directories are created `0o700` so their (possibly later) children can
721    /// be written; their archived mode — which may be read-only, e.g. Fedora's
722    /// `0o555` ca-trust dirs — is recorded and re-applied here, after the
723    /// whole layer is on disk. Modes are applied DEEPEST-FIRST (longest path
724    /// component count first): restoring a parent to read-only must never
725    /// block writing a still-pending child, and since this runs after all
726    /// entries are extracted, going deepest-first keeps each parent writable
727    /// until its descendants are sealed.
728    ///
729    /// The `Result<()>`/no-op shape mirrors [`set_permissions`]: load-bearing
730    /// on Unix, a pure no-op on non-Unix.
731    #[allow(clippy::unnecessary_wraps)]
732    fn restore_dir_modes(&mut self) -> Result<()> {
733        let mut pending = std::mem::take(&mut self.pending_dir_modes);
734        #[cfg(unix)]
735        {
736            use std::os::unix::fs::PermissionsExt;
737
738            // Deepest-first: more path components => applied earlier.
739            pending.sort_by_key(|b| std::cmp::Reverse(b.0.components().count()));
740
741            for (dir_path, mode) in pending {
742                let permissions = fs::Permissions::from_mode(mode);
743                fs::set_permissions(&dir_path, permissions).map_err(|e| {
744                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
745                        e.kind(),
746                        format!(
747                            "failed to restore deferred directory mode {:o} on {}: {}",
748                            mode,
749                            dir_path.display(),
750                            e
751                        ),
752                    )))
753                })?;
754            }
755        }
756
757        #[cfg(not(unix))]
758        {
759            let _ = &mut pending;
760        }
761
762        Ok(())
763    }
764
765    /// Validate that a path doesn't escape the rootfs directory
766    #[allow(clippy::unused_self)]
767    fn is_safe_path(&self, path: &Path) -> bool {
768        use std::path::Component;
769
770        // Reject platform-absolute paths (drive-letter on Windows, `/` on Unix).
771        if path.is_absolute() {
772            return false;
773        }
774
775        // Reject POSIX root-prefixed paths even on Windows — container tar
776        // layers carry `/etc/passwd`-style paths, and those must still be
777        // treated as root-escaping regardless of the host path semantics.
778        let mut components = path.components();
779        if matches!(
780            components.next(),
781            Some(Component::RootDir | Component::Prefix(_))
782        ) {
783            return false;
784        }
785
786        // Reject paths with .. components anywhere.
787        for component in path.components() {
788            if matches!(component, Component::ParentDir) {
789                return false;
790            }
791        }
792
793        true
794    }
795
796    /// Check if a path has been marked as deleted
797    fn is_deleted(&self, path: &Path) -> bool {
798        // Check if this exact path or any parent is deleted
799        let mut current = path.to_path_buf();
800        loop {
801            if self.deleted_paths.contains(&current) {
802                return true;
803            }
804            if !current.pop() {
805                break;
806            }
807        }
808        false
809    }
810
811    /// Apply a regular whiteout (delete a specific file or directory)
812    fn apply_whiteout(&mut self, path: &Path) -> Result<()> {
813        let full_path = self.rootfs_dir.join(path);
814        self.deleted_paths.insert(path.to_path_buf());
815
816        // Symlink-safe delete: a whiteout of `var/run` (a `-> /run` symlink) must
817        // unlink the LINK, never `remove_dir_all` through it into the host. The
818        // old `is_dir()` branch followed symlinks; `remove_path_no_follow` lstats.
819        zlayer_paths::safe_fs::remove_path_no_follow(&full_path).map_err(|e| {
820            RegistryError::Cache(CacheError::Io(std::io::Error::new(
821                e.kind(),
822                format!(
823                    "failed to remove whiteout target {}: {}",
824                    full_path.display(),
825                    e
826                ),
827            )))
828        })?;
829
830        Ok(())
831    }
832
833    /// Apply an opaque whiteout (delete all contents in a directory)
834    fn apply_opaque_whiteout(&mut self, dir_path: &Path) -> Result<()> {
835        let full_path = self.rootfs_dir.join(dir_path);
836
837        // Only enumerate a REAL directory. If `full_path` is a symlink, `is_dir()`
838        // would follow it and we'd `read_dir`/delete inside the link target (the
839        // host). `lstat` (symlink_metadata) keeps us inside the rootfs.
840        let is_real_dir = std::fs::symlink_metadata(&full_path).is_ok_and(|md| md.is_dir());
841        if is_real_dir {
842            // Remove all contents but keep the directory
843            for entry in fs::read_dir(&full_path).map_err(|e| {
844                RegistryError::Cache(CacheError::Io(std::io::Error::new(
845                    e.kind(),
846                    format!("failed to read directory {}: {}", full_path.display(), e),
847                )))
848            })? {
849                let entry = entry.map_err(|e| {
850                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
851                        e.kind(),
852                        format!("failed to read directory entry: {e}"),
853                    )))
854                })?;
855                let entry_path = entry.path();
856                let relative = entry_path
857                    .strip_prefix(&self.rootfs_dir)
858                    .unwrap_or(&entry_path);
859                self.deleted_paths.insert(relative.to_path_buf());
860
861                // Symlink-safe: unlink a symlinked child, never traverse it.
862                zlayer_paths::safe_fs::remove_path_no_follow(&entry_path).map_err(|e| {
863                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
864                        e.kind(),
865                        format!("failed to remove {}: {}", entry_path.display(), e),
866                    )))
867                })?;
868            }
869        }
870
871        Ok(())
872    }
873
874    /// Preserve a regular whiteout `.wh.<name>` as an overlayfs whiteout: a
875    /// `0:0` character device named `<name>` in the (real, in-rootfs) parent.
876    ///
877    /// This is the per-layer-lowerdir counterpart of [`apply_whiteout`]: there
878    /// is no merged lower file to delete in a single-layer dir, so the deletion
879    /// is recorded the way the kernel's overlay driver reads it — an opaque
880    /// `0:0` char device at the whited-out name shadows whatever a lower layer
881    /// provides at the same path. Requires `CAP_MKNOD` (root); Linux-only.
882    #[cfg(target_os = "linux")]
883    fn preserve_whiteout(&mut self, parent: &Path, target_name: &str) -> Result<()> {
884        use nix::sys::stat::{makedev, mknod, Mode, SFlag};
885
886        let parent_full = self.rootfs_dir.join(parent);
887        // The parent dir of the whiteout may not have been created yet in this
888        // single layer (e.g. a tar that only deletes `foo/bar` ships only the
889        // `.wh.bar` entry under `foo/`). Materialize a real in-rootfs parent so
890        // the char device cannot be created through an escaping symlink.
891        let target_full = parent_full.join(target_name);
892        zlayer_paths::safe_fs::materialize_real_parent(&self.rootfs_dir, &target_full).map_err(
893            |e| {
894                RegistryError::Cache(CacheError::Io(std::io::Error::new(
895                    e.kind(),
896                    format!(
897                        "failed to materialize parent for whiteout {}: {}",
898                        target_full.display(),
899                        e
900                    ),
901                )))
902            },
903        )?;
904        // Drop any pre-existing entry (file/dir/symlink) at the whiteout name so
905        // the char device replaces it. lstat-based, never follows a symlink out.
906        zlayer_paths::safe_fs::remove_path_no_follow(&target_full).map_err(|e| {
907            RegistryError::Cache(CacheError::Io(std::io::Error::new(
908                e.kind(),
909                format!(
910                    "failed to clear whiteout target {}: {}",
911                    target_full.display(),
912                    e
913                ),
914            )))
915        })?;
916
917        mknod(&target_full, SFlag::S_IFCHR, Mode::empty(), makedev(0, 0)).map_err(|e| {
918            RegistryError::Cache(CacheError::Io(std::io::Error::other(format!(
919                "failed to mknod overlay whiteout 0:0 char device at {} (needs CAP_MKNOD): {}",
920                target_full.display(),
921                e
922            ))))
923        })?;
924
925        Ok(())
926    }
927
928    /// Preserve a regular whiteout — non-Linux stub. mknod of a `0:0` char
929    /// device is a Linux+root operation; the overlay rootfs path only runs on
930    /// Linux, so this is unreachable elsewhere and errors loudly if hit.
931    #[cfg(not(target_os = "linux"))]
932    #[allow(clippy::unused_self)] // `&mut self` kept for parity with the cfg(linux) variant
933    fn preserve_whiteout(&mut self, _parent: &Path, _target_name: &str) -> Result<()> {
934        Err(RegistryError::Cache(CacheError::Corrupted(
935            "overlay whiteout preservation is only supported on Linux".to_string(),
936        )))
937    }
938
939    /// Preserve an opaque whiteout `.wh..wh..opq` as the overlayfs
940    /// `trusted.overlay.opaque="y"` xattr on the containing directory.
941    ///
942    /// The per-layer-lowerdir counterpart of [`apply_opaque_whiteout`]: instead
943    /// of emptying a merged dir, set the xattr the kernel reads to mean "this
944    /// dir fully masks all lower layers' versions of the same dir". Setting a
945    /// `trusted.*` xattr requires `CAP_SYS_ADMIN` (root); Linux-only.
946    #[cfg(target_os = "linux")]
947    fn preserve_opaque_whiteout(&mut self, dir_path: &Path) -> Result<()> {
948        let full_path = self.rootfs_dir.join(dir_path);
949        // Ensure the directory the opaque marker applies to actually exists as a
950        // real dir inside the rootfs (a layer can ship `<dir>/.wh..wh..opq`
951        // without a separate `<dir>/` entry).
952        fs::create_dir_all(&full_path).map_err(|e| {
953            RegistryError::Cache(CacheError::Io(std::io::Error::new(
954                e.kind(),
955                format!(
956                    "failed to create opaque-whiteout dir {}: {}",
957                    full_path.display(),
958                    e
959                ),
960            )))
961        })?;
962
963        xattr::set(&full_path, "trusted.overlay.opaque", b"y").map_err(|e| {
964            RegistryError::Cache(CacheError::Io(std::io::Error::new(
965                e.kind(),
966                format!(
967                    "failed to set trusted.overlay.opaque on {} (needs CAP_SYS_ADMIN): {}",
968                    full_path.display(),
969                    e
970                ),
971            )))
972        })?;
973
974        Ok(())
975    }
976
977    /// Preserve an opaque whiteout — non-Linux stub (see [`preserve_whiteout`]).
978    #[cfg(not(target_os = "linux"))]
979    #[allow(clippy::unused_self)] // `&mut self` kept for parity with the cfg(linux) variant
980    fn preserve_opaque_whiteout(&mut self, _dir_path: &Path) -> Result<()> {
981        Err(RegistryError::Cache(CacheError::Corrupted(
982            "overlay opaque-whiteout preservation is only supported on Linux".to_string(),
983        )))
984    }
985
986    /// Preserve a regular whiteout `.wh.<name>` the ROOTLESS way: write a plain
987    /// empty `.wh.<name>` regular file in the (real, in-rootfs) parent.
988    ///
989    /// The unprivileged counterpart of [`preserve_whiteout`](Self::preserve_whiteout):
990    /// `fuse-overlayfs` recognises a `.wh.<name>` regular file on a lower layer
991    /// as a deletion of `<name>` (its `src/overlay.rs` checks for exactly this
992    /// file during readdir), so no `mknod`/`CAP_MKNOD` is needed. The same
993    /// host-escape guards as the privileged path run first: a real in-rootfs
994    /// parent is materialized (replacing any escaping symlink component) and any
995    /// pre-existing entry at the whiteout name is lstat-removed.
996    fn preserve_whiteout_rootless(&mut self, parent: &Path, target_name: &str) -> Result<()> {
997        let parent_full = self.rootfs_dir.join(parent);
998        let target_full = parent_full.join(target_name);
999        // Materialize a real in-rootfs parent so the `.wh.` file cannot be
1000        // created through an escaping symlink.
1001        zlayer_paths::safe_fs::materialize_real_parent(&self.rootfs_dir, &target_full).map_err(
1002            |e| {
1003                RegistryError::Cache(CacheError::Io(std::io::Error::new(
1004                    e.kind(),
1005                    format!(
1006                        "failed to materialize parent for rootless whiteout {}: {}",
1007                        target_full.display(),
1008                        e
1009                    ),
1010                )))
1011            },
1012        )?;
1013        // Drop any pre-existing entry (file/dir/symlink) at the whiteout name so
1014        // the `.wh.` marker is unambiguous. lstat-based, never follows a symlink.
1015        zlayer_paths::safe_fs::remove_path_no_follow(&target_full).map_err(|e| {
1016            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1017                e.kind(),
1018                format!(
1019                    "failed to clear rootless whiteout target {}: {}",
1020                    target_full.display(),
1021                    e
1022                ),
1023            )))
1024        })?;
1025
1026        // The `.wh.<name>` marker is a sibling of `<name>` in the same parent.
1027        let wh_name = format!("{WHITEOUT_PREFIX}{target_name}");
1028        let wh_full = parent_full.join(&wh_name);
1029        File::create(&wh_full).map_err(|e| {
1030            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1031                e.kind(),
1032                format!(
1033                    "failed to create rootless .wh. whiteout file {}: {}",
1034                    wh_full.display(),
1035                    e
1036                ),
1037            )))
1038        })?;
1039
1040        Ok(())
1041    }
1042
1043    /// Preserve an opaque whiteout `.wh..wh..opq` the ROOTLESS way: set the
1044    /// `user.overlay.opaque="y"` xattr on the containing directory.
1045    ///
1046    /// The unprivileged counterpart of
1047    /// [`preserve_opaque_whiteout`](Self::preserve_opaque_whiteout): instead of
1048    /// the `CAP_SYS_ADMIN`-only `trusted.overlay.opaque`, set fuse-overlayfs's
1049    /// `UNPRIVILEGED_OPAQUE_XATTR` (`user.overlay.opaque`), which lives in the
1050    /// user xattr namespace and so is settable without privilege.
1051    /// fuse-overlayfs's `is_directory_opaque` checks this name. Also drops a
1052    /// `.wh..wh..opq` sentinel file as a belt-and-suspenders fallback (the same
1053    /// sentinel fuse-overlayfs falls back to when no opaque xattr is present),
1054    /// so the marker survives even on a backing filesystem that silently rejects
1055    /// `user.*` xattrs.
1056    fn preserve_opaque_whiteout_rootless(&mut self, dir_path: &Path) -> Result<()> {
1057        let full_path = self.rootfs_dir.join(dir_path);
1058        fs::create_dir_all(&full_path).map_err(|e| {
1059            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1060                e.kind(),
1061                format!(
1062                    "failed to create rootless opaque-whiteout dir {}: {}",
1063                    full_path.display(),
1064                    e
1065                ),
1066            )))
1067        })?;
1068
1069        // Primary marker: the user-namespace opaque xattr fuse-overlayfs reads.
1070        // The `xattr` crate is a Linux-only dependency and fuse-overlayfs is
1071        // itself Linux-only, so on other targets we skip the xattr and rely
1072        // solely on the `.wh..wh..opq` sentinel file written below.
1073        #[cfg(target_os = "linux")]
1074        let xattr_ok = xattr::set(&full_path, "user.overlay.opaque", b"y").is_ok();
1075        #[cfg(not(target_os = "linux"))]
1076        let xattr_ok = false;
1077
1078        // Fallback marker: the OCI `.wh..wh..opq` sentinel file. fuse-overlayfs
1079        // treats a directory containing this file as opaque too, so writing it
1080        // keeps the deletion correct even when the backing fs drops user xattrs.
1081        let sentinel = full_path.join(OPAQUE_WHITEOUT);
1082        let sentinel_ok = File::create(&sentinel).is_ok();
1083
1084        if xattr_ok || sentinel_ok {
1085            Ok(())
1086        } else {
1087            Err(RegistryError::Cache(CacheError::Io(std::io::Error::other(
1088                format!(
1089                    "failed to mark rootless opaque whiteout on {} \
1090                     (both user.overlay.opaque xattr and .wh..wh..opq sentinel failed)",
1091                    full_path.display()
1092                ),
1093            ))))
1094        }
1095    }
1096
1097    /// Extract a single tar entry to the filesystem
1098    #[allow(clippy::too_many_lines)]
1099    fn extract_entry<R: Read>(
1100        &mut self,
1101        entry: &mut tar::Entry<'_, R>,
1102        full_path: &Path,
1103    ) -> Result<()> {
1104        let entry_type = entry.header().entry_type();
1105
1106        // SECURITY (host-escape via rootfs symlink): `is_safe_path` only checks
1107        // the LOGICAL tar path for `..`/absolute — it does NOT resolve symlinks
1108        // already written to disk. A layer can ship the standard
1109        // `var/run -> /run` symlink and then an entry under `var/run/...`; the
1110        // create/write/chmod below would then follow the link onto the HOST's
1111        // `/run` and (e.g.) chmod `/run/sshd` group-writable, wedging sshd.
1112        // Force every parent component to be a real directory INSIDE the rootfs
1113        // (replacing any symlinked component), and drop a pre-existing symlink at
1114        // the target itself so the write/chmod can't traverse it.
1115        zlayer_paths::safe_fs::materialize_real_parent(&self.rootfs_dir, full_path).map_err(
1116            |e| {
1117                RegistryError::Cache(CacheError::Io(std::io::Error::new(
1118                    e.kind(),
1119                    format!(
1120                        "failed to materialize safe parent for {}: {}",
1121                        full_path.display(),
1122                        e
1123                    ),
1124                )))
1125            },
1126        )?;
1127        zlayer_paths::safe_fs::lremove_if_symlink(full_path).map_err(|e| {
1128            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1129                e.kind(),
1130                format!("failed to clear symlink at {}: {}", full_path.display(), e),
1131            )))
1132        })?;
1133
1134        match entry_type {
1135            tar::EntryType::Regular | tar::EntryType::Continuous => {
1136                self.extract_file(entry, full_path)?;
1137            }
1138            tar::EntryType::Directory => {
1139                fs::create_dir_all(full_path).map_err(|e| {
1140                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
1141                        e.kind(),
1142                        format!("failed to create directory {}: {}", full_path.display(), e),
1143                    )))
1144                })?;
1145                // DEFER the archived mode. A directory may be archived
1146                // read-only (Fedora's `etc/pki/ca-trust/...` arrives `0o555`)
1147                // yet still hold child entries that appear later in the tar.
1148                // Force it to a permissive `0o700` now so those children can
1149                // be written, and record the real mode to re-apply at the end
1150                // via `restore_dir_modes`. Idempotent across layers: an
1151                // earlier layer may have already created and left this dir at
1152                // `0o555`, so unconditionally force it back to `0o700`.
1153                #[cfg(unix)]
1154                {
1155                    use std::os::unix::fs::PermissionsExt;
1156
1157                    let writable = fs::Permissions::from_mode(0o700);
1158                    fs::set_permissions(full_path, writable).map_err(|e| {
1159                        RegistryError::Cache(CacheError::Io(std::io::Error::new(
1160                            e.kind(),
1161                            format!(
1162                                "failed to make directory writable {}: {}",
1163                                full_path.display(),
1164                                e
1165                            ),
1166                        )))
1167                    })?;
1168
1169                    if let Ok(archived_mode) = entry.header().mode() {
1170                        self.pending_dir_modes
1171                            .push((full_path.to_path_buf(), archived_mode));
1172                    }
1173                }
1174                #[cfg(not(unix))]
1175                {
1176                    self.set_permissions(entry, full_path)?;
1177                }
1178            }
1179            tar::EntryType::Symlink => {
1180                if let Ok(Some(target)) = entry.link_name() {
1181                    // Remove existing file/link if present
1182                    let _ = fs::remove_file(full_path);
1183                    #[cfg(unix)]
1184                    {
1185                        // Relativize an ABSOLUTE target so the unpacked rootfs
1186                        // stays self-contained. The standard `var/run -> /run`
1187                        // (absolute) lets any host-context filesystem op — a
1188                        // pre-pivot permissions/dir walk, the runtime's mount
1189                        // setup — follow the link onto the HOST's `/run`,
1190                        // chmod'ing host `/run`/`/run/sshd` (locks out
1191                        // systemd-resolved/-networkd, wedges host SSH). A
1192                        // relative `../run` resolves identically inside the
1193                        // container (post-pivot `/` IS the rootfs) but can
1194                        // never escape the rootfs. See
1195                        // `zlayer_paths::safe_fs::relativize_abs_symlink`.
1196                        let link_target: PathBuf = if target.is_absolute() {
1197                            full_path
1198                                .strip_prefix(&self.rootfs_dir)
1199                                .ok()
1200                                .and_then(|rel| {
1201                                    zlayer_paths::safe_fs::relativize_abs_symlink(rel, &target)
1202                                })
1203                                .unwrap_or_else(|| target.to_path_buf())
1204                        } else {
1205                            target.to_path_buf()
1206                        };
1207                        std::os::unix::fs::symlink(&link_target, full_path).map_err(|e| {
1208                            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1209                                e.kind(),
1210                                format!(
1211                                    "failed to create symlink {} -> {}: {}",
1212                                    full_path.display(),
1213                                    link_target.display(),
1214                                    e
1215                                ),
1216                            )))
1217                        })?;
1218                    }
1219                    #[cfg(not(unix))]
1220                    {
1221                        // On non-Unix, try to copy the file or create a placeholder
1222                        tracing::warn!(
1223                            path = %full_path.display(),
1224                            target = %target.display(),
1225                            "symlinks not fully supported on this platform"
1226                        );
1227                    }
1228                }
1229            }
1230            tar::EntryType::Link => {
1231                if let Ok(Some(target)) = entry.link_name() {
1232                    let target_full = self.rootfs_dir.join(&*target);
1233                    // Remove existing file if present
1234                    let _ = fs::remove_file(full_path);
1235                    if target_full.exists() {
1236                        fs::hard_link(&target_full, full_path).map_err(|e| {
1237                            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1238                                e.kind(),
1239                                format!(
1240                                    "failed to create hard link {} -> {}: {}",
1241                                    full_path.display(),
1242                                    target_full.display(),
1243                                    e
1244                                ),
1245                            )))
1246                        })?;
1247                    } else {
1248                        // Forward reference: the link's target appears later
1249                        // in this layer (tar entry order is not guaranteed).
1250                        // Defer and retry once the whole layer is extracted.
1251                        self.pending_hardlinks
1252                            .push((full_path.to_path_buf(), target_full));
1253                    }
1254                }
1255            }
1256            tar::EntryType::Char | tar::EntryType::Block | tar::EntryType::Fifo => {
1257                // Device nodes and FIFOs require special handling and usually root
1258                tracing::debug!(
1259                    path = %full_path.display(),
1260                    entry_type = ?entry_type,
1261                    "skipping special file (requires privileges)"
1262                );
1263            }
1264            _ => {
1265                tracing::trace!(
1266                    path = %full_path.display(),
1267                    entry_type = ?entry_type,
1268                    "skipping unknown entry type"
1269                );
1270            }
1271        }
1272
1273        Ok(())
1274    }
1275
1276    /// Extract a regular file
1277    fn extract_file<R: Read>(&self, entry: &mut tar::Entry<'_, R>, full_path: &Path) -> Result<()> {
1278        // Remove existing file if present (might be a different type)
1279        let _ = fs::remove_file(full_path);
1280
1281        let mut file = File::create(full_path).map_err(|e| {
1282            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1283                e.kind(),
1284                format!("failed to create file {}: {}", full_path.display(), e),
1285            )))
1286        })?;
1287
1288        std::io::copy(entry, &mut file).map_err(|e| {
1289            RegistryError::Cache(CacheError::Io(std::io::Error::new(
1290                e.kind(),
1291                format!("failed to write file {}: {}", full_path.display(), e),
1292            )))
1293        })?;
1294
1295        self.set_permissions(entry, full_path)?;
1296
1297        Ok(())
1298    }
1299
1300    /// Set file permissions from tar entry.
1301    ///
1302    /// The `Result<()>` return is load-bearing on Unix (where we can fail to
1303    /// apply the mode from the tar header); the Windows branch is a no-op
1304    /// and cannot fail, so clippy's `unnecessary_wraps` is allowed here.
1305    #[allow(clippy::unused_self, clippy::unnecessary_wraps)]
1306    fn set_permissions<R: Read>(&self, entry: &tar::Entry<'_, R>, full_path: &Path) -> Result<()> {
1307        #[cfg(unix)]
1308        {
1309            use std::os::unix::fs::PermissionsExt;
1310
1311            if let Ok(mode) = entry.header().mode() {
1312                let permissions = fs::Permissions::from_mode(mode);
1313                fs::set_permissions(full_path, permissions).map_err(|e| {
1314                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
1315                        e.kind(),
1316                        format!(
1317                            "failed to set permissions on {}: {}",
1318                            full_path.display(),
1319                            e
1320                        ),
1321                    )))
1322                })?;
1323            }
1324        }
1325
1326        #[cfg(not(unix))]
1327        {
1328            let _ = entry;
1329            let _ = full_path;
1330        }
1331
1332        Ok(())
1333    }
1334
1335    /// Clear the deleted paths tracking (useful between image extractions)
1336    pub fn reset(&mut self) {
1337        self.deleted_paths.clear();
1338        self.pending_hardlinks.clear();
1339        self.pending_dir_modes.clear();
1340    }
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345    use super::*;
1346    use std::io::Write;
1347    use tempfile::TempDir;
1348
1349    fn create_tar_gz(files: &[(&str, &[u8])]) -> Vec<u8> {
1350        let mut builder = tar::Builder::new(Vec::new());
1351
1352        for (path, content) in files {
1353            let mut header = tar::Header::new_gnu();
1354            header.set_path(path).unwrap();
1355            header.set_size(content.len() as u64);
1356            header.set_mode(0o644);
1357            header.set_cksum();
1358            builder.append(&header, *content).unwrap();
1359        }
1360
1361        let tar_data = builder.into_inner().unwrap();
1362
1363        // Compress with gzip
1364        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1365        encoder.write_all(&tar_data).unwrap();
1366        encoder.finish().unwrap()
1367    }
1368
1369    fn create_tar_zstd(files: &[(&str, &[u8])]) -> Vec<u8> {
1370        let mut builder = tar::Builder::new(Vec::new());
1371
1372        for (path, content) in files {
1373            let mut header = tar::Header::new_gnu();
1374            header.set_path(path).unwrap();
1375            header.set_size(content.len() as u64);
1376            header.set_mode(0o644);
1377            header.set_cksum();
1378            builder.append(&header, *content).unwrap();
1379        }
1380
1381        let tar_data = builder.into_inner().unwrap();
1382
1383        // Compress with zstd
1384        zstd::encode_all(std::io::Cursor::new(tar_data), 3).unwrap()
1385    }
1386
1387    /// Streaming a layer from a file produces the same rootfs as the in-memory
1388    /// path, for both gzip and zstd, including by-magic-bytes detection when the
1389    /// media type is unrecognized.
1390    #[tokio::test]
1391    async fn unpack_from_files_matches_unpack_layers() {
1392        let files: &[(&str, &[u8])] = &[
1393            ("etc/hostname", b"host\n"),
1394            ("usr/bin/app", b"\x7fELF binary-ish payload"),
1395            ("var/data/blob", &[42u8; 4096]),
1396        ];
1397        let gz = create_tar_gz(files);
1398        let zst = create_tar_zstd(files);
1399
1400        // Reference: in-memory unpack.
1401        let ref_dir = TempDir::new().unwrap();
1402        let ref_rootfs = ref_dir.path().join("rootfs");
1403        let mut ref_unpacker = LayerUnpacker::new(ref_rootfs.clone());
1404        ref_unpacker
1405            .unpack_layers(&[
1406                (gz.clone(), media_types::TAR_GZIP.to_string()),
1407                (zst.clone(), media_types::TAR_ZSTD.to_string()),
1408            ])
1409            .await
1410            .unwrap();
1411
1412        // Streamed: write layers to files, unpack from disk. Use an UNKNOWN
1413        // media type for the gzip layer to exercise magic-byte detection.
1414        let layer_dir = TempDir::new().unwrap();
1415        let gz_path = layer_dir.path().join("layer0.tar.gz");
1416        let zst_path = layer_dir.path().join("layer1.tar.zst");
1417        tokio::fs::write(&gz_path, &gz).await.unwrap();
1418        tokio::fs::write(&zst_path, &zst).await.unwrap();
1419
1420        let stream_dir = TempDir::new().unwrap();
1421        let stream_rootfs = stream_dir.path().join("rootfs");
1422        let mut stream_unpacker = LayerUnpacker::new(stream_rootfs.clone());
1423        stream_unpacker
1424            .unpack_layers_from_files(&[
1425                (gz_path, "application/octet-stream".to_string()), // unknown → magic bytes
1426                (zst_path, media_types::TAR_ZSTD.to_string()),
1427            ])
1428            .await
1429            .unwrap();
1430
1431        for (path, content) in files {
1432            let a = fs::read(ref_rootfs.join(path)).unwrap();
1433            let b = fs::read(stream_rootfs.join(path)).unwrap();
1434            assert_eq!(a, b, "mismatch for {path}");
1435            assert_eq!(a, *content, "content mismatch for {path}");
1436        }
1437    }
1438
1439    /// A hard-link entry whose TARGET appears later in the same layer tar
1440    /// (buildah emits alphabetical entry order, so Fedora's ca-trust tree
1441    /// links `extracted/openssl/... -> extracted/pem/...` forward). The
1442    /// unpacker must defer the link, not die — an immediate failure used to
1443    /// truncate the whole VZ rootfs at that point.
1444    #[tokio::test]
1445    async fn test_unpack_forward_referencing_hardlink() {
1446        let temp_dir = TempDir::new().unwrap();
1447        let rootfs = temp_dir.path().join("rootfs");
1448
1449        let mut builder = tar::Builder::new(Vec::new());
1450        // 1. The LINK entry first (forward reference).
1451        let mut link_header = tar::Header::new_gnu();
1452        link_header.set_entry_type(tar::EntryType::Link);
1453        link_header.set_size(0);
1454        link_header.set_mode(0o644);
1455        builder
1456            .append_link(&mut link_header, "dir/a-link.txt", "dir/z-target.txt")
1457            .unwrap();
1458        // 2. The target file afterwards.
1459        let mut file_header = tar::Header::new_gnu();
1460        file_header.set_path("dir/z-target.txt").unwrap();
1461        file_header.set_size(12);
1462        file_header.set_mode(0o644);
1463        file_header.set_cksum();
1464        builder.append(&file_header, &b"link content"[..]).unwrap();
1465        let tar_data = builder.into_inner().unwrap();
1466        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1467        encoder.write_all(&tar_data).unwrap();
1468        let layer = encoder.finish().unwrap();
1469
1470        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1471        unpacker
1472            .unpack_layer(&layer, media_types::TAR_GZIP)
1473            .await
1474            .unwrap();
1475
1476        assert_eq!(
1477            fs::read_to_string(rootfs.join("dir/z-target.txt")).unwrap(),
1478            "link content"
1479        );
1480        assert_eq!(
1481            fs::read_to_string(rootfs.join("dir/a-link.txt")).unwrap(),
1482            "link content",
1483            "forward-referencing hard link must resolve after the layer"
1484        );
1485        #[cfg(unix)]
1486        {
1487            use std::os::unix::fs::MetadataExt;
1488            assert_eq!(
1489                fs::metadata(rootfs.join("dir/a-link.txt")).unwrap().ino(),
1490                fs::metadata(rootfs.join("dir/z-target.txt")).unwrap().ino(),
1491                "must be a hard link, not a copy"
1492            );
1493        }
1494    }
1495
1496    /// A hard link whose target never appears must be a LOUD error — the
1497    /// silent-skip behavior is what let truncated rootfs unpacks masquerade
1498    /// as success.
1499    #[tokio::test]
1500    async fn test_unpack_dangling_hardlink_errors() {
1501        let temp_dir = TempDir::new().unwrap();
1502        let rootfs = temp_dir.path().join("rootfs");
1503
1504        let mut builder = tar::Builder::new(Vec::new());
1505        let mut link_header = tar::Header::new_gnu();
1506        link_header.set_entry_type(tar::EntryType::Link);
1507        link_header.set_size(0);
1508        link_header.set_mode(0o644);
1509        builder
1510            .append_link(&mut link_header, "orphan-link.txt", "never-exists.txt")
1511            .unwrap();
1512        let tar_data = builder.into_inner().unwrap();
1513        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1514        encoder.write_all(&tar_data).unwrap();
1515        let layer = encoder.finish().unwrap();
1516
1517        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1518        let err = unpacker
1519            .unpack_layer(&layer, media_types::TAR_GZIP)
1520            .await
1521            .expect_err("dangling hard link must fail the unpack");
1522        assert!(
1523            err.to_string().contains("deferred hard link"),
1524            "error should name the deferred-link failure: {err}"
1525        );
1526    }
1527
1528    /// The exact Fedora ca-trust case: a DIRECTORY entry archived mode `0o555`
1529    /// (read-only) appears BEFORE the symlink entries whose paths live inside
1530    /// it. Applying `0o555` to the dir before writing the symlinks would fail
1531    /// with `EACCES`. The unpacker must defer the dir mode, write the
1532    /// symlinks, then seal the dir back to `0o555`.
1533    #[tokio::test]
1534    async fn test_unpack_readonly_dir_with_symlinks_inside() {
1535        let temp_dir = TempDir::new().unwrap();
1536        let rootfs = temp_dir.path().join("rootfs");
1537
1538        let mut builder = tar::Builder::new(Vec::new());
1539        // 1. The read-only directory entry FIRST.
1540        let mut dir_header = tar::Header::new_gnu();
1541        dir_header.set_entry_type(tar::EntryType::Directory);
1542        dir_header.set_path("ca-trust/").unwrap();
1543        dir_header.set_size(0);
1544        dir_header.set_mode(0o555);
1545        dir_header.set_cksum();
1546        builder.append(&dir_header, std::io::empty()).unwrap();
1547        // 2. Symlink entries INSIDE that read-only dir afterwards.
1548        let mut link1 = tar::Header::new_gnu();
1549        link1.set_entry_type(tar::EntryType::Symlink);
1550        link1.set_size(0);
1551        link1.set_mode(0o777);
1552        builder
1553            .append_link(&mut link1, "ca-trust/cert.pem", "../actual/cert.pem")
1554            .unwrap();
1555        let mut link2 = tar::Header::new_gnu();
1556        link2.set_entry_type(tar::EntryType::Symlink);
1557        link2.set_size(0);
1558        link2.set_mode(0o777);
1559        builder
1560            .append_link(&mut link2, "ca-trust/bundle.pem", "../actual/bundle.pem")
1561            .unwrap();
1562        let tar_data = builder.into_inner().unwrap();
1563        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1564        encoder.write_all(&tar_data).unwrap();
1565        let layer = encoder.finish().unwrap();
1566
1567        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1568        unpacker
1569            .unpack_layer(&layer, media_types::TAR_GZIP)
1570            .await
1571            .expect("read-only dir holding later symlinks must unpack");
1572
1573        assert!(
1574            fs::symlink_metadata(rootfs.join("ca-trust/cert.pem"))
1575                .unwrap()
1576                .file_type()
1577                .is_symlink(),
1578            "symlink inside the read-only dir must exist"
1579        );
1580        assert!(
1581            fs::symlink_metadata(rootfs.join("ca-trust/bundle.pem"))
1582                .unwrap()
1583                .file_type()
1584                .is_symlink(),
1585            "second symlink inside the read-only dir must exist"
1586        );
1587        #[cfg(unix)]
1588        {
1589            use std::os::unix::fs::PermissionsExt;
1590            let mode = fs::metadata(rootfs.join("ca-trust"))
1591                .unwrap()
1592                .permissions()
1593                .mode()
1594                & 0o777;
1595            assert_eq!(
1596                mode, 0o555,
1597                "the directory's FINAL mode must be the archived read-only 0o555"
1598            );
1599        }
1600    }
1601
1602    /// A read-only (`0o555`) directory holding a forward-referenced hard link:
1603    /// the link entry inside the dir precedes its target, and the dir mode
1604    /// must be deferred so both the link and its target can be written before
1605    /// the dir is sealed read-only.
1606    #[tokio::test]
1607    async fn test_unpack_readonly_dir_with_hardlink_target_inside() {
1608        let temp_dir = TempDir::new().unwrap();
1609        let rootfs = temp_dir.path().join("rootfs");
1610
1611        let mut builder = tar::Builder::new(Vec::new());
1612        // 1. Read-only directory entry FIRST.
1613        let mut dir_header = tar::Header::new_gnu();
1614        dir_header.set_entry_type(tar::EntryType::Directory);
1615        dir_header.set_path("ro/").unwrap();
1616        dir_header.set_size(0);
1617        dir_header.set_mode(0o555);
1618        dir_header.set_cksum();
1619        builder.append(&dir_header, std::io::empty()).unwrap();
1620        // 2. Forward-referencing hard link INSIDE the dir.
1621        let mut link_header = tar::Header::new_gnu();
1622        link_header.set_entry_type(tar::EntryType::Link);
1623        link_header.set_size(0);
1624        link_header.set_mode(0o644);
1625        builder
1626            .append_link(&mut link_header, "ro/a-link.txt", "ro/z-target.txt")
1627            .unwrap();
1628        // 3. The hard link's target, also inside the read-only dir.
1629        let mut file_header = tar::Header::new_gnu();
1630        file_header.set_path("ro/z-target.txt").unwrap();
1631        file_header.set_size(12);
1632        file_header.set_mode(0o644);
1633        file_header.set_cksum();
1634        builder.append(&file_header, &b"link content"[..]).unwrap();
1635        let tar_data = builder.into_inner().unwrap();
1636        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1637        encoder.write_all(&tar_data).unwrap();
1638        let layer = encoder.finish().unwrap();
1639
1640        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1641        unpacker
1642            .unpack_layer(&layer, media_types::TAR_GZIP)
1643            .await
1644            .expect("read-only dir with forward hard link must unpack");
1645
1646        assert_eq!(
1647            fs::read_to_string(rootfs.join("ro/z-target.txt")).unwrap(),
1648            "link content"
1649        );
1650        assert_eq!(
1651            fs::read_to_string(rootfs.join("ro/a-link.txt")).unwrap(),
1652            "link content",
1653            "forward hard link inside the read-only dir must resolve"
1654        );
1655        #[cfg(unix)]
1656        {
1657            use std::os::unix::fs::{MetadataExt, PermissionsExt};
1658            assert_eq!(
1659                fs::metadata(rootfs.join("ro/a-link.txt")).unwrap().ino(),
1660                fs::metadata(rootfs.join("ro/z-target.txt")).unwrap().ino(),
1661                "must be a hard link, not a copy"
1662            );
1663            let mode = fs::metadata(rootfs.join("ro"))
1664                .unwrap()
1665                .permissions()
1666                .mode()
1667                & 0o777;
1668            assert_eq!(
1669                mode, 0o555,
1670                "the directory's FINAL mode must be the archived read-only 0o555"
1671            );
1672        }
1673    }
1674
1675    #[tokio::test]
1676    async fn test_unpack_gzip_layer() {
1677        let temp_dir = TempDir::new().unwrap();
1678        let rootfs = temp_dir.path().join("rootfs");
1679
1680        let layer_data = create_tar_gz(&[
1681            ("file.txt", b"hello world"),
1682            ("subdir/nested.txt", b"nested content"),
1683        ]);
1684
1685        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1686        unpacker
1687            .unpack_layer(&layer_data, media_types::TAR_GZIP)
1688            .await
1689            .unwrap();
1690
1691        assert!(rootfs.join("file.txt").exists());
1692        assert_eq!(
1693            fs::read_to_string(rootfs.join("file.txt")).unwrap(),
1694            "hello world"
1695        );
1696        assert!(rootfs.join("subdir/nested.txt").exists());
1697        assert_eq!(
1698            fs::read_to_string(rootfs.join("subdir/nested.txt")).unwrap(),
1699            "nested content"
1700        );
1701    }
1702
1703    #[tokio::test]
1704    async fn test_unpack_zstd_layer() {
1705        let temp_dir = TempDir::new().unwrap();
1706        let rootfs = temp_dir.path().join("rootfs");
1707
1708        let layer_data = create_tar_zstd(&[("zstd_file.txt", b"zstd compressed")]);
1709
1710        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1711        unpacker
1712            .unpack_layer(&layer_data, media_types::TAR_ZSTD)
1713            .await
1714            .unwrap();
1715
1716        assert!(rootfs.join("zstd_file.txt").exists());
1717        assert_eq!(
1718            fs::read_to_string(rootfs.join("zstd_file.txt")).unwrap(),
1719            "zstd compressed"
1720        );
1721    }
1722
1723    #[tokio::test]
1724    async fn test_compression_detection_magic_bytes() {
1725        // Gzip magic bytes
1726        let gzip_data = vec![0x1f, 0x8b, 0x08, 0x00];
1727        assert_eq!(
1728            CompressionType::from_magic_bytes(&gzip_data),
1729            CompressionType::Gzip
1730        );
1731
1732        // Zstd magic bytes
1733        let zstd_data = vec![0x28, 0xb5, 0x2f, 0xfd];
1734        assert_eq!(
1735            CompressionType::from_magic_bytes(&zstd_data),
1736            CompressionType::Zstd
1737        );
1738
1739        // No compression
1740        let tar_data = vec![0x00, 0x00, 0x00, 0x00];
1741        assert_eq!(
1742            CompressionType::from_magic_bytes(&tar_data),
1743            CompressionType::None
1744        );
1745    }
1746
1747    #[tokio::test]
1748    async fn test_whiteout_file_deletion() {
1749        let temp_dir = TempDir::new().unwrap();
1750        let rootfs = temp_dir.path().join("rootfs");
1751
1752        // First layer: create files - one to delete and one to keep
1753        let layer1 = create_tar_gz(&[
1754            ("to_delete.txt", b"will be deleted"),
1755            ("keep_me.txt", b"this file stays"),
1756        ]);
1757
1758        // Second layer: whiteout file to delete the specific file
1759        let layer2 = create_tar_gz(&[(".wh.to_delete.txt", b"")]);
1760
1761        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1762        unpacker
1763            .unpack_layers(&[
1764                (layer1, media_types::TAR_GZIP.to_string()),
1765                (layer2, media_types::TAR_GZIP.to_string()),
1766            ])
1767            .await
1768            .unwrap();
1769
1770        // The whiteout target should be deleted
1771        assert!(!rootfs.join("to_delete.txt").exists());
1772        // The other file should still exist
1773        assert!(rootfs.join("keep_me.txt").exists());
1774        assert_eq!(
1775            fs::read_to_string(rootfs.join("keep_me.txt")).unwrap(),
1776            "this file stays"
1777        );
1778    }
1779
1780    #[tokio::test]
1781    async fn test_path_traversal_prevention() {
1782        let temp_dir = TempDir::new().unwrap();
1783        let rootfs = temp_dir.path().join("rootfs");
1784
1785        let unpacker = LayerUnpacker::new(rootfs);
1786
1787        // These paths should be rejected
1788        assert!(!unpacker.is_safe_path(Path::new("/etc/passwd")));
1789        assert!(!unpacker.is_safe_path(Path::new("../../../etc/passwd")));
1790        assert!(!unpacker.is_safe_path(Path::new("foo/../../../etc/passwd")));
1791
1792        // These paths should be accepted
1793        assert!(unpacker.is_safe_path(Path::new("normal/path/file.txt")));
1794        assert!(unpacker.is_safe_path(Path::new("file.txt")));
1795    }
1796
1797    #[tokio::test]
1798    async fn test_layer_ordering() {
1799        let temp_dir = TempDir::new().unwrap();
1800        let rootfs = temp_dir.path().join("rootfs");
1801
1802        // First layer: create a file
1803        let layer1 = create_tar_gz(&[("file.txt", b"original")]);
1804
1805        // Second layer: modify the file
1806        let layer2 = create_tar_gz(&[("file.txt", b"modified")]);
1807
1808        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1809        unpacker
1810            .unpack_layers(&[
1811                (layer1, media_types::TAR_GZIP.to_string()),
1812                (layer2, media_types::TAR_GZIP.to_string()),
1813            ])
1814            .await
1815            .unwrap();
1816
1817        // Should have the modified content
1818        assert_eq!(
1819            fs::read_to_string(rootfs.join("file.txt")).unwrap(),
1820            "modified"
1821        );
1822    }
1823
1824    #[test]
1825    fn test_is_linux_layer_classifier() {
1826        assert!(is_linux_layer(media_types::TAR));
1827        assert!(is_linux_layer(media_types::TAR_GZIP));
1828        assert!(is_linux_layer(media_types::TAR_ZSTD));
1829        assert!(is_linux_layer(media_types::DOCKER_TAR_GZIP));
1830
1831        // Windows types must NOT be classified as Linux.
1832        assert!(!is_linux_layer(media_types::DOCKER_FOREIGN_TAR_GZIP));
1833        assert!(!is_linux_layer(media_types::OCI_NONDISTRIBUTABLE_TAR));
1834        assert!(!is_linux_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP));
1835        assert!(!is_linux_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD));
1836
1837        assert!(!is_linux_layer("application/vnd.oci.image.config.v1+json"));
1838        assert!(!is_linux_layer("application/unknown"));
1839    }
1840
1841    #[test]
1842    fn test_is_windows_layer_classifier() {
1843        assert!(is_windows_layer(media_types::DOCKER_FOREIGN_TAR_GZIP));
1844        assert!(is_windows_layer(media_types::OCI_NONDISTRIBUTABLE_TAR));
1845        assert!(is_windows_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP));
1846        assert!(is_windows_layer(media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD));
1847
1848        // Linux types must NOT be classified as Windows.
1849        assert!(!is_windows_layer(media_types::TAR));
1850        assert!(!is_windows_layer(media_types::TAR_GZIP));
1851        assert!(!is_windows_layer(media_types::TAR_ZSTD));
1852        assert!(!is_windows_layer(media_types::DOCKER_TAR_GZIP));
1853
1854        assert!(!is_windows_layer(
1855            "application/vnd.oci.image.config.v1+json"
1856        ));
1857        assert!(!is_windows_layer("application/unknown"));
1858    }
1859
1860    #[test]
1861    fn test_linux_and_windows_classifiers_are_disjoint() {
1862        // Every supported media type must classify as exactly one of
1863        // Linux or Windows (never both, never neither).
1864        let all = [
1865            media_types::TAR,
1866            media_types::TAR_GZIP,
1867            media_types::TAR_ZSTD,
1868            media_types::DOCKER_TAR_GZIP,
1869            media_types::DOCKER_FOREIGN_TAR_GZIP,
1870            media_types::OCI_NONDISTRIBUTABLE_TAR,
1871            media_types::OCI_NONDISTRIBUTABLE_TAR_GZIP,
1872            media_types::OCI_NONDISTRIBUTABLE_TAR_ZSTD,
1873        ];
1874        for mt in all {
1875            assert!(
1876                is_linux_layer(mt) ^ is_windows_layer(mt),
1877                "media type {mt} must be exactly one of linux/windows"
1878            );
1879        }
1880    }
1881
1882    #[test]
1883    fn test_media_type_detection() {
1884        assert_eq!(
1885            CompressionType::from_media_type(media_types::TAR_GZIP),
1886            Some(CompressionType::Gzip)
1887        );
1888        assert_eq!(
1889            CompressionType::from_media_type(media_types::DOCKER_TAR_GZIP),
1890            Some(CompressionType::Gzip)
1891        );
1892        assert_eq!(
1893            CompressionType::from_media_type(media_types::TAR_ZSTD),
1894            Some(CompressionType::Zstd)
1895        );
1896        assert_eq!(
1897            CompressionType::from_media_type(media_types::TAR),
1898            Some(CompressionType::None)
1899        );
1900        // Unknown media type returns None
1901        assert_eq!(
1902            CompressionType::from_media_type("application/unknown"),
1903            None
1904        );
1905    }
1906
1907    /// HOST-ESCAPE REGRESSION (the `/run/sshd` SSH-wedge bug): a layer that ships
1908    /// the standard `var/run -> /run` symlink followed by an entry under
1909    /// `var/run/...` must NOT write or chmod through the link onto the host. The
1910    /// unpacker must replace the symlinked parent with a real dir inside the
1911    /// rootfs and keep the write contained. Fails pre-fix (would clobber the host
1912    /// sentinel), passes post-fix.
1913    #[cfg(unix)]
1914    #[tokio::test]
1915    async fn unpack_never_writes_through_rootfs_symlink_to_host() {
1916        use std::os::unix::fs::PermissionsExt;
1917
1918        let temp_dir = TempDir::new().unwrap();
1919        // A sentinel standing in for the HOST's /run (the symlink target),
1920        // OUTSIDE the rootfs, with a protected file standing in for /run/sshd.
1921        let host_run = temp_dir.path().join("host_run");
1922        fs::create_dir_all(&host_run).unwrap();
1923        let host_sshd = host_run.join("sshd");
1924        fs::write(&host_sshd, b"HOST sshd runtime dir must NOT be touched").unwrap();
1925        fs::set_permissions(&host_sshd, fs::Permissions::from_mode(0o600)).unwrap();
1926
1927        let rootfs = temp_dir.path().join("rootfs");
1928
1929        let mut builder = tar::Builder::new(Vec::new());
1930        // 1. `var/run -> <host_run>` absolute symlink (like a real `var/run -> /run`).
1931        let mut link = tar::Header::new_gnu();
1932        link.set_entry_type(tar::EntryType::Symlink);
1933        link.set_size(0);
1934        link.set_mode(0o777);
1935        builder
1936            .append_link(&mut link, "var/run", host_run.to_str().unwrap())
1937            .unwrap();
1938        // 2. A file UNDER the symlinked dir — the escape vector.
1939        let mut file = tar::Header::new_gnu();
1940        file.set_path("var/run/sshd").unwrap();
1941        file.set_size(7);
1942        file.set_mode(0o666);
1943        file.set_cksum();
1944        builder.append(&file, &b"PAYLOAD"[..]).unwrap();
1945        let tar_data = builder.into_inner().unwrap();
1946        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1947        encoder.write_all(&tar_data).unwrap();
1948        let layer = encoder.finish().unwrap();
1949
1950        let mut unpacker = LayerUnpacker::new(rootfs.clone());
1951        unpacker
1952            .unpack_layer(&layer, media_types::TAR_GZIP)
1953            .await
1954            .expect("layer must unpack without escaping the rootfs");
1955
1956        // The host sentinel must be byte-for-byte and mode-for-mode untouched.
1957        assert_eq!(
1958            fs::read(&host_sshd).unwrap(),
1959            b"HOST sshd runtime dir must NOT be touched",
1960            "the host /run/sshd stand-in must NOT have been overwritten"
1961        );
1962        assert_eq!(
1963            fs::metadata(&host_sshd).unwrap().permissions().mode() & 0o777,
1964            0o600,
1965            "the host /run/sshd stand-in must NOT have been chmod'd (the sshd-wedge bug)"
1966        );
1967        assert_eq!(
1968            fs::read_dir(&host_run).unwrap().count(),
1969            1,
1970            "no extra files may be created in the host dir via the symlink"
1971        );
1972
1973        // The write must have been contained: var/run is now a REAL dir in the
1974        // rootfs with the payload inside it.
1975        let run_md = fs::symlink_metadata(rootfs.join("var/run")).unwrap();
1976        assert!(
1977            run_md.is_dir() && !run_md.file_type().is_symlink(),
1978            "rootfs/var/run must be a real directory, not the escaping symlink"
1979        );
1980        assert_eq!(
1981            fs::read(rootfs.join("var/run/sshd")).unwrap(),
1982            b"PAYLOAD",
1983            "the entry must land inside the rootfs"
1984        );
1985    }
1986
1987    /// Root-gated helper: skip a test (printing why) when not uid 0, since the
1988    /// overlay per-layer path needs `CAP_MKNOD` (mknod) and `CAP_SYS_ADMIN`
1989    /// (`trusted.*` xattr).
1990    #[cfg(target_os = "linux")]
1991    fn require_root_or_skip(test: &str) -> bool {
1992        if zlayer_paths::is_root() {
1993            return true;
1994        }
1995        eprintln!("skipping {test}: requires root (CAP_MKNOD / CAP_SYS_ADMIN)");
1996        false
1997    }
1998
1999    /// PRESERVE mode: a `.wh.foo` whiteout must become a `0:0` character device
2000    /// named `foo` (an overlayfs whiteout), NOT delete-from-merged.
2001    #[cfg(target_os = "linux")]
2002    #[tokio::test]
2003    async fn overlay_layer_preserves_regular_whiteout_as_chardev() {
2004        use std::os::unix::fs::{FileTypeExt, MetadataExt};
2005        if !require_root_or_skip("overlay_layer_preserves_regular_whiteout_as_chardev") {
2006            return;
2007        }
2008
2009        let temp_dir = TempDir::new().unwrap();
2010        let layer_dir = temp_dir.path().join("fs");
2011        let layer = create_tar_gz(&[(".wh.foo", b"")]);
2012        let layer_path = temp_dir.path().join("layer.tar.gz");
2013        std::fs::write(&layer_path, &layer).unwrap();
2014
2015        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
2016        unpacker
2017            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
2018            .expect("overlay whiteout extraction must succeed as root");
2019
2020        let wh = layer_dir.join("foo");
2021        let md = std::fs::symlink_metadata(&wh).expect("whiteout char dev must exist");
2022        assert!(
2023            md.file_type().is_char_device(),
2024            "regular whiteout must be a character device, got {:?}",
2025            md.file_type()
2026        );
2027        assert_eq!(md.rdev(), 0, "overlayfs whiteout must be device 0:0");
2028        // The `.wh.foo` marker file itself must NOT be present.
2029        assert!(
2030            !layer_dir.join(".wh.foo").exists(),
2031            "the .wh. marker must be consumed, not left on disk"
2032        );
2033    }
2034
2035    /// PRESERVE mode: a `.wh..wh..opq` opaque whiteout must set the
2036    /// `trusted.overlay.opaque="y"` xattr on the containing directory.
2037    #[cfg(target_os = "linux")]
2038    #[tokio::test]
2039    async fn overlay_layer_preserves_opaque_whiteout_as_xattr() {
2040        if !require_root_or_skip("overlay_layer_preserves_opaque_whiteout_as_xattr") {
2041            return;
2042        }
2043        let temp_dir = TempDir::new().unwrap();
2044        let layer_dir = temp_dir.path().join("fs");
2045        // A dir entry plus its opaque marker (.wh..wh..opq).
2046        let mut builder = tar::Builder::new(Vec::new());
2047        let mut dh = tar::Header::new_gnu();
2048        dh.set_entry_type(tar::EntryType::Directory);
2049        dh.set_path("etc/").unwrap();
2050        dh.set_size(0);
2051        dh.set_mode(0o755);
2052        dh.set_cksum();
2053        builder.append(&dh, std::io::empty()).unwrap();
2054        let mut oh = tar::Header::new_gnu();
2055        oh.set_path("etc/.wh..wh..opq").unwrap();
2056        oh.set_size(0);
2057        oh.set_mode(0o644);
2058        oh.set_cksum();
2059        builder.append(&oh, std::io::empty()).unwrap();
2060        let tar_data = builder.into_inner().unwrap();
2061        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2062        enc.write_all(&tar_data).unwrap();
2063        let layer = enc.finish().unwrap();
2064        let layer_path = temp_dir.path().join("layer.tar.gz");
2065        std::fs::write(&layer_path, &layer).unwrap();
2066
2067        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
2068        unpacker
2069            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
2070            .expect("opaque whiteout extraction must succeed as root");
2071
2072        let val = xattr::get(layer_dir.join("etc"), "trusted.overlay.opaque")
2073            .expect("xattr read must succeed")
2074            .expect("trusted.overlay.opaque must be set on the dir");
2075        assert_eq!(val, b"y", "opaque marker value must be \"y\"");
2076    }
2077
2078    /// PRESERVE mode: a normal file extracts with the archived mode (the
2079    /// non-whiteout path must behave like the merged extractor).
2080    #[cfg(target_os = "linux")]
2081    #[tokio::test]
2082    async fn overlay_layer_extracts_normal_file_with_mode() {
2083        use std::os::unix::fs::PermissionsExt;
2084        if !require_root_or_skip("overlay_layer_extracts_normal_file_with_mode") {
2085            return;
2086        }
2087
2088        let temp_dir = TempDir::new().unwrap();
2089        let layer_dir = temp_dir.path().join("fs");
2090        let mut builder = tar::Builder::new(Vec::new());
2091        let mut h = tar::Header::new_gnu();
2092        h.set_path("usr/bin/app").unwrap();
2093        h.set_size(5);
2094        h.set_mode(0o755);
2095        h.set_cksum();
2096        builder.append(&h, &b"hello"[..]).unwrap();
2097        let tar_data = builder.into_inner().unwrap();
2098        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2099        enc.write_all(&tar_data).unwrap();
2100        let layer = enc.finish().unwrap();
2101        let layer_path = temp_dir.path().join("layer.tar.gz");
2102        std::fs::write(&layer_path, &layer).unwrap();
2103
2104        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
2105        unpacker
2106            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
2107            .expect("normal file extraction must succeed");
2108
2109        let f = layer_dir.join("usr/bin/app");
2110        assert_eq!(std::fs::read(&f).unwrap(), b"hello");
2111        assert_eq!(
2112            std::fs::metadata(&f).unwrap().permissions().mode() & 0o777,
2113            0o755,
2114            "archived file mode must be applied in the overlay path too"
2115        );
2116    }
2117
2118    /// PRESERVE mode: the `var/run -> /run` absolute symlink must still be
2119    /// relativized to `../run` in the per-layer overlay path (the host-escape
2120    /// guard is not dropped when whiteouts are preserved).
2121    #[cfg(target_os = "linux")]
2122    #[tokio::test]
2123    async fn overlay_layer_relativizes_absolute_rootfs_symlink() {
2124        if !require_root_or_skip("overlay_layer_relativizes_absolute_rootfs_symlink") {
2125            return;
2126        }
2127        let temp_dir = TempDir::new().unwrap();
2128        let layer_dir = temp_dir.path().join("fs");
2129
2130        let mut builder = tar::Builder::new(Vec::new());
2131        let mut run_dir = tar::Header::new_gnu();
2132        run_dir.set_entry_type(tar::EntryType::Directory);
2133        run_dir.set_path("run/").unwrap();
2134        run_dir.set_size(0);
2135        run_dir.set_mode(0o700);
2136        run_dir.set_cksum();
2137        builder.append(&run_dir, std::io::empty()).unwrap();
2138        let mut link = tar::Header::new_gnu();
2139        link.set_entry_type(tar::EntryType::Symlink);
2140        link.set_size(0);
2141        link.set_mode(0o777);
2142        builder.append_link(&mut link, "var/run", "/run").unwrap();
2143        let tar_data = builder.into_inner().unwrap();
2144        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2145        enc.write_all(&tar_data).unwrap();
2146        let layer = enc.finish().unwrap();
2147        let layer_path = temp_dir.path().join("layer.tar.gz");
2148        std::fs::write(&layer_path, &layer).unwrap();
2149
2150        let mut unpacker = LayerUnpacker::new_for_overlay(layer_dir.clone());
2151        unpacker
2152            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
2153            .expect("layer must unpack");
2154
2155        let vr = layer_dir.join("var/run");
2156        let md = std::fs::symlink_metadata(&vr).unwrap();
2157        assert!(md.file_type().is_symlink(), "var/run must remain a symlink");
2158        assert_eq!(
2159            std::fs::read_link(&vr).unwrap(),
2160            std::path::PathBuf::from("../run"),
2161            "var/run must be relativized to ../run in the overlay path too"
2162        );
2163    }
2164
2165    /// A Collapse-mode unpacker must reject `unpack_layer_to_overlay_dir` (using
2166    /// the wrong mode would silently drop deletions). Runs without root.
2167    #[tokio::test]
2168    async fn overlay_dir_rejects_collapse_mode_unpacker() {
2169        let temp_dir = TempDir::new().unwrap();
2170        let layer = create_tar_gz(&[("x", b"y")]);
2171        let layer_path = temp_dir.path().join("layer.tar.gz");
2172        std::fs::write(&layer_path, &layer).unwrap();
2173
2174        let mut unpacker = LayerUnpacker::new(temp_dir.path().join("fs"));
2175        let err = unpacker
2176            .unpack_layer_to_overlay_dir(&layer_path, media_types::TAR_GZIP)
2177            .expect_err("collapse-mode unpacker must be rejected");
2178        assert!(
2179            err.to_string().contains("Preserve-mode"),
2180            "error must explain the mode requirement: {err}"
2181        );
2182    }
2183
2184    /// HOST-ESCAPE REGRESSION (the host `/run` 0700 corruption / DNS+networkd
2185    /// wedge): the exact `zql-ci-base` shape — an image ships the standard
2186    /// ABSOLUTE `var/run -> /run` symlink and its own real `/run` dir (mode
2187    /// 0700) but NO entry *under* `var/run` (so `materialize_real_parent` never
2188    /// fires). At container run-time a host-context op that resolves
2189    /// `<rootfs>/var/run` would then follow the absolute link onto the HOST's
2190    /// `/run` and chmod it. The unpacker must store the link RELATIVE
2191    /// (`../run`) so it can never escape the rootfs. Fails pre-fix (link stays
2192    /// absolute), passes post-fix.
2193    #[cfg(unix)]
2194    #[tokio::test]
2195    async fn unpack_relativizes_absolute_rootfs_symlink() {
2196        use std::os::unix::fs::PermissionsExt;
2197
2198        let temp_dir = TempDir::new().unwrap();
2199        let rootfs = temp_dir.path().join("rootfs");
2200
2201        let mut builder = tar::Builder::new(Vec::new());
2202        // 1. The image's own `/run` directory, mode 0700 (like zql-ci-base).
2203        let mut run_dir = tar::Header::new_gnu();
2204        run_dir.set_entry_type(tar::EntryType::Directory);
2205        run_dir.set_path("run/").unwrap();
2206        run_dir.set_size(0);
2207        run_dir.set_mode(0o700);
2208        run_dir.set_cksum();
2209        builder.append(&run_dir, std::io::empty()).unwrap();
2210        // 2. The standard ABSOLUTE `var/run -> /run` symlink, no child entries.
2211        let mut link = tar::Header::new_gnu();
2212        link.set_entry_type(tar::EntryType::Symlink);
2213        link.set_size(0);
2214        link.set_mode(0o777);
2215        builder.append_link(&mut link, "var/run", "/run").unwrap();
2216        let tar_data = builder.into_inner().unwrap();
2217        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2218        encoder.write_all(&tar_data).unwrap();
2219        let layer = encoder.finish().unwrap();
2220
2221        let mut unpacker = LayerUnpacker::new(rootfs.clone());
2222        unpacker
2223            .unpack_layer(&layer, media_types::TAR_GZIP)
2224            .await
2225            .expect("layer must unpack");
2226
2227        // `var/run` is still a symlink, but now RELATIVE and confined.
2228        let vr = rootfs.join("var/run");
2229        let md = fs::symlink_metadata(&vr).unwrap();
2230        assert!(
2231            md.file_type().is_symlink(),
2232            "var/run must remain a symlink (container semantics preserved)"
2233        );
2234        let target = fs::read_link(&vr).unwrap();
2235        assert!(
2236            target.is_relative(),
2237            "var/run must be relativized so it cannot escape the rootfs; got {target:?}"
2238        );
2239        assert_eq!(
2240            target,
2241            std::path::PathBuf::from("../run"),
2242            "var/run must resolve to the rootfs's own /run"
2243        );
2244        // It resolves to the rootfs's own /run, not anywhere outside.
2245        assert_eq!(
2246            fs::canonicalize(&vr).unwrap(),
2247            fs::canonicalize(rootfs.join("run")).unwrap(),
2248            "var/run must resolve inside the rootfs"
2249        );
2250        // The image's own /run dir landed correctly (mode restored to 0700).
2251        assert_eq!(
2252            fs::metadata(rootfs.join("run"))
2253                .unwrap()
2254                .permissions()
2255                .mode()
2256                & 0o777,
2257            0o700
2258        );
2259    }
2260
2261    /// Build a plain (uncompressed) layer tar with arbitrary entry types.
2262    /// Returns the raw tar bytes (media type `media_types::TAR`).
2263    fn tar_with(headers: impl FnOnce(&mut tar::Builder<Vec<u8>>)) -> Vec<u8> {
2264        let mut builder = tar::Builder::new(Vec::new());
2265        headers(&mut builder);
2266        builder.into_inner().unwrap()
2267    }
2268
2269    /// ROOTLESS overlay extract: a regular whiteout `.wh.<name>` must be
2270    /// PRESERVED as a plain `.wh.<name>` regular file (NOT a char device), and
2271    /// an opaque whiteout `.wh..wh..opq` must set the `user.overlay.opaque`
2272    /// xattr on the dir — exactly the markers fuse-overlayfs reads rootless. No
2273    /// privilege required, so this test is NOT root-gated.
2274    #[tokio::test]
2275    async fn rootless_overlay_extract_writes_wh_file_and_user_opaque_xattr() {
2276        let tmp = TempDir::new().unwrap();
2277        let layer_dir = tmp.path().join("fs-fuse");
2278
2279        // A layer that: ships a real file, whites out `gone.txt` via
2280        // `.wh.gone.txt`, and marks `opq/` opaque via `opq/.wh..wh..opq`.
2281        let layer = tar_with(|b| {
2282            let mut h = tar::Header::new_gnu();
2283            h.set_path("keep.txt").unwrap();
2284            h.set_size(5);
2285            h.set_mode(0o644);
2286            h.set_cksum();
2287            b.append(&h, &b"keep\n"[..]).unwrap();
2288
2289            let mut wh = tar::Header::new_gnu();
2290            wh.set_path(".wh.gone.txt").unwrap();
2291            wh.set_size(0);
2292            wh.set_mode(0o644);
2293            wh.set_cksum();
2294            b.append(&wh, std::io::empty()).unwrap();
2295
2296            let mut opq = tar::Header::new_gnu();
2297            opq.set_path("opq/.wh..wh..opq").unwrap();
2298            opq.set_size(0);
2299            opq.set_mode(0o644);
2300            opq.set_cksum();
2301            b.append(&opq, std::io::empty()).unwrap();
2302        });
2303        let layer_file = tmp.path().join("layer.tar");
2304        fs::write(&layer_file, &layer).unwrap();
2305
2306        let mut unpacker = LayerUnpacker::new_for_overlay_rootless(layer_dir.clone());
2307        unpacker
2308            .unpack_layer_to_overlay_dir_rootless(&layer_file, media_types::TAR)
2309            .expect("rootless overlay extract");
2310
2311        // Real file extracted.
2312        assert_eq!(
2313            fs::read_to_string(layer_dir.join("keep.txt")).unwrap(),
2314            "keep\n"
2315        );
2316
2317        // Regular whiteout: a PLAIN `.wh.gone.txt` file, NOT a char device.
2318        let wh = layer_dir.join(".wh.gone.txt");
2319        let md = fs::symlink_metadata(&wh).expect(".wh.gone.txt must exist");
2320        assert!(
2321            md.file_type().is_file(),
2322            ".wh. whiteout must be a regular file in rootless mode (got {:?})",
2323            md.file_type()
2324        );
2325        #[cfg(unix)]
2326        {
2327            use std::os::unix::fs::FileTypeExt;
2328            assert!(
2329                !md.file_type().is_char_device(),
2330                "rootless whiteout must NOT be a char device (that needs CAP_MKNOD)"
2331            );
2332        }
2333
2334        // Opaque whiteout: the `user.overlay.opaque` xattr is set to "y" on the
2335        // dir. (Backing fs must support user xattrs; tmpfs/ext4 do. If it does
2336        // not, the extract still wrote the `.wh..wh..opq` sentinel fallback.)
2337        let opq_dir = layer_dir.join("opq");
2338        assert!(opq_dir.is_dir(), "opaque dir must exist");
2339        #[cfg(target_os = "linux")]
2340        match xattr::get(&opq_dir, "user.overlay.opaque") {
2341            Ok(Some(v)) => assert_eq!(
2342                v, b"y",
2343                "user.overlay.opaque must be \"y\" (fuse-overlayfs opaque marker)"
2344            ),
2345            Ok(None) | Err(_) => {
2346                // Fallback path: the sentinel file must be present instead.
2347                assert!(
2348                    opq_dir.join(".wh..wh..opq").exists(),
2349                    "without the user.overlay.opaque xattr the .wh..wh..opq sentinel \
2350                     fallback must be present"
2351                );
2352            }
2353        }
2354        // On non-Linux the `xattr` crate is unavailable; the rootless extract
2355        // still writes the `.wh..wh..opq` sentinel, so assert that directly.
2356        #[cfg(not(target_os = "linux"))]
2357        assert!(
2358            opq_dir.join(".wh..wh..opq").exists(),
2359            "rootless opaque whiteout must write the .wh..wh..opq sentinel on non-Linux"
2360        );
2361    }
2362
2363    /// The rootless entrypoint must REJECT a non-`PreserveRootless` unpacker —
2364    /// using a collapse/preserve unpacker would write the wrong whiteout form.
2365    #[tokio::test]
2366    async fn rootless_overlay_extract_rejects_wrong_mode() {
2367        let tmp = TempDir::new().unwrap();
2368        let layer_file = tmp.path().join("layer.tar");
2369        fs::write(
2370            &layer_file,
2371            tar_with(|b| {
2372                let mut h = tar::Header::new_gnu();
2373                h.set_path("f").unwrap();
2374                h.set_size(1);
2375                h.set_mode(0o644);
2376                h.set_cksum();
2377                b.append(&h, &b"x"[..]).unwrap();
2378            }),
2379        )
2380        .unwrap();
2381
2382        // A Collapse-mode unpacker must be rejected by the rootless entrypoint.
2383        let mut wrong = LayerUnpacker::new(tmp.path().join("out"));
2384        let err = wrong
2385            .unpack_layer_to_overlay_dir_rootless(&layer_file, media_types::TAR)
2386            .expect_err("non-PreserveRootless unpacker must be rejected");
2387        assert!(
2388            err.to_string().contains("PreserveRootless"),
2389            "error should name the required mode: {err}"
2390        );
2391    }
2392}