Skip to main content

exarch_core/security/
validator.rs

1//! Entry validation orchestrator.
2//!
3//! This module provides the main `EntryValidator` type that coordinates all
4//! security validations for archive entries.
5
6use 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/// Whether an archive entry is a directory, as the root-entry rule sees it.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub(crate) enum NodeKind {
37    /// The entry is a directory (or stands for one, like ZIP's empty root
38    /// file).
39    Directory,
40    /// Any other entry: file, symlink, hardlink.
41    NonDirectory,
42}
43
44impl NodeKind {
45    /// Converts a format's directory flag at the boundary, so the rule itself
46    /// never takes a bare `bool`.
47    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/// An archive entry name, split into the archive root and everything else.
57///
58/// The root (`.`, `./`) names the destination itself, so it must not be taken
59/// for an ordinary path: handlers have to match on the variant. `P` is the
60/// path as carried at that stage (`&Path` for a raw name, `SafePath` once
61/// validated).
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(crate) enum EntryPath<P> {
64    /// The destination itself (`.`, `./`).
65    Root(P),
66    /// Any path below the destination.
67    Child(P),
68}
69
70impl<'a> EntryPath<&'a Path> {
71    /// Classifies a raw entry name; the single definition of "root" for names
72    /// not yet validated.
73    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    /// Whether this is the root; for tests and callers that only need to know
84    /// that, not to act on the path.
85    pub(crate) const fn is_root(&self) -> bool {
86        matches!(self, Self::Root(_))
87    }
88
89    /// The path, for callers that treat the root like any directory.
90    pub(crate) fn into_inner(self) -> P {
91        match self {
92            Self::Root(path) | Self::Child(path) => path,
93        }
94    }
95
96    /// Rejects a root entry that is not a directory.
97    ///
98    /// A file, symlink or hardlink standing for the root would be written
99    /// onto, or remove, the destination. Shared by entry validation and
100    /// listing so `extract`, `list` and `verify` agree.
101    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
111/// Rejects a root entry that is not a directory, for the TAR extractor, which
112/// checks the raw name before its extension filter.
113pub(crate) fn check_root_entry_is_directory(path: &Path, kind: NodeKind) -> Result<()> {
114    EntryPath::of(path).require_directory_root(kind).map(drop)
115}
116
117/// Rejects an empty entry name, so listing fails on the name that extraction
118/// and `verify` refuse, instead of joining it onto the destination directory.
119pub(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/// Result of entry validation.
127///
128/// Contains validated and sanitized entry information ready for extraction.
129///
130/// # Security Properties
131///
132/// - Can ONLY be constructed through [`EntryValidator::validate_entry`]
133/// - Fields are private; accessed through getters, so a `ValidatedEntry` cannot
134///   be hand-assembled from unvalidated parts anywhere else in the crate
135#[derive(Debug)]
136pub struct ValidatedEntry {
137    safe_path: SafePath,
138    entry_type: ValidatedEntryType,
139    mode: Option<SanitizedMode>,
140}
141
142impl ValidatedEntry {
143    /// Constructs a `ValidatedEntry` from its already-validated parts.
144    ///
145    /// `pub(crate)` rather than fully private so that unit tests elsewhere in
146    /// this crate (`formats::common`) can build fixtures without weakening
147    /// the sealing against external construction.
148    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    /// Returns the validated path within the destination directory.
161    #[inline]
162    #[must_use]
163    pub fn safe_path(&self) -> &SafePath {
164        &self.safe_path
165    }
166
167    /// Returns the validated entry type.
168    #[inline]
169    #[must_use]
170    pub fn entry_type(&self) -> &ValidatedEntryType {
171        &self.entry_type
172    }
173
174    /// Returns the sanitized file permissions, if applicable.
175    #[inline]
176    #[must_use]
177    pub fn mode(&self) -> Option<SanitizedMode> {
178        self.mode
179    }
180}
181
182/// Validated entry type variants.
183///
184/// This enum alone does not carry the sealing guarantee — the external seal
185/// comes from [`ValidatedEntry`]: its constructor is `pub(crate)`, so
186/// nothing outside this crate can assemble a `ValidatedEntry` at all,
187/// regardless of how its `ValidatedEntryType` field was produced. Within
188/// that guarantee, several variants add a second, crate-internal layer for
189/// their own payloads:
190///
191/// - The `Symlink` and `Hardlink` variants wrap [`SafeSymlink`] and
192///   [`SafePath`], which are independently sealed and can only be produced by
193///   their own validation routines, so even crate-internal code cannot forge a
194///   "validated" symlink/hardlink target.
195/// - The `File` variant wraps [`QuotaPermit`], whose only producer is
196///   [`QuotaTracker::reserve`]: a `File` variant cannot be built without a
197///   quota reservation having actually succeeded. This is crate-internal
198///   discipline, not an external-construction barrier — enum variant fields are
199///   as visible as the enum itself, so `ValidatedEntryType::File(todo!())`
200///   compiles from outside this crate too; it just can never *run*, since
201///   nothing outside this crate can produce a genuine `QuotaPermit`.
202///
203/// `#[non_exhaustive]` so a future variant is not a breaking change for
204/// downstream matches — [`ValidatedEntry::entry_type`] is the only way
205/// external code observes this type, and even that always sees output from
206/// [`EntryValidator::validate_entry`].
207#[derive(Debug)]
208#[non_exhaustive]
209pub enum ValidatedEntryType {
210    /// Regular file, carrying proof that its size was reserved against a
211    /// [`QuotaTracker`] before this entry was validated.
212    File(QuotaPermit),
213
214    /// Directory
215    Directory,
216
217    /// Validated symlink
218    Symlink(SafeSymlink),
219
220    /// Hardlink (validated in tracker, target path stored for two-pass)
221    #[non_exhaustive]
222    Hardlink {
223        /// Target path (already validated)
224        target: SafePath,
225        /// Proof the hardlink was counted against `max_file_count` in the
226        /// first pass; the second pass spends it to charge the copied bytes.
227        counted: EntryCount,
228    },
229}
230
231/// The validation state and rules shared by every extraction target: quota,
232/// hardlink and symlink tracking plus the per-entry checks.
233///
234/// It holds neither a root nor a view. Both are passed per call, tied by
235/// [`FsView::Root`], so a target can mutate its view between validations and a
236/// root can never be paired with the wrong view.
237pub(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    /// A context reflecting the symlinks seen so far; build a fresh one for
255    /// every entry.
256    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    /// See [`EntryValidator::validate_entry`].
265    #[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    /// Validates a regular file: path, quota reservation, ratio and mode.
324    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    /// Validates a directory entry: path and ratio.
346    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    /// Validates a symlink entry: path, ratio, policy, quota and target.
362    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    /// Validates a hardlink entry: path, ratio, policy, count and target.
386    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        // SAFETY: validate_hardlink_in verified target is relative, normalized,
406        // within the root
407        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    /// See [`EntryValidator::validate_entry_path`].
416    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
469/// Orchestrates security validation for archive entries.
470///
471/// This type maintains state across entry validations:
472/// - Quota tracking (file count, total size)
473/// - Compression ratio monitoring (zip bomb detection)
474/// - Hardlink target tracking
475/// - Symlink-seen flag (for canonicalize optimization)
476///
477/// # Lifecycle
478///
479/// 1. Create with `EntryValidator::new(&config, &dest)`
480/// 2. For each entry, call `validate_entry()`
481/// 3. After all entries processed, call `finish()` for final report
482///
483/// # Examples
484///
485/// ```no_run
486/// use exarch_core::SecurityConfig;
487/// use exarch_core::security::EntryValidator;
488/// use exarch_core::types::DestDir;
489/// use exarch_core::types::EntryType;
490/// use std::path::Path;
491/// use std::path::PathBuf;
492///
493/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
494/// let dest = DestDir::new(PathBuf::from("/tmp"))?;
495/// let config = SecurityConfig::default().validate()?;
496///
497/// let mut validator = EntryValidator::new(&config, &dest);
498///
499/// // Validate a file entry
500/// let entry = validator.validate_entry(
501///     Path::new("foo/bar.txt"),
502///     &EntryType::File,
503///     1024,        // uncompressed size
504///     Some(512),   // compressed size
505///     Some(0o644), // mode
506/// )?;
507///
508/// let report = validator.finish();
509/// println!("Validated {} files", report.files_validated);
510/// # Ok(())
511/// # }
512/// ```
513/// OPT-H004: Validator uses references to avoid cloning config and dest.
514/// This eliminates 1 clone per extraction (`SecurityConfig` + `DestDir`).
515pub struct EntryValidator<'a> {
516    core: ValidatorCore<'a>,
517    dest: &'a DestDir,
518}
519
520impl<'a> EntryValidator<'a> {
521    /// Creates a new entry validator with the given security configuration.
522    #[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    /// Validates an archive entry.
531    ///
532    /// This method orchestrates all security validations:
533    /// 1. Path validation (traversal, depth, banned components)
534    /// 2. Quota checking (file size, count, total size) — files and symlinks; a
535    ///    hardlink is counted here and charged its bytes in the second pass.
536    ///    Directories are not counted
537    /// 3. Compression ratio validation (zip bomb detection)
538    /// 4. Type-specific validation (symlink, hardlink, permissions)
539    ///
540    /// # Errors
541    ///
542    /// Returns an error if any validation fails. Common errors:
543    /// - `ArchiveError::PathTraversal` - Path escapes destination
544    /// - `ArchiveError::QuotaExceeded` - Size or count limits exceeded
545    /// - `ArchiveError::ZipBomb` - Compression ratio too high
546    /// - `ArchiveError::SymlinkEscape` - Symlink target escapes
547    /// - `ArchiveError::HardlinkEscape` - Hardlink target escapes
548    /// - `ArchiveError::InvalidPermissions` - Dangerous permissions
549    /// - `ArchiveError::SecurityViolation` - Root entry (`.`) that is not a
550    ///   directory. This is a backstop for formats that reach here without an
551    ///   earlier check; TAR checks first, in `process_entry`, so the root is
552    ///   rejected before the extension filter can skip it.
553    #[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    /// Charges a hardlink's copied byte count against the shared quota tracker,
576    /// returning a capability token that proves the charge succeeded.
577    ///
578    /// The hardlink was already counted against `max_file_count` in the first
579    /// pass (`validate_entry`), which is what `counted` proves; its size is
580    /// only known once the target file exists on disk, in the second pass. This
581    /// routes that size through the same `QuotaTracker` used for regular files,
582    /// so `max_file_size` and `max_total_size` are enforced uniformly
583    /// regardless of entry type, without counting the entry twice.
584    ///
585    /// # Errors
586    ///
587    /// Returns [`ArchiveError::QuotaExceeded`] if the copy would exceed
588    /// `max_file_size` or `max_total_size`.
589    #[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    /// Finishes validation and returns a summary report.
599    ///
600    /// This consumes the validator and returns statistics about the
601    /// validation process.
602    #[must_use]
603    pub fn finish(self) -> ValidationReport {
604        self.core.finish()
605    }
606}
607
608/// Summary report of validation process.
609#[derive(Debug)]
610pub struct ValidationReport {
611    /// Number of entries counted against `max_file_count`: files, symlinks and
612    /// hardlinks (directories are not counted)
613    pub files_validated: usize,
614
615    /// Total bytes processed
616    pub total_bytes: u64,
617
618    /// Number of hardlinks tracked
619    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)); // setuid stripped
855    }
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        // Validate multiple entry types
916        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); // File and hardlink; directories are not counted
944        assert_eq!(report.total_bytes, 1024);
945        assert_eq!(report.hardlinks_tracked, 1);
946    }
947
948    // M-TEST-1: Empty directory handling
949    #[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        // Empty directory should be valid
957        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        // Multiple nested empty directories
983        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    // OPT-H004: Test validator uses references (no cloning)
998    #[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        // Create validator with references
1005        let validator = EntryValidator::new(&config, &dest);
1006
1007        // Verify config and dest are still accessible (not moved)
1008        assert_eq!(
1009            config.max_file_size,
1010            SecurityConfig::default().max_file_size
1011        );
1012        // Note: dest.as_path() may be canonicalized on macOS (/var vs
1013        // /private/var) Just verify dest is still accessible
1014        let _ = dest.as_path();
1015
1016        // Validator can still be used
1017        drop(validator);
1018    }
1019
1020    // OPT-H004: Test multiple validators can share same config
1021    #[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        // Create two validators sharing the same config reference
1030        let mut validator1 = EntryValidator::new(&config, &dest1);
1031        let mut validator2 = EntryValidator::new(&config, &dest2);
1032
1033        // Both validators work independently
1034        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        // Config is still accessible
1053        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        // Validate a symlink entry
1071        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    // Issue #426: hardlink quota bypass regression tests.
1087
1088    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}