1use std::path::Path;
7
8use crate::ArchiveError;
9use crate::Result;
10use crate::SecurityConfig;
11use crate::config::Validated;
12use crate::security::admitted::EntrySize;
13use crate::security::admitted::ValidatedFile;
14use crate::security::admitted::ValidatedHardlink;
15use crate::security::admitted::ValidatedSymlink;
16use crate::security::context::ValidationContext;
17use crate::security::fs_view::FsView;
18use crate::security::fs_view::HostFs;
19use crate::security::hardlink::HardlinkTracker;
20use crate::security::hardlink::require_hardlinks_allowed;
21use crate::security::permissions::SanitizedMode;
22use crate::security::permissions::sanitize_permissions;
23use crate::security::quota::EntryCount;
24use crate::security::quota::QuotaPermit;
25use crate::security::quota::QuotaTracker;
26use crate::security::zipbomb::validate_compression_ratio;
27use crate::types::DestDir;
28use crate::types::EntryType;
29use crate::types::SafePath;
30use crate::types::SafeSymlink;
31use crate::types::safe_path::EMPTY_PATH_REASON;
32use crate::types::safe_symlink::require_symlinks_allowed;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub(crate) enum NodeKind {
37 Directory,
40 NonDirectory,
42}
43
44impl NodeKind {
45 pub(crate) const fn directory_if(is_directory: bool) -> Self {
48 if is_directory {
49 Self::Directory
50 } else {
51 Self::NonDirectory
52 }
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(crate) enum EntryPath<P> {
64 Root(P),
66 Child(P),
68}
69
70impl<'a> EntryPath<&'a Path> {
71 pub(crate) fn of(path: &'a Path) -> Self {
74 if path == Path::new(".") {
75 Self::Root(path)
76 } else {
77 Self::Child(path)
78 }
79 }
80}
81
82impl<P> EntryPath<P> {
83 pub(crate) const fn is_root(&self) -> bool {
86 matches!(self, Self::Root(_))
87 }
88
89 pub(crate) fn into_inner(self) -> P {
91 match self {
92 Self::Root(path) | Self::Child(path) => path,
93 }
94 }
95
96 pub(crate) fn require_directory_root(self, kind: NodeKind) -> Result<Self> {
102 if self.is_root() && kind == NodeKind::NonDirectory {
103 return Err(ArchiveError::violation(
104 "archive root entry '.' must be a directory".into(),
105 ));
106 }
107 Ok(self)
108 }
109}
110
111pub(crate) fn check_root_entry_is_directory(path: &Path, kind: NodeKind) -> Result<()> {
114 EntryPath::of(path).require_directory_root(kind).map(drop)
115}
116
117pub(crate) fn require_non_empty_name(path: &Path) -> Result<()> {
120 if path.is_empty() {
121 return Err(ArchiveError::violation(EMPTY_PATH_REASON.into()));
122 }
123 Ok(())
124}
125
126#[derive(Debug)]
136pub struct ValidatedEntry {
137 safe_path: SafePath,
138 entry_type: ValidatedEntryType,
139 mode: Option<SanitizedMode>,
140}
141
142impl ValidatedEntry {
143 pub(crate) fn new(
149 safe_path: SafePath,
150 entry_type: ValidatedEntryType,
151 mode: Option<SanitizedMode>,
152 ) -> Self {
153 Self {
154 safe_path,
155 entry_type,
156 mode,
157 }
158 }
159
160 #[inline]
162 #[must_use]
163 pub fn safe_path(&self) -> &SafePath {
164 &self.safe_path
165 }
166
167 #[inline]
169 #[must_use]
170 pub fn entry_type(&self) -> &ValidatedEntryType {
171 &self.entry_type
172 }
173
174 #[inline]
176 #[must_use]
177 pub fn mode(&self) -> Option<SanitizedMode> {
178 self.mode
179 }
180}
181
182#[derive(Debug)]
208#[non_exhaustive]
209pub enum ValidatedEntryType {
210 File(QuotaPermit),
213
214 Directory,
216
217 Symlink(SafeSymlink),
219
220 #[non_exhaustive]
222 Hardlink {
223 target: SafePath,
225 counted: EntryCount,
228 },
229}
230
231pub(crate) struct ValidatorCore<'a> {
238 config: &'a SecurityConfig<Validated>,
239 quota_tracker: QuotaTracker,
240 hardlink_tracker: HardlinkTracker,
241 symlink_seen: bool,
242}
243
244impl<'a> ValidatorCore<'a> {
245 pub(crate) fn new(config: &'a SecurityConfig<Validated>) -> Self {
246 Self {
247 config,
248 quota_tracker: QuotaTracker::new(),
249 hardlink_tracker: HardlinkTracker::new(),
250 symlink_seen: false,
251 }
252 }
253
254 pub(crate) fn context<V: FsView>(&self) -> ValidationContext<V> {
257 let mut ctx = ValidationContext::new(self.config.allowed.symlinks);
258 if self.symlink_seen {
259 ctx.mark_symlink_seen();
260 }
261 ctx
262 }
263
264 #[expect(
266 clippy::too_many_arguments,
267 reason = "mirrors the public validate_entry plus the root, view and context"
268 )]
269 pub(crate) fn validate_entry_in<V: FsView>(
270 &mut self,
271 path: &Path,
272 entry_type: &EntryType,
273 uncompressed_size: u64,
274 compressed_size: Option<u64>,
275 mode: Option<u32>,
276 root: &V::Root,
277 view: &V,
278 ctx: &ValidationContext<V>,
279 ) -> Result<ValidatedEntry> {
280 let size = EntrySize {
281 uncompressed: uncompressed_size,
282 compressed: compressed_size,
283 };
284 match entry_type {
285 EntryType::File => {
286 let file = self.validate_file_in(path, size, mode, root, view, ctx)?;
287 Ok(ValidatedEntry::new(
288 file.path,
289 ValidatedEntryType::File(file.permit),
290 file.mode,
291 ))
292 }
293 EntryType::Directory => {
294 let safe_path = self.validate_directory_in(path, size, root, view, ctx)?;
295 Ok(ValidatedEntry::new(
296 safe_path,
297 ValidatedEntryType::Directory,
298 None,
299 ))
300 }
301 EntryType::Symlink { target } => {
302 let symlink = self.validate_symlink_in(path, target, size, root, view, ctx)?;
303 Ok(ValidatedEntry::new(
304 symlink.link,
305 ValidatedEntryType::Symlink(symlink.symlink),
306 None,
307 ))
308 }
309 EntryType::Hardlink { target } => {
310 let link = self.validate_hardlink_in(path, target, size, root, view, ctx)?;
311 Ok(ValidatedEntry::new(
312 link.link,
313 ValidatedEntryType::Hardlink {
314 target: link.target,
315 counted: link.counted,
316 },
317 None,
318 ))
319 }
320 }
321 }
322
323 pub(crate) fn validate_file_in<V: FsView>(
325 &mut self,
326 path: &Path,
327 size: EntrySize,
328 mode: Option<u32>,
329 root: &V::Root,
330 view: &V,
331 ctx: &ValidationContext<V>,
332 ) -> Result<ValidatedFile> {
333 let safe_path = self
334 .validate_entry_path_in(path, NodeKind::NonDirectory, root, view, ctx)?
335 .into_inner();
336 let permit = self.quota_tracker.reserve(size.uncompressed, self.config)?;
337 self.check_ratio(size.compressed, size.uncompressed)?;
338 Ok(ValidatedFile {
339 path: safe_path,
340 permit,
341 mode: mode.map(|m| sanitize_permissions(m, self.config)),
342 })
343 }
344
345 pub(crate) fn validate_directory_in<V: FsView>(
347 &self,
348 path: &Path,
349 size: EntrySize,
350 root: &V::Root,
351 view: &V,
352 ctx: &ValidationContext<V>,
353 ) -> Result<SafePath> {
354 let safe_path = self
355 .validate_entry_path_in(path, NodeKind::Directory, root, view, ctx)?
356 .into_inner();
357 self.check_ratio(size.compressed, size.uncompressed)?;
358 Ok(safe_path)
359 }
360
361 pub(crate) fn validate_symlink_in<V: FsView>(
363 &mut self,
364 path: &Path,
365 target: &Path,
366 size: EntrySize,
367 root: &V::Root,
368 view: &V,
369 ctx: &ValidationContext<V>,
370 ) -> Result<ValidatedSymlink> {
371 let safe_path = self
372 .validate_entry_path_in(path, NodeKind::NonDirectory, root, view, ctx)?
373 .into_inner();
374 self.check_ratio(size.compressed, size.uncompressed)?;
375 require_symlinks_allowed(self.config)?;
376 self.reserve_symlink(size.uncompressed)?;
377 let symlink = SafeSymlink::validate_in(&safe_path, target, root, self.config, view)?;
378 self.symlink_seen = true;
379 Ok(ValidatedSymlink {
380 link: safe_path,
381 symlink,
382 })
383 }
384
385 pub(crate) fn validate_hardlink_in<V: FsView>(
387 &mut self,
388 path: &Path,
389 target: &Path,
390 size: EntrySize,
391 root: &V::Root,
392 view: &V,
393 ctx: &ValidationContext<V>,
394 ) -> Result<ValidatedHardlink> {
395 let safe_path = self
396 .validate_entry_path_in(path, NodeKind::NonDirectory, root, view, ctx)?
397 .into_inner();
398 self.check_ratio(size.compressed, size.uncompressed)?;
399 require_hardlinks_allowed(self.config)?;
400 let counted = self.quota_tracker.reserve_count(self.config)?;
401
402 self.hardlink_tracker
403 .validate_hardlink_in(&safe_path, target, root, self.config, view)?;
404
405 let target_safe = SafePath::new_unchecked(target.to_path_buf());
408 Ok(ValidatedHardlink {
409 link: safe_path,
410 target: target_safe,
411 counted,
412 })
413 }
414
415 pub(crate) fn validate_entry_path_in<V: FsView>(
417 &self,
418 path: &Path,
419 kind: NodeKind,
420 root: &V::Root,
421 view: &V,
422 ctx: &ValidationContext<V>,
423 ) -> Result<EntryPath<SafePath>> {
424 let entry_path = EntryPath::of(path).require_directory_root(kind)?;
425 let validate =
426 |path| SafePath::validate_with_context_in(path, root, self.config, ctx, view);
427 match entry_path {
428 EntryPath::Root(path) => validate(path).map(EntryPath::Root),
429 EntryPath::Child(path) => validate(path).map(EntryPath::Child),
430 }
431 }
432
433 pub(crate) fn reserve_file(&mut self, size: u64) -> Result<QuotaPermit> {
434 self.quota_tracker.reserve(size, self.config)
435 }
436
437 pub(crate) fn check_ratio(
438 &self,
439 compressed_size: Option<u64>,
440 uncompressed_size: u64,
441 ) -> Result<()> {
442 if let Some(compressed) = compressed_size {
443 validate_compression_ratio(compressed, uncompressed_size, self.config)?;
444 }
445 Ok(())
446 }
447
448 pub(crate) fn reserve_symlink(&mut self, size: u64) -> Result<()> {
449 self.quota_tracker.reserve(size, self.config).map(drop)
450 }
451
452 pub(crate) fn charge_hardlink(
453 &mut self,
454 counted: EntryCount,
455 size: u64,
456 ) -> Result<QuotaPermit> {
457 self.quota_tracker.charge(counted, size, self.config)
458 }
459
460 pub(crate) fn finish(self) -> ValidationReport {
461 ValidationReport {
462 files_validated: self.quota_tracker.files_extracted(),
463 total_bytes: self.quota_tracker.bytes_written(),
464 hardlinks_tracked: self.hardlink_tracker.count(),
465 }
466 }
467}
468
469pub struct EntryValidator<'a> {
516 core: ValidatorCore<'a>,
517 dest: &'a DestDir,
518}
519
520impl<'a> EntryValidator<'a> {
521 #[must_use]
523 pub fn new(config: &'a SecurityConfig<Validated>, dest: &'a DestDir) -> Self {
524 Self {
525 core: ValidatorCore::new(config),
526 dest,
527 }
528 }
529
530 #[inline]
554 pub fn validate_entry(
555 &mut self,
556 path: &Path,
557 entry_type: &EntryType,
558 uncompressed_size: u64,
559 compressed_size: Option<u64>,
560 mode: Option<u32>,
561 ) -> Result<ValidatedEntry> {
562 let ctx = self.core.context::<HostFs>();
563 self.core.validate_entry_in(
564 path,
565 entry_type,
566 uncompressed_size,
567 compressed_size,
568 mode,
569 self.dest,
570 &HostFs,
571 &ctx,
572 )
573 }
574
575 #[cfg(test)]
590 pub(crate) fn charge_hardlink(
591 &mut self,
592 counted: EntryCount,
593 size: u64,
594 ) -> Result<QuotaPermit> {
595 self.core.charge_hardlink(counted, size)
596 }
597
598 #[must_use]
603 pub fn finish(self) -> ValidationReport {
604 self.core.finish()
605 }
606}
607
608#[derive(Debug)]
610pub struct ValidationReport {
611 pub files_validated: usize,
614
615 pub total_bytes: u64,
617
618 pub hardlinks_tracked: usize,
620}
621
622#[cfg(test)]
623#[allow(
624 clippy::unwrap_used,
625 clippy::expect_used,
626 clippy::field_reassign_with_default
627)]
628mod tests {
629 use super::*;
630 use std::assert_matches;
631 use std::path::PathBuf;
632 use tempfile::TempDir;
633
634 #[test]
635 fn test_entry_path_of_splits_root_from_child() {
636 for root in [".", "./", "./."] {
637 assert!(EntryPath::of(Path::new(root)).is_root(), "{root:?}");
638 }
639 assert_eq!(
640 EntryPath::of(Path::new("a/b")),
641 EntryPath::Child(Path::new("a/b"))
642 );
643 }
644
645 #[test]
646 fn test_root_requires_directory() {
647 let root = EntryPath::of(Path::new("."));
648 assert!(root.require_directory_root(NodeKind::Directory).is_ok());
649 assert_matches!(
650 root.require_directory_root(NodeKind::NonDirectory),
651 Err(ArchiveError::SecurityViolation { .. })
652 );
653 let child = EntryPath::of(Path::new("a"));
654 assert!(child.require_directory_root(NodeKind::NonDirectory).is_ok());
655 }
656
657 #[test]
658 fn test_entry_validator_new() {
659 let temp = TempDir::new().expect("failed to create temp dir");
660 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
661 let config = SecurityConfig::default().validate().expect("valid config");
662 let validator = EntryValidator::new(&config, &dest);
663 let report = validator.finish();
664 assert_eq!(report.files_validated, 0);
665 assert_eq!(report.total_bytes, 0);
666 assert_eq!(report.hardlinks_tracked, 0);
667 }
668
669 #[test]
670 fn test_validate_file_entry() {
671 let temp = TempDir::new().expect("failed to create temp dir");
672 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
673 let config = SecurityConfig::default().validate().expect("valid config");
674 let mut validator = EntryValidator::new(&config, &dest);
675
676 let result = validator.validate_entry(
677 Path::new("file.txt"),
678 &EntryType::File,
679 1024,
680 None,
681 Some(0o644),
682 );
683
684 assert!(result.is_ok());
685 let entry = result.unwrap();
686 assert_eq!(entry.safe_path.as_path(), Path::new("file.txt"));
687 assert_matches!(entry.entry_type, ValidatedEntryType::File(_));
688 assert_eq!(entry.mode.map(SanitizedMode::as_u32), Some(0o644));
689 }
690
691 #[test]
692 fn test_validate_directory_entry() {
693 let temp = TempDir::new().expect("failed to create temp dir");
694 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
695 let config = SecurityConfig::default().validate().expect("valid config");
696 let mut validator = EntryValidator::new(&config, &dest);
697
698 let result =
699 validator.validate_entry(Path::new("dir"), &EntryType::Directory, 0, None, None);
700
701 assert!(result.is_ok());
702 let entry = result.unwrap();
703 assert_matches!(entry.entry_type, ValidatedEntryType::Directory);
704 assert!(entry.mode.is_none());
705 }
706
707 #[test]
708 fn test_validate_path_traversal_rejected() {
709 let temp = TempDir::new().expect("failed to create temp dir");
710 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
711 let config = SecurityConfig::default().validate().expect("valid config");
712 let mut validator = EntryValidator::new(&config, &dest);
713
714 let result = validator.validate_entry(
715 Path::new("../etc/passwd"),
716 &EntryType::File,
717 1024,
718 None,
719 Some(0o644),
720 );
721
722 assert!(result.is_err());
723 }
724
725 #[test]
726 fn test_quota_exceeded_file_size() {
727 let temp = TempDir::new().unwrap();
728 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
729 let mut config = SecurityConfig::default();
730 config.max_file_size = 100;
731 let config = config.validate().expect("valid config");
732 let mut validator = EntryValidator::new(&config, &dest);
733
734 let result = validator.validate_entry(
735 Path::new("large.txt"),
736 &EntryType::File,
737 1000,
738 None,
739 Some(0o644),
740 );
741
742 assert!(result.is_err());
743 }
744
745 #[test]
746 fn test_quota_exceeded_file_count() {
747 let temp = TempDir::new().unwrap();
748 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
749 let mut config = SecurityConfig::default();
750 config.max_file_count = 2;
751 let config = config.validate().expect("valid config");
752 let mut validator = EntryValidator::new(&config, &dest);
753
754 assert!(
755 validator
756 .validate_entry(
757 Path::new("file1.txt"),
758 &EntryType::File,
759 100,
760 None,
761 Some(0o644),
762 )
763 .is_ok()
764 );
765 assert!(
766 validator
767 .validate_entry(
768 Path::new("file2.txt"),
769 &EntryType::File,
770 100,
771 None,
772 Some(0o644),
773 )
774 .is_ok()
775 );
776
777 let result = validator.validate_entry(
778 Path::new("file3.txt"),
779 &EntryType::File,
780 100,
781 None,
782 Some(0o644),
783 );
784 assert!(result.is_err());
785 }
786
787 #[test]
788 fn test_zip_bomb_detected() {
789 let temp = TempDir::new().expect("failed to create temp dir");
790 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
791 let config = SecurityConfig::default().validate().expect("valid config");
792 let mut validator = EntryValidator::new(&config, &dest);
793
794 let result = validator.validate_entry(
795 Path::new("bomb.txt"),
796 &EntryType::File,
797 1_000_000,
798 Some(100),
799 Some(0o644),
800 );
801
802 assert!(result.is_err());
803 }
804
805 #[test]
806 fn test_validation_report() {
807 let temp = TempDir::new().expect("failed to create temp dir");
808 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
809 let config = SecurityConfig::default().validate().expect("valid config");
810 let mut validator = EntryValidator::new(&config, &dest);
811
812 validator
813 .validate_entry(
814 Path::new("file1.txt"),
815 &EntryType::File,
816 1024,
817 None,
818 Some(0o644),
819 )
820 .unwrap();
821
822 validator
823 .validate_entry(
824 Path::new("file2.txt"),
825 &EntryType::File,
826 2048,
827 None,
828 Some(0o644),
829 )
830 .unwrap();
831
832 let report = validator.finish();
833 assert_eq!(report.files_validated, 2);
834 assert_eq!(report.total_bytes, 1024 + 2048);
835 }
836
837 #[test]
838 fn test_sanitize_permissions_setuid() {
839 let temp = TempDir::new().expect("failed to create temp dir");
840 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
841 let config = SecurityConfig::default().validate().expect("valid config");
842 let mut validator = EntryValidator::new(&config, &dest);
843
844 let result = validator.validate_entry(
845 Path::new("file.txt"),
846 &EntryType::File,
847 1024,
848 None,
849 Some(0o4755),
850 );
851
852 assert!(result.is_ok());
853 let entry = result.unwrap();
854 assert_eq!(entry.mode.map(SanitizedMode::as_u32), Some(0o755)); }
856
857 #[test]
858 fn test_symlink_validation() {
859 let temp = TempDir::new().unwrap();
860 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
861 let mut config = SecurityConfig::default();
862 config.allowed.symlinks = true;
863 let config = config.validate().expect("valid config");
864 let mut validator = EntryValidator::new(&config, &dest);
865
866 let result = validator.validate_entry(
867 Path::new("link"),
868 &EntryType::Symlink {
869 target: PathBuf::from("target.txt"),
870 },
871 0,
872 None,
873 None,
874 );
875
876 assert!(result.is_ok());
877 let entry = result.unwrap();
878 assert_matches!(entry.entry_type, ValidatedEntryType::Symlink(_));
879 assert!(validator.core.symlink_seen);
880 }
881
882 #[test]
883 fn test_hardlink_validation() {
884 let temp = TempDir::new().unwrap();
885 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
886 let mut config = SecurityConfig::default();
887 config.allowed.hardlinks = true;
888 let config = config.validate().expect("valid config");
889 let mut validator = EntryValidator::new(&config, &dest);
890
891 let result = validator.validate_entry(
892 Path::new("link"),
893 &EntryType::Hardlink {
894 target: PathBuf::from("target.txt"),
895 },
896 0,
897 None,
898 None,
899 );
900
901 assert!(result.is_ok());
902 let entry = result.unwrap();
903 assert_matches!(entry.entry_type, ValidatedEntryType::Hardlink { .. });
904 }
905
906 #[test]
907 fn test_multiple_entries_with_report() {
908 let temp = TempDir::new().unwrap();
909 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
910 let mut config = SecurityConfig::default();
911 config.allowed.hardlinks = true;
912 let config = config.validate().expect("valid config");
913 let mut validator = EntryValidator::new(&config, &dest);
914
915 validator
917 .validate_entry(
918 Path::new("file1.txt"),
919 &EntryType::File,
920 1024,
921 None,
922 Some(0o644),
923 )
924 .unwrap();
925
926 validator
927 .validate_entry(Path::new("dir"), &EntryType::Directory, 0, None, None)
928 .unwrap();
929
930 validator
931 .validate_entry(
932 Path::new("hardlink"),
933 &EntryType::Hardlink {
934 target: PathBuf::from("file1.txt"),
935 },
936 0,
937 None,
938 None,
939 )
940 .unwrap();
941
942 let report = validator.finish();
943 assert_eq!(report.files_validated, 2); assert_eq!(report.total_bytes, 1024);
945 assert_eq!(report.hardlinks_tracked, 1);
946 }
947
948 #[test]
950 fn test_empty_directory_validation() {
951 let temp = TempDir::new().expect("failed to create temp dir");
952 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
953 let config = SecurityConfig::default().validate().expect("valid config");
954 let mut validator = EntryValidator::new(&config, &dest);
955
956 let result = validator.validate_entry(
958 Path::new("empty_dir/"),
959 &EntryType::Directory,
960 0,
961 None,
962 None,
963 );
964
965 assert!(result.is_ok(), "empty directory should be valid");
966 let entry = result.unwrap();
967 assert_matches!(
968 entry.entry_type,
969 ValidatedEntryType::Directory,
970 "should be directory type"
971 );
972 assert!(entry.mode.is_none(), "directory should not have mode set");
973 }
974
975 #[test]
976 fn test_nested_empty_directories() {
977 let temp = TempDir::new().expect("failed to create temp dir");
978 let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
979 let config = SecurityConfig::default().validate().expect("valid config");
980 let mut validator = EntryValidator::new(&config, &dest);
981
982 let dirs = ["a/", "a/b/", "a/b/c/"];
984 for dir in &dirs {
985 let result =
986 validator.validate_entry(Path::new(dir), &EntryType::Directory, 0, None, None);
987 assert!(result.is_ok(), "nested directory {dir} should be valid");
988 }
989
990 let report = validator.finish();
991 assert_eq!(
992 report.files_validated, 0,
993 "directories are not counted as files"
994 );
995 }
996
997 #[test]
999 fn test_validator_uses_references() {
1000 let temp = TempDir::new().unwrap();
1001 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1002 let config = SecurityConfig::default().validate().expect("valid config");
1003
1004 let validator = EntryValidator::new(&config, &dest);
1006
1007 assert_eq!(
1009 config.max_file_size,
1010 SecurityConfig::default().max_file_size
1011 );
1012 let _ = dest.as_path();
1015
1016 drop(validator);
1018 }
1019
1020 #[test]
1022 fn test_multiple_validators_share_config() {
1023 let temp1 = TempDir::new().unwrap();
1024 let temp2 = TempDir::new().unwrap();
1025 let dest1 = DestDir::new(temp1.path().to_path_buf()).unwrap();
1026 let dest2 = DestDir::new(temp2.path().to_path_buf()).unwrap();
1027 let config = SecurityConfig::default().validate().expect("valid config");
1028
1029 let mut validator1 = EntryValidator::new(&config, &dest1);
1031 let mut validator2 = EntryValidator::new(&config, &dest2);
1032
1033 let result1 = validator1.validate_entry(
1035 Path::new("file1.txt"),
1036 &EntryType::File,
1037 1024,
1038 None,
1039 Some(0o644),
1040 );
1041 assert!(result1.is_ok());
1042
1043 let result2 = validator2.validate_entry(
1044 Path::new("file2.txt"),
1045 &EntryType::File,
1046 2048,
1047 None,
1048 Some(0o644),
1049 );
1050 assert!(result2.is_ok());
1051
1052 assert_eq!(
1054 config.max_file_size,
1055 SecurityConfig::default().max_file_size
1056 );
1057 }
1058
1059 #[test]
1060 fn test_symlink_seen_flag_propagates() {
1061 let temp = TempDir::new().unwrap();
1062 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1063 let mut config = SecurityConfig::default();
1064 config.allowed.symlinks = true;
1065 let config = config.validate().expect("valid config");
1066 let mut validator = EntryValidator::new(&config, &dest);
1067
1068 assert!(!validator.core.symlink_seen);
1069
1070 validator
1072 .validate_entry(
1073 Path::new("link"),
1074 &EntryType::Symlink {
1075 target: PathBuf::from("target.txt"),
1076 },
1077 0,
1078 None,
1079 None,
1080 )
1081 .unwrap();
1082
1083 assert!(validator.core.symlink_seen);
1084 }
1085
1086 fn validate_hardlink_entry(
1089 validator: &mut EntryValidator<'_>,
1090 name: &str,
1091 ) -> crate::Result<EntryCount> {
1092 let entry = validator.validate_entry(
1093 Path::new(name),
1094 &EntryType::Hardlink {
1095 target: PathBuf::from("target.txt"),
1096 },
1097 0,
1098 None,
1099 None,
1100 )?;
1101 match entry.entry_type {
1102 ValidatedEntryType::Hardlink { counted, .. } => Ok(counted),
1103 other => panic!("expected a hardlink, got {other:?}"),
1104 }
1105 }
1106
1107 fn validate_symlink_entry(
1108 validator: &mut EntryValidator<'_>,
1109 name: &str,
1110 ) -> crate::Result<ValidatedEntry> {
1111 validator.validate_entry(
1112 Path::new(name),
1113 &EntryType::Symlink {
1114 target: PathBuf::from("target.txt"),
1115 },
1116 0,
1117 None,
1118 None,
1119 )
1120 }
1121
1122 #[test]
1123 fn test_charge_hardlink_exceeding_max_file_size_rejected() {
1124 let temp = TempDir::new().unwrap();
1125 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1126 let mut config = SecurityConfig::default();
1127 config.allowed.hardlinks = true;
1128 config.max_file_size = 100;
1129 let config = config.validate().expect("valid config");
1130 let mut validator = EntryValidator::new(&config, &dest);
1131
1132 let counted = validate_hardlink_entry(&mut validator, "link").unwrap();
1133 let result = validator.charge_hardlink(counted, 1_000);
1134
1135 assert_matches!(
1136 result,
1137 Err(crate::ArchiveError::QuotaExceeded {
1138 resource: crate::QuotaResource::FileSize { .. }
1139 }),
1140 "hardlink exceeding max_file_size must be rejected, got: {result:?}"
1141 );
1142 }
1143
1144 #[test]
1145 fn test_charge_hardlink_shares_quota_tracker_with_files() {
1146 let temp = TempDir::new().unwrap();
1147 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1148 let mut config = SecurityConfig::default();
1149 config.allowed.hardlinks = true;
1150 config.max_total_size = 250;
1151 let config = config.validate().expect("valid config");
1152 let mut validator = EntryValidator::new(&config, &dest);
1153
1154 validator
1155 .validate_entry(
1156 Path::new("file1.txt"),
1157 &EntryType::File,
1158 100,
1159 None,
1160 Some(0o644),
1161 )
1162 .unwrap();
1163
1164 let first = validate_hardlink_entry(&mut validator, "link1").unwrap();
1165 let second = validate_hardlink_entry(&mut validator, "link2").unwrap();
1166 assert!(validator.charge_hardlink(first, 100).is_ok());
1167
1168 let result = validator.charge_hardlink(second, 100);
1169 assert_matches!(
1170 result,
1171 Err(crate::ArchiveError::QuotaExceeded {
1172 resource: crate::QuotaResource::TotalSize { .. }
1173 }),
1174 "hardlink bytes must accumulate on the same tracker as file bytes \
1175 (200 already recorded + 100 more exceeds the 250 budget), got: {result:?}"
1176 );
1177 }
1178
1179 #[test]
1180 fn test_hardlink_counted_once_in_pass_one() {
1181 let temp = TempDir::new().unwrap();
1182 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1183 let mut config = SecurityConfig::default();
1184 config.allowed.hardlinks = true;
1185 config.max_file_count = 2;
1186 let config = config.validate().expect("valid config");
1187 let mut validator = EntryValidator::new(&config, &dest);
1188
1189 let first = validate_hardlink_entry(&mut validator, "link1").unwrap();
1190 let second = validate_hardlink_entry(&mut validator, "link2").unwrap();
1191
1192 let result = validate_hardlink_entry(&mut validator, "link3");
1193 assert_matches!(
1194 result,
1195 Err(crate::ArchiveError::QuotaExceeded {
1196 resource: crate::QuotaResource::FileCount { .. }
1197 }),
1198 "the third hardlink must exceed max_file_count in pass one, got: {result:?}"
1199 );
1200
1201 assert!(validator.charge_hardlink(first, 1).is_ok());
1202 assert!(validator.charge_hardlink(second, 1).is_ok());
1203 assert_eq!(validator.finish().files_validated, 3);
1204 }
1205
1206 #[test]
1207 fn test_symlink_exceeding_max_file_count_rejected() {
1208 let temp = TempDir::new().unwrap();
1209 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1210 let mut config = SecurityConfig::default();
1211 config.allowed.symlinks = true;
1212 config.max_file_count = 2;
1213 let config = config.validate().expect("valid config");
1214 let mut validator = EntryValidator::new(&config, &dest);
1215
1216 assert!(validate_symlink_entry(&mut validator, "l1").is_ok());
1217 assert!(validate_symlink_entry(&mut validator, "l2").is_ok());
1218
1219 let result = validate_symlink_entry(&mut validator, "l3");
1220 assert_matches!(
1221 result,
1222 Err(crate::ArchiveError::QuotaExceeded {
1223 resource: crate::QuotaResource::FileCount { .. }
1224 }),
1225 "symlinks must count against max_file_count, got: {result:?}"
1226 );
1227 }
1228
1229 #[test]
1230 fn test_symlink_policy_error_wins_over_file_count() {
1231 let temp = TempDir::new().unwrap();
1232 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1233 let mut config = SecurityConfig::default();
1234 config.max_file_count = 1;
1235 let config = config.validate().expect("valid config");
1236 let mut validator = EntryValidator::new(&config, &dest);
1237 validator
1238 .validate_entry(Path::new("f"), &EntryType::File, 1, None, None)
1239 .unwrap();
1240
1241 let result = validate_symlink_entry(&mut validator, "l1");
1242 assert_matches!(
1243 result,
1244 Err(crate::ArchiveError::SecurityViolation { ref reason, .. })
1245 if reason == "symlinks not allowed",
1246 "got: {result:?}"
1247 );
1248 }
1249
1250 #[test]
1251 fn test_hardlink_policy_error_wins_over_file_count() {
1252 let temp = TempDir::new().unwrap();
1253 let dest = DestDir::new(temp.path().to_path_buf()).unwrap();
1254 let mut config = SecurityConfig::default();
1255 config.max_file_count = 1;
1256 let config = config.validate().expect("valid config");
1257 let mut validator = EntryValidator::new(&config, &dest);
1258 validator
1259 .validate_entry(Path::new("f"), &EntryType::File, 1, None, None)
1260 .unwrap();
1261
1262 let result = validate_hardlink_entry(&mut validator, "l1");
1263 assert_matches!(
1264 result,
1265 Err(crate::ArchiveError::SecurityViolation { ref reason, .. })
1266 if reason == "hardlinks not allowed",
1267 "got: {result:?}"
1268 );
1269 }
1270}