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    ArtifactMember, ArtifactSet, BoundSources, InstallPlan, IntegrityRequirement, MemberId,
10    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.
481pub fn validate_acquired_archive(
482    projection: &ManifestProjection,
483    acquired_archive_path: &Path,
484) -> Result<(), AdapterError> {
485    use sha2::{Digest, Sha256};
486    use std::io::Read;
487    let (artifact_name, exact_size, sha256) = match projection {
488        ManifestProjection::Archive {
489            artifact_name,
490            exact_size,
491            sha256,
492            ..
493        } => (artifact_name, *exact_size, *sha256),
494        _ => return Err(AdapterError::ArchiveExtractionRequired),
495    };
496    if !acquired_archive_path.is_absolute() {
497        return Err(AdapterError::InvalidAcquiredFile(artifact_name.clone()));
498    }
499    let meta = fs::symlink_metadata(acquired_archive_path)
500        .map_err(|_| AdapterError::InvalidAcquiredFile(artifact_name.clone()))?;
501    if !meta.file_type().is_file() || meta.len() != exact_size {
502        return Err(AdapterError::InvalidAcquiredFile(artifact_name.clone()));
503    }
504    let mut file = fs::File::open(acquired_archive_path)
505        .map_err(|_| AdapterError::InvalidAcquiredFile(artifact_name.clone()))?;
506    let mut hasher = Sha256::new();
507    let mut chunk = [0u8; 16 * 1024];
508    loop {
509        let read = file
510            .read(&mut chunk)
511            .map_err(|_| AdapterError::InvalidAcquiredFile(artifact_name.clone()))?;
512        if read == 0 {
513            break;
514        }
515        hasher.update(&chunk[..read]);
516    }
517    let digest: [u8; 32] = hasher.finalize().into();
518    if digest != sha256 {
519        return Err(AdapterError::InvalidAcquiredFile(artifact_name.clone()));
520    }
521    Ok(())
522}
523
524/// Translate `ManifestProjection::Archive` into a validated `ArchivePlan`.
525///
526/// Each declared member maps `source -> eggup_archive::ArchiveMember::source_path`
527/// and `install -> eggup_archive::ArchiveMember::output_name`. Caller-supplied
528/// `expected_size` and `expected_sha256` come from the projection so the
529/// extractor can verify bytes against the manifest during extraction.
530///
531/// The caller must already have validated the acquired archive against the
532/// manifest's exact size and SHA-256; this helper does not re-validate the
533/// archive bytes and does not perform any I/O.
534pub fn archive_plan_for(
535    projection: &ManifestProjection,
536    archive_format: ArchiveFormat,
537    acquired_archive_path: &Path,
538    limits: ArchiveLimits,
539) -> Result<ArchivePlan, AdapterError> {
540    let members = match projection {
541        ManifestProjection::Archive { members, .. } => members,
542        _ => return Err(AdapterError::ArchiveExtractionRequired),
543    };
544    let mut declared = Vec::with_capacity(members.len());
545    for m in members {
546        let member = ArchiveMember::new(
547            m.source.clone(),
548            m.install.clone(),
549            Some(m.exact_size),
550            Some(m.sha256),
551        )
552        .map_err(|e| AdapterError::Eggup(e.to_string()))?;
553        declared.push(member);
554    }
555    ArchivePlan::new(acquired_archive_path, archive_format, declared, limits)
556        .map_err(|e| AdapterError::Eggup(e.to_string()))
557}
558
559/// Build the core `InstallPlan` for an archive projection with caller-bound
560/// destinations, recording each member's advisory path as
561/// `extraction_root.join(manifest install)`.
562///
563/// The caller destination map must exactly match the projected member
564/// identities: missing, extra, or colliding destinations fail closed before
565/// any plan is returned, and invalid destinations fail through Eggup
566/// destination validation into a bounded adapter error. Archive member
567/// identity, advisory extraction source paths, and member size/digest facts
568/// remain manifest-derived while destination strings come from caller policy.
569/// `BoundSources` and the object-bound extraction handoff are unchanged: the
570/// returned plan still carries empty bound sources until the caller transfers
571/// them via `bind_archive_members`.
572///
573/// The caller is responsible for capturing `extraction_root` (typically
574/// `ExtractedArchive::root()`) before any handle-bound handoff, and for
575/// keeping the path reachable until staging no longer needs it.
576/// Advisory paths are never opened during staging when a bound handle is
577/// supplied; the path is recorded solely to satisfy
578/// `ArtifactMember::new`'s validation and to expose diagnostics.
579///
580/// Replacement authorization stays outside this helper: it records where
581/// extracted bytes should be installed and never proves control of a live
582/// destination.
583pub fn core_plan_for_archive_with_destinations(
584    projection: &ManifestProjection,
585    extraction_root: &Path,
586    destination_root: &Path,
587    destinations: HashMap<MemberId, String>,
588    permissions: HashMap<MemberId, PermissionsIntent>,
589) -> Result<InstallPlan, AdapterError> {
590    let (product, release, members) = match projection {
591        ManifestProjection::Archive {
592            product,
593            release,
594            members,
595            ..
596        } => (product, release, members),
597        _ => return Err(AdapterError::ArchiveExtractionRequired),
598    };
599    if destinations.len() != members.len() {
600        return Err(AdapterError::MapMismatch("destinations"));
601    }
602    if permissions.len() != members.len() {
603        return Err(AdapterError::MapMismatch("permissions"));
604    }
605    let mut artifacts = Vec::with_capacity(members.len());
606    for m in members {
607        let id =
608            MemberId::new(m.install.clone()).map_err(|e| AdapterError::Eggup(e.to_string()))?;
609        let destination = destinations
610            .get(&id)
611            .ok_or(AdapterError::MapMismatch("destinations"))?;
612        let advisory = extraction_root.join(&m.install);
613        let permissions_intent = permissions
614            .get(&id)
615            .copied()
616            .ok_or(AdapterError::MapMismatch("permissions"))?;
617        let member = ArtifactMember::new(id.clone(), &advisory, destination)
618            .map_err(|e| AdapterError::Eggup(e.to_string()))?
619            .with_permissions(permissions_intent)
620            .with_integrity(IntegrityRequirement::Sha256(m.sha256));
621        artifacts.push(member);
622    }
623    let mut seen = HashSet::with_capacity(artifacts.len());
624    for member in &artifacts {
625        if !seen.insert(member.destination().to_path_buf()) {
626            return Err(AdapterError::MapMismatch("destinations"));
627        }
628    }
629    let set = ArtifactSet::new(artifacts).map_err(|e| AdapterError::Eggup(e.to_string()))?;
630    InstallPlan::new(product.clone(), release.clone(), destination_root, set)
631        .map_err(|e| AdapterError::Eggup(e.to_string()))
632}
633
634/// Build the core `InstallPlan` for an archive projection, recording each
635/// member's advisory path as `extraction_root.join(member.install)`.
636///
637/// Compatibility wrapper: builds the manifest-default destination map and
638/// delegates to [`core_plan_for_archive_with_destinations`]. There is one
639/// archive plan implementation.
640///
641/// The caller is responsible for capturing `extraction_root` (typically
642/// `ExtractedArchive::root()`) before any handle-bound handoff, and for
643/// keeping the path reachable until staging no longer needs it.
644/// Advisory paths are never opened during staging when a bound handle is
645/// supplied; the path is recorded solely to satisfy
646/// `ArtifactMember::new`'s validation and to expose diagnostics.
647///
648/// The returned plan's `BoundSources` are still empty at this point; the
649/// caller transfers bound members separately via `bind_archive_members`.
650pub fn core_plan_for_archive(
651    projection: &ManifestProjection,
652    extraction_root: &Path,
653    destination_root: &Path,
654    permissions: HashMap<MemberId, PermissionsIntent>,
655) -> Result<InstallPlan, AdapterError> {
656    let destinations = projection.default_destinations()?;
657    core_plan_for_archive_with_destinations(
658        projection,
659        extraction_root,
660        destination_root,
661        destinations,
662        permissions,
663    )
664}
665
666/// Build a `BoundSources` map from the projection's archive member list and
667/// the bound members returned by `BoundExtraction::into_members()`.
668///
669/// Identity is the projection's `install` string converted into a `MemberId`;
670/// bound members are paired to the projection's archive members in declaration
671/// order. Mismatched counts fail closed.
672pub fn bind_archive_members(
673    projection: &ManifestProjection,
674    bound_members: Vec<BoundMember>,
675) -> Result<BoundSources, AdapterError> {
676    let members = match projection {
677        ManifestProjection::Archive { members, .. } => members,
678        _ => return Err(AdapterError::ArchiveExtractionRequired),
679    };
680    if members.len() != bound_members.len() {
681        return Err(AdapterError::MapMismatch("archive bound members"));
682    }
683    let mut sources = BoundSources::new();
684    for (declared, bound) in members.iter().zip(bound_members) {
685        let id = MemberId::new(declared.install.clone())
686            .map_err(|e| AdapterError::Eggup(e.to_string()))?;
687        sources.insert(id, bound.into_open_object());
688    }
689    Ok(sources)
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695
696    fn direct_json() -> Vec<u8> {
697        include_bytes!("../tests/fixtures/direct-manifest.json").to_vec()
698    }
699
700    #[test]
701    fn bounded_json_projection_accepts_fixture_and_exact_limit() {
702        let fixture = direct_json();
703        assert!(fixture.len() < MAX_MANIFEST_BYTES);
704        assert!(matches!(
705            project_json(&fixture, "x86_64-unknown-linux-gnu").unwrap(),
706            ManifestProjection::Installable { .. }
707        ));
708
709        let mut at_limit = fixture;
710        at_limit.resize(MAX_MANIFEST_BYTES, b' ');
711        assert!(project_json(&at_limit, "x86_64-unknown-linux-gnu").is_ok());
712    }
713
714    #[test]
715    fn bounded_json_projection_rejects_invalid_documents_without_leaking_input() {
716        let oversized = vec![b' '; MAX_MANIFEST_BYTES + 1];
717        let invalid_utf8 = [b'{', 0xff, b'}'];
718        let malformed = br#"{"private":"https://user:super-secret@example.invalid/?token=hidden""#;
719        let unsupported: Vec<u8> = String::from_utf8(direct_json())
720            .unwrap()
721            .replace("\"schema_version\":1", "\"schema_version\":999")
722            .into_bytes();
723
724        for input in [
725            &oversized[..],
726            &invalid_utf8[..],
727            &malformed[..],
728            &unsupported[..],
729        ] {
730            let error = project_json(input, "x86_64-unknown-linux-gnu").unwrap_err();
731            assert!(matches!(error, AdapterError::InvalidManifest));
732            let diagnostic = format!("{error} {error:?}");
733            assert!(!diagnostic.contains("private"));
734            assert!(!diagnostic.contains("super-secret"));
735            assert!(!diagnostic.contains("token=hidden"));
736        }
737    }
738
739    #[test]
740    fn json_projection_keeps_exact_target_selection() {
741        let error = project_json(&direct_json(), "linux-x64").unwrap_err();
742        assert!(matches!(error, AdapterError::TargetNotFound));
743    }
744
745    #[test]
746    fn corrected_fixtures_project_and_archive_stays_separate() {
747        let direct: ReleaseManifest =
748            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
749        assert!(matches!(
750            project(&direct, "x86_64-unknown-linux-gnu").unwrap(),
751            ManifestProjection::Installable { .. }
752        ));
753        let archive: ReleaseManifest =
754            serde_json::from_str(include_str!("../tests/fixtures/archive-manifest.json")).unwrap();
755        let p = project(&archive, "x86_64-unknown-linux-gnu").unwrap();
756        assert!(matches!(p, ManifestProjection::Archive { .. }));
757        assert!(matches!(
758            p.bind_requests(HashMap::new(), FetchLimits::default()),
759            Err(AdapterError::MapMismatch(_))
760        ));
761        let b: ReleaseManifest =
762            serde_json::from_str(include_str!("../tests/fixtures/bundle-manifest.json")).unwrap();
763        assert!(
764            matches!(project(&b, "x86_64-unknown-linux-gnu").unwrap(), ManifestProjection::Installable { artifacts, .. } if artifacts.len() == 3)
765        );
766    }
767    #[test]
768    fn alias_target_is_not_resolved() {
769        let m: ReleaseManifest =
770            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
771        assert!(matches!(
772            project(&m, "linux-x64"),
773            Err(AdapterError::TargetNotFound)
774        ));
775    }
776
777    #[test]
778    fn exact_request_binding_preserves_url_and_tightens_byte_limit() {
779        let m: ReleaseManifest =
780            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
781        let p = project(&m, "x86_64-unknown-linux-gnu").unwrap();
782        let name = match &p {
783            ManifestProjection::Installable { artifacts, .. } => artifacts[0].artifact_name.clone(),
784            _ => unreachable!(),
785        };
786        let request =
787            AcquisitionRequest::new("https://user:secret@example.test/path?token=kept").unwrap();
788        let mut requests = HashMap::new();
789        requests.insert(name.clone(), request.clone());
790        let bound = p.bind_requests(requests, FetchLimits::default()).unwrap();
791        assert_eq!(bound[0].request, request);
792        assert_eq!(bound[0].limits.max_artifact_bytes, bound[0].exact_size);
793        let too_small = FetchLimits {
794            max_artifact_bytes: bound[0].exact_size - 1,
795            ..FetchLimits::default()
796        };
797        assert!(matches!(
798            p.bind_requests(HashMap::from([(name, request)]), too_small),
799            Err(AdapterError::CallerLimitTooSmall(_))
800        ));
801    }
802
803    #[test]
804    fn exact_size_and_explicit_permissions_gate_artifact_materialization() {
805        let m: ReleaseManifest =
806            serde_json::from_str(include_str!("../tests/fixtures/direct-manifest.json")).unwrap();
807        let p = project(&m, "x86_64-unknown-linux-gnu").unwrap();
808        let requirement = match &p {
809            ManifestProjection::Installable { artifacts, .. } => &artifacts[0],
810            _ => unreachable!(),
811        };
812        let dir = std::env::temp_dir().join(format!("eggup-eggpack-test-{}", std::process::id()));
813        let _ = fs::remove_dir_all(&dir);
814        fs::create_dir_all(&dir).unwrap();
815        let path = dir.join("source");
816        fs::write(&path, b"abc").unwrap();
817        let acquired = HashMap::from([(requirement.artifact_name.clone(), path.clone())]);
818        let permissions =
819            HashMap::from([(requirement.member_id.clone(), PermissionsIntent::Executable)]);
820        assert!(p
821            .materialize_artifact_set(acquired.clone(), permissions.clone())
822            .is_ok());
823        fs::write(&path, b"no").unwrap();
824        assert!(matches!(
825            p.materialize_artifact_set(acquired, permissions),
826            Err(AdapterError::InvalidAcquiredFile(_))
827        ));
828        let _ = fs::remove_dir_all(dir);
829    }
830}