1use 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
14pub mod media_types {
16 pub const TAR: &str = "application/vnd.oci.image.layer.v1.tar";
18 pub const TAR_GZIP: &str = "application/vnd.oci.image.layer.v1.tar+gzip";
20 pub const TAR_ZSTD: &str = "application/vnd.oci.image.layer.v1.tar+zstd";
22 pub const DOCKER_TAR_GZIP: &str = "application/vnd.docker.image.rootfs.diff.tar.gzip";
24
25 pub const DOCKER_FOREIGN_TAR_GZIP: &str =
36 "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip";
37 pub const OCI_NONDISTRIBUTABLE_TAR: &str =
39 "application/vnd.oci.image.layer.nondistributable.v1.tar";
40 pub const OCI_NONDISTRIBUTABLE_TAR_GZIP: &str =
42 "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip";
43 pub const OCI_NONDISTRIBUTABLE_TAR_ZSTD: &str =
45 "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd";
46}
47
48#[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#[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
84const WHITEOUT_PREFIX: &str = ".wh.";
86const OPAQUE_WHITEOUT: &str = ".wh..wh..opq";
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum WhiteoutMode {
117 Collapse,
119 Preserve,
122 PreserveRootless,
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum CompressionType {
130 None,
132 Gzip,
134 Zstd,
136}
137
138impl CompressionType {
139 #[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, }
149 }
150
151 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 if data[0] == 0x1f && data[1] == 0x8b {
163 return Self::Gzip;
164 }
165
166 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 pub fn detect(media_type: &str, data: &[u8]) -> Self {
181 if let Some(compression) = Self::from_media_type(media_type) {
183 return compression;
184 }
185 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
194pub struct LayerUnpacker {
196 rootfs_dir: PathBuf,
198 deleted_paths: HashSet<PathBuf>,
200 pending_hardlinks: Vec<(PathBuf, PathBuf)>,
208 pending_dir_modes: Vec<(std::path::PathBuf, u32)>,
218 whiteout_mode: WhiteoutMode,
221}
222
223impl LayerUnpacker {
224 #[must_use]
230 pub fn new(rootfs_dir: PathBuf) -> Self {
231 Self::with_whiteout_mode(rootfs_dir, WhiteoutMode::Collapse)
232 }
233
234 #[must_use]
240 pub fn new_for_overlay(layer_dir: PathBuf) -> Self {
241 Self::with_whiteout_mode(layer_dir, WhiteoutMode::Preserve)
242 }
243
244 #[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 #[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 #[must_use]
270 pub fn rootfs_dir(&self) -> &Path {
271 &self.rootfs_dir
272 }
273
274 #[allow(clippy::unused_async)]
283 pub async fn unpack_layer(&mut self, layer_data: &[u8], media_type: &str) -> Result<()> {
284 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 let compression = CompressionType::detect(media_type, layer_data);
294
295 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 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 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 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 self.unpack_layer_reader(file, media_type)
404 }
405
406 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 self.unpack_layer_reader(file, media_type)
468 }
469
470 #[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 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 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 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 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 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 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 fn unpack_gzip(&mut self, data: &[u8]) -> Result<()> {
569 self.extract_compressed(Cursor::new(data), CompressionType::Gzip)
570 }
571
572 fn unpack_zstd(&mut self, data: &[u8]) -> Result<()> {
574 self.extract_compressed(Cursor::new(data), CompressionType::Zstd)
575 }
576
577 fn unpack_tar(&mut self, data: &[u8]) -> Result<()> {
579 self.extract_compressed(Cursor::new(data), CompressionType::None)
580 }
581
582 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 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 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 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 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 let full_path = self.rootfs_dir.join(&path);
682 if self.is_deleted(&path) {
683 continue;
684 }
685
686 self.extract_entry(&mut entry, &full_path)?;
688 }
689
690 self.resolve_pending_hardlinks()?;
691 self.restore_dir_modes()
694 }
695
696 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 #[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 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 #[allow(clippy::unused_self)]
767 fn is_safe_path(&self, path: &Path) -> bool {
768 use std::path::Component;
769
770 if path.is_absolute() {
772 return false;
773 }
774
775 let mut components = path.components();
779 if matches!(
780 components.next(),
781 Some(Component::RootDir | Component::Prefix(_))
782 ) {
783 return false;
784 }
785
786 for component in path.components() {
788 if matches!(component, Component::ParentDir) {
789 return false;
790 }
791 }
792
793 true
794 }
795
796 fn is_deleted(&self, path: &Path) -> bool {
798 let mut current = path.to_path_buf();
800 loop {
801 if self.deleted_paths.contains(¤t) {
802 return true;
803 }
804 if !current.pop() {
805 break;
806 }
807 }
808 false
809 }
810
811 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 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 fn apply_opaque_whiteout(&mut self, dir_path: &Path) -> Result<()> {
835 let full_path = self.rootfs_dir.join(dir_path);
836
837 let is_real_dir = std::fs::symlink_metadata(&full_path).is_ok_and(|md| md.is_dir());
841 if is_real_dir {
842 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 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 #[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 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 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 #[cfg(not(target_os = "linux"))]
932 #[allow(clippy::unused_self)] 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 #[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 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 #[cfg(not(target_os = "linux"))]
979 #[allow(clippy::unused_self)] 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 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 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 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 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 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 #[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 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 #[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 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 #[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 let _ = fs::remove_file(full_path);
1183 #[cfg(unix)]
1184 {
1185 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 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 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 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 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 fn extract_file<R: Read>(&self, entry: &mut tar::Entry<'_, R>, full_path: &Path) -> Result<()> {
1278 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 #[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 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 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 zstd::encode_all(std::io::Cursor::new(tar_data), 3).unwrap()
1385 }
1386
1387 #[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 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 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()), (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 #[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 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 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 #[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 #[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 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 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 #[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 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 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 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 let gzip_data = vec![0x1f, 0x8b, 0x08, 0x00];
1727 assert_eq!(
1728 CompressionType::from_magic_bytes(&gzip_data),
1729 CompressionType::Gzip
1730 );
1731
1732 let zstd_data = vec![0x28, 0xb5, 0x2f, 0xfd];
1734 assert_eq!(
1735 CompressionType::from_magic_bytes(&zstd_data),
1736 CompressionType::Zstd
1737 );
1738
1739 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 let layer1 = create_tar_gz(&[
1754 ("to_delete.txt", b"will be deleted"),
1755 ("keep_me.txt", b"this file stays"),
1756 ]);
1757
1758 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 assert!(!rootfs.join("to_delete.txt").exists());
1772 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 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 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 let layer1 = create_tar_gz(&[("file.txt", b"original")]);
1804
1805 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 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 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 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 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 assert_eq!(
1902 CompressionType::from_media_type("application/unknown"),
1903 None
1904 );
1905 }
1906
1907 #[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 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 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 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 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 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 #[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 #[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 assert!(
2030 !layer_dir.join(".wh.foo").exists(),
2031 "the .wh. marker must be consumed, not left on disk"
2032 );
2033 }
2034
2035 #[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 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 #[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 #[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 #[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 #[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 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 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 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 assert_eq!(
2246 fs::canonicalize(&vr).unwrap(),
2247 fs::canonicalize(rootfs.join("run")).unwrap(),
2248 "var/run must resolve inside the rootfs"
2249 );
2250 assert_eq!(
2252 fs::metadata(rootfs.join("run"))
2253 .unwrap()
2254 .permissions()
2255 .mode()
2256 & 0o777,
2257 0o700
2258 );
2259 }
2260
2261 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 #[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 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 assert_eq!(
2313 fs::read_to_string(layer_dir.join("keep.txt")).unwrap(),
2314 "keep\n"
2315 );
2316
2317 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 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 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 #[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 #[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 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}