Skip to main content

eggup_eggpack/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Optional consumer-side adapter from Eggpack ReleaseManifest v1 to Eggup inputs."]
4
5use eggpack_manifest::{ArtifactForm, ReleaseManifest, MAX_DOCUMENT_BYTES};
6use eggup_acquisition::{AcquisitionRequest, FetchLimits};
7use eggup_archive::{ArchiveFormat, ArchiveLimits, ArchiveMember, ArchivePlan, BoundMember};
8use eggup_core::{
9    hash_file, ArtifactMember, ArtifactSet, BoundSources, InstallPlan, IntegrityRequirement,
10    MemberId, PermissionsIntent, ProductId, ReleaseId,
11};
12use std::{
13    collections::{HashMap, HashSet},
14    fmt, fs,
15    path::{Path, PathBuf},
16};
17
18/// Typed adapter failure. Details never contain URLs or file contents.
19#[derive(Debug)]
20#[non_exhaustive]
21pub enum AdapterError {
22    /// Manifest or Eggup identity is invalid.
23    InvalidManifest,
24    /// Exact canonical target is absent.
25    TargetNotFound,
26    /// Request, acquired-file, or permission maps differ from the required set.
27    MapMismatch(&'static str),
28    /// Caller artifact limit is lower than the manifest exact size.
29    CallerLimitTooSmall(String),
30    /// Acquired path is relative, missing, linked, non-regular, or the wrong size.
31    InvalidAcquiredFile(String),
32    /// Archive member bytes cannot be made installable without qualified extraction.
33    ArchiveExtractionRequired,
34    /// Caller-selected artifact name does not name a supported archive format.
35    UnsupportedArchiveFormat,
36    /// Construction in a lower Eggup layer failed.
37    Eggup(String),
38}
39
40impl fmt::Display for AdapterError {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            Self::InvalidManifest => f.write_str("invalid manifest or identity"),
44            Self::TargetNotFound => f.write_str("canonical target not found"),
45            Self::MapMismatch(kind) => write!(f, "{kind} map does not exactly match manifest"),
46            Self::CallerLimitTooSmall(name) => {
47                write!(f, "caller byte limit is below manifest size for {name}")
48            }
49            Self::InvalidAcquiredFile(name) => write!(f, "acquired file is invalid for {name}"),
50            Self::ArchiveExtractionRequired => f.write_str("archive extraction is required"),
51            Self::UnsupportedArchiveFormat => {
52                f.write_str("artifact name does not name a supported archive format")
53            }
54            Self::Eggup(detail) => write!(f, "Eggup input construction failed: {detail}"),
55        }
56    }
57}
58impl std::error::Error for AdapterError {}
59
60/// Maximum accepted UTF-8 JSON document size, as defined by Eggpack's manifest schema.
61pub const MAX_MANIFEST_BYTES: usize = MAX_DOCUMENT_BYTES;
62
63/// One manifest artifact paired with its exact installed member relationship.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct ArtifactRequirement {
66    /// Manifest artifact name used only as an exact map key.
67    pub artifact_name: String,
68    /// Exact expected byte count.
69    pub exact_size: u64,
70    /// Manifest SHA-256 bytes.
71    pub sha256: [u8; 32],
72    /// Eggup member identity.
73    pub member_id: MemberId,
74    /// Flat relative install destination.
75    pub destination: String,
76}
77
78/// Preserved archive member evidence; extraction remains a separate boundary.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct ArchiveMemberRequirement {
81    /// Normalized archive source path.
82    pub source: String,
83    /// Flat installation identity.
84    pub install: String,
85    /// Exact member size.
86    pub exact_size: u64,
87    /// Member SHA-256 bytes.
88    pub sha256: [u8; 32],
89}
90
91/// Manifest projection for one exact canonical target.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum ManifestProjection {
94    /// Direct or bundle files can become one ArtifactSet after acquisition.
95    Installable {
96        /// Opaque product identity.
97        product: ProductId,
98        /// Opaque release identity.
99        release: ReleaseId,
100        /// Exact selected canonical triple.
101        target: String,
102        /// Ordered direct or bundle relationships.
103        artifacts: Vec<ArtifactRequirement>,
104    },
105    /// Archive facts are retained but require separately qualified extraction.
106    Archive {
107        /// Opaque product identity.
108        product: ProductId,
109        /// Opaque release identity.
110        release: ReleaseId,
111        /// Exact selected canonical triple.
112        target: String,
113        /// Archive artifact key.
114        artifact_name: String,
115        /// Exact archive byte count.
116        exact_size: u64,
117        /// Archive SHA-256 bytes.
118        sha256: [u8; 32],
119        /// Expected member relationships, not verified extracted files.
120        members: Vec<ArchiveMemberRequirement>,
121    },
122}
123
124impl ManifestProjection {
125    fn installable(
126        &self,
127    ) -> Result<(&ProductId, &ReleaseId, &[ArtifactRequirement]), AdapterError> {
128        match self {
129            Self::Installable {
130                product,
131                release,
132                artifacts,
133                ..
134            } => Ok((product, release, artifacts)),
135            Self::Archive { .. } => Err(AdapterError::ArchiveExtractionRequired),
136        }
137    }
138
139    /// Manifest-default destinations keyed by stable member identity.
140    ///
141    /// Pure helper with no I/O. For installable projections each entry maps
142    /// the projected `MemberId` to its manifest `install` default
143    /// destination. For archive projections each entry maps
144    /// `MemberId::new(install)` to the manifest `install` identity. Callers
145    /// that bind their own destinations do not need this helper; the
146    /// compatibility wrappers use it to preserve prior default behavior.
147    pub fn default_destinations(&self) -> Result<HashMap<MemberId, String>, AdapterError> {
148        match self {
149            Self::Installable { artifacts, .. } => Ok(artifacts
150                .iter()
151                .map(|a| (a.member_id.clone(), a.destination.clone()))
152                .collect()),
153            Self::Archive { members, .. } => members
154                .iter()
155                .map(|m| {
156                    let id = MemberId::new(m.install.clone())
157                        .map_err(|e| AdapterError::Eggup(e.to_string()))?;
158                    Ok((id, m.install.clone()))
159                })
160                .collect(),
161        }
162    }
163
164    /// Bind every artifact to one exact caller-selected request and tightened limit.
165    pub fn bind_requests(
166        &self,
167        requests: HashMap<String, AcquisitionRequest>,
168        baseline: FetchLimits,
169    ) -> Result<Vec<PlannedAcquisition>, AdapterError> {
170        baseline
171            .validate()
172            .map_err(|e| AdapterError::Eggup(e.to_string()))?;
173        let requirements = match self {
174            Self::Installable { artifacts, .. } => artifacts
175                .iter()
176                .map(|a| {
177                    (
178                        a.artifact_name.clone(),
179                        a.exact_size,
180                        a.sha256,
181                        a.member_id.clone(),
182                    )
183                })
184                .collect::<Vec<_>>(),
185            Self::Archive {
186                artifact_name,
187                exact_size,
188                sha256,
189                ..
190            } => vec![(
191                artifact_name.clone(),
192                *exact_size,
193                *sha256,
194                MemberId::new(artifact_name.clone())
195                    .map_err(|e| AdapterError::Eggup(e.to_string()))?,
196            )],
197        };
198        if requests.len() != requirements.len()
199            || requirements.iter().any(|(n, ..)| !requests.contains_key(n))
200        {
201            return Err(AdapterError::MapMismatch("acquisition request"));
202        }
203        requirements
204            .into_iter()
205            .map(|(name, size, sha, member)| {
206                if baseline.max_artifact_bytes < size {
207                    return Err(AdapterError::CallerLimitTooSmall(name.clone()));
208                }
209                Ok(PlannedAcquisition {
210                    artifact_name: name.clone(),
211                    request: requests.get(&name).expect("checked map").clone(),
212                    limits: FetchLimits {
213                        max_artifact_bytes: size,
214                        ..baseline
215                    },
216                    exact_size: size,
217                    sha256: sha,
218                    member_id: member,
219                })
220            })
221            .collect()
222    }
223
224    /// Validate acquired files and build one all-or-nothing direct/bundle
225    /// `ArtifactSet` with caller-bound destinations.
226    ///
227    /// Manifest `install` values remain producer default identity only: the
228    /// exact relative destination of every member comes from `destinations`,
229    /// which must contain exactly the projected member set. Missing, extra,
230    /// or colliding destinations fail closed before any set is returned, and
231    /// invalid destinations fail through Eggup destination validation into a
232    /// bounded adapter error. Artifact filename to acquired-path
233    /// relationships, stable member identities, exact sizes, regular-file
234    /// checks, SHA-256 evidence, and permission binding are unchanged.
235    /// Replacement authorization stays outside this helper: it records where
236    /// bytes should be installed and never proves control of a live
237    /// destination. No URL or filesystem content is echoed in diagnostics.
238    pub fn materialize_artifact_set_with_destinations(
239        &self,
240        acquired: HashMap<String, PathBuf>,
241        destinations: HashMap<MemberId, String>,
242        permissions: HashMap<MemberId, PermissionsIntent>,
243    ) -> Result<ArtifactSet, AdapterError> {
244        let (_, _, reqs) = self.installable()?;
245        if acquired.len() != reqs.len()
246            || reqs
247                .iter()
248                .any(|r| !acquired.contains_key(&r.artifact_name))
249        {
250            return Err(AdapterError::MapMismatch("acquired path"));
251        }
252        if destinations.len() != reqs.len()
253            || reqs
254                .iter()
255                .any(|r| !destinations.contains_key(&r.member_id))
256        {
257            return Err(AdapterError::MapMismatch("destinations"));
258        }
259        if permissions.len() != reqs.len()
260            || reqs.iter().any(|r| !permissions.contains_key(&r.member_id))
261        {
262            return Err(AdapterError::MapMismatch("permissions"));
263        }
264        let mut members = Vec::with_capacity(reqs.len());
265        for r in reqs {
266            let path = acquired.get(&r.artifact_name).expect("checked map");
267            if !path.is_absolute() {
268                return Err(AdapterError::InvalidAcquiredFile(r.artifact_name.clone()));
269            }
270            let meta = fs::symlink_metadata(path)
271                .map_err(|_| AdapterError::InvalidAcquiredFile(r.artifact_name.clone()))?;
272            if !meta.file_type().is_file() || meta.len() != r.exact_size {
273                return Err(AdapterError::InvalidAcquiredFile(r.artifact_name.clone()));
274            }
275            let destination = destinations.get(&r.member_id).expect("checked map");
276            members.push(
277                ArtifactMember::new(r.member_id.clone(), path, destination)
278                    .map_err(|e| AdapterError::Eggup(e.to_string()))?
279                    .with_permissions(*permissions.get(&r.member_id).expect("checked map"))
280                    .with_integrity(IntegrityRequirement::Sha256(r.sha256)),
281            );
282        }
283        let mut seen = HashSet::with_capacity(members.len());
284        for member in &members {
285            if !seen.insert(member.destination().to_path_buf()) {
286                return Err(AdapterError::MapMismatch("destinations"));
287            }
288        }
289        ArtifactSet::new(members).map_err(|e| AdapterError::Eggup(e.to_string()))
290    }
291
292    /// Validate acquired files and build one all-or-nothing direct/bundle ArtifactSet.
293    ///
294    /// Compatibility wrapper: builds the manifest-default destination map and
295    /// delegates to
296    /// [`materialize_artifact_set_with_destinations`](Self::materialize_artifact_set_with_destinations).
297    /// There is one materialization implementation.
298    pub fn materialize_artifact_set(
299        &self,
300        acquired: HashMap<String, PathBuf>,
301        permissions: HashMap<MemberId, PermissionsIntent>,
302    ) -> Result<ArtifactSet, AdapterError> {
303        let destinations = self.default_destinations()?;
304        self.materialize_artifact_set_with_destinations(acquired, destinations, permissions)
305    }
306}
307
308/// Exact request and manifest evidence to pass to an acquisition transport.
309#[derive(Debug, Clone)]
310pub struct PlannedAcquisition {
311    /// Exact manifest artifact key.
312    pub artifact_name: String,
313    /// Exact unmodified caller request.
314    pub request: AcquisitionRequest,
315    /// Caller limits with artifact byte cap tightened to manifest size.
316    pub limits: FetchLimits,
317    /// Expected byte count.
318    pub exact_size: u64,
319    /// Expected SHA-256 bytes.
320    pub sha256: [u8; 32],
321    /// Related Eggup member identity.
322    pub member_id: MemberId,
323}
324
325/// Validate and project one exact canonical target without performing I/O.
326pub fn project(
327    manifest: &ReleaseManifest,
328    canonical_target: &str,
329) -> Result<ManifestProjection, AdapterError> {
330    manifest
331        .validate()
332        .map_err(|_| AdapterError::InvalidManifest)?;
333    let target = manifest
334        .target(canonical_target)
335        .map_err(|_| AdapterError::TargetNotFound)?;
336    let product = ProductId::new(manifest.product_id.clone())
337        .map_err(|e| AdapterError::Eggup(e.to_string()))?;
338    let release = ReleaseId::new(manifest.release_id.clone())
339        .map_err(|e| AdapterError::Eggup(e.to_string()))?;
340    let common = (product, release, target.target.clone());
341    match &target.form {
342        ArtifactForm::Direct { artifact, install } => Ok(ManifestProjection::Installable {
343            product: common.0,
344            release: common.1,
345            target: common.2,
346            artifacts: vec![ArtifactRequirement {
347                artifact_name: artifact.name.clone(),
348                exact_size: artifact.size,
349                sha256: artifact
350                    .sha256_bytes()
351                    .map_err(|_| AdapterError::InvalidManifest)?,
352                member_id: MemberId::new(install.clone())
353                    .map_err(|e| AdapterError::Eggup(e.to_string()))?,
354                destination: install.clone(),
355            }],
356        }),
357        ArtifactForm::Bundle { entries } => Ok(ManifestProjection::Installable {
358            product: common.0,
359            release: common.1,
360            target: common.2,
361            artifacts: entries
362                .iter()
363                .map(|e| {
364                    Ok(ArtifactRequirement {
365                        artifact_name: e.artifact.name.clone(),
366                        exact_size: e.artifact.size,
367                        sha256: e
368                            .artifact
369                            .sha256_bytes()
370                            .map_err(|_| AdapterError::InvalidManifest)?,
371                        member_id: MemberId::new(e.install.clone())
372                            .map_err(|x| AdapterError::Eggup(x.to_string()))?,
373                        destination: e.install.clone(),
374                    })
375                })
376                .collect::<Result<_, AdapterError>>()?,
377        }),
378        ArtifactForm::Archive { artifact, members } => Ok(ManifestProjection::Archive {
379            product: common.0,
380            release: common.1,
381            target: common.2,
382            artifact_name: artifact.name.clone(),
383            exact_size: artifact.size,
384            sha256: artifact
385                .sha256_bytes()
386                .map_err(|_| AdapterError::InvalidManifest)?,
387            members: members
388                .iter()
389                .map(|m| {
390                    Ok(ArchiveMemberRequirement {
391                        source: m.source.clone(),
392                        install: m.install.clone(),
393                        exact_size: m.bytes.size,
394                        sha256: m
395                            .bytes
396                            .sha256_bytes()
397                            .map_err(|_| AdapterError::InvalidManifest)?,
398                    })
399                })
400                .collect::<Result<_, AdapterError>>()?,
401        }),
402    }
403}
404
405/// Parse bounded ReleaseManifest JSON and project one exact canonical target.
406///
407/// Parsing and schema validation are delegated to `eggpack-manifest`. Input
408/// contents and parser diagnostics are never included in returned errors.
409pub fn project_json(
410    input: &[u8],
411    canonical_target: &str,
412) -> Result<ManifestProjection, AdapterError> {
413    if input.len() > MAX_MANIFEST_BYTES {
414        return Err(AdapterError::InvalidManifest);
415    }
416    let json = std::str::from_utf8(input).map_err(|_| AdapterError::InvalidManifest)?;
417    let manifest = ReleaseManifest::from_json(json).map_err(|_| AdapterError::InvalidManifest)?;
418    project(&manifest, canonical_target)
419}
420
421/// Return product and release identities for an installable projection.
422pub fn install_ids(
423    projection: &ManifestProjection,
424) -> Result<(&ProductId, &ReleaseId), AdapterError> {
425    let (product, release, _) = projection.installable()?;
426    Ok((product, release))
427}
428
429// ---------------------------------------------------------------------------
430// Archive extraction handoff (M002).
431//
432// These helpers translate `ManifestProjection::Archive` into typed inputs the
433// caller feeds to `eggup-archive::extract` and `eggup-core`'s
434// `BoundSources`-based prepare seam. They perform no I/O, no extraction, no
435// commit, and never reach outside their arguments; composition stays
436// caller-owned so lifetimes and authority stay obvious.
437//
438// Required caller order:
439//   1. validate the acquired archive against `projection` (size + SHA-256);
440//   2. call `archive_plan_for` to obtain an `ArchivePlan`;
441//   3. extract with `eggup_archive::extract`;
442//   4. capture `extracted.root()` before persisting;
443//   5. call `core_plan_for_archive` to obtain the core `InstallPlan` while
444//      advisory paths are still meaningful;
445//   6. call `extracted.persist().into_bound_sources()?.into_members()` to
446//      obtain the bound members and deferred cleanup;
447//   7. call `bind_archive_members` to obtain a `BoundSources` keyed by member
448//      identity from the projection;
449//   8. call `InstallPlan::prepare_with_bound_sources`.
450// ---------------------------------------------------------------------------
451
452/// Map a caller-selected archive artifact file name to a supported format.
453///
454/// Only `.tar.gz`, `.tgz`, and `.zip` suffixes (ASCII case-insensitive) are
455/// accepted; anything else fails closed. The caller owns artifact selection:
456/// this helper never fetches, lists, or ranks releases, it only classifies
457/// the name the caller already chose.
458pub fn archive_format_for_name(file_name: &str) -> Result<ArchiveFormat, AdapterError> {
459    if file_name.is_empty() || !file_name.is_ascii() {
460        return Err(AdapterError::UnsupportedArchiveFormat);
461    }
462    let lower = file_name.to_ascii_lowercase();
463    if lower.ends_with(".tar.gz") || lower.ends_with(".tgz") {
464        Ok(ArchiveFormat::TarGz)
465    } else if lower.ends_with(".zip") {
466        Ok(ArchiveFormat::Zip)
467    } else {
468        Err(AdapterError::UnsupportedArchiveFormat)
469    }
470}
471
472/// Validate caller-owned acquired archive continuity against the manifest.
473///
474/// Checks that `acquired_archive_path` is absolute, names a regular file
475/// (never a symlink, directory, or missing path), is exactly the manifest
476/// archive byte count, and hashes to the manifest archive SHA-256. This is
477/// the same continuity gate `materialize_artifact_set` applies to
478/// direct/bundle files, moved ahead of extraction so no unverified byte is
479/// ever extracted. Performs bounded streaming reads only; no network, no
480/// alternate-source retry, no provenance claim.
481///
482/// # Errors
483///
484/// Returns [`AdapterError::InvalidAcquiredFile`] for every failure on this
485/// path: a relative path, a missing path, a path that is not a regular file
486/// (a symlink, directory, FIFO, or device), a size that differs from the
487/// declared exact size, a digest that differs from the manifest digest, and
488/// a digest step that cannot open or read the file.
489///
490/// The digest is computed by [`eggup_core::hash_file`]. Its open and read
491/// failures are collapsed into the same variant and payload as the digest
492/// mismatch, exactly as the adapter's own inline digest routine reported
493/// them. The collapse is deliberate: [`AdapterError`] carries only the
494/// artifact name and has no `source()` chain, so distinguishing "the acquired
495/// file is invalid" from "the acquired file could not be read" would change
496/// what a published consumer observes and belongs to a separate API decision.
497pub fn validate_acquired_archive(
498    projection: &ManifestProjection,
499    acquired_archive_path: &Path,
500) -> Result<(), AdapterError> {
501    let (artifact_name, exact_size, sha256) = match projection {
502        ManifestProjection::Archive {
503            artifact_name,
504            exact_size,
505            sha256,
506            ..
507        } => (artifact_name, *exact_size, *sha256),
508        _ => return Err(AdapterError::ArchiveExtractionRequired),
509    };
510    if !acquired_archive_path.is_absolute() {
511        return Err(AdapterError::InvalidAcquiredFile(artifact_name.clone()));
512    }
513    let meta = fs::symlink_metadata(acquired_archive_path)
514        .map_err(|_| AdapterError::InvalidAcquiredFile(artifact_name.clone()))?;
515    if !meta.file_type().is_file() || meta.len() != exact_size {
516        return Err(AdapterError::InvalidAcquiredFile(artifact_name.clone()));
517    }
518    // The guard above runs first: `hash_file` follows symlinks when it opens
519    // the path, so this is the only link rejection on the path. The digest
520    // step's own failures collapse into the same variant and payload as the
521    // mismatch below, preserving the adapter's published error surface.
522    let digest: [u8; 32] = hash_file(acquired_archive_path)
523        .map_err(|_| AdapterError::InvalidAcquiredFile(artifact_name.clone()))?;
524    if digest != sha256 {
525        return Err(AdapterError::InvalidAcquiredFile(artifact_name.clone()));
526    }
527    Ok(())
528}
529
530/// Translate `ManifestProjection::Archive` into a validated `ArchivePlan`.
531///
532/// Each declared member maps `source -> eggup_archive::ArchiveMember::source_path`
533/// and `install -> eggup_archive::ArchiveMember::output_name`. Caller-supplied
534/// `expected_size` and `expected_sha256` come from the projection so the
535/// extractor can verify bytes against the manifest during extraction.
536///
537/// The caller must already have validated the acquired archive against the
538/// manifest's exact size and SHA-256; this helper does not re-validate the
539/// archive bytes and does not perform any I/O.
540pub fn archive_plan_for(
541    projection: &ManifestProjection,
542    archive_format: ArchiveFormat,
543    acquired_archive_path: &Path,
544    limits: ArchiveLimits,
545) -> Result<ArchivePlan, AdapterError> {
546    let members = match projection {
547        ManifestProjection::Archive { members, .. } => members,
548        _ => return Err(AdapterError::ArchiveExtractionRequired),
549    };
550    let mut declared = Vec::with_capacity(members.len());
551    for m in members {
552        let member = ArchiveMember::new(
553            m.source.clone(),
554            m.install.clone(),
555            Some(m.exact_size),
556            Some(m.sha256),
557        )
558        .map_err(|e| AdapterError::Eggup(e.to_string()))?;
559        declared.push(member);
560    }
561    ArchivePlan::new(acquired_archive_path, archive_format, declared, limits)
562        .map_err(|e| AdapterError::Eggup(e.to_string()))
563}
564
565/// Build the core `InstallPlan` for an archive projection with caller-bound
566/// destinations, recording each member's advisory path as
567/// `extraction_root.join(manifest install)`.
568///
569/// The caller destination map must exactly match the projected member
570/// identities: missing, extra, or colliding destinations fail closed before
571/// any plan is returned, and invalid destinations fail through Eggup
572/// destination validation into a bounded adapter error. Archive member
573/// identity, advisory extraction source paths, and member size/digest facts
574/// remain manifest-derived while destination strings come from caller policy.
575/// `BoundSources` and the object-bound extraction handoff are unchanged: the
576/// returned plan still carries empty bound sources until the caller transfers
577/// them via `bind_archive_members`.
578///
579/// The caller is responsible for capturing `extraction_root` (typically
580/// `ExtractedArchive::root()`) before any handle-bound handoff, and for
581/// keeping the path reachable until staging no longer needs it.
582/// Advisory paths are never opened during staging when a bound handle is
583/// supplied; the path is recorded solely to satisfy
584/// `ArtifactMember::new`'s validation and to expose diagnostics.
585///
586/// Replacement authorization stays outside this helper: it records where
587/// extracted bytes should be installed and never proves control of a live
588/// destination.
589pub fn core_plan_for_archive_with_destinations(
590    projection: &ManifestProjection,
591    extraction_root: &Path,
592    destination_root: &Path,
593    destinations: HashMap<MemberId, String>,
594    permissions: HashMap<MemberId, PermissionsIntent>,
595) -> Result<InstallPlan, AdapterError> {
596    let (product, release, members) = match projection {
597        ManifestProjection::Archive {
598            product,
599            release,
600            members,
601            ..
602        } => (product, release, members),
603        _ => return Err(AdapterError::ArchiveExtractionRequired),
604    };
605    if destinations.len() != members.len() {
606        return Err(AdapterError::MapMismatch("destinations"));
607    }
608    if permissions.len() != members.len() {
609        return Err(AdapterError::MapMismatch("permissions"));
610    }
611    let mut artifacts = Vec::with_capacity(members.len());
612    for m in members {
613        let id =
614            MemberId::new(m.install.clone()).map_err(|e| AdapterError::Eggup(e.to_string()))?;
615        let destination = destinations
616            .get(&id)
617            .ok_or(AdapterError::MapMismatch("destinations"))?;
618        let advisory = extraction_root.join(&m.install);
619        let permissions_intent = permissions
620            .get(&id)
621            .copied()
622            .ok_or(AdapterError::MapMismatch("permissions"))?;
623        let member = ArtifactMember::new(id.clone(), &advisory, destination)
624            .map_err(|e| AdapterError::Eggup(e.to_string()))?
625            .with_permissions(permissions_intent)
626            .with_integrity(IntegrityRequirement::Sha256(m.sha256));
627        artifacts.push(member);
628    }
629    let mut seen = HashSet::with_capacity(artifacts.len());
630    for member in &artifacts {
631        if !seen.insert(member.destination().to_path_buf()) {
632            return Err(AdapterError::MapMismatch("destinations"));
633        }
634    }
635    let set = ArtifactSet::new(artifacts).map_err(|e| AdapterError::Eggup(e.to_string()))?;
636    InstallPlan::new(product.clone(), release.clone(), destination_root, set)
637        .map_err(|e| AdapterError::Eggup(e.to_string()))
638}
639
640/// Build the core `InstallPlan` for an archive projection, recording each
641/// member's advisory path as `extraction_root.join(member.install)`.
642///
643/// Compatibility wrapper: builds the manifest-default destination map and
644/// delegates to [`core_plan_for_archive_with_destinations`]. There is one
645/// archive plan implementation.
646///
647/// The caller is responsible for capturing `extraction_root` (typically
648/// `ExtractedArchive::root()`) before any handle-bound handoff, and for
649/// keeping the path reachable until staging no longer needs it.
650/// Advisory paths are never opened during staging when a bound handle is
651/// supplied; the path is recorded solely to satisfy
652/// `ArtifactMember::new`'s validation and to expose diagnostics.
653///
654/// The returned plan's `BoundSources` are still empty at this point; the
655/// caller transfers bound members separately via `bind_archive_members`.
656pub fn core_plan_for_archive(
657    projection: &ManifestProjection,
658    extraction_root: &Path,
659    destination_root: &Path,
660    permissions: HashMap<MemberId, PermissionsIntent>,
661) -> Result<InstallPlan, AdapterError> {
662    let destinations = projection.default_destinations()?;
663    core_plan_for_archive_with_destinations(
664        projection,
665        extraction_root,
666        destination_root,
667        destinations,
668        permissions,
669    )
670}
671
672/// Build a `BoundSources` map from the projection's archive member list and
673/// the bound members returned by `BoundExtraction::into_members()`.
674///
675/// Identity is the projection's `install` string converted into a `MemberId`;
676/// bound members are paired to the projection's archive members in declaration
677/// order. Mismatched counts fail closed, and so does a member whose own
678/// recorded identity (`source_path`/`output_name`) does not match the declared
679/// member it would be bound to.
680///
681/// The identity cross-check is what stops bytes being labelled positionally
682/// rather than by proven identity: a `BoundExtraction` produced from a
683/// different `ArchivePlan`, or reused after a re-projection, pairs by count
684/// alone and would otherwise commit foreign bytes under a declared identity.
685/// That substitution is digest-invisible whenever two declared members happen
686/// to share identical content, which is exactly when it is most dangerous.
687pub fn bind_archive_members(
688    projection: &ManifestProjection,
689    bound_members: Vec<BoundMember>,
690) -> Result<BoundSources, AdapterError> {
691    let members = match projection {
692        ManifestProjection::Archive { members, .. } => members,
693        _ => return Err(AdapterError::ArchiveExtractionRequired),
694    };
695    if members.len() != bound_members.len() {
696        return Err(AdapterError::MapMismatch("archive bound members"));
697    }
698    let mut sources = BoundSources::new();
699    for (declared, bound) in members.iter().zip(bound_members) {
700        // `archive_plan_for` builds each `ArchiveMember` with
701        // `source_path = declared.source` and `output_name = declared.install`,
702        // so these are the exact identities a correctly-projected extraction
703        // carries.
704        if bound.source_path() != declared.source || bound.output_name() != declared.install {
705            return Err(AdapterError::MapMismatch("archive bound member identity"));
706        }
707        let id = MemberId::new(declared.install.clone())
708            .map_err(|e| AdapterError::Eggup(e.to_string()))?;
709        // `insert` returns the displaced handle; declaration order and the
710        // validated projection make a duplicate `install` impossible here, and
711        // it is dropped with the map on the error paths above.
712        sources.insert(id, bound.into_open_object());
713    }
714    Ok(sources)
715}
716
717#[cfg(test)]
718mod tests {
719    use super::*;
720
721    fn direct_json() -> Vec<u8> {
722        include_bytes!("../tests/fixtures/direct-manifest.json").to_vec()
723    }
724
725    #[test]
726    fn bounded_json_projection_accepts_fixture_and_exact_limit() {
727        let fixture = direct_json();
728        assert!(fixture.len() < MAX_MANIFEST_BYTES);
729        assert!(matches!(
730            project_json(&fixture, "x86_64-unknown-linux-gnu").unwrap(),
731            ManifestProjection::Installable { .. }
732        ));
733
734        let mut at_limit = fixture;
735        at_limit.resize(MAX_MANIFEST_BYTES, b' ');
736        assert!(project_json(&at_limit, "x86_64-unknown-linux-gnu").is_ok());
737    }
738
739    #[test]
740    fn bounded_json_projection_rejects_invalid_documents_without_leaking_input() {
741        let oversized = vec![b' '; MAX_MANIFEST_BYTES + 1];
742        let invalid_utf8 = [b'{', 0xff, b'}'];
743        let malformed = br#"{"private":"https://user:super-secret@example.invalid/?token=hidden""#;
744        let unsupported: Vec<u8> = String::from_utf8(direct_json())
745            .unwrap()
746            .replace("\"schema_version\":1", "\"schema_version\":999")
747            .into_bytes();
748
749        for input in [
750            &oversized[..],
751            &invalid_utf8[..],
752            &malformed[..],
753            &unsupported[..],
754        ] {
755            let error = project_json(input, "x86_64-unknown-linux-gnu").unwrap_err();
756            assert!(matches!(error, AdapterError::InvalidManifest));
757            let diagnostic = format!("{error} {error:?}");
758            assert!(!diagnostic.contains("private"));
759            assert!(!diagnostic.contains("super-secret"));
760            assert!(!diagnostic.contains("token=hidden"));
761        }
762    }
763
764    #[test]
765    fn json_projection_keeps_exact_target_selection() {
766        let error = project_json(&direct_json(), "linux-x64").unwrap_err();
767        assert!(matches!(error, AdapterError::TargetNotFound));
768    }
769
770    #[test]
771    fn corrected_fixtures_project_and_archive_stays_separate() {
772        let direct: ReleaseManifest =
773            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
774        assert!(matches!(
775            project(&direct, "x86_64-unknown-linux-gnu").unwrap(),
776            ManifestProjection::Installable { .. }
777        ));
778        let archive: ReleaseManifest =
779            serde_json::from_str(include_str!("../tests/fixtures/archive-manifest.json")).unwrap();
780        let p = project(&archive, "x86_64-unknown-linux-gnu").unwrap();
781        assert!(matches!(p, ManifestProjection::Archive { .. }));
782        assert!(matches!(
783            p.bind_requests(HashMap::new(), FetchLimits::default()),
784            Err(AdapterError::MapMismatch(_))
785        ));
786        let b: ReleaseManifest =
787            serde_json::from_str(include_str!("../tests/fixtures/bundle-manifest.json")).unwrap();
788        assert!(
789            matches!(project(&b, "x86_64-unknown-linux-gnu").unwrap(), ManifestProjection::Installable { artifacts, .. } if artifacts.len() == 3)
790        );
791    }
792    #[test]
793    fn alias_target_is_not_resolved() {
794        let m: ReleaseManifest =
795            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
796        assert!(matches!(
797            project(&m, "linux-x64"),
798            Err(AdapterError::TargetNotFound)
799        ));
800    }
801
802    #[test]
803    fn exact_request_binding_preserves_url_and_tightens_byte_limit() {
804        let m: ReleaseManifest =
805            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
806        let p = project(&m, "x86_64-unknown-linux-gnu").unwrap();
807        let name = match &p {
808            ManifestProjection::Installable { artifacts, .. } => artifacts[0].artifact_name.clone(),
809            _ => unreachable!(),
810        };
811        let request =
812            AcquisitionRequest::new("https://user:secret@example.test/path?token=kept").unwrap();
813        let mut requests = HashMap::new();
814        requests.insert(name.clone(), request.clone());
815        let bound = p.bind_requests(requests, FetchLimits::default()).unwrap();
816        assert_eq!(bound[0].request, request);
817        assert_eq!(bound[0].limits.max_artifact_bytes, bound[0].exact_size);
818        let too_small = FetchLimits {
819            max_artifact_bytes: bound[0].exact_size - 1,
820            ..FetchLimits::default()
821        };
822        assert!(matches!(
823            p.bind_requests(HashMap::from([(name, request)]), too_small),
824            Err(AdapterError::CallerLimitTooSmall(_))
825        ));
826    }
827
828    #[test]
829    fn exact_size_and_explicit_permissions_gate_artifact_materialization() {
830        let m: ReleaseManifest =
831            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
832        let p = project(&m, "x86_64-unknown-linux-gnu").unwrap();
833        let requirement = match &p {
834            ManifestProjection::Installable { artifacts, .. } => &artifacts[0],
835            _ => unreachable!(),
836        };
837        let dir = std::env::temp_dir().join(format!("eggup-eggpack-test-{}", std::process::id()));
838        let _ = fs::remove_dir_all(&dir);
839        fs::create_dir_all(&dir).unwrap();
840        let path = dir.join("source");
841        fs::write(&path, b"abc").unwrap();
842        let acquired = HashMap::from([(requirement.artifact_name.clone(), path.clone())]);
843        let permissions =
844            HashMap::from([(requirement.member_id.clone(), PermissionsIntent::Executable)]);
845        assert!(p
846            .materialize_artifact_set(acquired.clone(), permissions.clone())
847            .is_ok());
848        fs::write(&path, b"no").unwrap();
849        assert!(matches!(
850            p.materialize_artifact_set(acquired, permissions),
851            Err(AdapterError::InvalidAcquiredFile(_))
852        ));
853        let _ = fs::remove_dir_all(dir);
854    }
855}