Skip to main content

eggup_archive/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Bounded allowlisted extraction of already verified local archives."]
4#![doc = ""]
5#![doc = "The crate supports regular-file members from tar.gz and zip archives"]
6#![doc = "without transport, authenticity, or live-installation policy."]
7
8use flate2::read::GzDecoder;
9use sha2::{Digest, Sha256};
10use std::collections::{HashMap, HashSet};
11use std::ffi::OsStr;
12use std::fmt;
13use std::fs::{self, File};
14use std::io::{Read, Seek, SeekFrom, Write};
15use std::path::{Component, Path, PathBuf};
16use std::sync::atomic::{AtomicU64, Ordering};
17use zip::ZipArchive;
18
19const ROOT_ATTEMPTS: u32 = 32;
20const IO_CHUNK_SIZE: usize = 16 * 1024;
21const TAR_TRAILING_PADDING_LIMIT: u64 = 1024 * 1024;
22const CLEANUP_MAX_PASSES: u32 = 8;
23const CLEANUP_MAX_ENTRIES_PER_PASS: usize = 10_000;
24const CLEANUP_MAX_DEPTH: usize = 32;
25static NEXT_ROOT_ID: AtomicU64 = AtomicU64::new(1);
26
27/// Supported local archive formats.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum ArchiveFormat {
30    /// A single-member gzip stream containing a tar archive.
31    TarGz,
32    /// A zip archive using stored or deflate-compressed entries.
33    Zip,
34}
35
36/// Finite resource limits applied to one extraction operation.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct ArchiveLimits {
39    max_archive_bytes: u64,
40    max_entries: usize,
41    max_path_bytes: usize,
42    max_member_bytes: u64,
43    max_total_uncompressed_bytes: u64,
44}
45
46impl ArchiveLimits {
47    /// Creates validated, finite limits.
48    pub fn new(
49        max_archive_bytes: u64,
50        max_entries: usize,
51        max_path_bytes: usize,
52        max_member_bytes: u64,
53        max_total_uncompressed_bytes: u64,
54    ) -> Result<Self, ExtractionError> {
55        if max_archive_bytes == 0
56            || max_entries == 0
57            || max_entries > 100_000
58            || max_path_bytes == 0
59            || max_path_bytes > 4096
60            || max_member_bytes == 0
61            || max_total_uncompressed_bytes == 0
62            || max_member_bytes > max_total_uncompressed_bytes
63        {
64            return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
65        }
66        Ok(Self {
67            max_archive_bytes,
68            max_entries,
69            max_path_bytes,
70            max_member_bytes,
71            max_total_uncompressed_bytes,
72        })
73    }
74
75    /// Conservative finite limits suitable as a starting point for consumers.
76    pub fn strict_default() -> Self {
77        Self {
78            max_archive_bytes: 512 * 1024 * 1024,
79            max_entries: 10_000,
80            max_path_bytes: 1024,
81            max_member_bytes: 256 * 1024 * 1024,
82            max_total_uncompressed_bytes: 512 * 1024 * 1024,
83        }
84    }
85}
86
87/// One declared archive path and its single-component extraction filename.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct ArchiveMember {
90    source_path: String,
91    output_name: String,
92    expected_size: Option<u64>,
93    expected_sha256: Option<[u8; 32]>,
94}
95
96impl ArchiveMember {
97    /// Declares one member. Expected size and SHA-256 are checked when present.
98    pub fn new(
99        source_path: impl Into<String>,
100        output_name: impl Into<String>,
101        expected_size: Option<u64>,
102        expected_sha256: Option<[u8; 32]>,
103    ) -> Result<Self, ExtractionError> {
104        let source_path = source_path.into();
105        let output_name = output_name.into();
106        validate_archive_path(&source_path, false, 4096)?;
107        validate_output_name(&output_name, 4096)?;
108        Ok(Self {
109            source_path,
110            output_name,
111            expected_size,
112            expected_sha256,
113        })
114    }
115
116    /// Returns the exact normalized member path expected in the archive.
117    pub fn source_path(&self) -> &str {
118        &self.source_path
119    }
120
121    /// Returns the output filename inside the private extraction root.
122    pub fn output_name(&self) -> &str {
123        &self.output_name
124    }
125}
126
127/// A validated declaration for one local archive extraction.
128#[derive(Debug, Clone)]
129pub struct ArchivePlan {
130    archive_path: PathBuf,
131    format: ArchiveFormat,
132    members: Vec<ArchiveMember>,
133    limits: ArchiveLimits,
134}
135
136impl ArchivePlan {
137    /// Creates a plan for an archive whose integrity/authenticity decisions are
138    /// already complete in the caller's policy layer.
139    pub fn new(
140        archive_path: impl Into<PathBuf>,
141        format: ArchiveFormat,
142        members: Vec<ArchiveMember>,
143        limits: ArchiveLimits,
144    ) -> Result<Self, ExtractionError> {
145        if members.is_empty() || members.len() > limits.max_entries {
146            return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
147        }
148        let mut sources = HashSet::new();
149        let mut outputs = HashSet::new();
150        let mut expected_total = 0u64;
151        for member in &members {
152            validate_archive_path(&member.source_path, false, limits.max_path_bytes)?;
153            validate_output_name(&member.output_name, limits.max_path_bytes)?;
154            if !sources.insert(member.source_path.clone())
155                || !outputs.insert(member.output_name.to_ascii_lowercase())
156            {
157                return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
158            }
159            if let Some(size) = member.expected_size {
160                if size > limits.max_member_bytes {
161                    return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
162                }
163                expected_total = expected_total
164                    .checked_add(size)
165                    .ok_or_else(|| ExtractionError::new(ExtractionErrorKind::InvalidPlan))?;
166            }
167        }
168        if expected_total > limits.max_total_uncompressed_bytes {
169            return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
170        }
171        Ok(Self {
172            archive_path: archive_path.into(),
173            format,
174            members,
175            limits,
176        })
177    }
178}
179
180/// Stable error categories for extraction and cleanup.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum ExtractionErrorKind {
183    /// The plan or a caller-selected directory is invalid.
184    InvalidPlan,
185    /// The source archive or private output could not be read or written.
186    Io,
187    /// The archive structure, compression stream, or checksum is malformed.
188    MalformedArchive,
189    /// A member path is ambiguous, unsupported, or unsafe.
190    InvalidPath,
191    /// The archive contains more entries than the declared bound.
192    TooManyEntries,
193    /// The compressed archive file exceeds its declared byte limit.
194    ArchiveTooLarge,
195    /// A declared member is a link, directory, or special file.
196    NonRegularMember,
197    /// Two archive entries have the same normalized member path.
198    DuplicateArchiveMember,
199    /// A required declared member does not occur in the archive.
200    MissingMember,
201    /// A member exceeds its finite decompressed-byte limit.
202    MemberTooLarge,
203    /// The operation exceeds its aggregate decompressed-byte limit.
204    TotalTooLarge,
205    /// A member's observed size differs from its declared exact size.
206    SizeMismatch,
207    /// A member's observed SHA-256 differs from its declared digest.
208    DigestMismatch,
209    /// The owned root could not be fully emptied.
210    ///
211    /// The residue path is available from [`ExtractionError::residue_path`].
212    /// The residue may be partially emptied and its emptiness is **not**
213    /// guaranteed, so a caller must inspect the directory itself.
214    CleanupFailed,
215}
216
217/// An extraction failure with optional bounded recovery location evidence.
218#[derive(Debug)]
219pub struct ExtractionError {
220    kind: ExtractionErrorKind,
221    residue_path: Option<PathBuf>,
222}
223
224impl ExtractionError {
225    fn new(kind: ExtractionErrorKind) -> Self {
226        Self {
227            kind,
228            residue_path: None,
229        }
230    }
231
232    /// Records residue at `path` for a cleanup that could **not** empty the
233    /// owned root.
234    ///
235    /// The residue may be partially emptied: emptiness is never promised on
236    /// this path, and the failure category is promoted to `CleanupFailed`,
237    /// which is what actually happened.
238    fn with_residue(mut self, path: PathBuf) -> Self {
239        self.kind = ExtractionErrorKind::CleanupFailed;
240        self.residue_path = Some(path);
241        self
242    }
243
244    /// Records residue at `path` after the owned root was emptied.
245    ///
246    /// Emptiness is verified before it is promised, so `kind()` and
247    /// `residue_path()` can never report a partial cleanup as a clean one: a
248    /// non-empty root is promoted to `CleanupFailed`, which is what actually
249    /// happened.
250    fn with_empty_residue(mut self, path: PathBuf) -> Self {
251        if !private_root_is_empty(&path) {
252            return self.with_residue(path);
253        }
254        self.residue_path = Some(path);
255        self
256    }
257
258    /// Returns the stable failure category.
259    pub fn kind(&self) -> ExtractionErrorKind {
260        self.kind
261    }
262
263    /// Returns the private-root residue location, when there is one.
264    ///
265    /// The path has two proven meanings, and a caller must not read them as
266    /// one:
267    ///
268    /// - On the [`extract`] failure path, the owned root was emptied and the
269    ///   leftover directory was verified empty before the path was recorded.
270    /// - On the explicit-cleanup failure path, the owned root could **not** be
271    ///   fully emptied. The residue may be partially emptied, its emptiness is
272    ///   **not** guaranteed, and the caller must inspect the directory itself.
273    ///
274    /// The path is **advisory**: if the root was renamed or replaced by a
275    /// third party, the crate emptied the owned object and left whatever
276    /// occupies the recorded pathname untouched.
277    pub fn residue_path(&self) -> Option<&Path> {
278        self.residue_path.as_deref()
279    }
280}
281
282impl fmt::Display for ExtractionError {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        write!(f, "archive extraction failed ({:?})", self.kind)
285    }
286}
287
288impl std::error::Error for ExtractionError {}
289
290/// Verified output evidence for one extracted regular file.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct ExtractedMember {
293    source_path: String,
294    output_name: String,
295    path: PathBuf,
296    bytes_written: u64,
297    sha256: [u8; 32],
298}
299
300impl ExtractedMember {
301    /// Returns the normalized archive path that supplied these bytes.
302    pub fn source_path(&self) -> &str {
303        &self.source_path
304    }
305
306    /// Returns the output filename inside the extraction root.
307    pub fn output_name(&self) -> &str {
308        &self.output_name
309    }
310
311    /// Returns the local regular-file path.
312    ///
313    /// This pathname is advisory diagnostics only, never staging authority:
314    /// a root rename/replacement after extraction can leave it stale or
315    /// foreign while the bytes remain in the handle-owned directory. Stage
316    /// archive members through [`BoundMember`] (see
317    /// [`PersistedExtraction::into_bound_sources`]) so staged bytes come from
318    /// the already-open member object instead of re-resolving this path.
319    pub fn path(&self) -> &Path {
320        &self.path
321    }
322
323    /// Returns the exact bytes written and verified.
324    pub fn bytes_written(&self) -> u64 {
325        self.bytes_written
326    }
327
328    /// Returns the SHA-256 digest of the extracted bytes.
329    pub fn sha256(&self) -> [u8; 32] {
330        self.sha256
331    }
332}
333
334/// Extraction output whose private directory is emptied when dropped.
335///
336/// The private root directory itself is never removed by this crate; it is
337/// left in place as an empty directory for the caller to remove.
338#[derive(Debug)]
339pub struct ExtractedArchive {
340    guard: Option<DirectoryGuard>,
341    members: Vec<ExtractedMember>,
342    /// Already-open readable member objects, paired by index with `members`.
343    /// Retained so the object-bound handoff never re-resolves a pathname.
344    handles: Vec<File>,
345}
346
347impl ExtractedArchive {
348    /// Returns the owner-private extraction root.
349    pub fn root(&self) -> &Path {
350        self.guard.as_ref().expect("active extraction guard").path()
351    }
352
353    /// Returns member evidence in declaration order.
354    pub fn members(&self) -> &[ExtractedMember] {
355        &self.members
356    }
357
358    /// Transfers cleanup responsibility to the caller after transaction
359    /// preparation or another explicit ownership handoff.
360    pub fn persist(mut self) -> PersistedExtraction {
361        let guard = self.guard.take().expect("active extraction guard");
362        let (root, handle) = guard.disarm();
363        let handles = std::mem::take(&mut self.handles);
364        PersistedExtraction {
365            root,
366            handle,
367            members: self.members,
368            handles,
369        }
370    }
371
372    /// Empties the operation-owned extraction root through the retained root
373    /// handle.
374    ///
375    /// The crate empties the owned tree through the retained directory handle.
376    /// It never removes the root directory itself and never traverses the root
377    /// pathname, so a foreign directory, file, symlink, or reparse point
378    /// installed at the recorded pathname is never touched.
379    ///
380    /// # Contract
381    ///
382    /// - [`Ok`] means the owned root object held no entries at the final
383    ///   handle-relative listing: the owned tree was emptied.
384    /// - [`Err`] with [`ExtractionErrorKind::CleanupFailed`] means the owned
385    ///   root could **not** be fully emptied. The residue may be partially
386    ///   emptied, its emptiness is **not** guaranteed, and
387    ///   [`ExtractionError::residue_path`] names the recorded root path.
388    ///
389    /// The residual directory is the **caller's to remove**: this crate never
390    /// removes it and offers no convenience that removes it by pathname.
391    /// Because this call consumes the value, capture the residual path from
392    /// [`root`](Self::root) **before** calling it.
393    ///
394    /// The recorded root path is **advisory**: if the root was renamed or
395    /// replaced by a third party, the crate emptied the owned object and left
396    /// whatever occupies the recorded pathname untouched.
397    pub fn cleanup(mut self) -> Result<(), ExtractionError> {
398        let guard = self.guard.take().expect("active extraction guard");
399        // Close member objects before emptying the root: cleanup never races
400        // a still-open member, and no pathname fallback is consulted.
401        drop(std::mem::take(&mut self.handles));
402        guard.cleanup()
403    }
404}
405
406/// Extracted output whose cleanup responsibility has been transferred.
407pub struct PersistedExtraction {
408    root: PathBuf,
409    handle: File,
410    members: Vec<ExtractedMember>,
411    /// Already-open readable member objects, paired by index with `members`.
412    handles: Vec<File>,
413}
414
415impl std::fmt::Debug for PersistedExtraction {
416    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417        f.debug_struct("PersistedExtraction")
418            .field("root", &self.root)
419            .field("members", &self.members)
420            .finish_non_exhaustive()
421    }
422}
423
424impl PersistedExtraction {
425    /// Returns the retained private extraction root.
426    pub fn root(&self) -> &Path {
427        &self.root
428    }
429
430    /// Returns member evidence in declaration order.
431    pub fn members(&self) -> &[ExtractedMember] {
432        &self.members
433    }
434
435    /// Empties the retained operation-owned extraction root through the
436    /// retained root handle.
437    ///
438    /// The crate empties the owned tree through the retained directory handle.
439    /// It never removes the root directory itself and never traverses the root
440    /// pathname, so a foreign directory, file, symlink, or reparse point
441    /// installed at the recorded pathname is never touched.
442    ///
443    /// # Contract
444    ///
445    /// - [`Ok`] means the owned root object held no entries at the final
446    ///   handle-relative listing: the owned tree was emptied.
447    /// - [`Err`] with [`ExtractionErrorKind::CleanupFailed`] means the owned
448    ///   root could **not** be fully emptied. The residue may be partially
449    ///   emptied, its emptiness is **not** guaranteed, and
450    ///   [`ExtractionError::residue_path`] names the recorded root path.
451    ///
452    /// The residual directory is the **caller's to remove**: this crate never
453    /// removes it and offers no convenience that removes it by pathname.
454    /// Because this call consumes the value, capture the residual path from
455    /// [`root`](Self::root) **before** calling it.
456    ///
457    /// The recorded root path is **advisory**: if the root was renamed or
458    /// replaced by a third party, the crate emptied the owned object and left
459    /// whatever occupies the recorded pathname untouched.
460    pub fn cleanup(self) -> Result<(), ExtractionError> {
461        let Self {
462            root,
463            handle,
464            members: _,
465            handles,
466        } = self;
467        // Close member objects before emptying the root (see
468        // `ExtractedArchive::cleanup` for the ordering rationale).
469        drop(handles);
470        remove_owned_root_via_handle(root, handle)
471    }
472
473    /// Converts every member into an object-bound staging source.
474    ///
475    /// This is the handle-backed handoff: each returned [`BoundMember`] owns
476    /// the already-open readable member object created by the atomic
477    /// handle-relative write, rewound to byte zero, so later staging reads
478    /// the verified object instead of re-resolving the recorded pathname or
479    /// member name. Call this before any staging; a root rename or member
480    /// replacement afterwards cannot redirect the bound objects.
481    ///
482    /// Member handles are closed when their [`BoundMember`] is consumed or
483    /// dropped. Run cleanup only after bound handles are consumed or closed
484    /// (see [`BoundExtraction::into_members`]); residue remains acceptable
485    /// under the same semantics as [`cleanup`](Self::cleanup).
486    pub fn into_bound_sources(self) -> Result<BoundExtraction, ExtractionError> {
487        let Self {
488            root,
489            handle: root_handle,
490            members,
491            handles,
492        } = self;
493        assert_eq!(
494            members.len(),
495            handles.len(),
496            "extraction members and retained handles must stay paired"
497        );
498        let mut bound = Vec::with_capacity(members.len());
499        for (evidence, mut file) in members.into_iter().zip(handles) {
500            file.flush()
501                .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
502            file.seek(SeekFrom::Start(0))
503                .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
504            bound.push(BoundMember {
505                source_path: evidence.source_path,
506                output_name: evidence.output_name,
507                advisory_path: evidence.path,
508                bytes_written: evidence.bytes_written,
509                sha256: evidence.sha256,
510                handle: file,
511            });
512        }
513        Ok(BoundExtraction {
514            members: bound,
515            root,
516            root_handle,
517        })
518    }
519}
520
521/// One extracted member proven by its already-open member object.
522///
523/// A bound member carries the same size/digest evidence as
524/// [`ExtractedMember`], but its bytes are proven by object identity: `handle`
525/// is the exact object created by the atomic handle-relative write and
526/// verified during extraction, rewound to byte zero at handoff. Staging from
527/// this object performs no name lookup after the handoff boundary, so a
528/// concurrent member-entry replacement cannot redirect staged bytes.
529///
530/// The handle is single-owner and move-only. [`File`] cursors are shared
531/// across clones, so this type is deliberately not [`Clone`]: move the object
532/// into staging (see [`into_open_object`](Self::into_open_object)), which
533/// rewinds it again before reading. Never [`try_clone`](File::try_clone) a
534/// bound handle and assume an independent offset.
535///
536/// `advisory_path` is diagnostics only and explicitly non-authoritative: it
537/// may be stale (root renamed) or foreign (member entry replaced) while the
538/// handle still proves the owned bytes. Never stage by opening it.
539#[derive(Debug)]
540pub struct BoundMember {
541    source_path: String,
542    output_name: String,
543    advisory_path: PathBuf,
544    bytes_written: u64,
545    sha256: [u8; 32],
546    handle: File,
547}
548
549impl BoundMember {
550    /// Returns the normalized archive path that supplied these bytes.
551    pub fn source_path(&self) -> &str {
552        &self.source_path
553    }
554
555    /// Returns the output filename inside the extraction root.
556    pub fn output_name(&self) -> &str {
557        &self.output_name
558    }
559
560    /// Returns the recorded member pathname for diagnostics only.
561    ///
562    /// Non-authoritative: may be stale or foreign after a root
563    /// rename/replacement. Never open this path to obtain staged bytes; move
564    /// [`into_open_object`](Self::into_open_object) into staging instead.
565    pub fn advisory_path(&self) -> &Path {
566        &self.advisory_path
567    }
568
569    /// Returns the exact bytes written and verified.
570    pub fn bytes_written(&self) -> u64 {
571        self.bytes_written
572    }
573
574    /// Returns the SHA-256 digest of the extracted bytes.
575    pub fn sha256(&self) -> [u8; 32] {
576        self.sha256
577    }
578
579    /// Borrows the open member object, for example to prove cursor ownership
580    /// in tests. The holder owns the shared cursor: any read/seek moves it
581    /// for all borrowers, and staging rewinds to byte zero before reading.
582    pub fn handle_mut(&mut self) -> &mut File {
583        &mut self.handle
584    }
585
586    /// Releases the already-open readable member object for staging.
587    ///
588    /// The object arrives rewound to byte zero by
589    /// [`into_bound_sources`](PersistedExtraction::into_bound_sources);
590    /// staging must still rewind before reading (it does) so a cursor moved
591    /// after handoff cannot truncate staged bytes.
592    pub fn into_open_object(self) -> File {
593        self.handle
594    }
595}
596
597/// Object-bound extraction output awaiting staging and deferred cleanup.
598///
599/// Created by [`PersistedExtraction::into_bound_sources`]. Members stage from
600/// their open objects; the retained root handle stays owned here until
601/// cleanup so directory authority is never lost while bound sources are
602/// outstanding.
603#[derive(Debug)]
604pub struct BoundExtraction {
605    members: Vec<BoundMember>,
606    root: PathBuf,
607    root_handle: File,
608}
609
610impl BoundExtraction {
611    /// Returns the bound members in declaration order.
612    pub fn members(&self) -> &[BoundMember] {
613        &self.members
614    }
615
616    /// Mutably borrows the bound members, for example to prove cursor
617    /// ownership before staging. The holder owns every shared cursor.
618    pub fn members_mut(&mut self) -> &mut [BoundMember] {
619        &mut self.members
620    }
621
622    /// Returns the retained private extraction root.
623    pub fn root(&self) -> &Path {
624        &self.root
625    }
626
627    /// Splits bound staging sources from deferred root cleanup.
628    ///
629    /// The returned members own their open objects; stage them first, then
630    /// let their handles close (by consumption into staging or drop) before
631    /// running [`cleanup`](DeferredCleanup::cleanup). Cleanup ordered before
632    /// staging completes fails closed on platforms where open handles pin
633    /// directory entries, and is never pathname-recursive.
634    pub fn into_members(self) -> (Vec<BoundMember>, DeferredCleanup) {
635        let Self {
636            members,
637            root,
638            root_handle,
639        } = self;
640        (members, DeferredCleanup { root, root_handle })
641    }
642
643    /// Empties the retained operation-owned extraction root through the
644    /// retained root handle, without staging.
645    ///
646    /// The crate empties the owned tree through the retained directory handle.
647    /// It never removes the root directory itself and never traverses the root
648    /// pathname, so a foreign directory, file, symlink, or reparse point
649    /// installed at the recorded pathname is never touched.
650    ///
651    /// # Contract
652    ///
653    /// - [`Ok`] means the owned root object held no entries at the final
654    ///   handle-relative listing: the owned tree was emptied.
655    /// - [`Err`] with [`ExtractionErrorKind::CleanupFailed`] means the owned
656    ///   root could **not** be fully emptied. The residue may be partially
657    ///   emptied, its emptiness is **not** guaranteed, and
658    ///   [`ExtractionError::residue_path`] names the recorded root path.
659    ///
660    /// The residual directory is the **caller's to remove**: this crate never
661    /// removes it and offers no convenience that removes it by pathname.
662    /// Because this call consumes the value, capture the residual path from
663    /// [`root`](Self::root) **before** calling it.
664    ///
665    /// The recorded root path is **advisory**: if the root was renamed or
666    /// replaced by a third party, the crate emptied the owned object and left
667    /// whatever occupies the recorded pathname untouched.
668    ///
669    /// Member objects are closed first (see [`ExtractedArchive::cleanup`]).
670    pub fn cleanup(self) -> Result<(), ExtractionError> {
671        let Self {
672            members,
673            root,
674            root_handle,
675        } = self;
676        drop(members);
677        remove_owned_root_via_handle(root, root_handle)
678    }
679}
680
681/// Deferred extraction-root cleanup paired with outstanding bound sources.
682///
683/// Returned by [`BoundExtraction::into_members`]. Run this only after bound
684/// handles are consumed or closed; cleanup empties the owned root solely via
685/// the retained handle, never by traversing a pathname.
686pub struct DeferredCleanup {
687    root: PathBuf,
688    root_handle: File,
689}
690
691impl std::fmt::Debug for DeferredCleanup {
692    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
693        f.debug_struct("DeferredCleanup")
694            .field("root", &self.root)
695            .finish_non_exhaustive()
696    }
697}
698
699impl DeferredCleanup {
700    /// Returns the retained private extraction root for residue diagnostics.
701    pub fn root(&self) -> &Path {
702        &self.root
703    }
704
705    /// Empties the owned extraction root through the retained root handle.
706    ///
707    /// The crate empties the owned tree through the retained directory handle.
708    /// It never removes the root directory itself and never traverses the root
709    /// pathname, so a foreign directory, file, symlink, or reparse point
710    /// installed at the recorded pathname is never touched.
711    ///
712    /// # Contract
713    ///
714    /// - [`Ok`] means the owned root object held no entries at the final
715    ///   handle-relative listing: the owned tree was emptied.
716    /// - [`Err`] with [`ExtractionErrorKind::CleanupFailed`] means the owned
717    ///   root could **not** be fully emptied. The residue may be partially
718    ///   emptied, its emptiness is **not** guaranteed, and
719    ///   [`ExtractionError::residue_path`] names the recorded root path.
720    ///
721    /// The residual directory is the **caller's to remove**: this crate never
722    /// removes it and offers no convenience that removes it by pathname.
723    /// Because this call consumes the value, capture the residual path from
724    /// [`root`](Self::root) **before** calling it.
725    ///
726    /// The recorded root path is **advisory**: if the root was renamed or
727    /// replaced by a third party, the crate emptied the owned object and left
728    /// whatever occupies the recorded pathname untouched.
729    pub fn cleanup(self) -> Result<(), ExtractionError> {
730        remove_owned_root_via_handle(self.root, self.root_handle)
731    }
732}
733
734/// Extracts the exact declared members from an already verified local archive.
735///
736/// `output_parent` must already be an existing real directory. The function
737/// creates an exclusive child directory there and never touches the live
738/// installation. Dropping a successful [`ExtractedArchive`] best-effort empties
739/// only that operation-owned child via its retained handle and leaves the
740/// now-empty directory as residue; call [`ExtractedArchive::persist`] to
741/// transfer that cleanup responsibility.
742///
743/// The crate never removes the private root directory on any path, including
744/// the success path: the residual empty directory is the caller's to remove.
745/// On the failure path the crate empties the owned tree through the retained
746/// handle and reports the leftover directory through
747/// [`ExtractionError::residue_path`]. The original failure category is
748/// preserved, unless the owned root could not be emptied at all — in which
749/// case the failure is reported as [`ExtractionErrorKind::CleanupFailed`] and
750/// the residue may be partially emptied.
751pub fn extract(
752    plan: &ArchivePlan,
753    output_parent: &Path,
754) -> Result<ExtractedArchive, ExtractionError> {
755    let archive_meta = fs::symlink_metadata(&plan.archive_path)
756        .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
757    if !archive_meta.is_file() || archive_meta.file_type().is_symlink() {
758        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
759    }
760    if archive_meta.len() > plan.limits.max_archive_bytes {
761        return Err(ExtractionError::new(ExtractionErrorKind::ArchiveTooLarge));
762    }
763    let (root, handle) = create_private_root(output_parent)?;
764    match extract_with_hook_inner(plan, &root, &handle, None) {
765        Ok((members, handles)) => Ok(ExtractedArchive {
766            guard: Some(DirectoryGuard::new(root, handle)),
767            members,
768            handles,
769        }),
770        Err(error) => match remove_owned_root_with_hook(root.clone(), handle, None) {
771            // The owned root was emptied: the leftover directory is empty, so
772            // the original failure category is preserved and the residue path
773            // names the empty directory.
774            Ok(()) => Err(error.with_empty_residue(root)),
775            // The owned root could not be emptied: the residue may be partially
776            // emptied, so the failure is reported as `CleanupFailed` and
777            // emptiness is never claimed.
778            Err(_) => Err(error.with_residue(root)),
779        },
780    }
781}
782
783/// Test seam for deterministic root rename/replacement races.
784/// Deterministic pre-write hook for root rename/replacement races.
785///
786/// Runs synchronously on the extraction thread before each declared-member
787/// file creation with the zero-based declared-write sequence number and the
788/// recorded root path. Production passes `None`.
789type MaterializationHook<'a> = Option<&'a dyn Fn(usize, &Path)>;
790
791/// Retained root authority borrowed by both format handlers.
792///
793/// Carries the recorded root pathname together with the open root directory
794/// object that authorizes every member write, plus the declared-write
795/// sequence counter and optional deterministic test hook. This keeps tar and
796/// zip on one shared authority path instead of duplicating handle logic.
797struct ExtractionScope<'a> {
798    root_path: &'a Path,
799    root_handle: &'a File,
800    write_seq: usize,
801    hook: MaterializationHook<'a>,
802}
803
804impl<'a> ExtractionScope<'a> {
805    /// Runs the deterministic hook (if any) before the next declared write.
806    fn run_hook(&self) {
807        if let Some(hook) = self.hook {
808            hook(self.write_seq, self.root_path);
809        }
810    }
811
812    /// Creates the next declared member file through the retained handle.
813    fn create_member(&mut self, output_name: &str) -> Result<File, ExtractionError> {
814        self.run_hook();
815        let file = create_private_file_at(self.root_handle, Path::new(output_name))?;
816        self.write_seq += 1;
817        Ok(file)
818    }
819
820    /// Records the handoff pathname for a member written via the handle.
821    ///
822    /// The returned path is evidence only, never write authority (see the
823    /// M001c stop record for why it may be stale after a rename).
824    fn member_path(&self, output_name: &str) -> PathBuf {
825        self.root_path.join(output_name)
826    }
827}
828
829///
830/// The optional `hook` runs synchronously on the extraction thread before
831/// each declared-member file creation, with the zero-based declared-write
832/// sequence number and the recorded root path. Production passes `None`.
833#[cfg(test)]
834fn extract_with_hook(
835    plan: &ArchivePlan,
836    output_parent: &Path,
837    hook: MaterializationHook<'_>,
838) -> Result<ExtractedArchive, ExtractionError> {
839    let archive_meta = fs::symlink_metadata(&plan.archive_path)
840        .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
841    if !archive_meta.is_file() || archive_meta.file_type().is_symlink() {
842        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
843    }
844    if archive_meta.len() > plan.limits.max_archive_bytes {
845        return Err(ExtractionError::new(ExtractionErrorKind::ArchiveTooLarge));
846    }
847    let (root, handle) = create_private_root(output_parent)?;
848    match extract_with_hook_inner(plan, &root, &handle, hook) {
849        Ok((members, handles)) => Ok(ExtractedArchive {
850            guard: Some(DirectoryGuard::new(root, handle)),
851            members,
852            handles,
853        }),
854        Err(error) => match remove_owned_root_with_hook(root.clone(), handle, None) {
855            // The owned root was emptied: the leftover directory is empty, so
856            // the original failure category is preserved and the residue path
857            // names the empty directory.
858            Ok(()) => Err(error.with_empty_residue(root)),
859            // The owned root could not be emptied: the residue may be partially
860            // emptied, so the failure is reported as `CleanupFailed` and
861            // emptiness is never claimed.
862            Err(_) => Err(error.with_residue(root)),
863        },
864    }
865}
866
867fn extract_with_hook_inner(
868    plan: &ArchivePlan,
869    root: &Path,
870    root_handle: &File,
871    hook: MaterializationHook<'_>,
872) -> Result<(Vec<ExtractedMember>, Vec<File>), ExtractionError> {
873    let mut total = 0u64;
874    let mut seen = HashSet::new();
875    let mut extracted: HashMap<String, (ExtractedMember, File)> = HashMap::new();
876    let mut scope = ExtractionScope {
877        root_path: root,
878        root_handle,
879        write_seq: 0,
880        hook,
881    };
882    match plan.format {
883        ArchiveFormat::TarGz => {
884            extract_tar_gz(plan, &mut scope, &mut total, &mut seen, &mut extracted)?
885        }
886        ArchiveFormat::Zip => extract_zip(plan, &mut scope, &mut total, &mut seen, &mut extracted)?,
887    }
888    let mut ordered = Vec::with_capacity(plan.members.len());
889    let mut handles = Vec::with_capacity(plan.members.len());
890    for member in &plan.members {
891        let (evidence, handle) = extracted
892            .remove(&member.source_path)
893            .ok_or_else(|| ExtractionError::new(ExtractionErrorKind::MissingMember))?;
894        ordered.push(evidence);
895        handles.push(handle);
896    }
897    Ok((ordered, handles))
898}
899
900/// The single member-write path shared by the tar.gz and zip handlers.
901///
902/// The steps, in order, are format-independent:
903///
904/// 1. look up the declared member for the normalized archive path;
905/// 2. a declared member whose entry is not regular fails closed
906///    ([`ExtractionErrorKind::NonRegularMember`]);
907/// 3. an undeclared or non-regular entry is drained under budget and is never
908///    materialized;
909/// 4. a declared regular member is created through the retained root handle,
910///    copied under budget with streaming SHA-256, flushed, verified against
911///    the declared facts, and recorded as evidence.
912///
913/// `is_regular` is the caller's per-format entry-kind predicate. The shared
914/// path never re-derives regularity from the format, so the two format
915/// handlers cannot drift apart in what they materialize.
916fn write_declared_member<R: Read>(
917    entry: &mut R,
918    plan: &ArchivePlan,
919    scope: &mut ExtractionScope<'_>,
920    total: &mut u64,
921    normalized: &str,
922    is_regular: bool,
923    extracted: &mut HashMap<String, (ExtractedMember, File)>,
924) -> Result<(), ExtractionError> {
925    let declared = plan
926        .members
927        .iter()
928        .find(|member| member.source_path == normalized);
929    if declared.is_some() && !is_regular {
930        return Err(ExtractionError::new(ExtractionErrorKind::NonRegularMember));
931    }
932    if !is_regular {
933        drain_bounded(entry, plan.limits, total)?;
934        return Ok(());
935    }
936    let Some(member) = declared else {
937        drain_bounded(entry, plan.limits, total)?;
938        return Ok(());
939    };
940    let mut output = scope.create_member(&member.output_name)?;
941    // The recorded member path is handoff evidence only; the write itself was
942    // authorized by the retained root handle, never by this pathname. If the
943    // root namespace entry is renamed/replaced during extraction, this
944    // pathname may be stale/foreign (see the M001c stop record); the bytes
945    // remain in the handle-owned directory.
946    let path = scope.member_path(&member.output_name);
947    let (bytes_written, digest) = copy_bounded(entry, Some(&mut output), plan.limits, total)?;
948    output
949        .flush()
950        .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
951    validate_expected(member, bytes_written, digest)?;
952    extracted.insert(
953        normalized.to_string(),
954        (
955            ExtractedMember {
956                source_path: normalized.to_string(),
957                output_name: member.output_name.clone(),
958                path,
959                bytes_written,
960                sha256: digest,
961            },
962            output,
963        ),
964    );
965    Ok(())
966}
967
968fn extract_tar_gz(
969    plan: &ArchivePlan,
970    scope: &mut ExtractionScope<'_>,
971    total: &mut u64,
972    seen: &mut HashSet<String>,
973    extracted: &mut HashMap<String, (ExtractedMember, File)>,
974) -> Result<(), ExtractionError> {
975    let input = File::open(&plan.archive_path)
976        .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
977    let decoder = GzDecoder::new(input);
978    let mut archive = tar::Archive::new(decoder);
979    let entries = archive
980        .entries()
981        .map_err(|_| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
982    for (index, entry) in entries.enumerate() {
983        if index >= plan.limits.max_entries {
984            return Err(ExtractionError::new(ExtractionErrorKind::TooManyEntries));
985        }
986        let mut entry =
987            entry.map_err(|_| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
988        if entry.header().path_bytes().contains(&b'\\') {
989            return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath));
990        }
991        let path_bytes = entry.path_bytes().into_owned();
992        let path = std::str::from_utf8(&path_bytes)
993            .map_err(|_| ExtractionError::new(ExtractionErrorKind::InvalidPath))?;
994        let entry_type = entry.header().entry_type();
995        let normalized =
996            validate_archive_path(path, entry_type.is_dir(), plan.limits.max_path_bytes)?;
997        if !seen.insert(normalized.clone()) {
998            return Err(ExtractionError::new(
999                ExtractionErrorKind::DuplicateArchiveMember,
1000            ));
1001        }
1002        let is_regular = matches!(entry_type.as_byte(), 0 | b'0');
1003        write_declared_member(
1004            &mut entry,
1005            plan,
1006            scope,
1007            total,
1008            &normalized,
1009            is_regular,
1010            extracted,
1011        )?;
1012    }
1013    // The tar iterator can stop at the tar end marker before the gzip footer
1014    // is consumed. Drain a strictly bounded zero-padding tail to validate gzip
1015    // integrity without accepting a concatenated second tar or an inflate tail.
1016    let mut decoder = archive.into_inner();
1017    let mut trailing = 0u64;
1018    let mut buffer = [0u8; IO_CHUNK_SIZE];
1019    loop {
1020        let n = decoder
1021            .read(&mut buffer)
1022            .map_err(|_| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
1023        if n == 0 {
1024            break;
1025        }
1026        trailing = trailing
1027            .checked_add(n as u64)
1028            .ok_or_else(|| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
1029        if trailing > TAR_TRAILING_PADDING_LIMIT || buffer[..n].iter().any(|byte| *byte != 0) {
1030            return Err(ExtractionError::new(ExtractionErrorKind::MalformedArchive));
1031        }
1032    }
1033    Ok(())
1034}
1035
1036fn extract_zip(
1037    plan: &ArchivePlan,
1038    scope: &mut ExtractionScope<'_>,
1039    total: &mut u64,
1040    seen: &mut HashSet<String>,
1041    extracted: &mut HashMap<String, (ExtractedMember, File)>,
1042) -> Result<(), ExtractionError> {
1043    let input = File::open(&plan.archive_path)
1044        .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
1045    let mut archive = ZipArchive::new(input)
1046        .map_err(|_| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
1047    if archive.len() > plan.limits.max_entries {
1048        return Err(ExtractionError::new(ExtractionErrorKind::TooManyEntries));
1049    }
1050    for index in 0..archive.len() {
1051        let mut entry = archive
1052            .by_index(index)
1053            .map_err(|_| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
1054        let path = std::str::from_utf8(entry.name_raw())
1055            .map_err(|_| ExtractionError::new(ExtractionErrorKind::InvalidPath))?;
1056        let normalized = validate_archive_path(path, entry.is_dir(), plan.limits.max_path_bytes)?;
1057        if !seen.insert(normalized.clone()) {
1058            return Err(ExtractionError::new(
1059                ExtractionErrorKind::DuplicateArchiveMember,
1060            ));
1061        }
1062        let regular = zip_entry_is_regular(&entry);
1063        write_declared_member(
1064            &mut entry,
1065            plan,
1066            scope,
1067            total,
1068            &normalized,
1069            regular,
1070            extracted,
1071        )?;
1072    }
1073    Ok(())
1074}
1075
1076fn zip_entry_is_regular<R: Read>(entry: &zip::read::ZipFile<'_, R>) -> bool {
1077    if !entry.is_file() || entry.is_symlink() || entry.is_dir() || entry.enclosed_name().is_none() {
1078        return false;
1079    }
1080    entry.unix_mode().is_none_or(|mode| {
1081        let file_type = mode & 0o170000;
1082        file_type == 0 || file_type == 0o100000
1083    })
1084}
1085
1086fn copy_bounded<R: Read>(
1087    input: &mut R,
1088    mut output: Option<&mut File>,
1089    limits: ArchiveLimits,
1090    total: &mut u64,
1091) -> Result<(u64, [u8; 32]), ExtractionError> {
1092    let mut member_bytes = 0u64;
1093    let mut hasher = Sha256::new();
1094    let mut buffer = [0u8; IO_CHUNK_SIZE];
1095    loop {
1096        let n = input
1097            .read(&mut buffer)
1098            .map_err(|_| ExtractionError::new(ExtractionErrorKind::MalformedArchive))?;
1099        if n == 0 {
1100            break;
1101        }
1102        let next_member = member_bytes
1103            .checked_add(n as u64)
1104            .ok_or_else(|| ExtractionError::new(ExtractionErrorKind::MemberTooLarge))?;
1105        let next_total = total
1106            .checked_add(n as u64)
1107            .ok_or_else(|| ExtractionError::new(ExtractionErrorKind::TotalTooLarge))?;
1108        if next_member > limits.max_member_bytes {
1109            return Err(ExtractionError::new(ExtractionErrorKind::MemberTooLarge));
1110        }
1111        if next_total > limits.max_total_uncompressed_bytes {
1112            return Err(ExtractionError::new(ExtractionErrorKind::TotalTooLarge));
1113        }
1114        if let Some(file) = output.as_deref_mut() {
1115            file.write_all(&buffer[..n])
1116                .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
1117        }
1118        hasher.update(&buffer[..n]);
1119        member_bytes = next_member;
1120        *total = next_total;
1121    }
1122    let digest: [u8; 32] = hasher.finalize().into();
1123    Ok((member_bytes, digest))
1124}
1125
1126fn drain_bounded<R: Read>(
1127    input: &mut R,
1128    limits: ArchiveLimits,
1129    total: &mut u64,
1130) -> Result<(), ExtractionError> {
1131    copy_bounded(input, None, limits, total).map(|_| ())
1132}
1133
1134fn validate_expected(
1135    member: &ArchiveMember,
1136    observed_size: u64,
1137    observed_sha256: [u8; 32],
1138) -> Result<(), ExtractionError> {
1139    if member
1140        .expected_size
1141        .is_some_and(|expected| expected != observed_size)
1142    {
1143        return Err(ExtractionError::new(ExtractionErrorKind::SizeMismatch));
1144    }
1145    if member
1146        .expected_sha256
1147        .is_some_and(|expected| expected != observed_sha256)
1148    {
1149        return Err(ExtractionError::new(ExtractionErrorKind::DigestMismatch));
1150    }
1151    Ok(())
1152}
1153
1154fn validate_archive_path(
1155    path: &str,
1156    directory: bool,
1157    max_path_bytes: usize,
1158) -> Result<String, ExtractionError> {
1159    if path.is_empty()
1160        || path.len() > max_path_bytes
1161        || path.starts_with('/')
1162        || path.contains('\\')
1163        || path.contains(':')
1164        || path.chars().any(|ch| ch.is_control())
1165    {
1166        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath));
1167    }
1168    let candidate = if directory {
1169        path.strip_suffix('/').unwrap_or(path)
1170    } else {
1171        path
1172    };
1173    if candidate.is_empty() {
1174        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath));
1175    }
1176    let path_obj = Path::new(candidate);
1177    for component in path_obj.components() {
1178        match component {
1179            Component::Normal(_) => {}
1180            _ => return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath)),
1181        }
1182    }
1183    if candidate
1184        .split('/')
1185        .any(|part| part.is_empty() || part == "." || part == "..")
1186    {
1187        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath));
1188    }
1189    Ok(candidate.to_string())
1190}
1191
1192fn validate_output_name(name: &str, max_path_bytes: usize) -> Result<(), ExtractionError> {
1193    if name.is_empty()
1194        || name.len() > max_path_bytes
1195        || name == "."
1196        || name == ".."
1197        || name.contains('/')
1198        || name.contains('\\')
1199        || name.contains(':')
1200        || name.ends_with('.')
1201        || name.ends_with(' ')
1202        || !name.is_ascii()
1203        || name
1204            .chars()
1205            .any(|ch| ch.is_control() || "<>\"|?*".contains(ch))
1206    {
1207        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath));
1208    }
1209    let stem = name.split('.').next().unwrap_or(name).to_ascii_uppercase();
1210    let reserved = matches!(
1211        stem.as_str(),
1212        // `CONIN$`/`CONOUT$` are the console device names and are reserved too.
1213        "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$"
1214    ) || ["COM", "LPT"].iter().any(|prefix| {
1215        // `COM0`/`LPT0` are reserved alongside `COM1`..`COM9`: Windows maps every
1216        // digit, not just 1-9, and `COM0` in particular is a documented device
1217        // name. Accepting the whole digit range is strictly safer.
1218        stem.strip_prefix(prefix)
1219            .is_some_and(|suffix| suffix.len() == 1 && suffix.as_bytes()[0].is_ascii_digit())
1220    });
1221    if reserved {
1222        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPath));
1223    }
1224    // A name that would be reserved only because of a trailing digit appended to
1225    // a device stem is covered above; the `name.ends_with('.')`/`ends_with(' ')`
1226    // rejections above additionally stop `NUL.` / `NUL ` style aliases that
1227    // Windows would otherwise normalise onto a device.
1228    Ok(())
1229}
1230
1231/// Returns true only when `path` holds no entries.
1232///
1233/// A root that has already been removed also counts as empty: nothing can
1234/// remain, and reporting that as non-empty would invent a cleanup failure.
1235fn private_root_is_empty(path: &Path) -> bool {
1236    match fs::read_dir(path) {
1237        Ok(mut entries) => entries.next().is_none(),
1238        Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
1239        Err(_) => false,
1240    }
1241}
1242
1243fn open_dir_handle(path: &Path) -> std::io::Result<File> {
1244    #[cfg(windows)]
1245    {
1246        use std::os::windows::fs::OpenOptionsExt;
1247        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
1248        std::fs::OpenOptions::new()
1249            .read(true)
1250            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1251            .open(path)
1252    }
1253    #[cfg(not(windows))]
1254    {
1255        File::open(path)
1256    }
1257}
1258
1259fn create_private_root(parent: &Path) -> Result<(PathBuf, File), ExtractionError> {
1260    let meta = fs::symlink_metadata(parent)
1261        .map_err(|_| ExtractionError::new(ExtractionErrorKind::InvalidPlan))?;
1262    if !meta.is_dir() || meta.file_type().is_symlink() {
1263        return Err(ExtractionError::new(ExtractionErrorKind::InvalidPlan));
1264    }
1265    let parent_handle =
1266        open_dir_handle(parent).map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
1267    for _ in 0..ROOT_ATTEMPTS {
1268        let id = NEXT_ROOT_ID.fetch_add(1, Ordering::Relaxed);
1269        let file_name = format!(".eggup-extract-{}-{id:016x}", std::process::id());
1270        let mut options = fs_at::OpenOptions::default();
1271        #[cfg(unix)]
1272        {
1273            use fs_at::os::unix::OpenOptionsExt;
1274            options.mode(0o700);
1275        }
1276        match options.mkdir_at(&parent_handle, &file_name) {
1277            Ok(root_handle) => {
1278                let path = parent.join(&file_name);
1279                return Ok((path, root_handle));
1280            }
1281            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
1282            Err(_) => return Err(ExtractionError::new(ExtractionErrorKind::Io)),
1283        }
1284    }
1285    Err(ExtractionError::new(ExtractionErrorKind::Io))
1286}
1287
1288/// Creates one owner-private member file relative to the retained
1289/// extraction-root handle.
1290///
1291/// The write authority is the open root directory object, never the recorded
1292/// root pathname: `fs_at::OpenOptions::open_at` resolves only relative to
1293/// `root`, `create_new(true)` rejects any existing file/link/directory
1294/// atomically where the filesystem supports it, and `follow(false)` refuses
1295/// to follow a final-component symlink/reparse point. Unix creation mode is
1296/// `0600`, preserving the previous owner-private intent.
1297///
1298/// The returned object carries read authority from the outset on the same
1299/// file description: no later staging step may regain readability by
1300/// reopening the member by pathname/name. The object-backed handoff rewinds
1301/// it to byte zero before staging consumption.
1302///
1303/// `name` must be an already-validated single-component `output_name`; no
1304/// multi-component archive-controlled path is accepted here.
1305fn create_private_file_at(root: &File, name: &Path) -> Result<File, ExtractionError> {
1306    let mut options = fs_at::OpenOptions::default();
1307    options
1308        .read(true)
1309        .write(fs_at::OpenOptionsWriteMode::Write)
1310        .create_new(true)
1311        .follow(false);
1312    #[cfg(unix)]
1313    {
1314        use fs_at::os::unix::OpenOptionsExt;
1315        options.mode(0o600);
1316    }
1317    options
1318        .open_at(root, name)
1319        .map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))
1320}
1321
1322/// Recursively deletes only the directory object referenced by the retained
1323/// handle. All deletions are `*at` operations relative to that handle (or a
1324/// child handle derived from it); the replacement pathname is never traversed.
1325/// Symlinks and reparse points are unlinked, never followed.
1326fn empty_dir_contents(dir: &mut File) -> Result<(), ExtractionError> {
1327    empty_dir_contents_at_depth(dir, 0)
1328}
1329
1330fn empty_dir_contents_at_depth(dir: &mut File, depth: usize) -> Result<(), ExtractionError> {
1331    if depth > CLEANUP_MAX_DEPTH {
1332        return Err(ExtractionError::new(ExtractionErrorKind::Io));
1333    }
1334    for _ in 0..CLEANUP_MAX_PASSES {
1335        let names: Vec<std::ffi::OsString> = {
1336            let iter =
1337                fs_at::read_dir(dir).map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
1338            let mut names = Vec::new();
1339            for entry in iter {
1340                let entry = entry.map_err(|_| ExtractionError::new(ExtractionErrorKind::Io))?;
1341                let name = entry.name();
1342                if name == OsStr::new(".") || name == OsStr::new("..") {
1343                    continue;
1344                }
1345                names.push(name.to_os_string());
1346                if names.len() > CLEANUP_MAX_ENTRIES_PER_PASS {
1347                    return Err(ExtractionError::new(ExtractionErrorKind::Io));
1348                }
1349            }
1350            names
1351        };
1352        if names.is_empty() {
1353            return Ok(());
1354        }
1355        let mut deleted_any = false;
1356        for name in &names {
1357            let name_path = Path::new(name);
1358            match fs_at::OpenOptions::default().open_dir_at(dir, name_path) {
1359                Ok(mut child) => {
1360                    let is_dir = child
1361                        .metadata()
1362                        .map(|metadata| metadata.is_dir())
1363                        .unwrap_or(false);
1364                    // On Unix `openat2`/`O_NOFOLLOW` means this `metadata()` is
1365                    // an `fstat` of the opened child, so a symlink is already
1366                    // excluded: `is_symlink` is always false and the check below
1367                    // is belt-and-braces. On Windows there is no `O_NOFOLLOW`
1368                    // equivalent, so this check is load-bearing there.
1369                    let is_symlink = child
1370                        .metadata()
1371                        .map(|metadata| metadata.is_symlink())
1372                        .unwrap_or(false);
1373                    if is_dir && !is_symlink {
1374                        empty_dir_contents_at_depth(&mut child, depth + 1)?;
1375                        drop(child);
1376                        match fs_at::OpenOptions::default().rmdir_at(dir, name_path) {
1377                            Ok(()) => deleted_any = true,
1378                            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1379                                deleted_any = true;
1380                            }
1381                            Err(_) => {
1382                                return Err(ExtractionError::new(ExtractionErrorKind::Io));
1383                            }
1384                        }
1385                    } else {
1386                        drop(child);
1387                        match fs_at::OpenOptions::default().unlink_at(dir, name_path) {
1388                            Ok(()) => deleted_any = true,
1389                            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1390                                deleted_any = true;
1391                            }
1392                            Err(_) => {
1393                                return Err(ExtractionError::new(ExtractionErrorKind::Io));
1394                            }
1395                        }
1396                    }
1397                }
1398                Err(error) => {
1399                    if error.kind() == std::io::ErrorKind::NotFound {
1400                        deleted_any = true;
1401                        continue;
1402                    }
1403                    match fs_at::OpenOptions::default().unlink_at(dir, name_path) {
1404                        Ok(()) => deleted_any = true,
1405                        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1406                            deleted_any = true;
1407                        }
1408                        Err(_) => {
1409                            return Err(ExtractionError::new(ExtractionErrorKind::Io));
1410                        }
1411                    }
1412                }
1413            }
1414        }
1415        if !deleted_any {
1416            return Err(ExtractionError::new(ExtractionErrorKind::Io));
1417        }
1418    }
1419    Err(ExtractionError::new(ExtractionErrorKind::Io))
1420}
1421
1422fn remove_owned_root_via_handle(path: PathBuf, handle: File) -> Result<(), ExtractionError> {
1423    remove_owned_root_with_hook(path, handle, None)
1424}
1425
1426/// Empties the owned root through the retained root handle and reports
1427/// whether the owned root was emptied.
1428///
1429/// The root directory itself is never removed and the root pathname is never
1430/// traversed: the emptying runs entirely through `*at` operations relative to
1431/// the retained handle, so a foreign object installed at the recorded
1432/// pathname is left untouched.
1433///
1434/// `Ok(())` means the owned root object held no entries at the final
1435/// handle-relative listing. `Err` means it could not be fully emptied; the
1436/// residue may be partially emptied, so the failure is reported as
1437/// [`ExtractionErrorKind::CleanupFailed`] with the recorded root path
1438/// attached and emptiness is never claimed.
1439fn remove_owned_root_with_hook(
1440    path: PathBuf,
1441    mut handle: File,
1442    hook: Option<&dyn Fn(&Path)>,
1443) -> Result<(), ExtractionError> {
1444    let empty_result = empty_dir_contents(&mut handle);
1445    if let Some(hook) = hook {
1446        hook(&path);
1447    }
1448    match empty_result {
1449        Ok(()) => Ok(()),
1450        Err(_) => Err(ExtractionError::new(ExtractionErrorKind::CleanupFailed).with_residue(path)),
1451    }
1452}
1453
1454/// Retained directory authority for an extraction root.
1455///
1456/// The open [`File`] handle is captured atomically at creation time via
1457/// `mkdir_at` before any archive bytes are materialized. Recursive cleanup
1458/// operates only through that handle (and child handles derived from it) via
1459/// `fs_at` `*at` operations. The original pathname is used only as residue
1460/// evidence; it is never recursively traversed or deleted.
1461struct DirectoryGuard {
1462    path: PathBuf,
1463    handle: Option<File>,
1464    active: bool,
1465}
1466
1467impl std::fmt::Debug for DirectoryGuard {
1468    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1469        f.debug_struct("DirectoryGuard")
1470            .field("path", &self.path)
1471            .field("active", &self.active)
1472            .finish_non_exhaustive()
1473    }
1474}
1475
1476impl DirectoryGuard {
1477    fn new(path: PathBuf, handle: File) -> Self {
1478        Self {
1479            path,
1480            handle: Some(handle),
1481            active: true,
1482        }
1483    }
1484
1485    fn path(&self) -> &Path {
1486        &self.path
1487    }
1488
1489    fn disarm(mut self) -> (PathBuf, File) {
1490        self.active = false;
1491        let handle = self.handle.take().expect("active extraction guard");
1492        (self.path.clone(), handle)
1493    }
1494
1495    fn cleanup(mut self) -> Result<(), ExtractionError> {
1496        self.active = false;
1497        let handle = self.handle.take().expect("active extraction guard");
1498        remove_owned_root_via_handle(self.path.clone(), handle)
1499    }
1500}
1501
1502impl Drop for DirectoryGuard {
1503    fn drop(&mut self) {
1504        if self.active {
1505            if let Some(handle) = self.handle.as_mut() {
1506                let _ = empty_dir_contents(handle);
1507            }
1508        }
1509    }
1510}
1511
1512#[cfg(test)]
1513mod tests {
1514    use super::*;
1515    use eggup_core::{
1516        ArtifactMember, ArtifactSet, BoundSources, InstallPlan, MemberId, ProductId, ReleaseId,
1517    };
1518    use flate2::write::GzEncoder;
1519    use flate2::Compression;
1520    use std::io::Cursor;
1521    use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
1522    use tar::{Builder as TarBuilder, EntryType as TarEntryType, Header};
1523    use zip::write::SimpleFileOptions;
1524    use zip::{CompressionMethod, ZipWriter};
1525
1526    static NEXT_TEST_DIR: AtomicU64 = AtomicU64::new(1);
1527
1528    struct TestDir(PathBuf);
1529
1530    impl TestDir {
1531        fn new() -> Self {
1532            let id = NEXT_TEST_DIR.fetch_add(1, AtomicOrdering::Relaxed);
1533            let path = std::env::temp_dir().join(format!(
1534                "eggup-archive-test-{}-{id:016x}",
1535                std::process::id()
1536            ));
1537            fs::create_dir(&path).unwrap();
1538            Self(path)
1539        }
1540
1541        fn path(&self) -> &Path {
1542            &self.0
1543        }
1544    }
1545
1546    impl Drop for TestDir {
1547        fn drop(&mut self) {
1548            let _ = fs::remove_dir_all(&self.0);
1549        }
1550    }
1551
1552    struct TarFixture<'a> {
1553        path: &'a str,
1554        kind: u8,
1555        body: &'a [u8],
1556        link: Option<&'a str>,
1557    }
1558
1559    fn limits() -> ArchiveLimits {
1560        ArchiveLimits::new(2 * 1024 * 1024, 32, 256, 1024, 2048).unwrap()
1561    }
1562
1563    fn member(path: &str, output: &str, bytes: &[u8]) -> ArchiveMember {
1564        ArchiveMember::new(
1565            path,
1566            output,
1567            Some(bytes.len() as u64),
1568            Some(Sha256::digest(bytes).into()),
1569        )
1570        .unwrap()
1571    }
1572
1573    fn make_plan(
1574        archive: PathBuf,
1575        format: ArchiveFormat,
1576        members: Vec<ArchiveMember>,
1577        limits: ArchiveLimits,
1578    ) -> ArchivePlan {
1579        ArchivePlan::new(archive, format, members, limits).unwrap()
1580    }
1581
1582    fn tar_file(dir: &Path, name: &str, entries: &[TarFixture<'_>]) -> PathBuf {
1583        let archive_path = dir.join(name);
1584        let gzip = GzEncoder::new(Vec::new(), Compression::default());
1585        let mut builder = TarBuilder::new(gzip);
1586        for entry in entries {
1587            let mut header = Header::new_gnu();
1588            header.set_entry_type(TarEntryType::new(entry.kind));
1589            header.set_size(entry.body.len() as u64);
1590            header.set_mode(0o644);
1591            header.set_path(entry.path).unwrap();
1592            if let Some(link) = entry.link {
1593                header.set_link_name(link).unwrap();
1594            }
1595            header.set_cksum();
1596            builder.append(&header, entry.body).unwrap();
1597        }
1598        let gzip = builder.into_inner().unwrap();
1599        let bytes = gzip.finish().unwrap();
1600        fs::write(&archive_path, bytes).unwrap();
1601        archive_path
1602    }
1603
1604    fn zip_file(dir: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
1605        let path = dir.join(name);
1606        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
1607        let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
1608        for (entry_name, body) in entries {
1609            writer.start_file(*entry_name, options).unwrap();
1610            writer.write_all(body).unwrap();
1611        }
1612        let bytes = writer.finish().unwrap().into_inner();
1613        fs::write(&path, bytes).unwrap();
1614        path
1615    }
1616
1617    /// Writes a tar.gz whose single entry carries a **raw, unvalidated** path.
1618    ///
1619    /// `Header::set_path` sanitises traversal names outright, so a genuinely
1620    /// hostile tar entry can only be produced by writing the raw ustar name
1621    /// field. That is exactly the untrusted input the extraction loop must
1622    /// defend against, so the test must be able to build it.
1623    fn tar_file_raw_path(dir: &Path, name: &str) -> PathBuf {
1624        let archive_path = dir.join("hostile.tar.gz");
1625        let gzip = GzEncoder::new(Vec::new(), Compression::default());
1626        let mut builder = TarBuilder::new(gzip);
1627        let mut header = Header::new_gnu();
1628        header.set_entry_type(TarEntryType::new(b'0'));
1629        header.set_size(1);
1630        header.set_mode(0o644);
1631        {
1632            // ustar name field is bytes 0..100; the prefix field is 345..500 and
1633            // must be empty so the entry name is exactly `name`.
1634            let raw = header.as_mut_bytes();
1635            raw[0..100].fill(0);
1636            let bytes = name.as_bytes();
1637            assert!(bytes.len() <= 100, "probe name must fit the raw field");
1638            raw[0..bytes.len()].copy_from_slice(bytes);
1639            raw[345..500].fill(0);
1640        }
1641        header.set_cksum();
1642        builder.append(&header, &b"x"[..]).unwrap();
1643        let gzip = builder.into_inner().unwrap();
1644        fs::write(&archive_path, gzip.finish().unwrap()).unwrap();
1645        archive_path
1646    }
1647
1648    /// Sorted directory listing, used to prove nothing escaped or persisted.
1649    fn names_in(dir: &Path) -> Vec<String> {
1650        let mut out: Vec<String> = fs::read_dir(dir)
1651            .unwrap()
1652            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
1653            .collect();
1654        out.sort();
1655        out
1656    }
1657
1658    /// Asserts a failed extraction created nothing outside its owned root, and
1659    /// left nothing inside it.
1660    ///
1661    /// The crate's documented contract is that a failure empties the owned
1662    /// private root and leaves it as residue, so the invariant to check is that
1663    /// the parent holds only the archive and (at most) an empty owned root, and
1664    /// that the owned root holds no partial extraction.
1665    fn assert_no_escape_or_residue(dir: &Path, archive_name: &str, context: &str) {
1666        for name in names_in(dir) {
1667            if name == archive_name {
1668                continue;
1669            }
1670            assert!(
1671                name.starts_with(".eggup-extract-"),
1672                "{context}: unexpected entry {name:?} escaped into the parent directory"
1673            );
1674            let path = dir.join(&name);
1675            let meta = fs::symlink_metadata(&path).unwrap();
1676            assert!(
1677                meta.is_dir() && !meta.file_type().is_symlink(),
1678                "{context}: owned root {name:?} is not a real directory"
1679            );
1680            let mut inside: Vec<String> = fs::read_dir(&path)
1681                .unwrap()
1682                .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
1683                .collect();
1684            inside.sort();
1685            assert!(
1686                inside.is_empty(),
1687                "{context}: owned root {name:?} retained a partial extraction {inside:?}"
1688            );
1689        }
1690    }
1691
1692    /// Every traversal vector in the crate, fed through a real archive entry.
1693    ///
1694    /// The pre-existing coverage feeds these names to `ArchiveMember::new`, the
1695    /// *caller-declared plan* path. This test drives the untrusted path instead:
1696    /// an archive that declares nothing, containing a hostile entry name that a
1697    /// refactor moving validation after `create_member`, or dropping the
1698    /// non-`Normal` component check, would happily write through.
1699    const HOSTILE_ENTRY_NAMES: [&str; 8] = [
1700        "../escape",
1701        "a/../../escape",
1702        "/etc/passwd",
1703        "..\\..\\evil.exe",
1704        "a\\b",
1705        "a//b",
1706        "./app",
1707        "C:/Windows/x",
1708    ];
1709
1710    #[test]
1711    fn hostile_undeclared_tar_entry_names_fail_closed() {
1712        for name in HOSTILE_ENTRY_NAMES {
1713            let dir = TestDir::new();
1714            let archive = tar_file_raw_path(dir.path(), name);
1715            let plan = make_plan(
1716                archive,
1717                ArchiveFormat::TarGz,
1718                vec![member("app", "app", b"v1")],
1719                limits(),
1720            );
1721            assert_eq!(
1722                extract_error(&plan, dir.path()),
1723                ExtractionErrorKind::InvalidPath,
1724                "tar entry {name:?} must be rejected on its raw entry bytes"
1725            );
1726            assert_no_escape_or_residue(dir.path(), "hostile.tar.gz", &format!("tar {name:?}"));
1727        }
1728    }
1729
1730    #[test]
1731    fn hostile_undeclared_zip_entry_names_fail_closed() {
1732        for name in HOSTILE_ENTRY_NAMES {
1733            let dir = TestDir::new();
1734            // The zip writer stores the entry name verbatim.
1735            let archive = zip_file(dir.path(), "hostile.zip", &[(name, b"x")]);
1736            let plan = make_plan(
1737                archive,
1738                ArchiveFormat::Zip,
1739                vec![member("app", "app", b"v1")],
1740                limits(),
1741            );
1742            assert_eq!(
1743                extract_error(&plan, dir.path()),
1744                ExtractionErrorKind::InvalidPath,
1745                "zip entry {name:?} must be rejected on its raw entry bytes"
1746            );
1747            assert_no_escape_or_residue(dir.path(), "hostile.zip", &format!("zip {name:?}"));
1748        }
1749    }
1750
1751    /// Validation runs on raw entry bytes *before* any write, so a hostile
1752    /// entry that follows a valid declared member must still leave nothing
1753    /// observable: the private root is removed and the caller sees only `Err`.
1754    #[test]
1755    fn hostile_entry_after_a_valid_member_leaves_no_partial_extraction() {
1756        for name in ["../escape", "/etc/passwd", "a\\b"] {
1757            let dir = TestDir::new();
1758            // Valid declared member first, hostile undeclared entry second.
1759            let archive_path = dir.path().join("mixed.tar.gz");
1760            let gzip = GzEncoder::new(Vec::new(), Compression::default());
1761            let mut builder = TarBuilder::new(gzip);
1762            let mut good = Header::new_gnu();
1763            good.set_entry_type(TarEntryType::new(b'0'));
1764            good.set_size(2);
1765            good.set_mode(0o644);
1766            good.set_path("app").unwrap();
1767            good.set_cksum();
1768            builder.append(&good, &b"v1"[..]).unwrap();
1769            let mut bad = Header::new_gnu();
1770            bad.set_entry_type(TarEntryType::new(b'0'));
1771            bad.set_size(1);
1772            bad.set_mode(0o644);
1773            {
1774                let raw = bad.as_mut_bytes();
1775                raw[0..100].fill(0);
1776                let bytes = name.as_bytes();
1777                raw[0..bytes.len()].copy_from_slice(bytes);
1778                raw[345..500].fill(0);
1779            }
1780            bad.set_cksum();
1781            builder.append(&bad, &b"x"[..]).unwrap();
1782            let gzip = builder.into_inner().unwrap();
1783            fs::write(&archive_path, gzip.finish().unwrap()).unwrap();
1784
1785            let plan = make_plan(
1786                archive_path,
1787                ArchiveFormat::TarGz,
1788                vec![member("app", "app", b"v1")],
1789                limits(),
1790            );
1791            assert_eq!(
1792                extract_error(&plan, dir.path()),
1793                ExtractionErrorKind::InvalidPath,
1794                "hostile entry {name:?} after a valid member must still fail closed"
1795            );
1796            assert_no_escape_or_residue(dir.path(), "mixed.tar.gz", &format!("mixed tar {name:?}"));
1797        }
1798    }
1799
1800    fn extract_error(plan: &ArchivePlan, dir: &Path) -> ExtractionErrorKind {
1801        extract(plan, dir).unwrap_err().kind()
1802    }
1803
1804    #[test]
1805    fn valid_tar_gz_extracts_allowlisted_members_in_declaration_order() {
1806        let dir = TestDir::new();
1807        let archive = tar_file(
1808            dir.path(),
1809            "bundle.tar.gz",
1810            &[
1811                TarFixture {
1812                    path: "bin/helper",
1813                    kind: b'0',
1814                    body: b"helper-v1",
1815                    link: None,
1816                },
1817                TarFixture {
1818                    path: "bin/main",
1819                    kind: b'0',
1820                    body: b"main-v1",
1821                    link: None,
1822                },
1823                TarFixture {
1824                    path: "notes.txt",
1825                    kind: b'0',
1826                    body: b"ignored",
1827                    link: None,
1828                },
1829            ],
1830        );
1831        let plan = make_plan(
1832            archive,
1833            ArchiveFormat::TarGz,
1834            vec![
1835                member("bin/main", "main", b"main-v1"),
1836                member("bin/helper", "helper", b"helper-v1"),
1837            ],
1838            limits(),
1839        );
1840        let extracted = extract(&plan, dir.path()).unwrap();
1841        assert_eq!(extracted.members()[0].source_path(), "bin/main");
1842        assert_eq!(extracted.members()[1].source_path(), "bin/helper");
1843        assert_eq!(fs::read(extracted.members()[0].path()).unwrap(), b"main-v1");
1844        assert!(!extracted.root().join("notes.txt").exists());
1845        assert_eq!(extracted.members()[0].bytes_written(), 7);
1846    }
1847
1848    #[test]
1849    fn valid_zip_extracts_members_and_returns_digest_evidence() {
1850        let dir = TestDir::new();
1851        let archive = zip_file(
1852            dir.path(),
1853            "bundle.zip",
1854            &[("app.exe", b"windows-bin"), ("helper.dll", b"helper")],
1855        );
1856        let plan = make_plan(
1857            archive,
1858            ArchiveFormat::Zip,
1859            vec![
1860                member("app.exe", "app.exe", b"windows-bin"),
1861                member("helper.dll", "helper.dll", b"helper"),
1862            ],
1863            limits(),
1864        );
1865        let extracted = extract(&plan, dir.path()).unwrap();
1866        assert_eq!(
1867            fs::read(extracted.members()[0].path()).unwrap(),
1868            b"windows-bin"
1869        );
1870        assert_eq!(fs::read(extracted.members()[1].path()).unwrap(), b"helper");
1871        let expected_digest: [u8; 32] = Sha256::digest(b"windows-bin").into();
1872        assert_eq!(extracted.members()[0].sha256(), expected_digest);
1873    }
1874
1875    #[cfg(unix)]
1876    #[test]
1877    fn extraction_root_and_files_are_owner_private() {
1878        use std::os::unix::fs::PermissionsExt;
1879
1880        let dir = TestDir::new();
1881        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
1882        let plan = make_plan(
1883            archive,
1884            ArchiveFormat::Zip,
1885            vec![member("app", "app", b"binary")],
1886            limits(),
1887        );
1888        let extracted = extract(&plan, dir.path()).unwrap();
1889        assert_eq!(
1890            fs::metadata(extracted.root()).unwrap().permissions().mode() & 0o777,
1891            0o700
1892        );
1893        assert_eq!(
1894            fs::metadata(extracted.members()[0].path())
1895                .unwrap()
1896                .permissions()
1897                .mode()
1898                & 0o777,
1899            0o600
1900        );
1901    }
1902
1903    #[test]
1904    fn archive_paths_reject_traversal_absolute_prefix_alias_and_overlong_names() {
1905        for path in [
1906            "",
1907            "../escape",
1908            "a/../../escape",
1909            "/etc/passwd",
1910            "C:/Windows/x",
1911            "a\\b",
1912            "a//b",
1913            "./app",
1914        ] {
1915            assert_eq!(
1916                ArchiveMember::new(path, "app", None, None)
1917                    .unwrap_err()
1918                    .kind(),
1919                ExtractionErrorKind::InvalidPath,
1920                "path {path:?}"
1921            );
1922        }
1923        assert_eq!(
1924            ArchiveMember::new("a".repeat(5000), "app", None, None)
1925                .unwrap_err()
1926                .kind(),
1927            ExtractionErrorKind::InvalidPath
1928        );
1929    }
1930
1931    #[test]
1932    fn output_names_reject_windows_reserved_or_ambiguous_names() {
1933        for name in ["../app", "a/b", "a\\b", "CON", "nul.txt", "app.", "app "] {
1934            assert_eq!(
1935                ArchiveMember::new("app", name, None, None)
1936                    .unwrap_err()
1937                    .kind(),
1938                ExtractionErrorKind::InvalidPath,
1939                "name {name:?}"
1940            );
1941        }
1942        assert_eq!(
1943            ArchivePlan::new(
1944                "archive.zip",
1945                ArchiveFormat::Zip,
1946                vec![
1947                    ArchiveMember::new("one", "App", None, None).unwrap(),
1948                    ArchiveMember::new("two", "app", None, None).unwrap()
1949                ],
1950                limits(),
1951            )
1952            .unwrap_err()
1953            .kind(),
1954            ExtractionErrorKind::InvalidPlan
1955        );
1956    }
1957
1958    #[test]
1959    fn output_names_reject_every_windows_device_name_not_just_1_to_9() {
1960        // Windows reserves every digit suffix, not just 1-9, and additionally
1961        // reserves the console device names. Each of these resolves to a device
1962        // on Windows, so accepting one would let a declared member alias a
1963        // device instead of writing a file.
1964        for name in [
1965            "COM0",
1966            "LPT0",
1967            "com0.txt",
1968            "lpt9",
1969            "LPT0.bin",
1970            "CONIN$",
1971            "CONOUT$",
1972            "conin$.txt",
1973            "CLOCK$",
1974        ] {
1975            assert_eq!(
1976                ArchiveMember::new("app", name, None, None)
1977                    .unwrap_err()
1978                    .kind(),
1979                ExtractionErrorKind::InvalidPath,
1980                "name {name:?} must be rejected as a reserved Windows device name"
1981            );
1982        }
1983        // The 1-9 forms stay rejected, and near-miss names are still usable.
1984        for name in ["COM1", "LPT9"] {
1985            assert_eq!(
1986                ArchiveMember::new("app", name, None, None)
1987                    .unwrap_err()
1988                    .kind(),
1989                ExtractionErrorKind::InvalidPath,
1990                "name {name:?}"
1991            );
1992        }
1993        for name in ["console", "com10", "auxiliary", "clock"] {
1994            assert!(
1995                ArchiveMember::new("app", name, None, None).is_ok(),
1996                "name {name:?} must remain a usable output name"
1997            );
1998        }
1999    }
2000
2001    #[test]
2002    fn residue_path_is_only_reported_when_the_root_is_actually_empty() {
2003        use crate::{ExtractionError, ExtractionErrorKind};
2004
2005        let dir = TestDir::new();
2006        let empty = dir.path().join("empty");
2007        fs::create_dir(&empty).unwrap();
2008        // An emptied root keeps the original category: the operation's real
2009        // failure is still what the caller must handle.
2010        let err = ExtractionError::new(ExtractionErrorKind::InvalidPath).with_empty_residue(empty);
2011        assert_eq!(err.kind(), ExtractionErrorKind::InvalidPath);
2012        assert!(err.residue_path().is_some());
2013
2014        let full = dir.path().join("full");
2015        fs::create_dir(&full).unwrap();
2016        fs::write(full.join("leftover"), b"x").unwrap();
2017        // A root that still holds evidence is a cleanup failure, not a clean one.
2018        let err = ExtractionError::new(ExtractionErrorKind::InvalidPath).with_empty_residue(full);
2019        assert_eq!(err.kind(), ExtractionErrorKind::CleanupFailed);
2020        assert!(err.residue_path().is_some());
2021    }
2022
2023    #[test]
2024    fn plan_rejects_duplicate_members_and_nonpositive_or_inconsistent_limits() {
2025        let duplicate = ArchiveMember::new("bin/app", "app", None, None).unwrap();
2026        assert_eq!(
2027            ArchivePlan::new(
2028                "x",
2029                ArchiveFormat::Zip,
2030                vec![duplicate.clone(), duplicate],
2031                limits()
2032            )
2033            .unwrap_err()
2034            .kind(),
2035            ExtractionErrorKind::InvalidPlan
2036        );
2037        assert!(ArchiveLimits::new(0, 1, 10, 10, 10).is_err());
2038        assert!(ArchiveLimits::new(10, 0, 10, 10, 10).is_err());
2039        assert!(ArchiveLimits::new(10, 1, 0, 10, 10).is_err());
2040        assert!(ArchiveLimits::new(10, 1, 10, 11, 10).is_err());
2041    }
2042
2043    #[test]
2044    fn missing_and_duplicate_archive_members_fail_closed() {
2045        let dir = TestDir::new();
2046        let missing = tar_file(dir.path(), "missing.tar.gz", &[]);
2047        let plan = make_plan(
2048            missing,
2049            ArchiveFormat::TarGz,
2050            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2051            limits(),
2052        );
2053        assert_eq!(
2054            extract_error(&plan, dir.path()),
2055            ExtractionErrorKind::MissingMember
2056        );
2057
2058        let duplicate = tar_file(
2059            dir.path(),
2060            "duplicate.tar.gz",
2061            &[
2062                TarFixture {
2063                    path: "app",
2064                    kind: b'0',
2065                    body: b"first",
2066                    link: None,
2067                },
2068                TarFixture {
2069                    path: "app",
2070                    kind: b'0',
2071                    body: b"second",
2072                    link: None,
2073                },
2074            ],
2075        );
2076        let plan = make_plan(
2077            duplicate,
2078            ArchiveFormat::TarGz,
2079            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2080            limits(),
2081        );
2082        assert_eq!(
2083            extract_error(&plan, dir.path()),
2084            ExtractionErrorKind::DuplicateArchiveMember
2085        );
2086    }
2087
2088    #[test]
2089    fn declared_tar_links_and_special_files_are_rejected() {
2090        for (name, kind, link) in [
2091            ("symlink", b'2', Some("target")),
2092            ("hardlink", b'1', Some("target")),
2093            ("fifo", b'6', None),
2094            ("device", b'3', None),
2095        ] {
2096            let dir = TestDir::new();
2097            let archive = tar_file(
2098                dir.path(),
2099                "bad.tar.gz",
2100                &[TarFixture {
2101                    path: name,
2102                    kind,
2103                    body: b"",
2104                    link,
2105                }],
2106            );
2107            let plan = make_plan(
2108                archive,
2109                ArchiveFormat::TarGz,
2110                vec![ArchiveMember::new(name, "output", None, None).unwrap()],
2111                limits(),
2112            );
2113            assert_eq!(
2114                extract_error(&plan, dir.path()),
2115                ExtractionErrorKind::NonRegularMember,
2116                "{name}"
2117            );
2118        }
2119    }
2120
2121    #[test]
2122    fn declared_zip_symlink_is_rejected() {
2123        let dir = TestDir::new();
2124        let path = dir.path().join("symlink.zip");
2125        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2126        writer
2127            .add_symlink("app", "target", SimpleFileOptions::default())
2128            .unwrap();
2129        fs::write(path, writer.finish().unwrap().into_inner()).unwrap();
2130        let plan = make_plan(
2131            dir.path().join("symlink.zip"),
2132            ArchiveFormat::Zip,
2133            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2134            limits(),
2135        );
2136        assert_eq!(
2137            extract_error(&plan, dir.path()),
2138            ExtractionErrorKind::NonRegularMember
2139        );
2140    }
2141
2142    #[test]
2143    fn per_member_and_aggregate_decompression_limits_are_enforced() {
2144        let dir = TestDir::new();
2145        let archive = zip_file(dir.path(), "large.zip", &[("app", b"123456789")]);
2146        let member_limit = ArchiveLimits::new(1024, 10, 100, 8, 20).unwrap();
2147        let plan = make_plan(
2148            archive.clone(),
2149            ArchiveFormat::Zip,
2150            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2151            member_limit,
2152        );
2153        assert_eq!(
2154            extract_error(&plan, dir.path()),
2155            ExtractionErrorKind::MemberTooLarge
2156        );
2157
2158        let archive = zip_file(
2159            dir.path(),
2160            "aggregate.zip",
2161            &[("one", b"12345678"), ("two", b"abcdefgh")],
2162        );
2163        let aggregate_limit = ArchiveLimits::new(2048, 10, 100, 8, 12).unwrap();
2164        let plan = make_plan(
2165            archive,
2166            ArchiveFormat::Zip,
2167            vec![
2168                ArchiveMember::new("one", "one", None, None).unwrap(),
2169                ArchiveMember::new("two", "two", None, None).unwrap(),
2170            ],
2171            aggregate_limit,
2172        );
2173        assert_eq!(
2174            extract_error(&plan, dir.path()),
2175            ExtractionErrorKind::TotalTooLarge
2176        );
2177    }
2178
2179    #[test]
2180    fn entry_count_and_compressed_archive_size_are_bounded() {
2181        let dir = TestDir::new();
2182        let archive = zip_file(dir.path(), "entries.zip", &[("app", b"a"), ("extra", b"b")]);
2183        let entry_limit = ArchiveLimits::new(2048, 1, 100, 10, 10).unwrap();
2184        let plan = make_plan(
2185            archive.clone(),
2186            ArchiveFormat::Zip,
2187            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2188            entry_limit,
2189        );
2190        assert_eq!(
2191            extract_error(&plan, dir.path()),
2192            ExtractionErrorKind::TooManyEntries
2193        );
2194
2195        let bytes = fs::metadata(&archive).unwrap().len();
2196        let archive_limit = ArchiveLimits::new(bytes - 1, 10, 100, 10, 10).unwrap();
2197        let plan = make_plan(
2198            archive,
2199            ArchiveFormat::Zip,
2200            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2201            archive_limit,
2202        );
2203        assert_eq!(
2204            extract_error(&plan, dir.path()),
2205            ExtractionErrorKind::ArchiveTooLarge
2206        );
2207    }
2208
2209    #[test]
2210    fn exact_size_and_sha256_mismatches_fail() {
2211        let dir = TestDir::new();
2212        let archive = zip_file(dir.path(), "verify.zip", &[("app", b"correct")]);
2213        let wrong_size = ArchiveMember::new("app", "app", Some(99), None).unwrap();
2214        let plan = make_plan(
2215            archive.clone(),
2216            ArchiveFormat::Zip,
2217            vec![wrong_size],
2218            limits(),
2219        );
2220        assert_eq!(
2221            extract_error(&plan, dir.path()),
2222            ExtractionErrorKind::SizeMismatch
2223        );
2224
2225        let wrong_digest = ArchiveMember::new("app", "app", None, Some([0; 32])).unwrap();
2226        let plan = make_plan(archive, ArchiveFormat::Zip, vec![wrong_digest], limits());
2227        assert_eq!(
2228            extract_error(&plan, dir.path()),
2229            ExtractionErrorKind::DigestMismatch
2230        );
2231    }
2232
2233    #[test]
2234    fn corrupt_and_truncated_tar_gz_and_zip_fail() {
2235        let dir = TestDir::new();
2236        let tar = tar_file(
2237            dir.path(),
2238            "ok.tar.gz",
2239            &[TarFixture {
2240                path: "app",
2241                kind: b'0',
2242                body: b"ok",
2243                link: None,
2244            }],
2245        );
2246        let mut bytes = fs::read(&tar).unwrap();
2247        bytes.truncate(bytes.len() - 4);
2248        let broken_tar = dir.path().join("broken.tar.gz");
2249        fs::write(&broken_tar, bytes).unwrap();
2250        let plan = make_plan(
2251            broken_tar,
2252            ArchiveFormat::TarGz,
2253            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2254            limits(),
2255        );
2256        assert_ne!(extract_error(&plan, dir.path()), ExtractionErrorKind::Io);
2257
2258        let zip = zip_file(dir.path(), "ok.zip", &[("app", b"ok")]);
2259        let mut bytes = fs::read(zip).unwrap();
2260        bytes.truncate(bytes.len() / 2);
2261        let broken_zip = dir.path().join("broken.zip");
2262        fs::write(&broken_zip, bytes).unwrap();
2263        let plan = make_plan(
2264            broken_zip,
2265            ArchiveFormat::Zip,
2266            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2267            limits(),
2268        );
2269        assert_eq!(
2270            extract_error(&plan, dir.path()),
2271            ExtractionErrorKind::MalformedArchive
2272        );
2273    }
2274
2275    #[test]
2276    fn failure_cleans_only_its_owned_partial_root_and_drop_cleans_success() {
2277        let dir = TestDir::new();
2278        let sentinel = dir.path().join("foreign");
2279        fs::write(&sentinel, b"keep").unwrap();
2280        let archive = zip_file(dir.path(), "bad.zip", &[("app", b"123456789")]);
2281        let cap = ArchiveLimits::new(2048, 10, 100, 8, 10).unwrap();
2282        let plan = make_plan(
2283            archive,
2284            ArchiveFormat::Zip,
2285            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2286            cap,
2287        );
2288        let error = extract(&plan, dir.path()).unwrap_err();
2289        assert_eq!(error.kind(), ExtractionErrorKind::MemberTooLarge);
2290        assert_eq!(fs::read(&sentinel).unwrap(), b"keep");
2291        // Handle-bound failure cleanup empties the owned partial root via its
2292        // retained handle and leaves the now-empty directory as bounded
2293        // residue; it never touches the foreign sentinel.
2294        let residue = error.residue_path().expect("empty residue").to_path_buf();
2295        assert!(residue.exists());
2296        assert_eq!(fs::read_dir(&residue).unwrap().count(), 0);
2297        fs::remove_dir(&residue).unwrap();
2298        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
2299
2300        let archive = zip_file(dir.path(), "good.zip", &[("app", b"ok")]);
2301        let plan = make_plan(
2302            archive,
2303            ArchiveFormat::Zip,
2304            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2305            limits(),
2306        );
2307        let root = {
2308            let output = extract(&plan, dir.path()).unwrap();
2309            output.root().to_path_buf()
2310        };
2311        // Drop best-effort empties the owned root via its handle but never
2312        // falls back to pathname recursion, so the now-empty directory
2313        // remains as residue.
2314        assert!(root.exists());
2315        assert_eq!(fs::read_dir(&root).unwrap().count(), 0);
2316        fs::remove_dir(&root).unwrap();
2317    }
2318
2319    #[test]
2320    fn persist_transfers_cleanup_responsibility_and_cleanup_is_explicit() {
2321        let dir = TestDir::new();
2322        let archive = zip_file(dir.path(), "good.zip", &[("app", b"ok")]);
2323        let plan = make_plan(
2324            archive,
2325            ArchiveFormat::Zip,
2326            vec![ArchiveMember::new("app", "app", None, None).unwrap()],
2327            limits(),
2328        );
2329        let persisted = extract(&plan, dir.path()).unwrap().persist();
2330        let root = persisted.root().to_path_buf();
2331        assert!(root.exists());
2332        // No object-bound root unlink exists on all platforms, so explicit
2333        // cleanup empties only the owned tree via its handle and never touches
2334        // the root pathname. The residual empty directory is the caller's to
2335        // remove; the crate never removes it and reports success.
2336        persisted
2337            .cleanup()
2338            .expect("cleanup empties the owned root and reports success");
2339        assert!(root.exists());
2340        assert_eq!(fs::read_dir(&root).unwrap().count(), 0);
2341        fs::remove_dir(&root).unwrap();
2342    }
2343
2344    // M001d note: member objects are retained open from creation, and
2345    // Windows refuses directory renames while objects inside are held
2346    // (fail-safe: the rename attack itself is blocked by the OS). The race
2347    // setups below therefore rename before the first write — no object held
2348    // yet — so foreign state still lands at the recorded path on every
2349    // platform; every cleanup assertion is unchanged. Rename-with-held-object
2350    // redirect resistance is proven on Unix by the `#[cfg(unix)]` tests and
2351    // the M001d bound-read races; on Windows the member-entry replacement
2352    // races prove no pathname re-resolution.
2353    #[test]
2354    fn cleanup_after_replacement_empties_owned_root_without_deleting_replacement() {
2355        let dir = TestDir::new();
2356        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2357        let plan = make_plan(
2358            archive,
2359            ArchiveFormat::Zip,
2360            vec![member("app", "app", b"binary")],
2361            limits(),
2362        );
2363        let moved = dir.path().join("moved-root");
2364        let extracted = extract_with_hook(
2365            &plan,
2366            dir.path(),
2367            Some(&|seq: usize, root: &Path| {
2368                assert_eq!(seq, 0);
2369                fs::rename(root, &moved).unwrap();
2370                fs::write(root, b"foreign replacement").unwrap();
2371            }),
2372        )
2373        .unwrap();
2374        let root = extracted.root().to_path_buf();
2375
2376        // The owned root object was emptied through the retained handle, so
2377        // cleanup succeeds. The foreign replacement at the recorded pathname
2378        // is never traversed and survives untouched.
2379        extracted
2380            .persist()
2381            .cleanup()
2382            .expect("cleanup empties the owned root and reports success");
2383        assert_eq!(fs::read(&root).unwrap(), b"foreign replacement");
2384        fs::remove_file(&root).unwrap();
2385        fs::remove_dir_all(moved).unwrap();
2386    }
2387
2388    #[test]
2389    fn cleanup_preserves_foreign_non_empty_directory_at_original_path() {
2390        let dir = TestDir::new();
2391        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2392        let plan = make_plan(
2393            archive,
2394            ArchiveFormat::Zip,
2395            vec![member("app", "app", b"binary")],
2396            limits(),
2397        );
2398        let moved = dir.path().join("moved-root");
2399        let extracted = extract_with_hook(
2400            &plan,
2401            dir.path(),
2402            Some(&|seq: usize, root: &Path| {
2403                assert_eq!(seq, 0);
2404                // Pre-write rename: no member object held yet (see note
2405                // above `cleanup_after_replacement_empties_owned_root_...`).
2406                fs::rename(root, &moved).unwrap();
2407                // Replace the old pathname with a foreign non-empty directory
2408                // that would be catastrophic if any pathname-only recursive
2409                // cleanup ran against it.
2410                fs::create_dir(root).unwrap();
2411                for i in 0..6 {
2412                    fs::write(root.join(format!("foreign-{i}")), b"keep").unwrap();
2413                }
2414            }),
2415        )
2416        .unwrap();
2417        let root = extracted.root().to_path_buf();
2418        let foreign = root.clone();
2419
2420        // The owned root object was emptied through the retained handle, so
2421        // cleanup succeeds. The foreign replacement at the recorded pathname
2422        // is never traversed: all six foreign files survive untouched.
2423        extracted
2424            .persist()
2425            .cleanup()
2426            .expect("cleanup empties the owned root and reports success");
2427        assert!(foreign.exists());
2428        for i in 0..6 {
2429            assert_eq!(
2430                fs::read(foreign.join(format!("foreign-{i}"))).unwrap(),
2431                b"keep"
2432            );
2433        }
2434        assert!(moved.exists());
2435        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2436        fs::remove_dir_all(&foreign).unwrap();
2437        fs::remove_dir_all(moved).unwrap();
2438    }
2439
2440    #[test]
2441    fn cleanup_preserves_foreign_empty_directory_at_original_path() {
2442        let dir = TestDir::new();
2443        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2444        let plan = make_plan(
2445            archive,
2446            ArchiveFormat::Zip,
2447            vec![member("app", "app", b"binary")],
2448            limits(),
2449        );
2450        // Pre-write rename + foreign install (see note above
2451        // `cleanup_after_replacement_empties_owned_root_...`).
2452        let moved = dir.path().join("moved-root");
2453        let extracted = extract_with_hook(
2454            &plan,
2455            dir.path(),
2456            Some(&|seq: usize, root: &Path| {
2457                assert_eq!(seq, 0);
2458                fs::rename(root, &moved).unwrap();
2459                fs::create_dir(root).unwrap();
2460            }),
2461        )
2462        .unwrap();
2463        let root = extracted.root().to_path_buf();
2464        let foreign = root.clone();
2465        // Empty foreign directory: its identity still differs, so cleanup must
2466        // not rmdir the foreign dir. The owned root object was emptied through
2467        // the retained handle, so cleanup succeeds and the foreign directory
2468        // survives untouched.
2469        extracted
2470            .persist()
2471            .cleanup()
2472            .expect("cleanup empties the owned root and reports success");
2473        assert!(foreign.exists());
2474        assert_eq!(fs::read_dir(&foreign).unwrap().count(), 0);
2475        fs::remove_dir(&foreign).unwrap();
2476        fs::remove_dir_all(moved).unwrap();
2477    }
2478
2479    #[test]
2480    fn drop_cleanup_preserves_foreign_replacement_at_original_path() {
2481        let dir = TestDir::new();
2482        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2483        let plan = make_plan(
2484            archive,
2485            ArchiveFormat::Zip,
2486            vec![member("app", "app", b"binary")],
2487            limits(),
2488        );
2489        let root = {
2490            // Pre-write rename + foreign install (see note above
2491            // `cleanup_after_replacement_empties_owned_root_...`).
2492            let moved = dir.path().join("moved-root");
2493            let extracted = extract_with_hook(
2494                &plan,
2495                dir.path(),
2496                Some(&|seq: usize, root: &Path| {
2497                    assert_eq!(seq, 0);
2498                    fs::rename(root, &moved).unwrap();
2499                    let foreign = root.to_path_buf();
2500                    fs::create_dir(&foreign).unwrap();
2501                    fs::write(foreign.join("foreign"), b"keep").unwrap();
2502                }),
2503            )
2504            .unwrap();
2505            let root = extracted.root().to_path_buf();
2506            let foreign = root.clone();
2507            // Drop the extraction; best-effort drop cleanup empties only the
2508            // originally opened tree via its handle and never falls back to
2509            // `fs::remove_dir_all(path)`.
2510            drop(extracted);
2511            // The original owned root (now at `moved`) is emptied via its
2512            // handle; the foreign replacement is untouched.
2513            assert!(moved.exists());
2514            assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2515            assert!(foreign.exists());
2516            assert_eq!(fs::read(foreign.join("foreign")).unwrap(), b"keep");
2517            moved
2518        };
2519        fs::remove_dir_all(root).unwrap();
2520    }
2521
2522    #[cfg(unix)]
2523    #[test]
2524    fn cleanup_preserves_symlink_substitution_at_original_path() {
2525        use std::os::unix::fs::symlink;
2526        let dir = TestDir::new();
2527        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2528        let plan = make_plan(
2529            archive,
2530            ArchiveFormat::Zip,
2531            vec![member("app", "app", b"binary")],
2532            limits(),
2533        );
2534        let extracted = extract(&plan, dir.path()).unwrap();
2535        let root = extracted.root().to_path_buf();
2536        let moved = dir.path().join("moved-root");
2537        fs::rename(&root, &moved).unwrap();
2538        // Replace the old pathname with a symlink pointing somewhere else;
2539        // recursive cleanup must not follow it.
2540        let target = dir.path().join("link-target");
2541        fs::create_dir(&target).unwrap();
2542        fs::write(target.join("keep"), b"keep").unwrap();
2543        symlink(&target, &root).unwrap();
2544
2545        // The symlink is never followed: the owned root object was emptied
2546        // through the retained handle, cleanup succeeds, and the link target
2547        // is untouched.
2548        extracted
2549            .persist()
2550            .cleanup()
2551            .expect("cleanup empties the owned root and reports success");
2552        assert!(target.exists());
2553        assert_eq!(fs::read(target.join("keep")).unwrap(), b"keep");
2554        fs::remove_dir_all(moved).unwrap();
2555        fs::remove_dir_all(&target).unwrap();
2556        fs::remove_file(&root).unwrap();
2557    }
2558
2559    #[test]
2560    fn explicit_cleanup_after_replacement_empties_owned_root_and_preserves_identity() {
2561        let dir = TestDir::new();
2562        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2563        let plan = make_plan(
2564            archive,
2565            ArchiveFormat::Zip,
2566            vec![member("app", "app", b"binary")],
2567            limits(),
2568        );
2569        // Pre-write rename + foreign install (see note above
2570        // `cleanup_after_replacement_empties_owned_root_...`).
2571        let moved = dir.path().join("moved-root");
2572        let extracted = extract_with_hook(
2573            &plan,
2574            dir.path(),
2575            Some(&|seq: usize, root: &Path| {
2576                assert_eq!(seq, 0);
2577                fs::rename(root, &moved).unwrap();
2578                fs::create_dir(root).unwrap();
2579                fs::write(root.join("foreign"), b"keep").unwrap();
2580            }),
2581        )
2582        .unwrap();
2583        let persisted = extracted.persist();
2584        let root = persisted.root().to_path_buf();
2585        let foreign = root.clone();
2586
2587        // The owned root object was emptied through the retained handle, so
2588        // cleanup succeeds. The foreign directory installed at the recorded
2589        // pathname keeps its identity and contents.
2590        persisted
2591            .cleanup()
2592            .expect("cleanup empties the owned root and reports success");
2593        assert!(foreign.exists());
2594        assert_eq!(fs::read(foreign.join("foreign")).unwrap(), b"keep");
2595        assert!(moved.exists());
2596        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2597        fs::remove_dir_all(&foreign).unwrap();
2598        fs::remove_dir_all(moved).unwrap();
2599    }
2600
2601    fn owned_root_with_files(parent: &Path, files: &[&str]) -> (PathBuf, File) {
2602        let (root, handle) = create_private_root(parent).unwrap();
2603        for name in files {
2604            fs::write(root.join(name), b"owned").unwrap();
2605        }
2606        (root, handle)
2607    }
2608
2609    #[test]
2610    fn deterministic_race_foreign_non_empty_after_content_deletion_remains_intact() {
2611        let dir = TestDir::new();
2612        let (root, handle) = owned_root_with_files(dir.path(), &["owned"]);
2613        let moved = dir.path().join("moved-owned");
2614        remove_owned_root_with_hook(
2615            root.clone(),
2616            handle,
2617            Some(&|path: &Path| {
2618                fs::rename(path, &moved).unwrap();
2619                fs::create_dir(path).unwrap();
2620                for i in 0..4 {
2621                    fs::write(path.join(format!("foreign-{i}")), b"keep").unwrap();
2622                }
2623            }),
2624        )
2625        .expect("the owned root was emptied through the retained handle");
2626        for i in 0..4 {
2627            assert_eq!(
2628                fs::read(root.join(format!("foreign-{i}"))).unwrap(),
2629                b"keep"
2630            );
2631        }
2632        assert!(moved.exists());
2633        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2634        fs::remove_dir_all(&root).unwrap();
2635        fs::remove_dir(&moved).unwrap();
2636    }
2637
2638    #[test]
2639    fn deterministic_race_foreign_empty_after_content_deletion_remains_intact() {
2640        let dir = TestDir::new();
2641        let (root, handle) = owned_root_with_files(dir.path(), &["owned"]);
2642        let moved = dir.path().join("moved-owned");
2643        remove_owned_root_with_hook(
2644            root.clone(),
2645            handle,
2646            Some(&|path: &Path| {
2647                fs::rename(path, &moved).unwrap();
2648                fs::create_dir(path).unwrap();
2649            }),
2650        )
2651        .expect("the owned root was emptied through the retained handle");
2652        assert!(root.exists());
2653        assert_eq!(fs::read_dir(&root).unwrap().count(), 0);
2654        assert!(moved.exists());
2655        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2656        fs::remove_dir(&root).unwrap();
2657        fs::remove_dir(&moved).unwrap();
2658    }
2659
2660    #[cfg(unix)]
2661    #[test]
2662    fn deterministic_race_symlink_after_content_deletion_is_not_followed() {
2663        use std::os::unix::fs::symlink;
2664        let dir = TestDir::new();
2665        let (root, handle) = owned_root_with_files(dir.path(), &["owned"]);
2666        let moved = dir.path().join("moved-owned");
2667        let target = dir.path().join("hook-target");
2668        fs::create_dir(&target).unwrap();
2669        fs::write(target.join("keep"), b"keep").unwrap();
2670        remove_owned_root_with_hook(
2671            root.clone(),
2672            handle,
2673            Some(&|path: &Path| {
2674                fs::rename(path, &moved).unwrap();
2675                symlink(&target, path).unwrap();
2676            }),
2677        )
2678        .expect("the owned root was emptied through the retained handle");
2679        assert_eq!(fs::read(target.join("keep")).unwrap(), b"keep");
2680        assert!(moved.exists());
2681        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2682        fs::remove_dir_all(&moved).unwrap();
2683        fs::remove_dir_all(&target).unwrap();
2684        fs::remove_file(&root).unwrap();
2685    }
2686
2687    #[test]
2688    fn deterministic_race_persisted_cleanup_uses_same_handle_authority() {
2689        let dir = TestDir::new();
2690        let (root, handle) = owned_root_with_files(dir.path(), &["owned"]);
2691        let moved = dir.path().join("moved-owned");
2692        remove_owned_root_with_hook(
2693            root.clone(),
2694            handle,
2695            Some(&|path: &Path| {
2696                fs::rename(path, &moved).unwrap();
2697                fs::create_dir(path).unwrap();
2698                fs::write(path.join("foreign"), b"keep").unwrap();
2699            }),
2700        )
2701        .expect("the owned root was emptied through the retained handle");
2702        assert_eq!(fs::read(root.join("foreign")).unwrap(), b"keep");
2703        assert!(moved.exists());
2704        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
2705        fs::remove_dir_all(&root).unwrap();
2706        fs::remove_dir(&moved).unwrap();
2707    }
2708
2709    #[test]
2710    fn cleanup_remains_bounded_under_concurrent_file_creation() {
2711        use std::sync::atomic::{AtomicBool, Ordering};
2712        use std::sync::Arc;
2713        let dir = TestDir::new();
2714        let (root, handle) = owned_root_with_files(dir.path(), &["owned"]);
2715        let root_clone = root.clone();
2716        let stop = Arc::new(AtomicBool::new(false));
2717        let stop_writer = Arc::clone(&stop);
2718        // The writer keeps creating files until the cleanup has returned, so
2719        // the bounded pass loop always meets a non-empty listing.
2720        let writer = std::thread::spawn(move || {
2721            let mut index = 0u64;
2722            while !stop_writer.load(Ordering::Relaxed) {
2723                let _ = fs::write(root_clone.join(format!("race-{index}")), b"x");
2724                index += 1;
2725            }
2726        });
2727        let result = remove_owned_root_with_hook(root.clone(), handle, None);
2728        stop.store(true, Ordering::Relaxed);
2729        writer.join().unwrap();
2730        // Cleanup is bounded: it returned instead of chasing the writer. The
2731        // contract has exactly two outcomes, and the failure one never claims
2732        // the residue is empty.
2733        if let Err(error) = result {
2734            assert_eq!(error.kind(), ExtractionErrorKind::CleanupFailed);
2735            assert_eq!(error.residue_path(), Some(root.as_path()));
2736        }
2737        let _ = fs::remove_dir_all(&root);
2738    }
2739
2740    #[test]
2741    fn cleanup_that_cannot_empty_the_root_fails_closed_with_residue_evidence() {
2742        let dir = TestDir::new();
2743        let (root, handle) = create_private_root(dir.path()).unwrap();
2744        // Exceed the crate's own private cleanup depth bound, so the emptying
2745        // fails deterministically on every supported platform without
2746        // privileges or platform-specific behavior: the deepest nested
2747        // directory is reached at a depth greater than `CLEANUP_MAX_DEPTH`.
2748        let mut nested = root.clone();
2749        for index in 0..=CLEANUP_MAX_DEPTH {
2750            nested = nested.join(format!("d{index}"));
2751            fs::create_dir(&nested).unwrap();
2752        }
2753        let error = remove_owned_root_with_hook(root.clone(), handle, None).unwrap_err();
2754        assert_eq!(error.kind(), ExtractionErrorKind::CleanupFailed);
2755        assert_eq!(error.residue_path(), Some(root.as_path()));
2756        // The crate never promotes a partial cleanup to success and never
2757        // claims the residue is empty.
2758        assert!(root.exists());
2759        let _ = fs::remove_dir_all(&root);
2760    }
2761
2762    #[cfg(windows)]
2763    #[test]
2764    fn deterministic_race_windows_reparse_after_authority_boundary_is_preserved() {
2765        let dir = TestDir::new();
2766        let (root, handle) = owned_root_with_files(dir.path(), &["owned"]);
2767        let moved = dir.path().join("moved-owned");
2768        let target = dir.path().join("hook-target");
2769        fs::create_dir(&target).unwrap();
2770        fs::write(target.join("keep"), b"keep").unwrap();
2771        let result = remove_owned_root_with_hook(
2772            root.clone(),
2773            handle,
2774            Some(&|path: &Path| {
2775                fs::rename(path, &moved).unwrap();
2776                let _ = std::os::windows::fs::symlink_dir(&target, path);
2777            }),
2778        );
2779        result.expect("the owned root was emptied through the retained handle");
2780        assert_eq!(fs::read(target.join("keep")).unwrap(), b"keep");
2781        let _ = fs::remove_dir_all(&root);
2782        let _ = fs::remove_file(&root);
2783        let _ = fs::remove_dir_all(&moved);
2784        let _ = fs::remove_dir(&moved);
2785        let _ = fs::remove_dir_all(&target);
2786    }
2787
2788    #[test]
2789    fn normal_explicit_cleanup_empties_owned_root_and_leaves_empty_residue() {
2790        let dir = TestDir::new();
2791        let archive = zip_file(dir.path(), "bundle.zip", &[("app", b"binary")]);
2792        let plan = make_plan(
2793            archive,
2794            ArchiveFormat::Zip,
2795            vec![member("app", "app", b"binary")],
2796            limits(),
2797        );
2798        let persisted = extract(&plan, dir.path()).unwrap().persist();
2799        let root = persisted.root().to_path_buf();
2800        let member_path = persisted.members()[0].path().to_path_buf();
2801        assert!(member_path.exists());
2802        // The owned tree is emptied and cleanup reports success; the residual
2803        // empty directory is the caller's to remove.
2804        persisted
2805            .cleanup()
2806            .expect("cleanup empties the owned root and reports success");
2807        assert!(!member_path.exists());
2808        assert!(root.exists());
2809        assert_eq!(fs::read_dir(&root).unwrap().count(), 0);
2810        fs::remove_dir(&root).unwrap();
2811    }
2812
2813    #[test]
2814    fn exclusive_output_creation_preserves_an_existing_file() {
2815        let dir = TestDir::new();
2816        let (root, root_handle) = create_private_root(dir.path()).unwrap();
2817        fs::write(root.join("existing"), b"foreign").unwrap();
2818        assert_eq!(
2819            create_private_file_at(&root_handle, Path::new("existing"))
2820                .unwrap_err()
2821                .kind(),
2822            ExtractionErrorKind::Io
2823        );
2824        assert_eq!(fs::read(root.join("existing")).unwrap(), b"foreign");
2825        drop(root_handle);
2826        fs::remove_dir_all(&root).unwrap();
2827    }
2828
2829    #[test]
2830    fn extracted_file_can_be_prepared_as_an_ordinary_core_artifact() {
2831        let dir = TestDir::new();
2832        let archive = zip_file(dir.path(), "release.zip", &[("main", b"new binary")]);
2833        let plan = make_plan(
2834            archive,
2835            ArchiveFormat::Zip,
2836            vec![member("main", "main", b"new binary")],
2837            limits(),
2838        );
2839        // M001d handoff: the member stages from its already-open object, not
2840        // by re-resolving the recorded pathname.
2841        let bound = extract(&plan, dir.path())
2842            .unwrap()
2843            .persist()
2844            .into_bound_sources()
2845            .unwrap();
2846        assert_eq!(bound.members()[0].bytes_written(), 10);
2847        let install_root = dir.path().join("install");
2848        fs::create_dir(&install_root).unwrap();
2849        let root = bound.root().to_path_buf();
2850        let core_plan = bound_plan(&bound, &install_root);
2851        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
2852        assert_eq!(
2853            fs::read(
2854                prepared
2855                    .staged_path(&MemberId::new("main").unwrap())
2856                    .unwrap()
2857            )
2858            .unwrap(),
2859            b"new binary"
2860        );
2861        assert!(prepared.stage_root().exists());
2862        cleanup
2863            .cleanup()
2864            .expect("cleanup empties the owned root and reports success");
2865        assert!(root.exists());
2866        assert_eq!(fs::read_dir(&root).unwrap().count(), 0);
2867        fs::remove_dir(&root).unwrap();
2868    }
2869
2870    // ---- M001c handle-relative materialization races ----
2871    //
2872    // Each test renames the operation-owned root synchronously on the
2873    // extraction thread (deterministic hook, no sleeps) before or between
2874    // declared-member creations, then installs a foreign replacement at the
2875    // recorded pathname. Writes must remain in the renamed original through
2876    // the retained handle; the foreign replacement must stay untouched. The
2877    // recorded `ExtractedMember::path()` is expected to be stale here — that
2878    // handoff gap is the documented M001c Section 14 stop (see closure
2879    // record), so these tests read owned bytes via the known moved location
2880    // rather than the returned path.
2881
2882    #[test]
2883    fn tar_handle_relative_write_survives_root_rename_before_first_member() {
2884        let dir = TestDir::new();
2885        let archive = tar_file(
2886            dir.path(),
2887            "race.tar.gz",
2888            &[TarFixture {
2889                path: "app",
2890                kind: b'0',
2891                body: b"owned-bytes",
2892                link: None,
2893            }],
2894        );
2895        let plan = make_plan(
2896            archive,
2897            ArchiveFormat::TarGz,
2898            vec![member("app", "app", b"owned-bytes")],
2899            limits(),
2900        );
2901        let moved = dir.path().join("moved-owned-tar");
2902        let extracted = extract_with_hook(
2903            &plan,
2904            dir.path(),
2905            Some(&|seq: usize, root: &Path| {
2906                assert_eq!(seq, 0);
2907                fs::rename(root, &moved).unwrap();
2908                fs::create_dir(root).unwrap();
2909                for i in 0..3 {
2910                    fs::write(root.join(format!("foreign-{i}")), b"keep").unwrap();
2911                }
2912            }),
2913        )
2914        .unwrap();
2915        let root = extracted.root().to_path_buf();
2916        // Owned bytes landed in the renamed original via the handle.
2917        assert_eq!(fs::read(moved.join("app")).unwrap(), b"owned-bytes");
2918        // Foreign replacement is byte-for-byte untouched: only attacker files.
2919        for i in 0..3 {
2920            assert_eq!(
2921                fs::read(root.join(format!("foreign-{i}"))).unwrap(),
2922                b"keep"
2923            );
2924        }
2925        assert!(!root.join("app").exists());
2926        // Recorded path is stale (points into the foreign replacement).
2927        assert_eq!(extracted.members()[0].path(), root.join("app").as_path());
2928        drop(extracted);
2929        fs::remove_dir_all(&moved).unwrap();
2930        fs::remove_dir_all(&root).unwrap();
2931    }
2932
2933    #[test]
2934    fn zip_handle_relative_write_survives_root_rename_before_first_member() {
2935        let dir = TestDir::new();
2936        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
2937        let plan = make_plan(
2938            archive,
2939            ArchiveFormat::Zip,
2940            vec![member("app", "app", b"owned-bytes")],
2941            limits(),
2942        );
2943        let moved = dir.path().join("moved-owned-zip");
2944        let extracted = extract_with_hook(
2945            &plan,
2946            dir.path(),
2947            Some(&|seq: usize, root: &Path| {
2948                assert_eq!(seq, 0);
2949                fs::rename(root, &moved).unwrap();
2950                fs::create_dir(root).unwrap();
2951                for i in 0..3 {
2952                    fs::write(root.join(format!("foreign-{i}")), b"keep").unwrap();
2953                }
2954            }),
2955        )
2956        .unwrap();
2957        let root = extracted.root().to_path_buf();
2958        assert_eq!(fs::read(moved.join("app")).unwrap(), b"owned-bytes");
2959        for i in 0..3 {
2960            assert_eq!(
2961                fs::read(root.join(format!("foreign-{i}"))).unwrap(),
2962                b"keep"
2963            );
2964        }
2965        assert!(!root.join("app").exists());
2966        drop(extracted);
2967        fs::remove_dir_all(&moved).unwrap();
2968        fs::remove_dir_all(&root).unwrap();
2969    }
2970
2971    // Unix-only: the hook renames after the first member object is already
2972    // held open, and Windows refuses directory renames while objects inside
2973    // are held (fail-safe). Windows redirect resistance is proven by the
2974    // member-entry replacement races, which perform no rename.
2975    #[cfg(unix)]
2976    #[test]
2977    fn two_member_replacement_between_writes_stays_in_owned_root() {
2978        let dir = TestDir::new();
2979        let archive = tar_file(
2980            dir.path(),
2981            "two.tar.gz",
2982            &[
2983                TarFixture {
2984                    path: "one",
2985                    kind: b'0',
2986                    body: b"first",
2987                    link: None,
2988                },
2989                TarFixture {
2990                    path: "two",
2991                    kind: b'0',
2992                    body: b"second",
2993                    link: None,
2994                },
2995            ],
2996        );
2997        let plan = make_plan(
2998            archive,
2999            ArchiveFormat::TarGz,
3000            vec![
3001                member("one", "one", b"first"),
3002                member("two", "two", b"second"),
3003            ],
3004            limits(),
3005        );
3006        let moved = dir.path().join("moved-owned-two");
3007        let extracted = extract_with_hook(
3008            &plan,
3009            dir.path(),
3010            Some(&|seq: usize, root: &Path| {
3011                if seq == 1 {
3012                    fs::rename(root, &moved).unwrap();
3013                    fs::create_dir(root).unwrap();
3014                    fs::write(root.join("foreign"), b"keep").unwrap();
3015                }
3016            }),
3017        )
3018        .unwrap();
3019        let root = extracted.root().to_path_buf();
3020        // First member was written before the rename; second after. Both
3021        // must live in the handle-owned (renamed) directory.
3022        assert_eq!(fs::read(moved.join("one")).unwrap(), b"first");
3023        assert_eq!(fs::read(moved.join("two")).unwrap(), b"second");
3024        // Foreign replacement untouched: exactly the one attacker file.
3025        assert_eq!(fs::read(root.join("foreign")).unwrap(), b"keep");
3026        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
3027        assert_eq!(extracted.members().len(), 2);
3028        drop(extracted);
3029        fs::remove_dir_all(&moved).unwrap();
3030        fs::remove_dir_all(&root).unwrap();
3031    }
3032
3033    #[cfg(unix)]
3034    #[test]
3035    fn root_symlink_replacement_is_not_followed_by_materialization() {
3036        use std::os::unix::fs::symlink;
3037        let dir = TestDir::new();
3038        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
3039        let plan = make_plan(
3040            archive,
3041            ArchiveFormat::Zip,
3042            vec![member("app", "app", b"owned-bytes")],
3043            limits(),
3044        );
3045        let moved = dir.path().join("moved-owned-link");
3046        let target = dir.path().join("link-target");
3047        fs::create_dir(&target).unwrap();
3048        fs::write(target.join("keep"), b"keep").unwrap();
3049        let extracted = extract_with_hook(
3050            &plan,
3051            dir.path(),
3052            Some(&|seq: usize, root: &Path| {
3053                assert_eq!(seq, 0);
3054                fs::rename(root, &moved).unwrap();
3055                symlink(&target, root).unwrap();
3056            }),
3057        )
3058        .unwrap();
3059        let root = extracted.root().to_path_buf();
3060        // Write stayed in the owned directory; the link target is untouched.
3061        assert_eq!(fs::read(moved.join("app")).unwrap(), b"owned-bytes");
3062        assert_eq!(fs::read(target.join("keep")).unwrap(), b"keep");
3063        assert_eq!(fs::read_dir(&target).unwrap().count(), 1);
3064        drop(extracted);
3065        fs::remove_dir_all(&moved).unwrap();
3066        fs::remove_dir_all(&target).unwrap();
3067        fs::remove_file(&root).unwrap();
3068    }
3069
3070    #[cfg(windows)]
3071    #[test]
3072    fn windows_reparse_replacement_is_not_followed_by_materialization() {
3073        let dir = TestDir::new();
3074        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
3075        let plan = make_plan(
3076            archive,
3077            ArchiveFormat::Zip,
3078            vec![member("app", "app", b"owned-bytes")],
3079            limits(),
3080        );
3081        let moved = dir.path().join("moved-owned-reparse");
3082        let target = dir.path().join("reparse-target");
3083        fs::create_dir(&target).unwrap();
3084        fs::write(target.join("keep"), b"keep").unwrap();
3085        let extracted = extract_with_hook(
3086            &plan,
3087            dir.path(),
3088            Some(&|seq: usize, root: &Path| {
3089                assert_eq!(seq, 0);
3090                fs::rename(root, &moved).unwrap();
3091                // Best-effort reparse/symlink: may require privileges. If
3092                // creation is denied, the old pathname simply stays absent;
3093                // either way materialization must not enter the target.
3094                let _ = std::os::windows::fs::symlink_dir(&target, root);
3095                if !root.exists() {
3096                    fs::create_dir(root).unwrap();
3097                    fs::write(root.join("foreign"), b"keep").unwrap();
3098                }
3099            }),
3100        )
3101        .unwrap();
3102        let root = extracted.root().to_path_buf();
3103        assert_eq!(fs::read(moved.join("app")).unwrap(), b"owned-bytes");
3104        assert_eq!(fs::read(target.join("keep")).unwrap(), b"keep");
3105        assert_eq!(fs::read_dir(&target).unwrap().count(), 1);
3106        drop(extracted);
3107        let _ = fs::remove_dir_all(&root);
3108        let _ = fs::remove_file(&root);
3109        let _ = fs::remove_dir_all(&moved);
3110        let _ = fs::remove_dir(&moved);
3111        let _ = fs::remove_dir_all(&target);
3112    }
3113
3114    #[test]
3115    fn raced_existing_output_file_in_owned_root_fails_without_clobber() {
3116        let dir = TestDir::new();
3117        let archive = zip_file(dir.path(), "race.zip", &[("app", b"new-bytes")]);
3118        let plan = make_plan(
3119            archive,
3120            ArchiveFormat::Zip,
3121            vec![member("app", "app", b"new-bytes")],
3122            limits(),
3123        );
3124        let error = extract_with_hook(
3125            &plan,
3126            dir.path(),
3127            Some(&|seq: usize, root: &Path| {
3128                assert_eq!(seq, 0);
3129                // Concurrent creation inside the owned root (no rename here,
3130                // so pathname and handle agree on the directory).
3131                fs::write(root.join("app"), b"existing").unwrap();
3132            }),
3133        )
3134        .unwrap_err();
3135        assert_eq!(error.kind(), ExtractionErrorKind::Io);
3136        // No clobber: residue (if any) never contains the new bytes at the
3137        // raced name; the failure cleans only the owned partial root.
3138        if let Some(residue) = error.residue_path() {
3139            if residue.join("app").exists() {
3140                assert_eq!(fs::read(residue.join("app")).unwrap(), b"existing");
3141            }
3142            let _ = fs::remove_dir_all(residue);
3143        }
3144    }
3145
3146    #[cfg(unix)]
3147    #[test]
3148    fn raced_output_symlink_in_owned_root_fails_and_target_untouched() {
3149        use std::os::unix::fs::symlink;
3150        let dir = TestDir::new();
3151        let archive = zip_file(dir.path(), "race.zip", &[("app", b"new-bytes")]);
3152        let plan = make_plan(
3153            archive,
3154            ArchiveFormat::Zip,
3155            vec![member("app", "app", b"new-bytes")],
3156            limits(),
3157        );
3158        let target = dir.path().join("race-target");
3159        fs::write(&target, b"keep").unwrap();
3160        let error = extract_with_hook(
3161            &plan,
3162            dir.path(),
3163            Some(&|seq: usize, root: &Path| {
3164                assert_eq!(seq, 0);
3165                symlink(&target, root.join("app")).unwrap();
3166            }),
3167        )
3168        .unwrap_err();
3169        // create_new + no-follow must refuse the symlink; the target is
3170        // never opened for write.
3171        assert_eq!(error.kind(), ExtractionErrorKind::Io);
3172        assert_eq!(fs::read(&target).unwrap(), b"keep");
3173        if let Some(residue) = error.residue_path() {
3174            let _ = fs::remove_dir_all(residue);
3175        }
3176        fs::remove_file(&target).unwrap();
3177    }
3178
3179    // ---- M001d handle-backed source handoff ----
3180    //
3181    // These tests prove staged bytes come from the already-open member
3182    // object, never from re-resolving a recorded pathname or member name.
3183    // All races are deterministic (synchronous hooks or explicit post-handoff
3184    // filesystem operations); no test sleeps. The plan is always built from
3185    // advisory paths while they are still valid — the attacks below happen
3186    // after the handoff boundary, before staging — except where the attack
3187    // itself must precede the first write (hook races), in which case bound
3188    // reads are proven at the archive level.
3189
3190    /// Replaces a member directory entry while retaining the original object
3191    /// via its open handle. Portable: member handles carry full share access.
3192    fn replace_member_entry(path: &Path, foreign: &[u8]) {
3193        fs::remove_file(path).unwrap();
3194        fs::write(path, foreign).unwrap();
3195    }
3196
3197    /// Builds a core plan from bound advisory paths. Call while advisory
3198    /// paths are still valid; attacks happen after this returns.
3199    fn bound_plan(extraction: &BoundExtraction, install_root: &Path) -> InstallPlan {
3200        let artifacts = ArtifactSet::new(
3201            extraction
3202                .members()
3203                .iter()
3204                .map(|member| {
3205                    ArtifactMember::new(
3206                        MemberId::new(member.output_name()).unwrap(),
3207                        member.advisory_path(),
3208                        member.output_name(),
3209                    )
3210                    .unwrap()
3211                })
3212                .collect(),
3213        )
3214        .unwrap();
3215        InstallPlan::new(
3216            ProductId::new("example").unwrap(),
3217            ReleaseId::new("1.0.0").unwrap(),
3218            install_root,
3219            artifacts,
3220        )
3221        .unwrap()
3222    }
3223
3224    /// Stages bound members from their open objects and returns the prepared
3225    /// transaction with deferred root cleanup.
3226    fn stage_bound_members(
3227        extraction: BoundExtraction,
3228        plan: InstallPlan,
3229    ) -> (eggup_core::PreparedTransaction, DeferredCleanup) {
3230        let (members, cleanup) = extraction.into_members();
3231        let mut sources = BoundSources::new();
3232        for member in members {
3233            let id = MemberId::new(member.output_name()).unwrap();
3234            sources.insert(id, member.into_open_object());
3235        }
3236        (plan.prepare_with_bound_sources(sources).unwrap(), cleanup)
3237    }
3238
3239    /// Asserts handle-authorized cleanup semantics: the owned root is emptied
3240    /// via the retained handle and cleanup reports success. The residual empty
3241    /// directory is the caller's to remove; the crate never removes it.
3242    fn assert_cleanup_empties_owned_root(cleanup: DeferredCleanup, emptied: &Path) {
3243        cleanup
3244            .cleanup()
3245            .expect("cleanup empties the owned root and reports success");
3246        assert_eq!(fs::read_dir(emptied).unwrap().count(), 0);
3247        fs::remove_dir(emptied).unwrap();
3248    }
3249
3250    #[test]
3251    fn bound_tar_member_entry_replacement_after_handoff_stages_owned_bytes() {
3252        let dir = TestDir::new();
3253        let archive = tar_file(
3254            dir.path(),
3255            "race.tar.gz",
3256            &[TarFixture {
3257                path: "app",
3258                kind: b'0',
3259                body: b"owned-bytes",
3260                link: None,
3261            }],
3262        );
3263        let plan = make_plan(
3264            archive,
3265            ArchiveFormat::TarGz,
3266            vec![member("app", "app", b"owned-bytes")],
3267            limits(),
3268        );
3269        let bound = extract(&plan, dir.path())
3270            .unwrap()
3271            .persist()
3272            .into_bound_sources()
3273            .unwrap();
3274        let expected: [u8; 32] = Sha256::digest(b"owned-bytes").into();
3275        assert_eq!(bound.members()[0].bytes_written(), 11);
3276        assert_eq!(bound.members()[0].sha256(), expected);
3277        let install_root = dir.path().join("install");
3278        fs::create_dir(&install_root).unwrap();
3279        let root = bound.root().to_path_buf();
3280        let core_plan = bound_plan(&bound, &install_root);
3281        // Post-handoff replacement inside the still-owned root: the advisory
3282        // path now resolves to foreign bytes while the open object still
3283        // proves the owned bytes.
3284        let advisory = bound.members()[0].advisory_path().to_path_buf();
3285        replace_member_entry(&advisory, b"foreign-bytes");
3286        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
3287        assert_eq!(
3288            fs::read(
3289                prepared
3290                    .staged_path(&MemberId::new("app").unwrap())
3291                    .unwrap()
3292            )
3293            .unwrap(),
3294            b"owned-bytes"
3295        );
3296        assert_eq!(fs::read(&advisory).unwrap(), b"foreign-bytes");
3297        assert_cleanup_empties_owned_root(cleanup, &root);
3298    }
3299
3300    #[test]
3301    fn bound_zip_member_entry_replacement_after_handoff_stages_owned_bytes() {
3302        let dir = TestDir::new();
3303        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
3304        let plan = make_plan(
3305            archive,
3306            ArchiveFormat::Zip,
3307            vec![member("app", "app", b"owned-bytes")],
3308            limits(),
3309        );
3310        let bound = extract(&plan, dir.path())
3311            .unwrap()
3312            .persist()
3313            .into_bound_sources()
3314            .unwrap();
3315        let expected: [u8; 32] = Sha256::digest(b"owned-bytes").into();
3316        assert_eq!(bound.members()[0].bytes_written(), 11);
3317        assert_eq!(bound.members()[0].sha256(), expected);
3318        let install_root = dir.path().join("install");
3319        fs::create_dir(&install_root).unwrap();
3320        let root = bound.root().to_path_buf();
3321        let core_plan = bound_plan(&bound, &install_root);
3322        let advisory = bound.members()[0].advisory_path().to_path_buf();
3323        replace_member_entry(&advisory, b"foreign-bytes");
3324        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
3325        assert_eq!(
3326            fs::read(
3327                prepared
3328                    .staged_path(&MemberId::new("app").unwrap())
3329                    .unwrap()
3330            )
3331            .unwrap(),
3332            b"owned-bytes"
3333        );
3334        assert_eq!(fs::read(&advisory).unwrap(), b"foreign-bytes");
3335        assert_cleanup_empties_owned_root(cleanup, &root);
3336    }
3337
3338    #[test]
3339    fn bound_two_member_replacement_after_handoff_stages_owned_bytes() {
3340        let dir = TestDir::new();
3341        let archive = tar_file(
3342            dir.path(),
3343            "two.tar.gz",
3344            &[
3345                TarFixture {
3346                    path: "one",
3347                    kind: b'0',
3348                    body: b"first",
3349                    link: None,
3350                },
3351                TarFixture {
3352                    path: "two",
3353                    kind: b'0',
3354                    body: b"second",
3355                    link: None,
3356                },
3357            ],
3358        );
3359        let plan = make_plan(
3360            archive,
3361            ArchiveFormat::TarGz,
3362            vec![
3363                member("one", "one", b"first"),
3364                member("two", "two", b"second"),
3365            ],
3366            limits(),
3367        );
3368        let bound = extract(&plan, dir.path())
3369            .unwrap()
3370            .persist()
3371            .into_bound_sources()
3372            .unwrap();
3373        let install_root = dir.path().join("install");
3374        fs::create_dir(&install_root).unwrap();
3375        let root = bound.root().to_path_buf();
3376        let core_plan = bound_plan(&bound, &install_root);
3377        // Replace both member entries after the handoff; neither staged byte
3378        // may come from the replacements.
3379        let first_advisory = bound.members()[0].advisory_path().to_path_buf();
3380        let second_advisory = bound.members()[1].advisory_path().to_path_buf();
3381        replace_member_entry(&first_advisory, b"foreign-one");
3382        replace_member_entry(&second_advisory, b"foreign-two");
3383        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
3384        assert_eq!(
3385            fs::read(
3386                prepared
3387                    .staged_path(&MemberId::new("one").unwrap())
3388                    .unwrap()
3389            )
3390            .unwrap(),
3391            b"first"
3392        );
3393        assert_eq!(
3394            fs::read(
3395                prepared
3396                    .staged_path(&MemberId::new("two").unwrap())
3397                    .unwrap()
3398            )
3399            .unwrap(),
3400            b"second"
3401        );
3402        assert_eq!(fs::read(&first_advisory).unwrap(), b"foreign-one");
3403        assert_eq!(fs::read(&second_advisory).unwrap(), b"foreign-two");
3404        assert_cleanup_empties_owned_root(cleanup, &root);
3405    }
3406
3407    // Unix-only: renames the root while member objects are held open.
3408    // Windows refuses that rename (fail-safe OS-enforced binding); the
3409    // portable member-entry replacement races above prove no pathname
3410    // re-resolution on every platform.
3411    #[cfg(unix)]
3412    #[test]
3413    fn bound_post_handoff_root_replacement_stages_owned_bytes() {
3414        let dir = TestDir::new();
3415        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
3416        let plan = make_plan(
3417            archive,
3418            ArchiveFormat::Zip,
3419            vec![member("app", "app", b"owned-bytes")],
3420            limits(),
3421        );
3422        let bound = extract(&plan, dir.path())
3423            .unwrap()
3424            .persist()
3425            .into_bound_sources()
3426            .unwrap();
3427        let install_root = dir.path().join("install");
3428        fs::create_dir(&install_root).unwrap();
3429        let root = bound.root().to_path_buf();
3430        let core_plan = bound_plan(&bound, &install_root);
3431        // Post-handoff root replacement: the recorded root name now belongs
3432        // to foreign state while the retained handle still owns the original.
3433        let moved = dir.path().join("moved-owned-post-handoff");
3434        fs::rename(&root, &moved).unwrap();
3435        fs::create_dir(&root).unwrap();
3436        fs::write(root.join("foreign"), b"keep").unwrap();
3437        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
3438        assert_eq!(
3439            fs::read(
3440                prepared
3441                    .staged_path(&MemberId::new("app").unwrap())
3442                    .unwrap()
3443            )
3444            .unwrap(),
3445            b"owned-bytes"
3446        );
3447        assert_eq!(fs::read(root.join("foreign")).unwrap(), b"keep");
3448        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
3449        assert_cleanup_empties_owned_root(cleanup, &moved);
3450        fs::remove_dir_all(&root).unwrap();
3451    }
3452
3453    #[test]
3454    fn bound_tar_root_rename_before_first_write_reads_owned_bytes() {
3455        let dir = TestDir::new();
3456        let archive = tar_file(
3457            dir.path(),
3458            "race.tar.gz",
3459            &[TarFixture {
3460                path: "app",
3461                kind: b'0',
3462                body: b"owned-bytes",
3463                link: None,
3464            }],
3465        );
3466        let plan = make_plan(
3467            archive,
3468            ArchiveFormat::TarGz,
3469            vec![member("app", "app", b"owned-bytes")],
3470            limits(),
3471        );
3472        let moved = dir.path().join("moved-owned-bound-tar");
3473        let extracted = extract_with_hook(
3474            &plan,
3475            dir.path(),
3476            Some(&|seq: usize, root: &Path| {
3477                assert_eq!(seq, 0);
3478                fs::rename(root, &moved).unwrap();
3479                fs::create_dir(root).unwrap();
3480                fs::write(root.join("foreign"), b"keep").unwrap();
3481            }),
3482        )
3483        .unwrap();
3484        let root = extracted.root().to_path_buf();
3485        // Bound reads resolve the retained object despite the stale pathname.
3486        let (members, cleanup) = extracted
3487            .persist()
3488            .into_bound_sources()
3489            .unwrap()
3490            .into_members();
3491        assert_eq!(members.len(), 1);
3492        let mut owned = Vec::new();
3493        let mut object = members.into_iter().next().unwrap().into_open_object();
3494        use std::io::Read as _;
3495        object.read_to_end(&mut owned).unwrap();
3496        assert_eq!(owned, b"owned-bytes");
3497        assert_eq!(fs::read(root.join("foreign")).unwrap(), b"keep");
3498        assert!(!root.join("app").exists());
3499        cleanup
3500            .cleanup()
3501            .expect("cleanup empties the owned root and reports success");
3502        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
3503        fs::remove_dir(&moved).unwrap();
3504        fs::remove_dir_all(&root).unwrap();
3505    }
3506
3507    #[test]
3508    fn bound_zip_root_rename_before_first_write_reads_owned_bytes() {
3509        let dir = TestDir::new();
3510        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
3511        let plan = make_plan(
3512            archive,
3513            ArchiveFormat::Zip,
3514            vec![member("app", "app", b"owned-bytes")],
3515            limits(),
3516        );
3517        let moved = dir.path().join("moved-owned-bound-zip");
3518        let extracted = extract_with_hook(
3519            &plan,
3520            dir.path(),
3521            Some(&|seq: usize, root: &Path| {
3522                assert_eq!(seq, 0);
3523                fs::rename(root, &moved).unwrap();
3524                fs::create_dir(root).unwrap();
3525                fs::write(root.join("foreign"), b"keep").unwrap();
3526            }),
3527        )
3528        .unwrap();
3529        let root = extracted.root().to_path_buf();
3530        let (members, cleanup) = extracted
3531            .persist()
3532            .into_bound_sources()
3533            .unwrap()
3534            .into_members();
3535        assert_eq!(members.len(), 1);
3536        let mut owned = Vec::new();
3537        let mut object = members.into_iter().next().unwrap().into_open_object();
3538        use std::io::Read as _;
3539        object.read_to_end(&mut owned).unwrap();
3540        assert_eq!(owned, b"owned-bytes");
3541        assert_eq!(fs::read(root.join("foreign")).unwrap(), b"keep");
3542        assert!(!root.join("app").exists());
3543        cleanup
3544            .cleanup()
3545            .expect("cleanup empties the owned root and reports success");
3546        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
3547        fs::remove_dir(&moved).unwrap();
3548        fs::remove_dir_all(&root).unwrap();
3549    }
3550
3551    // Unix-only: the hook renames after the first member object is already
3552    // held open (see note above `bound_post_handoff_root_replacement_...`).
3553    #[cfg(unix)]
3554    #[test]
3555    fn bound_two_member_replacement_between_writes_reads_owned_bytes() {
3556        let dir = TestDir::new();
3557        let archive = tar_file(
3558            dir.path(),
3559            "two.tar.gz",
3560            &[
3561                TarFixture {
3562                    path: "one",
3563                    kind: b'0',
3564                    body: b"first",
3565                    link: None,
3566                },
3567                TarFixture {
3568                    path: "two",
3569                    kind: b'0',
3570                    body: b"second",
3571                    link: None,
3572                },
3573            ],
3574        );
3575        let plan = make_plan(
3576            archive,
3577            ArchiveFormat::TarGz,
3578            vec![
3579                member("one", "one", b"first"),
3580                member("two", "two", b"second"),
3581            ],
3582            limits(),
3583        );
3584        let moved = dir.path().join("moved-owned-bound-two");
3585        let extracted = extract_with_hook(
3586            &plan,
3587            dir.path(),
3588            Some(&|seq: usize, root: &Path| {
3589                if seq == 1 {
3590                    fs::rename(root, &moved).unwrap();
3591                    fs::create_dir(root).unwrap();
3592                    fs::write(root.join("foreign"), b"keep").unwrap();
3593                }
3594            }),
3595        )
3596        .unwrap();
3597        let root = extracted.root().to_path_buf();
3598        let (members, cleanup) = extracted
3599            .persist()
3600            .into_bound_sources()
3601            .unwrap()
3602            .into_members();
3603        assert_eq!(members.len(), 2);
3604        use std::io::Read as _;
3605        let mut bodies = Vec::new();
3606        for member in members {
3607            let mut object = member.into_open_object();
3608            let mut body = Vec::new();
3609            object.read_to_end(&mut body).unwrap();
3610            bodies.push(body);
3611        }
3612        assert_eq!(bodies, vec![b"first".to_vec(), b"second".to_vec()]);
3613        assert_eq!(fs::read(root.join("foreign")).unwrap(), b"keep");
3614        assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
3615        cleanup
3616            .cleanup()
3617            .expect("cleanup empties the owned root and reports success");
3618        assert_eq!(fs::read_dir(&moved).unwrap().count(), 0);
3619        fs::remove_dir(&moved).unwrap();
3620        fs::remove_dir_all(&root).unwrap();
3621    }
3622
3623    #[test]
3624    fn bound_nonzero_cursor_stages_full_file_from_byte_zero() {
3625        let dir = TestDir::new();
3626        let archive = zip_file(dir.path(), "race.zip", &[("app", b"owned-bytes")]);
3627        let plan = make_plan(
3628            archive,
3629            ArchiveFormat::Zip,
3630            vec![member("app", "app", b"owned-bytes")],
3631            limits(),
3632        );
3633        let mut bound = extract(&plan, dir.path())
3634            .unwrap()
3635            .persist()
3636            .into_bound_sources()
3637            .unwrap();
3638        // Move the shared cursor after handoff: staging must still consume
3639        // the full file from byte zero, never from the moved cursor.
3640        let mut prefix = [0u8; 4];
3641        use std::io::Read as _;
3642        bound.members_mut()[0]
3643            .handle_mut()
3644            .read_exact(&mut prefix)
3645            .unwrap();
3646        assert_eq!(&prefix, b"owne");
3647        let install_root = dir.path().join("install");
3648        fs::create_dir(&install_root).unwrap();
3649        let root = bound.root().to_path_buf();
3650        let core_plan = bound_plan(&bound, &install_root);
3651        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
3652        assert_eq!(
3653            fs::read(
3654                prepared
3655                    .staged_path(&MemberId::new("app").unwrap())
3656                    .unwrap()
3657            )
3658            .unwrap(),
3659            b"owned-bytes"
3660        );
3661        assert_cleanup_empties_owned_root(cleanup, &root);
3662    }
3663
3664    #[cfg(unix)]
3665    #[test]
3666    fn bound_sources_preserve_owner_private_mode_and_exact_evidence() {
3667        use std::os::unix::fs::PermissionsExt;
3668        let dir = TestDir::new();
3669        let archive = tar_file(
3670            dir.path(),
3671            "race.tar.gz",
3672            &[TarFixture {
3673                path: "app",
3674                kind: b'0',
3675                body: b"owned-bytes",
3676                link: None,
3677            }],
3678        );
3679        let plan = make_plan(
3680            archive,
3681            ArchiveFormat::TarGz,
3682            vec![member("app", "app", b"owned-bytes")],
3683            limits(),
3684        );
3685        let bound = extract(&plan, dir.path())
3686            .unwrap()
3687            .persist()
3688            .into_bound_sources()
3689            .unwrap();
3690        let expected: [u8; 32] = Sha256::digest(b"owned-bytes").into();
3691        assert_eq!(bound.members()[0].bytes_written(), 11);
3692        assert_eq!(bound.members()[0].sha256(), expected);
3693        assert_eq!(bound.members()[0].source_path(), "app");
3694        assert_eq!(bound.members()[0].output_name(), "app");
3695        // Handle-relative creation stays owner-private with read authority.
3696        let mode = fs::metadata(bound.members()[0].advisory_path())
3697            .unwrap()
3698            .permissions()
3699            .mode();
3700        assert_eq!(mode & 0o777, 0o600);
3701        let install_root = dir.path().join("install");
3702        fs::create_dir(&install_root).unwrap();
3703        let root = bound.root().to_path_buf();
3704        let core_plan = bound_plan(&bound, &install_root);
3705        let (prepared, cleanup) = stage_bound_members(bound, core_plan);
3706        let staged_mode = fs::metadata(
3707            prepared
3708                .staged_path(&MemberId::new("app").unwrap())
3709                .unwrap(),
3710        )
3711        .unwrap()
3712        .permissions()
3713        .mode();
3714        assert_eq!(staged_mode & 0o777, 0o600);
3715        assert_cleanup_empties_owned_root(cleanup, &root);
3716    }
3717}