zlayer-registry 0.1.0

OCI container registry client with blob caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! OCI layer unpacking and extraction
//!
//! This module handles extracting OCI image layers to a rootfs directory,
//! supporting gzip, zstd, and uncompressed tar formats.

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

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

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

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

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

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

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

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

        Self::None
    }

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

/// Layer unpacker for extracting OCI layers to a rootfs
pub struct LayerUnpacker {
    /// Root filesystem directory
    rootfs_dir: PathBuf,
    /// Track deleted paths from whiteouts
    deleted_paths: HashSet<PathBuf>,
}

impl LayerUnpacker {
    /// Create a new layer unpacker targeting the specified rootfs directory
    pub fn new(rootfs_dir: PathBuf) -> Self {
        Self {
            rootfs_dir,
            deleted_paths: HashSet::new(),
        }
    }

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

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

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

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

    /// Unpack multiple layers in order (base layer first)
    pub async fn unpack_layers(&mut self, layers: &[(Vec<u8>, String)]) -> Result<()> {
        if layers.is_empty() {
            return Err(RegistryError::Cache(CacheError::Corrupted(
                "no layers to unpack".to_string(),
            )));
        }

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

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

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

        Ok(())
    }

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

    /// Unpack a gzip-compressed tar archive
    async fn unpack_gzip(&mut self, data: &[u8]) -> Result<()> {
        let cursor = Cursor::new(data);
        let decoder = GzDecoder::new(cursor);
        let mut archive = Archive::new(decoder);
        self.extract_archive(&mut archive)
    }

    /// Unpack a zstd-compressed tar archive
    async fn unpack_zstd(&mut self, data: &[u8]) -> Result<()> {
        let cursor = Cursor::new(data);
        let decoder = zstd::stream::Decoder::new(cursor).map_err(|e| {
            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("zstd decompression failed: {}", e),
            )))
        })?;
        let mut archive = Archive::new(decoder);
        self.extract_archive(&mut archive)
    }

    /// Unpack an uncompressed tar archive
    async fn unpack_tar(&mut self, data: &[u8]) -> Result<()> {
        let cursor = Cursor::new(data);
        let mut archive = Archive::new(cursor);
        self.extract_archive(&mut archive)
    }

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

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

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

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

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

            // Handle opaque whiteout (delete all contents in directory)
            if file_name == OPAQUE_WHITEOUT {
                if let Some(parent) = path.parent() {
                    self.apply_opaque_whiteout(parent)?;
                }
                continue;
            }

            // Handle regular whiteout (delete specific file/dir)
            if let Some(target_name) = file_name.strip_prefix(WHITEOUT_PREFIX) {
                if let Some(parent) = path.parent() {
                    let target_path = parent.join(target_name);
                    self.apply_whiteout(&target_path)?;
                }
                continue;
            }

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

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

        Ok(())
    }

    /// Validate that a path doesn't escape the rootfs directory
    fn is_safe_path(&self, path: &Path) -> bool {
        // Reject absolute paths
        if path.is_absolute() {
            return false;
        }

        // Reject paths with .. components
        for component in path.components() {
            if let std::path::Component::ParentDir = component {
                return false;
            }
        }

        true
    }

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

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

        if full_path.exists() {
            if full_path.is_dir() {
                fs::remove_dir_all(&full_path).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to remove directory {}: {}", full_path.display(), e),
                    )))
                })?;
            } else {
                fs::remove_file(&full_path).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to remove file {}: {}", full_path.display(), e),
                    )))
                })?;
            }
        }

        Ok(())
    }

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

        if full_path.is_dir() {
            // Remove all contents but keep the directory
            for entry in fs::read_dir(&full_path).map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to read directory {}: {}", full_path.display(), e),
                )))
            })? {
                let entry = entry.map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to read directory entry: {}", e),
                    )))
                })?;
                let entry_path = entry.path();
                let relative = entry_path
                    .strip_prefix(&self.rootfs_dir)
                    .unwrap_or(&entry_path);
                self.deleted_paths.insert(relative.to_path_buf());

                if entry_path.is_dir() {
                    fs::remove_dir_all(&entry_path).map_err(|e| {
                        RegistryError::Cache(CacheError::Io(std::io::Error::new(
                            e.kind(),
                            format!("failed to remove directory {}: {}", entry_path.display(), e),
                        )))
                    })?;
                } else {
                    fs::remove_file(&entry_path).map_err(|e| {
                        RegistryError::Cache(CacheError::Io(std::io::Error::new(
                            e.kind(),
                            format!("failed to remove file {}: {}", entry_path.display(), e),
                        )))
                    })?;
                }
            }
        }

        Ok(())
    }

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

        // Ensure parent directory exists
        if let Some(parent) = full_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                RegistryError::Cache(CacheError::Io(std::io::Error::new(
                    e.kind(),
                    format!("failed to create parent directory: {}", e),
                )))
            })?;
        }

        match entry_type {
            tar::EntryType::Regular | tar::EntryType::Continuous => {
                self.extract_file(entry, full_path)?;
            }
            tar::EntryType::Directory => {
                fs::create_dir_all(full_path).map_err(|e| {
                    RegistryError::Cache(CacheError::Io(std::io::Error::new(
                        e.kind(),
                        format!("failed to create directory {}: {}", full_path.display(), e),
                    )))
                })?;
                self.set_permissions(entry, full_path)?;
            }
            tar::EntryType::Symlink => {
                if let Ok(Some(target)) = entry.link_name() {
                    // Remove existing file/link if present
                    let _ = fs::remove_file(full_path);
                    #[cfg(unix)]
                    {
                        std::os::unix::fs::symlink(&target, full_path).map_err(|e| {
                            RegistryError::Cache(CacheError::Io(std::io::Error::new(
                                e.kind(),
                                format!(
                                    "failed to create symlink {} -> {}: {}",
                                    full_path.display(),
                                    target.display(),
                                    e
                                ),
                            )))
                        })?;
                    }
                    #[cfg(not(unix))]
                    {
                        // On non-Unix, try to copy the file or create a placeholder
                        tracing::warn!(
                            path = %full_path.display(),
                            target = %target.display(),
                            "symlinks not fully supported on this platform"
                        );
                    }
                }
            }
            tar::EntryType::Link => {
                if let Ok(Some(target)) = entry.link_name() {
                    let target_full = self.rootfs_dir.join(&*target);
                    // Remove existing file if present
                    let _ = fs::remove_file(full_path);
                    fs::hard_link(&target_full, full_path).map_err(|e| {
                        RegistryError::Cache(CacheError::Io(std::io::Error::new(
                            e.kind(),
                            format!(
                                "failed to create hard link {} -> {}: {}",
                                full_path.display(),
                                target_full.display(),
                                e
                            ),
                        )))
                    })?;
                }
            }
            tar::EntryType::Char | tar::EntryType::Block | tar::EntryType::Fifo => {
                // Device nodes and FIFOs require special handling and usually root
                tracing::debug!(
                    path = %full_path.display(),
                    entry_type = ?entry_type,
                    "skipping special file (requires privileges)"
                );
            }
            _ => {
                tracing::trace!(
                    path = %full_path.display(),
                    entry_type = ?entry_type,
                    "skipping unknown entry type"
                );
            }
        }

        Ok(())
    }

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

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

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

        self.set_permissions(entry, full_path)?;

        Ok(())
    }

    /// Set file permissions from tar entry
    fn set_permissions<R: Read>(&self, entry: &tar::Entry<'_, R>, full_path: &Path) -> Result<()> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

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

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

        Ok(())
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        let unpacker = LayerUnpacker::new(rootfs);

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

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

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

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

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

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

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

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