Skip to main content

eggpack_contract/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Versioned distribution contract schema for release-time tooling."]
4#![doc = ""]
5#![doc = "A `DistributionContract` describes one product's release layout once:"]
6#![doc = "target triples, platform aliases, asset file names, checksum sidecar"]
7#![doc = "names, archive members, and install names. It does not fetch releases,"]
8#![doc = "order versions, verify checksums, extract archives, generate installers,"]
9#![doc = "or become a runtime dependency of ordinary consumers."]
10
11use std::collections::{HashMap, HashSet};
12use std::fmt;
13
14/// Schema version 1. The only version understood by this crate.
15pub const SCHEMA_V1: u32 = 1;
16
17/// Maximum lengths to keep diagnostics bounded.
18const MAX_ID_LEN: usize = 64;
19const MAX_NAME_LEN: usize = 128;
20const MAX_TEMPLATE_LEN: usize = 256;
21const MAX_DETAIL_LEN: usize = 512;
22/// Maximum entries accepted in caller-supplied inventories and observations.
23pub const MAX_OBSERVED_ENTRIES: usize = 256;
24const MAX_CONFORMANCE_FINDINGS: usize = MAX_OBSERVED_ENTRIES * 2;
25
26/// Namespace in which an expanded filename collision occurred.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum NameNamespace {
29    /// Release assets and checksum sidecars share one flat namespace.
30    ReleaseFiles,
31    /// Installed filenames share one flat namespace.
32    InstallNames,
33}
34
35impl fmt::Display for NameNamespace {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::ReleaseFiles => f.write_str("release-file"),
39            Self::InstallNames => f.write_str("install-name"),
40        }
41    }
42}
43
44/// Typed distribution errors. Parsing never guesses or falls back.
45#[derive(Debug, Clone, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum DistError {
48    /// Input violates the schema contract.
49    InvalidInput(String),
50    /// The document declares an unsupported schema version.
51    UnsupportedVersion {
52        /// The declared version.
53        found: u32,
54    },
55    /// Two targets share a canonical triple.
56    DuplicateTarget(String),
57    /// An alias collides with another alias or triple.
58    DuplicateAlias(String),
59    /// No target matches the requested triple or alias.
60    UnknownTarget(String),
61    /// A template contains an unknown placeholder.
62    UnknownPlaceholder(String),
63    /// A template requires an input that was not supplied.
64    MissingInput(String),
65    /// An archive member path is unsafe.
66    InvalidMemberPath(String),
67    /// Two logical filename fields collide after portable case folding.
68    NameCollision {
69        /// The filename namespace that contains the collision.
70        namespace: NameNamespace,
71        /// Bounded logical field label; no arbitrary filename is included.
72        first: String,
73        /// Bounded logical field label; no arbitrary filename is included.
74        second: String,
75    },
76    /// A caller-supplied flat release inventory is invalid.
77    InvalidReleaseInventory(String),
78    /// A caller-supplied archive-member inventory is invalid.
79    InvalidArchiveMemberInventory(String),
80}
81
82impl DistError {
83    fn invalid(detail: impl Into<String>) -> Self {
84        Self::InvalidInput(bound(detail.into()))
85    }
86}
87
88impl fmt::Display for DistError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::InvalidInput(d) => write!(f, "invalid distribution contract: {d}"),
92            Self::UnsupportedVersion { found } => {
93                write!(f, "unsupported distribution schema version: {found}")
94            }
95            Self::DuplicateTarget(t) => write!(f, "duplicate distribution target: {t}"),
96            Self::DuplicateAlias(a) => write!(f, "duplicate distribution alias: {a}"),
97            Self::UnknownTarget(t) => write!(f, "unsupported distribution target: {t}"),
98            Self::UnknownPlaceholder(p) => {
99                write!(f, "unknown name-template placeholder: {p}")
100            }
101            Self::MissingInput(m) => write!(f, "missing template input: {m}"),
102            Self::InvalidMemberPath(p) => write!(f, "unsafe archive member path: {p}"),
103            Self::NameCollision {
104                namespace,
105                first,
106                second,
107            } => write!(
108                f,
109                "expanded {namespace} filename collision between {first} and {second}"
110            ),
111            Self::InvalidReleaseInventory(detail) => {
112                write!(f, "invalid release inventory: {detail}")
113            }
114            Self::InvalidArchiveMemberInventory(detail) => {
115                write!(f, "invalid archive member inventory: {detail}")
116            }
117        }
118    }
119}
120
121impl std::error::Error for DistError {}
122
123/// Bound a diagnostic detail to [`MAX_DETAIL_LEN`] bytes without ever
124/// splitting a multi-byte character.
125///
126/// `String::truncate` panics unless the index is a char boundary, so the
127/// byte bound is first rounded down to one. `bound` is the single chokepoint
128/// for every `DistError` construction in this crate, so a byte-bounded
129/// `truncate` here would turn any caller-supplied detail — an unknown target
130/// name, or the parser diagnostic quoting an untrusted source line — into a
131/// process abort instead of a fail-closed rejection.
132fn bound(mut s: String) -> String {
133    if s.len() > MAX_DETAIL_LEN {
134        s.truncate(char_boundary_floor(&s, MAX_DETAIL_LEN));
135    }
136    s
137}
138
139/// Largest index at or below `limit` that is a `char` boundary of `s`.
140///
141/// A UTF-8 character is at most four bytes, so this walks back at most three
142/// steps. `str::floor_char_boundary` expresses this directly but is newer than
143/// the workspace MSRV.
144fn char_boundary_floor(s: &str, limit: usize) -> usize {
145    let mut cut = limit;
146    while !s.is_char_boundary(cut) {
147        cut -= 1;
148    }
149    cut
150}
151
152/// Opaque product identity. Version semantics remain caller-owned.
153#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
154#[serde(deny_unknown_fields)]
155pub struct ProductIdentity {
156    /// Opaque product id (for example `eggsact`). Used for `{product}` expansion.
157    pub id: String,
158    /// Optional human-readable display name. Never participates in expansion.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub display_name: Option<String>,
161}
162
163/// Checksum sidecar naming. Integrity metadata only; never authenticity.
164#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
165#[serde(deny_unknown_fields)]
166pub struct ChecksumSpec {
167    /// Sidecar file-name template. May use `{product}`, `{version}`,
168    /// `{target}`, `{alias}`, and `{asset}` (the expanded asset file name).
169    pub sidecar: String,
170}
171
172/// One bundle entry: a single asset file plus its install name.
173#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
174#[serde(deny_unknown_fields)]
175pub struct BundleEntry {
176    /// Release asset file-name template (flat, no directories).
177    pub asset: String,
178    /// Install/display file-name template (flat, no directories).
179    pub install: String,
180}
181
182/// One archive member: a literal relative source path plus its install name.
183#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
184#[serde(deny_unknown_fields)]
185pub struct ArchiveMember {
186    /// Literal relative path inside the archive. No templates; must be
187    /// traversal-free (`a/b/c`, never `/abs`, `..`, or empty components).
188    pub source: String,
189    /// Install/display file-name template (flat, no directories).
190    pub install: String,
191}
192
193/// Asset layout for one target. A small tagged enum, not a generic package language.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub enum AssetForm {
196    /// One release asset corresponds to one member.
197    Direct {
198        /// Release asset file-name template.
199        asset: String,
200        /// Install file-name template.
201        install: String,
202    },
203    /// Multiple release assets together form one logical release.
204    Bundle {
205        /// Each direct asset in the bundle.
206        entries: Vec<BundleEntry>,
207    },
208    /// One release asset contains multiple required members.
209    Archive {
210        /// Archive file-name template.
211        asset: String,
212        /// Required members inside the archive.
213        members: Vec<ArchiveMember>,
214    },
215}
216
217/// One supported target entry.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct TargetEntry {
220    /// Canonical Rust target triple.
221    pub triple: String,
222    /// Zero or more consumer/platform aliases (globally unambiguous).
223    pub aliases: Vec<String>,
224    /// Asset mapping for this target.
225    pub asset: AssetForm,
226    /// Checksum sidecar naming for this target.
227    pub checksum: ChecksumSpec,
228}
229
230/// A versioned distribution contract (schema v1).
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub struct DistributionContract {
233    /// Always [`SCHEMA_V1`].
234    pub schema_version: u32,
235    /// Opaque product identity.
236    pub product: ProductIdentity,
237    /// Supported targets (non-empty, deterministic order as written).
238    pub targets: Vec<TargetEntry>,
239}
240
241// ---- Raw TOML shapes (deny unknown fields for typo safety) ----
242
243#[derive(Debug, serde::Serialize, serde::Deserialize)]
244#[serde(deny_unknown_fields)]
245struct RawContract {
246    schema_version: u32,
247    product: ProductIdentity,
248    targets: Vec<RawTarget>,
249}
250
251#[derive(Debug, serde::Serialize, serde::Deserialize)]
252#[serde(deny_unknown_fields)]
253struct RawTarget {
254    triple: String,
255    #[serde(default)]
256    aliases: Vec<String>,
257    asset: RawAsset,
258    checksum: ChecksumSpec,
259}
260
261#[derive(Debug, serde::Serialize, serde::Deserialize)]
262#[serde(deny_unknown_fields)]
263struct RawAsset {
264    kind: String,
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    asset: Option<String>,
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    install: Option<String>,
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    entries: Option<Vec<BundleEntry>>,
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    members: Option<Vec<ArchiveMember>>,
273}
274
275// ---- Parsing and validation ----
276
277impl DistributionContract {
278    /// Parses and structurally validates a TOML distribution contract.
279    ///
280    /// Returns typed validation errors; never guesses, falls back, touches
281    /// the network, or rewrites the source. Unknown future schema versions
282    /// fail with [`DistError::UnsupportedVersion`].
283    pub fn parse_toml_str(s: &str) -> Result<Self, DistError> {
284        let raw: RawContract =
285            toml::from_str(s).map_err(|e| DistError::invalid(format!("TOML parse: {e}")))?;
286        Self::from_raw(raw)
287    }
288
289    /// Serializes the contract deterministically to TOML.
290    ///
291    /// Field and target order are preserved as stored, so golden outputs are
292    /// stable for a given contract value.
293    pub fn to_toml_string(&self) -> Result<String, DistError> {
294        let raw = self.to_raw();
295        toml::to_string(&raw).map_err(|e| DistError::invalid(format!("TOML render: {e}")))
296    }
297
298    /// Resolves a canonical triple or alias to its target entry.
299    ///
300    /// Aliases are globally unambiguous; unknown inputs fail with
301    /// [`DistError::UnknownTarget`] instead of guessing a nearby architecture.
302    pub fn resolve(&self, target_or_alias: &str) -> Result<&TargetEntry, DistError> {
303        for t in &self.targets {
304            if t.triple == target_or_alias {
305                return Ok(t);
306            }
307            if t.aliases.iter().any(|a| a == target_or_alias) {
308                return Ok(t);
309            }
310        }
311        Err(DistError::UnknownTarget(bound(target_or_alias.to_string())))
312    }
313
314    /// Expands all file names for one target and opaque version string.
315    ///
316    /// `version` is opaque (no SemVer ordering) but must be portable, because
317    /// it is interpolated into release file names: `[A-Za-z0-9-_.+]` only, so
318    /// no path separator, no platform-reserved character, and nothing
319    /// `eggpack-manifest` would later refuse as an artifact file name.
320    /// `{alias}` templates require looking up via that alias; looking up via
321    /// the triple when the template needs `{alias}` fails with
322    /// [`DistError::MissingInput`]. The expanded result is rejected if any
323    /// release or install filename collides, including ASCII case-only
324    /// collisions.
325    pub fn expand(
326        &self,
327        target_or_alias: &str,
328        version: &str,
329    ) -> Result<ExpandedTarget, DistError> {
330        validate_version(version)?;
331        let target = self.resolve(target_or_alias)?;
332        // `{alias}` expands to the alias used for lookup, when the lookup was
333        // via an alias. A triple lookup leaves alias empty.
334        let alias_used: Option<&str> = if target.triple == target_or_alias {
335            None
336        } else {
337            Some(target_or_alias)
338        };
339        let ctx = ExpansionCtx {
340            product: &self.product.id,
341            version,
342            target: &target.triple,
343            alias: alias_used,
344        };
345        let assets = match &target.asset {
346            AssetForm::Direct { asset, install } => {
347                let asset_file = expand_template(asset, &ctx, None)?;
348                let install_name = expand_template(install, &ctx, None)?;
349                let sidecar_file =
350                    expand_template(&target.checksum.sidecar, &ctx, Some(&asset_file))?;
351                ExpandedAssets::Direct(ExpandedDirect {
352                    asset_file,
353                    install_name,
354                    sidecar_file,
355                })
356            }
357            AssetForm::Bundle { entries } => {
358                let mut out = Vec::with_capacity(entries.len());
359                for e in entries {
360                    let asset_file = expand_template(&e.asset, &ctx, None)?;
361                    let install_name = expand_template(&e.install, &ctx, None)?;
362                    let sidecar_file =
363                        expand_template(&target.checksum.sidecar, &ctx, Some(&asset_file))?;
364                    out.push(ExpandedDirect {
365                        asset_file,
366                        install_name,
367                        sidecar_file,
368                    });
369                }
370                ExpandedAssets::Bundle(ExpandedBundle { entries: out })
371            }
372            AssetForm::Archive { asset, members } => {
373                let archive_file = expand_template(asset, &ctx, None)?;
374                let sidecar_file =
375                    expand_template(&target.checksum.sidecar, &ctx, Some(&archive_file))?;
376                let mut expanded_members = Vec::with_capacity(members.len());
377                for m in members {
378                    let install_name = expand_template(&m.install, &ctx, None)?;
379                    expanded_members.push(ExpandedArchiveMember {
380                        source: m.source.clone(),
381                        install_name,
382                    });
383                }
384                ExpandedAssets::Archive(ExpandedArchive {
385                    archive_file,
386                    sidecar_file,
387                    members: expanded_members,
388                })
389            }
390        };
391        let expanded = ExpandedTarget {
392            triple: target.triple.clone(),
393            assets,
394        };
395        validate_expanded_names(&expanded)?;
396        Ok(expanded)
397    }
398
399    fn from_raw(raw: RawContract) -> Result<Self, DistError> {
400        if raw.schema_version != SCHEMA_V1 {
401            return Err(DistError::UnsupportedVersion {
402                found: raw.schema_version,
403            });
404        }
405        validate_product_id(&raw.product.id)?;
406        if let Some(display) = &raw.product.display_name {
407            validate_display_name(display)?;
408        }
409        if raw.targets.is_empty() {
410            return Err(DistError::invalid("contract declares no targets"));
411        }
412        let all_triples: HashSet<&str> = raw.targets.iter().map(|t| t.triple.as_str()).collect();
413        // Target triples must be unique.
414        {
415            let mut seen: HashSet<&str> = HashSet::new();
416            for t in &raw.targets {
417                if !seen.insert(t.triple.as_str()) {
418                    return Err(DistError::DuplicateTarget(bound(t.triple.clone())));
419                }
420            }
421        }
422        // Aliases must be valid, must not collide with any triple (even their
423        // own) to keep triple-vs-alias resolution unambiguous, and must not
424        // map one alias to different targets.
425        let mut alias_owner: HashMap<&str, &str> = HashMap::new();
426        for t in &raw.targets {
427            validate_triple(&t.triple)?;
428            for a in &t.aliases {
429                validate_alias(a)?;
430                if all_triples.contains(a.as_str()) {
431                    return Err(DistError::DuplicateAlias(bound(format!(
432                        "{a} collides with a target triple"
433                    ))));
434                }
435                if let Some(owner) = alias_owner.get(a.as_str()) {
436                    if *owner != t.triple.as_str() {
437                        return Err(DistError::DuplicateAlias(bound(a.clone())));
438                    }
439                } else {
440                    alias_owner.insert(a.as_str(), t.triple.as_str());
441                }
442            }
443        }
444        let mut out_targets = Vec::with_capacity(raw.targets.len());
445        for t in raw.targets {
446            let asset = convert_asset(t.asset)?;
447            validate_checksum_template(&asset, &t.checksum.sidecar)?;
448            out_targets.push(TargetEntry {
449                triple: t.triple,
450                aliases: t.aliases,
451                asset,
452                checksum: t.checksum,
453            });
454        }
455        Ok(Self {
456            schema_version: SCHEMA_V1,
457            product: raw.product,
458            targets: out_targets,
459        })
460    }
461
462    fn to_raw(&self) -> RawContract {
463        let targets = self
464            .targets
465            .iter()
466            .map(|t| {
467                let (kind, asset, install, entries, members) = match &t.asset {
468                    AssetForm::Direct { asset, install } => (
469                        "direct".to_string(),
470                        Some(asset.clone()),
471                        Some(install.clone()),
472                        None,
473                        None,
474                    ),
475                    AssetForm::Bundle { entries } => (
476                        "bundle".to_string(),
477                        None,
478                        None,
479                        Some(entries.clone()),
480                        None,
481                    ),
482                    AssetForm::Archive { asset, members } => (
483                        "archive".to_string(),
484                        Some(asset.clone()),
485                        None,
486                        None,
487                        Some(members.clone()),
488                    ),
489                };
490                RawTarget {
491                    triple: t.triple.clone(),
492                    aliases: t.aliases.clone(),
493                    asset: RawAsset {
494                        kind,
495                        asset,
496                        install,
497                        entries,
498                        members,
499                    },
500                    checksum: t.checksum.clone(),
501                }
502            })
503            .collect();
504        RawContract {
505            schema_version: self.schema_version,
506            product: self.product.clone(),
507            targets,
508        }
509    }
510}
511
512// ---- Asset conversion ----
513
514fn convert_asset(raw: RawAsset) -> Result<AssetForm, DistError> {
515    match raw.kind.as_str() {
516        "direct" => {
517            let asset = raw
518                .asset
519                .ok_or_else(|| DistError::invalid("direct asset requires `asset`"))?;
520            let install = raw
521                .install
522                .ok_or_else(|| DistError::invalid("direct asset requires `install`"))?;
523            if raw.entries.is_some() || raw.members.is_some() {
524                return Err(DistError::invalid(
525                    "direct asset must not declare `entries` or `members`",
526                ));
527            }
528            validate_file_template(&asset, false)?;
529            validate_file_template(&install, false)?;
530            Ok(AssetForm::Direct { asset, install })
531        }
532        "bundle" => {
533            let entries = raw
534                .entries
535                .ok_or_else(|| DistError::invalid("bundle asset requires `entries`"))?;
536            if raw.asset.is_some() || raw.install.is_some() || raw.members.is_some() {
537                return Err(DistError::invalid(
538                    "bundle asset must declare only `entries`",
539                ));
540            }
541            if entries.is_empty() {
542                return Err(DistError::invalid("bundle asset declares no entries"));
543            }
544            if entries.len() > 64 {
545                return Err(DistError::invalid("bundle asset declares too many entries"));
546            }
547            for e in &entries {
548                validate_file_template(&e.asset, false)?;
549                validate_file_template(&e.install, false)?;
550            }
551            ensure_unique_raw_templates(
552                NameNamespace::ReleaseFiles,
553                entries
554                    .iter()
555                    .enumerate()
556                    .map(|(i, e)| (e.asset.as_str(), format!("entries[{i}].asset"))),
557            )?;
558            ensure_unique_raw_templates(
559                NameNamespace::InstallNames,
560                entries
561                    .iter()
562                    .enumerate()
563                    .map(|(i, e)| (e.install.as_str(), format!("entries[{i}].install"))),
564            )?;
565            Ok(AssetForm::Bundle { entries })
566        }
567        "archive" => {
568            let asset = raw
569                .asset
570                .ok_or_else(|| DistError::invalid("archive asset requires `asset`"))?;
571            let members = raw
572                .members
573                .ok_or_else(|| DistError::invalid("archive asset requires `members`"))?;
574            if raw.install.is_some() || raw.entries.is_some() {
575                return Err(DistError::invalid(
576                    "archive asset must declare only `asset` and `members`",
577                ));
578            }
579            validate_file_template(&asset, false)?;
580            if members.is_empty() {
581                return Err(DistError::invalid("archive asset declares no members"));
582            }
583            if members.len() > 64 {
584                return Err(DistError::invalid(
585                    "archive asset declares too many members",
586                ));
587            }
588            // Uniqueness is keyed on the ASCII-lowercased source, matching
589            // `ArchiveMemberInventory::new` and `validate_observed_mapping`.
590            // Exact-match keying here would let a case-colliding pair parse
591            // and expand, producing members that this crate's own inventory
592            // then refuses — and that also collide on a case-insensitive
593            // filesystem at extraction.
594            let mut seen: HashSet<String> = HashSet::new();
595            for m in &members {
596                validate_member_source(&m.source)?;
597                validate_file_template(&m.install, false)?;
598                if !seen.insert(m.source.to_ascii_lowercase()) {
599                    return Err(DistError::invalid(format!(
600                        "duplicate or ASCII-case-colliding archive member: {}",
601                        m.source
602                    )));
603                }
604            }
605            ensure_unique_raw_templates(
606                NameNamespace::InstallNames,
607                members
608                    .iter()
609                    .enumerate()
610                    .map(|(i, m)| (m.install.as_str(), format!("members[{i}].install"))),
611            )?;
612            Ok(AssetForm::Archive { asset, members })
613        }
614        other => Err(DistError::invalid(format!(
615            "unknown asset kind: {other} (expected direct|bundle|archive)"
616        ))),
617    }
618}
619
620// ---- Validation helpers ----
621
622fn is_safe_name_char(c: char) -> bool {
623    c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'
624}
625
626fn validate_product_id(id: &str) -> Result<(), DistError> {
627    if id.is_empty() || id.len() > MAX_ID_LEN {
628        return Err(DistError::invalid("product id is empty or overlong"));
629    }
630    if id.chars().any(|c| c.is_control()) {
631        return Err(DistError::invalid("product id has control characters"));
632    }
633    if !id.chars().all(is_safe_name_char) {
634        return Err(DistError::invalid(
635            "product id must use [A-Za-z0-9-_.] only",
636        ));
637    }
638    if id == "." || id == ".." {
639        return Err(DistError::invalid("product id must name a product"));
640    }
641    Ok(())
642}
643
644fn validate_display_name(name: &str) -> Result<(), DistError> {
645    if name.is_empty() || name.len() > 256 {
646        return Err(DistError::invalid("display name is empty or overlong"));
647    }
648    if name.chars().any(|c| c.is_control()) {
649        return Err(DistError::invalid("display name has control characters"));
650    }
651    Ok(())
652}
653
654fn validate_triple(triple: &str) -> Result<(), DistError> {
655    if triple.is_empty() || triple.len() > MAX_NAME_LEN {
656        return Err(DistError::invalid("target triple is empty or overlong"));
657    }
658    if triple.chars().any(|c| c.is_control()) {
659        return Err(DistError::invalid("target triple has control characters"));
660    }
661    if triple.contains(['/', '\\', ' ', '@', '?', '#', ':']) {
662        return Err(DistError::invalid(
663            "target triple must be a bare triple without separators",
664        ));
665    }
666    if !triple.chars().all(is_safe_name_char) {
667        return Err(DistError::invalid(
668            "target triple must use [A-Za-z0-9-_.] only",
669        ));
670    }
671    if !triple.contains('-') {
672        return Err(DistError::invalid(
673            "target triple must contain '-' (canonical Rust triple)",
674        ));
675    }
676    Ok(())
677}
678
679fn validate_alias(alias: &str) -> Result<(), DistError> {
680    if alias.is_empty() || alias.len() > MAX_NAME_LEN {
681        return Err(DistError::invalid("alias is empty or overlong"));
682    }
683    if alias.chars().any(|c| c.is_control()) {
684        return Err(DistError::invalid("alias has control characters"));
685    }
686    if alias.contains(['/', '\\', ' ', '@', '?', '#', ':']) {
687        return Err(DistError::invalid("alias must not contain separators"));
688    }
689    if !alias.chars().all(is_safe_name_char) {
690        return Err(DistError::invalid("alias must use [A-Za-z0-9-_.] only"));
691    }
692    Ok(())
693}
694
695/// Validates the opaque release/version string.
696///
697/// Eggpack applies no SemVer semantics and no release selection to it, but it
698/// is interpolated straight into release artifact file names, so it is held to
699/// the alphabet that both sides can materialize: what `eggpack-manifest`
700/// accepts as a release name, intersected with what every supported platform
701/// (POSIX and Windows) can store on disk. `+` is admitted because SemVer build
702/// metadata (`1.2.3-rc.1+build.5`) is legitimate; `:`, `*`, `?`, `"`, `<`,
703/// `>`, `|`, spaces and path separators are not, and rejecting them here is
704/// what stops a contract that parses and expands cleanly from producing an
705/// artifact name its own manifest rejects, hours later at finalization.
706fn validate_version(version: &str) -> Result<(), DistError> {
707    if version.is_empty() || version.len() > MAX_NAME_LEN {
708        return Err(DistError::invalid(
709            "version is empty or overlong (opaque but filesystem-safe)",
710        ));
711    }
712    if version.chars().any(|c| c.is_control()) {
713        return Err(DistError::invalid("version has control characters"));
714    }
715    if !version.chars().all(|c| is_safe_name_char(c) || c == '+') {
716        return Err(DistError::invalid("version must use [A-Za-z0-9-_.+] only"));
717    }
718    Ok(())
719}
720
721/// Validates a flat file-name template (asset, install, or sidecar).
722///
723/// `allow_asset` permits the `{asset}` placeholder (checksum sidecars only).
724/// Rejects path separators, control characters, and unknown placeholders.
725/// Archive member sources are literals and validated separately.
726fn validate_file_template(template: &str, allow_asset: bool) -> Result<(), DistError> {
727    if template.is_empty() || template.len() > MAX_TEMPLATE_LEN {
728        return Err(DistError::invalid("name template is empty or overlong"));
729    }
730    if template.chars().any(|c| c.is_control()) {
731        return Err(DistError::invalid("name template has control characters"));
732    }
733    if template.contains(['/', '\\']) {
734        return Err(DistError::invalid(
735            "name template must be a flat file name without directories",
736        ));
737    }
738    parse_template(template, allow_asset)?;
739    Ok(())
740}
741
742fn validate_checksum_template(_asset: &AssetForm, sidecar: &str) -> Result<(), DistError> {
743    validate_file_template(sidecar, true)
744}
745
746/// Validates a literal archive member source path (no templates).
747fn validate_member_source(source: &str) -> Result<(), DistError> {
748    if source.is_empty() || source.len() > MAX_TEMPLATE_LEN {
749        return Err(DistError::InvalidMemberPath(bound(
750            "member path is empty or overlong".to_string(),
751        )));
752    }
753    if source.chars().any(|c| c.is_control()) {
754        return Err(DistError::InvalidMemberPath(bound(
755            "member path has control characters".to_string(),
756        )));
757    }
758    if source.contains('{') || source.contains('}') {
759        return Err(DistError::InvalidMemberPath(bound(
760            "member source must be literal (no templates)".to_string(),
761        )));
762    }
763    if source.contains('\\') {
764        return Err(DistError::InvalidMemberPath(bound(
765            "member path must use '/' separators".to_string(),
766        )));
767    }
768    if source.starts_with('/') {
769        return Err(DistError::InvalidMemberPath(bound(format!(
770            "absolute member path: {source}"
771        ))));
772    }
773    if source.contains(':') {
774        return Err(DistError::InvalidMemberPath(bound(format!(
775            "member path must not contain drive prefixes: {source}"
776        ))));
777    }
778    for comp in source.split('/') {
779        if comp.is_empty() {
780            return Err(DistError::InvalidMemberPath(bound(format!(
781                "empty member path component: {source}"
782            ))));
783        }
784        if comp == "." || comp == ".." {
785            return Err(DistError::InvalidMemberPath(bound(format!(
786                "member path escapes root: {source}"
787            ))));
788        }
789    }
790    Ok(())
791}
792
793// ---- Template expansion ----
794
795#[derive(Debug, Clone, Copy)]
796enum Placeholder {
797    Product,
798    Version,
799    Target,
800    Alias,
801    Asset,
802}
803
804enum TemplatePart<'a> {
805    Literal(&'a str),
806    Placeholder(Placeholder),
807}
808
809/// Parses the complete v1 grammar. Braces are reserved exclusively for exact
810/// placeholder names; there is no escaping, nesting, or deferred syntax.
811fn parse_template(template: &str, allow_asset: bool) -> Result<Vec<TemplatePart<'_>>, DistError> {
812    let bytes = template.as_bytes();
813    let mut parts = Vec::new();
814    let mut cursor = 0;
815    let mut i = 0;
816    while i < bytes.len() {
817        match bytes[i] {
818            b'{' => {
819                if cursor < i {
820                    parts.push(TemplatePart::Literal(&template[cursor..i]));
821                }
822                let Some(relative_end) = template[i + 1..].find('}') else {
823                    return Err(DistError::invalid(
824                        "unmatched opening brace in name template",
825                    ));
826                };
827                let end = i + 1 + relative_end;
828                let name = &template[i + 1..end];
829                if name.is_empty() {
830                    return Err(DistError::invalid("empty placeholder in name template"));
831                }
832                if name.contains(['{', '}']) {
833                    return Err(DistError::invalid("nested braces in name template"));
834                }
835                if !name.bytes().all(|b| b.is_ascii_alphanumeric()) {
836                    return Err(DistError::invalid("malformed placeholder in name template"));
837                }
838                let placeholder = match name {
839                    "product" => Placeholder::Product,
840                    "version" => Placeholder::Version,
841                    "target" => Placeholder::Target,
842                    "alias" => Placeholder::Alias,
843                    "asset" if allow_asset => Placeholder::Asset,
844                    _ => return Err(DistError::UnknownPlaceholder(bound(name.to_string()))),
845                };
846                parts.push(TemplatePart::Placeholder(placeholder));
847                i = end + 1;
848                cursor = i;
849            }
850            b'}' => return Err(DistError::invalid("stray closing brace in name template")),
851            byte => {
852                if !is_safe_name_char(char::from(byte)) {
853                    return Err(DistError::invalid(
854                        "name template literal must use [A-Za-z0-9-_.] only",
855                    ));
856                }
857                i += 1;
858            }
859        }
860    }
861    if cursor < bytes.len() {
862        parts.push(TemplatePart::Literal(&template[cursor..]));
863    }
864    Ok(parts)
865}
866
867struct ExpansionCtx<'a> {
868    product: &'a str,
869    version: &'a str,
870    target: &'a str,
871    alias: Option<&'a str>,
872}
873
874fn expand_template(
875    template: &str,
876    ctx: &ExpansionCtx<'_>,
877    asset: Option<&str>,
878) -> Result<String, DistError> {
879    let parts = parse_template(template, asset.is_some())?;
880    let mut out = String::with_capacity(template.len());
881    for part in parts {
882        match part {
883            TemplatePart::Literal(literal) => out.push_str(literal),
884            TemplatePart::Placeholder(Placeholder::Product) => out.push_str(ctx.product),
885            TemplatePart::Placeholder(Placeholder::Version) => out.push_str(ctx.version),
886            TemplatePart::Placeholder(Placeholder::Target) => out.push_str(ctx.target),
887            TemplatePart::Placeholder(Placeholder::Alias) => {
888                let alias = ctx.alias.ok_or_else(|| {
889                    DistError::MissingInput(bound(
890                        "`{alias}` requires lookup via that alias".to_string(),
891                    ))
892                })?;
893                out.push_str(alias);
894            }
895            TemplatePart::Placeholder(Placeholder::Asset) => {
896                let asset = asset.ok_or_else(|| {
897                    DistError::MissingInput(bound(
898                        "`{asset}` requires a checksum context".to_string(),
899                    ))
900                })?;
901                out.push_str(asset);
902            }
903        }
904    }
905    if out.is_empty() || out.len() > MAX_TEMPLATE_LEN {
906        return Err(DistError::invalid("expanded name is empty or overlong"));
907    }
908    if out.contains(['{', '}']) {
909        return Err(DistError::invalid("expanded name contains reserved braces"));
910    }
911    if out.contains(['/', '\\']) {
912        return Err(DistError::invalid(
913            "expanded name must remain a flat file name",
914        ));
915    }
916    Ok(out)
917}
918
919fn ensure_unique_names(
920    namespace: NameNamespace,
921    names: impl IntoIterator<Item = (String, String)>,
922) -> Result<(), DistError> {
923    let mut seen: HashMap<String, String> = HashMap::new();
924    for (name, field) in names {
925        let key = name.to_ascii_lowercase();
926        if let Some(first) = seen.get(&key) {
927            return Err(DistError::NameCollision {
928                namespace,
929                first: bound(first.clone()),
930                second: bound(field),
931            });
932        }
933        seen.insert(key, field);
934    }
935    Ok(())
936}
937
938fn ensure_unique_raw_templates<'a>(
939    namespace: NameNamespace,
940    templates: impl IntoIterator<Item = (&'a str, String)>,
941) -> Result<(), DistError> {
942    ensure_unique_names(
943        namespace,
944        templates
945            .into_iter()
946            .map(|(template, field)| (template.to_string(), field)),
947    )
948}
949
950fn validate_expanded_names(target: &ExpandedTarget) -> Result<(), DistError> {
951    let mut release_names = Vec::new();
952    let mut install_names = Vec::new();
953    match &target.assets {
954        ExpandedAssets::Direct(direct) => {
955            release_names.push((direct.asset_file.clone(), "asset_file".to_string()));
956            release_names.push((direct.sidecar_file.clone(), "sidecar_file".to_string()));
957            install_names.push((direct.install_name.clone(), "install_name".to_string()));
958        }
959        ExpandedAssets::Bundle(bundle) => {
960            for (index, entry) in bundle.entries.iter().enumerate() {
961                release_names.push((
962                    entry.asset_file.clone(),
963                    format!("entries[{index}].asset_file"),
964                ));
965                release_names.push((
966                    entry.sidecar_file.clone(),
967                    format!("entries[{index}].sidecar_file"),
968                ));
969                install_names.push((
970                    entry.install_name.clone(),
971                    format!("entries[{index}].install_name"),
972                ));
973            }
974        }
975        ExpandedAssets::Archive(archive) => {
976            release_names.push((archive.archive_file.clone(), "archive_file".to_string()));
977            release_names.push((archive.sidecar_file.clone(), "sidecar_file".to_string()));
978            for (index, member) in archive.members.iter().enumerate() {
979                install_names.push((
980                    member.install_name.clone(),
981                    format!("members[{index}].install_name"),
982                ));
983            }
984        }
985    }
986    ensure_unique_names(NameNamespace::ReleaseFiles, release_names)?;
987    ensure_unique_names(NameNamespace::InstallNames, install_names)
988}
989
990// ---- Expanded model ----
991
992/// One expanded direct asset (file, install name, and sidecar).
993#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct ExpandedDirect {
995    /// Expanded release asset file name.
996    pub asset_file: String,
997    /// Expanded install/display file name.
998    pub install_name: String,
999    /// Expanded checksum sidecar file name.
1000    pub sidecar_file: String,
1001}
1002
1003/// Expanded multi-asset bundle.
1004#[derive(Debug, Clone, PartialEq, Eq)]
1005pub struct ExpandedBundle {
1006    /// Each entry in the bundle.
1007    pub entries: Vec<ExpandedDirect>,
1008}
1009
1010/// One expanded archive member.
1011#[derive(Debug, Clone, PartialEq, Eq)]
1012pub struct ExpandedArchiveMember {
1013    /// Literal source path inside the archive.
1014    pub source: String,
1015    /// Expanded install/display file name.
1016    pub install_name: String,
1017}
1018
1019/// Expanded archive asset.
1020#[derive(Debug, Clone, PartialEq, Eq)]
1021pub struct ExpandedArchive {
1022    /// Expanded archive file name.
1023    pub archive_file: String,
1024    /// Expanded checksum sidecar file name.
1025    pub sidecar_file: String,
1026    /// Required members.
1027    pub members: Vec<ExpandedArchiveMember>,
1028}
1029
1030/// Expanded asset forms.
1031#[derive(Debug, Clone, PartialEq, Eq)]
1032pub enum ExpandedAssets {
1033    /// Single direct asset.
1034    Direct(ExpandedDirect),
1035    /// Multi-asset bundle.
1036    Bundle(ExpandedBundle),
1037    /// Archive with members.
1038    Archive(ExpandedArchive),
1039}
1040
1041/// A resolved and expanded target.
1042#[derive(Debug, Clone, PartialEq, Eq)]
1043pub struct ExpandedTarget {
1044    /// Canonical triple.
1045    pub triple: String,
1046    /// Expanded file names.
1047    pub assets: ExpandedAssets,
1048}
1049
1050/// Caller policy for observed names that the contract does not require.
1051#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1052pub enum ExtrasPolicy {
1053    /// Permit unrelated release files or archive members.
1054    #[default]
1055    AllowExtras,
1056    /// Require the observed set to contain only names declared by the contract.
1057    Exact,
1058}
1059
1060/// One required flat release file and its stable diagnostic label.
1061#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
1062pub struct ExpectedReleaseFile {
1063    /// Stable contract-field label such as `asset`, `sidecar`, or `entries[0].asset`.
1064    pub label: String,
1065    /// Exact release inventory filename.
1066    pub file_name: String,
1067}
1068
1069/// Derive the required release file names for a concrete target and version.
1070///
1071/// Target aliases are resolved using the contract's normal expansion rules.
1072/// Results are ordered by contract declaration and stable within each asset
1073/// form. This function does not inspect a release or touch the network.
1074pub fn expected_release_files(
1075    contract: &DistributionContract,
1076    target_or_alias: &str,
1077    version: &str,
1078) -> Result<Vec<ExpectedReleaseFile>, DistError> {
1079    let expanded = contract.expand(target_or_alias, version)?;
1080    let mut files = Vec::new();
1081    match expanded.assets {
1082        ExpandedAssets::Direct(direct) => {
1083            files.push(expected_file("asset", direct.asset_file));
1084            files.push(expected_file("sidecar", direct.sidecar_file));
1085        }
1086        ExpandedAssets::Bundle(bundle) => {
1087            for (index, entry) in bundle.entries.into_iter().enumerate() {
1088                files.push(expected_file(
1089                    &format!("entries[{index}].asset"),
1090                    entry.asset_file,
1091                ));
1092                files.push(expected_file(
1093                    &format!("entries[{index}].sidecar"),
1094                    entry.sidecar_file,
1095                ));
1096            }
1097        }
1098        ExpandedAssets::Archive(archive) => {
1099            files.push(expected_file("archive", archive.archive_file));
1100            files.push(expected_file("sidecar", archive.sidecar_file));
1101        }
1102    }
1103    Ok(files)
1104}
1105
1106fn expected_file(label: &str, file_name: String) -> ExpectedReleaseFile {
1107    ExpectedReleaseFile {
1108        label: label.to_string(),
1109        file_name,
1110    }
1111}
1112
1113/// Bounded, validated list of flat names supplied by a release client or fixture.
1114#[derive(Debug, Clone, PartialEq, Eq)]
1115pub struct ReleaseInventory {
1116    files: Vec<String>,
1117}
1118
1119impl ReleaseInventory {
1120    /// Construct an inventory from flat release filenames.
1121    ///
1122    /// Empty, overlong, control/separator-containing, exact-duplicate, and
1123    /// ASCII-case-colliding names are rejected. Names are sorted so reports
1124    /// do not depend on provider response order.
1125    pub fn new<I, S>(files: I) -> Result<Self, DistError>
1126    where
1127        I: IntoIterator<Item = S>,
1128        S: Into<String>,
1129    {
1130        let mut names = Vec::new();
1131        let mut seen = HashSet::new();
1132        for value in files {
1133            if names.len() == MAX_OBSERVED_ENTRIES {
1134                return Err(DistError::InvalidReleaseInventory(bound(format!(
1135                    "more than {MAX_OBSERVED_ENTRIES} entries"
1136                ))));
1137            }
1138            let name = value.into();
1139            validate_observed_flat_name(&name)
1140                .map_err(|detail| DistError::InvalidReleaseInventory(bound(detail)))?;
1141            let key = name.to_ascii_lowercase();
1142            if !seen.insert(key) {
1143                return Err(DistError::InvalidReleaseInventory(bound(format!(
1144                    "duplicate or ASCII-case-colliding filename: {name}"
1145                ))));
1146            }
1147            names.push(name);
1148        }
1149        names.sort();
1150        Ok(Self { files: names })
1151    }
1152
1153    /// The validated filenames in deterministic order.
1154    pub fn files(&self) -> &[String] {
1155        &self.files
1156    }
1157}
1158
1159fn validate_observed_flat_name(name: &str) -> Result<(), String> {
1160    if name.is_empty() || name.len() > MAX_TEMPLATE_LEN {
1161        return Err("filename is empty or overlong".to_string());
1162    }
1163    if name.chars().any(|c| c.is_control()) {
1164        return Err("filename contains control characters".to_string());
1165    }
1166    if name.contains(['/', '\\']) {
1167        return Err("filename must be flat and contain no path separators".to_string());
1168    }
1169    Ok(())
1170}
1171
1172/// Validate release completeness for an expanded target.
1173///
1174/// Required files are always errors when missing. Unrelated files are ignored
1175/// by [`ExtrasPolicy::AllowExtras`] and reported by [`ExtrasPolicy::Exact`].
1176pub fn validate_release_inventory(
1177    expected: &[ExpectedReleaseFile],
1178    observed: &ReleaseInventory,
1179    extras: ExtrasPolicy,
1180) -> ConformanceReport {
1181    if expected.len() > MAX_OBSERVED_ENTRIES
1182        || expected.iter().any(|file| {
1183            file.label.is_empty()
1184                || file.label.len() > MAX_DETAIL_LEN
1185                || validate_observed_flat_name(&file.file_name).is_err()
1186        })
1187    {
1188        return ConformanceReport::new(vec![ConformanceFinding::new(
1189            FindingKind::InvalidObservation,
1190            "expected release files",
1191            None,
1192            Some("invalid or over limit"),
1193        )]);
1194    }
1195    let mut expected_names = HashSet::new();
1196    if expected
1197        .iter()
1198        .any(|file| !expected_names.insert(file.file_name.to_ascii_lowercase()))
1199    {
1200        return ConformanceReport::new(vec![ConformanceFinding::new(
1201            FindingKind::InvalidObservation,
1202            "expected release files",
1203            None,
1204            Some("duplicate or ASCII-case-colliding expected filename"),
1205        )]);
1206    }
1207    let required: HashSet<&str> = expected.iter().map(|f| f.file_name.as_str()).collect();
1208    let observed_set: HashSet<&str> = observed.files.iter().map(String::as_str).collect();
1209    let mut findings = Vec::new();
1210    for file in expected {
1211        if !observed_set.contains(file.file_name.as_str()) {
1212            findings.push(ConformanceFinding::new(
1213                FindingKind::MissingReleaseFile,
1214                &file.label,
1215                Some(&file.file_name),
1216                None,
1217            ));
1218        }
1219    }
1220    if extras == ExtrasPolicy::Exact {
1221        for name in &observed.files {
1222            if !required.contains(name.as_str()) {
1223                findings.push(ConformanceFinding::new(
1224                    FindingKind::UnexpectedReleaseFile,
1225                    "release inventory",
1226                    None,
1227                    Some(name),
1228                ));
1229            }
1230        }
1231    }
1232    ConformanceReport::new(findings)
1233}
1234
1235/// Bounded, validated archive member paths supplied by a listing tool or fixture.
1236#[derive(Debug, Clone, PartialEq, Eq)]
1237pub struct ArchiveMemberInventory {
1238    members: Vec<String>,
1239}
1240
1241impl ArchiveMemberInventory {
1242    /// Construct an inventory from caller-supplied archive member paths.
1243    ///
1244    /// Paths use the same traversal-free, forward-slash rules as schema v1;
1245    /// exact and ASCII-case duplicates fail. Members are sorted deterministically.
1246    pub fn new<I, S>(members: I) -> Result<Self, DistError>
1247    where
1248        I: IntoIterator<Item = S>,
1249        S: Into<String>,
1250    {
1251        let mut paths = Vec::new();
1252        let mut seen = HashSet::new();
1253        for value in members {
1254            if paths.len() == MAX_OBSERVED_ENTRIES {
1255                return Err(DistError::InvalidArchiveMemberInventory(bound(format!(
1256                    "more than {MAX_OBSERVED_ENTRIES} entries"
1257                ))));
1258            }
1259            let path = value.into();
1260            validate_member_source(&path).map_err(|error| {
1261                DistError::InvalidArchiveMemberInventory(bound(error.to_string()))
1262            })?;
1263            let key = path.to_ascii_lowercase();
1264            if !seen.insert(key) {
1265                return Err(DistError::InvalidArchiveMemberInventory(bound(format!(
1266                    "duplicate or ASCII-case-colliding member path: {path}"
1267                ))));
1268            }
1269            paths.push(path);
1270        }
1271        paths.sort();
1272        Ok(Self { members: paths })
1273    }
1274
1275    /// The validated member paths in deterministic order.
1276    pub fn members(&self) -> &[String] {
1277        &self.members
1278    }
1279}
1280
1281/// Validate required archive members for an expanded archive target.
1282///
1283/// This function compares supplied names only. It never opens or extracts an archive.
1284pub fn validate_archive_member_inventory(
1285    expected: &ExpandedTarget,
1286    observed: &ArchiveMemberInventory,
1287    extras: ExtrasPolicy,
1288) -> Result<ConformanceReport, DistError> {
1289    let ExpandedAssets::Archive(archive) = &expected.assets else {
1290        return Err(DistError::invalid(
1291            "archive member validation requires an archive target",
1292        ));
1293    };
1294    if archive.members.len() > MAX_OBSERVED_ENTRIES
1295        || archive
1296            .members
1297            .iter()
1298            .any(|member| validate_member_source(&member.source).is_err())
1299    {
1300        return Ok(ConformanceReport::new(vec![ConformanceFinding::new(
1301            FindingKind::InvalidObservation,
1302            "expected archive members",
1303            None,
1304            Some("invalid or over limit"),
1305        )]));
1306    }
1307    let required: HashSet<&str> = archive.members.iter().map(|m| m.source.as_str()).collect();
1308    let observed_set: HashSet<&str> = observed.members.iter().map(String::as_str).collect();
1309    let mut findings = Vec::new();
1310    for member in &archive.members {
1311        if !observed_set.contains(member.source.as_str()) {
1312            findings.push(ConformanceFinding::new(
1313                FindingKind::MissingArchiveMember,
1314                &member.source,
1315                Some(&member.source),
1316                None,
1317            ));
1318        }
1319    }
1320    if extras == ExtrasPolicy::Exact {
1321        for path in &observed.members {
1322            if !required.contains(path.as_str()) {
1323                findings.push(ConformanceFinding::new(
1324                    FindingKind::UnexpectedArchiveMember,
1325                    "archive inventory",
1326                    None,
1327                    Some(path),
1328                ));
1329            }
1330        }
1331    }
1332    Ok(ConformanceReport::new(findings))
1333}
1334
1335/// One observed direct asset mapping reported by consumer-owned runtime/bootstrap tests.
1336#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1337#[serde(deny_unknown_fields)]
1338pub struct ObservedDirectMapping {
1339    /// Release asset filename selected by the consumer.
1340    pub asset_file: String,
1341    /// Checksum sidecar filename selected by the consumer.
1342    pub sidecar_file: String,
1343    /// Installed filename selected by the consumer.
1344    pub install_name: String,
1345}
1346
1347/// One observed archive-member-to-install-name mapping.
1348#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1349#[serde(deny_unknown_fields)]
1350pub struct ObservedArchiveMapping {
1351    /// Member path selected by the consumer.
1352    pub source: String,
1353    /// Installed filename selected by the consumer.
1354    pub install_name: String,
1355}
1356
1357/// Consumer-observed release layout for one target.
1358#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1359#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1360pub enum ObservedTargetAssets {
1361    /// One direct asset.
1362    Direct(ObservedDirectMapping),
1363    /// Several direct assets forming one logical release.
1364    Bundle {
1365        /// Observed entries.
1366        entries: Vec<ObservedDirectMapping>,
1367    },
1368    /// One archive and its required member mappings.
1369    Archive {
1370        /// Archive filename selected by the consumer.
1371        archive_file: String,
1372        /// Checksum sidecar filename selected by the consumer.
1373        sidecar_file: String,
1374        /// Observed member mappings.
1375        members: Vec<ObservedArchiveMapping>,
1376    },
1377}
1378
1379/// Machine-readable mapping facts extracted by consumer-owned tests or tooling.
1380///
1381/// This type deliberately contains no URLs, version policy, commands, privileges,
1382/// scripts, or service behavior. It can be serialized as TOML by a consumer;
1383/// Eggpack compares the data and does not parse consumer source code.
1384#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1385#[serde(deny_unknown_fields)]
1386pub struct ObservedTargetMapping {
1387    /// Target triple or alias the consumer claims to use.
1388    pub target: String,
1389    /// Canonical triple the consumer claims that target resolved to.
1390    pub canonical_target: String,
1391    /// Observed file/install mapping.
1392    pub assets: ObservedTargetAssets,
1393}
1394
1395/// Stable kind for one conformance finding.
1396#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
1397#[serde(rename_all = "snake_case")]
1398pub enum FindingKind {
1399    /// A required release filename was absent.
1400    MissingReleaseFile,
1401    /// Exact release-set validation found an unrelated filename.
1402    UnexpectedReleaseFile,
1403    /// Target resolution or canonical target differed.
1404    TargetMismatch,
1405    /// Release asset filenames differed.
1406    AssetMismatch,
1407    /// Checksum sidecar filenames differed.
1408    SidecarMismatch,
1409    /// Install filenames differed.
1410    InstallNameMismatch,
1411    /// A required archive member path was absent.
1412    MissingArchiveMember,
1413    /// Exact archive-set validation found an undeclared member path.
1414    UnexpectedArchiveMember,
1415    /// An archive member/install-name pair differed.
1416    ArchiveMappingMismatch,
1417    /// Observed mapping data violated an input bound or path/name rule.
1418    InvalidObservation,
1419}
1420
1421/// One deterministic conformance finding with bounded expected/observed values.
1422#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
1423pub struct ConformanceFinding {
1424    /// Finding category.
1425    pub kind: FindingKind,
1426    /// Stable logical label or inventory category.
1427    pub label: String,
1428    /// Expected value, when applicable.
1429    pub expected: Option<String>,
1430    /// Observed value, when applicable.
1431    pub observed: Option<String>,
1432}
1433
1434impl ConformanceFinding {
1435    fn new(kind: FindingKind, label: &str, expected: Option<&str>, observed: Option<&str>) -> Self {
1436        Self {
1437            kind,
1438            label: bound(label.to_string()),
1439            expected: expected.map(|value| bound(value.to_string())),
1440            observed: observed.map(|value| bound(value.to_string())),
1441        }
1442    }
1443}
1444
1445/// Deterministic, bounded result of a conformance check.
1446#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
1447pub struct ConformanceReport {
1448    /// Findings sorted by kind, label, expected value, then observed value.
1449    pub findings: Vec<ConformanceFinding>,
1450    /// True if findings were omitted at the report bound.
1451    pub truncated: bool,
1452}
1453
1454impl ConformanceReport {
1455    fn new(mut findings: Vec<ConformanceFinding>) -> Self {
1456        findings.sort();
1457        let truncated = findings.len() > MAX_CONFORMANCE_FINDINGS;
1458        findings.truncate(MAX_CONFORMANCE_FINDINGS);
1459        Self {
1460            findings,
1461            truncated,
1462        }
1463    }
1464
1465    /// Whether no conformance mismatch was found.
1466    pub fn is_conformant(&self) -> bool {
1467        self.findings.is_empty()
1468    }
1469
1470    /// Return success for a conformant report, otherwise return the report itself.
1471    pub fn into_result(self) -> Result<(), Self> {
1472        if self.is_conformant() {
1473            Ok(())
1474        } else {
1475            Err(self)
1476        }
1477    }
1478}
1479
1480/// Compare consumer-observed target facts against one contract expansion.
1481///
1482/// `target` may be a canonical triple or declared alias. Aliases are resolved
1483/// by the contract with no nearest-target fallback. Observation collections
1484/// and every reported value are bounded; malformed observations produce a
1485/// structured `InvalidObservation` finding.
1486pub fn validate_observed_mapping(
1487    contract: &DistributionContract,
1488    version: &str,
1489    observed: &ObservedTargetMapping,
1490) -> ConformanceReport {
1491    if !valid_observation(observed) {
1492        return ConformanceReport::new(vec![ConformanceFinding::new(
1493            FindingKind::InvalidObservation,
1494            "observation",
1495            None,
1496            Some("invalid or over limit"),
1497        )]);
1498    }
1499    let expected = match contract.expand(&observed.target, version) {
1500        Ok(expanded) => expanded,
1501        // Only an unresolvable target or alias is a target mismatch.
1502        Err(DistError::UnknownTarget(_)) => {
1503            return ConformanceReport::new(vec![ConformanceFinding::new(
1504                FindingKind::TargetMismatch,
1505                "target",
1506                Some("declared target or alias"),
1507                Some(&observed.target),
1508            )]);
1509        }
1510        // Every other expansion failure is a fault in the comparison's own
1511        // inputs — an unusable release id, an `{alias}` template looked up by
1512        // triple, a template or collision problem — not in the observed
1513        // target. Reporting it as a target mismatch would send the operator
1514        // after the target when the cause is elsewhere.
1515        Err(error) => {
1516            return ConformanceReport::new(vec![ConformanceFinding::new(
1517                FindingKind::InvalidObservation,
1518                "expansion",
1519                Some(version),
1520                Some(&error.to_string()),
1521            )]);
1522        }
1523    };
1524    let mut findings = Vec::new();
1525    if expected.triple != observed.canonical_target {
1526        findings.push(ConformanceFinding::new(
1527            FindingKind::TargetMismatch,
1528            "canonical target",
1529            Some(&expected.triple),
1530            Some(&observed.canonical_target),
1531        ));
1532    }
1533    compare_observed_assets(&expected.assets, &observed.assets, &mut findings);
1534    ConformanceReport::new(findings)
1535}
1536
1537fn valid_observation(observed: &ObservedTargetMapping) -> bool {
1538    if observed.target.is_empty()
1539        || observed.target.len() > MAX_NAME_LEN
1540        || observed.canonical_target.is_empty()
1541        || observed.canonical_target.len() > MAX_NAME_LEN
1542        || observed.target.chars().any(char::is_control)
1543        || observed.canonical_target.chars().any(char::is_control)
1544    {
1545        return false;
1546    }
1547    let mut count = 0usize;
1548    let valid_names = |count: &mut usize, names: &[&str]| {
1549        *count = (*count).saturating_add(names.len());
1550        *count <= MAX_OBSERVED_ENTRIES
1551            && names
1552                .iter()
1553                .all(|name| validate_observed_flat_name(name).is_ok())
1554    };
1555    match &observed.assets {
1556        ObservedTargetAssets::Direct(entry) => {
1557            valid_names(
1558                &mut count,
1559                &[&entry.asset_file, &entry.sidecar_file, &entry.install_name],
1560            ) && unique_ascii_names(&[&entry.asset_file, &entry.sidecar_file])
1561        }
1562        ObservedTargetAssets::Bundle { entries } => {
1563            let fields_valid = entries.iter().all(|entry| {
1564                valid_names(
1565                    &mut count,
1566                    &[&entry.asset_file, &entry.sidecar_file, &entry.install_name],
1567                )
1568            });
1569            let release_files: Vec<&str> = entries
1570                .iter()
1571                .flat_map(|entry| [&entry.asset_file[..], &entry.sidecar_file[..]])
1572                .collect();
1573            fields_valid && unique_ascii_names(&release_files)
1574        }
1575        ObservedTargetAssets::Archive {
1576            archive_file,
1577            sidecar_file,
1578            members,
1579        } => {
1580            if !valid_names(&mut count, &[archive_file, sidecar_file]) {
1581                return false;
1582            }
1583            let mut seen = HashSet::new();
1584            let fields_valid = members.iter().all(|member| {
1585                count = count.saturating_add(2);
1586                count <= MAX_OBSERVED_ENTRIES
1587                    && validate_member_source(&member.source).is_ok()
1588                    && validate_observed_flat_name(&member.install_name).is_ok()
1589                    && seen.insert(member.source.to_ascii_lowercase())
1590            });
1591            fields_valid && unique_ascii_names(&[archive_file, sidecar_file])
1592        }
1593    }
1594}
1595
1596fn unique_ascii_names(names: &[&str]) -> bool {
1597    let mut seen = HashSet::new();
1598    names
1599        .iter()
1600        .all(|name| seen.insert(name.to_ascii_lowercase()))
1601}
1602
1603fn compare_observed_assets(
1604    expected: &ExpandedAssets,
1605    observed: &ObservedTargetAssets,
1606    findings: &mut Vec<ConformanceFinding>,
1607) {
1608    match (expected, observed) {
1609        (ExpandedAssets::Direct(expected), ObservedTargetAssets::Direct(observed)) => {
1610            compare_names(
1611                FindingKind::AssetMismatch,
1612                "asset",
1613                &[expected.asset_file.as_str()],
1614                &[observed.asset_file.as_str()],
1615                findings,
1616            );
1617            compare_names(
1618                FindingKind::SidecarMismatch,
1619                "sidecar",
1620                &[expected.sidecar_file.as_str()],
1621                &[observed.sidecar_file.as_str()],
1622                findings,
1623            );
1624            compare_names(
1625                FindingKind::InstallNameMismatch,
1626                "install",
1627                &[expected.install_name.as_str()],
1628                &[observed.install_name.as_str()],
1629                findings,
1630            );
1631        }
1632        (ExpandedAssets::Bundle(expected), ObservedTargetAssets::Bundle { entries }) => {
1633            let mut expected = expected.entries.iter().collect::<Vec<_>>();
1634            let mut observed = entries.iter().collect::<Vec<_>>();
1635            expected.sort_by(|a, b| a.asset_file.cmp(&b.asset_file));
1636            observed.sort_by(|a, b| a.asset_file.cmp(&b.asset_file));
1637            for (index, (expected, observed)) in expected.iter().zip(observed.iter()).enumerate() {
1638                let label = format!("bundle entries[{index}]");
1639                compare_names(
1640                    FindingKind::AssetMismatch,
1641                    &format!("{label} asset"),
1642                    &[expected.asset_file.as_str()],
1643                    &[observed.asset_file.as_str()],
1644                    findings,
1645                );
1646                compare_names(
1647                    FindingKind::SidecarMismatch,
1648                    &format!("{label} sidecar"),
1649                    &[expected.sidecar_file.as_str()],
1650                    &[observed.sidecar_file.as_str()],
1651                    findings,
1652                );
1653                compare_names(
1654                    FindingKind::InstallNameMismatch,
1655                    &format!("{label} install"),
1656                    &[expected.install_name.as_str()],
1657                    &[observed.install_name.as_str()],
1658                    findings,
1659                );
1660            }
1661            if expected.len() != observed.len() {
1662                let expected_assets = expected
1663                    .iter()
1664                    .map(|entry| entry.asset_file.as_str())
1665                    .collect::<Vec<_>>();
1666                let observed_assets = observed
1667                    .iter()
1668                    .map(|entry| entry.asset_file.as_str())
1669                    .collect::<Vec<_>>();
1670                compare_names(
1671                    FindingKind::AssetMismatch,
1672                    "bundle entry count",
1673                    &expected_assets,
1674                    &observed_assets,
1675                    findings,
1676                );
1677            }
1678        }
1679        (
1680            ExpandedAssets::Archive(expected),
1681            ObservedTargetAssets::Archive {
1682                archive_file,
1683                sidecar_file,
1684                members,
1685            },
1686        ) => {
1687            compare_names(
1688                FindingKind::AssetMismatch,
1689                "archive asset",
1690                &[expected.archive_file.as_str()],
1691                &[archive_file.as_str()],
1692                findings,
1693            );
1694            compare_names(
1695                FindingKind::SidecarMismatch,
1696                "archive sidecar",
1697                &[expected.sidecar_file.as_str()],
1698                &[sidecar_file.as_str()],
1699                findings,
1700            );
1701            let expected_members: HashMap<&str, &str> = expected
1702                .members
1703                .iter()
1704                .map(|member| (member.source.as_str(), member.install_name.as_str()))
1705                .collect();
1706            let observed_members: HashMap<&str, &str> = members
1707                .iter()
1708                .map(|member| (member.source.as_str(), member.install_name.as_str()))
1709                .collect();
1710            let mut sources: Vec<&str> = expected_members
1711                .keys()
1712                .chain(observed_members.keys())
1713                .copied()
1714                .collect();
1715            sources.sort_unstable();
1716            sources.dedup();
1717            for source in sources {
1718                let expected_install = expected_members.get(source).copied();
1719                let observed_install = observed_members.get(source).copied();
1720                if expected_install != observed_install {
1721                    findings.push(ConformanceFinding::new(
1722                        FindingKind::ArchiveMappingMismatch,
1723                        source,
1724                        expected_install,
1725                        observed_install,
1726                    ));
1727                }
1728            }
1729        }
1730        (expected, observed) => findings.push(ConformanceFinding::new(
1731            FindingKind::AssetMismatch,
1732            "asset form",
1733            Some(asset_form_name(expected)),
1734            Some(observed_form_name(observed)),
1735        )),
1736    }
1737}
1738
1739fn compare_names(
1740    kind: FindingKind,
1741    label: &str,
1742    expected: &[&str],
1743    observed: &[&str],
1744    findings: &mut Vec<ConformanceFinding>,
1745) {
1746    let mut expected = expected.to_vec();
1747    let mut observed = observed.to_vec();
1748    expected.sort();
1749    observed.sort();
1750    for index in 0..expected.len().max(observed.len()) {
1751        let expected_value = expected.get(index).copied();
1752        let observed_value = observed.get(index).copied();
1753        if expected_value != observed_value {
1754            findings.push(ConformanceFinding::new(
1755                kind,
1756                label,
1757                expected_value,
1758                observed_value,
1759            ));
1760        }
1761    }
1762}
1763
1764fn asset_form_name(assets: &ExpandedAssets) -> &'static str {
1765    match assets {
1766        ExpandedAssets::Direct(_) => "direct",
1767        ExpandedAssets::Bundle(_) => "bundle",
1768        ExpandedAssets::Archive(_) => "archive",
1769    }
1770}
1771
1772fn observed_form_name(assets: &ObservedTargetAssets) -> &'static str {
1773    match assets {
1774        ObservedTargetAssets::Direct(_) => "direct",
1775        ObservedTargetAssets::Bundle { .. } => "bundle",
1776        ObservedTargetAssets::Archive { .. } => "archive",
1777    }
1778}
1779
1780#[cfg(test)]
1781mod tests {
1782    use super::*;
1783
1784    const SIMPLE: &str = r#"
1785schema_version = 1
1786
1787[product]
1788id = "eggsact"
1789
1790[[targets]]
1791triple = "x86_64-unknown-linux-gnu"
1792aliases = ["linux-x64"]
1793
1794[targets.asset]
1795kind = "direct"
1796asset = "{product}-{version}-{target}"
1797install = "{product}"
1798
1799[targets.checksum]
1800sidecar = "{asset}.sha256"
1801"#;
1802
1803    const BUNDLE: &str = r#"
1804schema_version = 1
1805
1806[product]
1807id = "codegg"
1808
1809[[targets]]
1810triple = "x86_64-unknown-linux-gnu"
1811aliases = []
1812
1813[targets.asset]
1814kind = "bundle"
1815
1816[[targets.asset.entries]]
1817asset = "{product}-{version}-{target}"
1818install = "{product}"
1819
1820[[targets.asset.entries]]
1821asset = "{product}-helper-{version}-{target}"
1822install = "{product}-helper"
1823
1824[[targets.asset.entries]]
1825asset = "{product}-manifest-{version}.json"
1826install = "{product}-manifest.json"
1827
1828[targets.checksum]
1829sidecar = "{asset}.sha256"
1830"#;
1831
1832    const ARCHIVE: &str = r#"
1833schema_version = 1
1834
1835[product]
1836id = "egress"
1837
1838[[targets]]
1839triple = "aarch64-apple-darwin"
1840aliases = ["macos-arm64"]
1841
1842[targets.asset]
1843kind = "archive"
1844asset = "{product}-{version}-{target}.tar.gz"
1845
1846[[targets.asset.members]]
1847source = "egress"
1848install = "egress"
1849
1850[[targets.asset.members]]
1851source = "bin/egress-helper"
1852install = "egress-helper"
1853
1854[targets.checksum]
1855sidecar = "{asset}.sha256"
1856"#;
1857
1858    fn bundle_with(
1859        asset0: &str,
1860        asset1: &str,
1861        install0: &str,
1862        install1: &str,
1863        sidecar: &str,
1864    ) -> Result<DistributionContract, DistError> {
1865        let source = BUNDLE
1866            .replacen(
1867                "asset = \"{product}-{version}-{target}\"",
1868                &format!("asset = \"{asset0}\""),
1869                1,
1870            )
1871            .replacen(
1872                "asset = \"{product}-helper-{version}-{target}\"",
1873                &format!("asset = \"{asset1}\""),
1874                1,
1875            )
1876            .replacen(
1877                "install = \"{product}\"",
1878                &format!("install = \"{install0}\""),
1879                1,
1880            )
1881            .replacen(
1882                "install = \"{product}-helper\"",
1883                &format!("install = \"{install1}\""),
1884                1,
1885            )
1886            .replace(
1887                "sidecar = \"{asset}.sha256\"",
1888                &format!("sidecar = \"{sidecar}\""),
1889            );
1890        DistributionContract::parse_toml_str(&source)
1891    }
1892
1893    fn archive_with(install0: &str, install1: &str) -> Result<DistributionContract, DistError> {
1894        let source = ARCHIVE
1895            .replacen(
1896                "install = \"egress\"",
1897                &format!("install = \"{install0}\""),
1898                1,
1899            )
1900            .replacen(
1901                "install = \"egress-helper\"",
1902                &format!("install = \"{install1}\""),
1903                1,
1904            );
1905        DistributionContract::parse_toml_str(&source)
1906    }
1907
1908    #[test]
1909    fn parse_minimal_valid_v1() {
1910        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
1911        assert_eq!(c.schema_version, 1);
1912        assert_eq!(c.product.id, "eggsact");
1913        assert_eq!(c.targets.len(), 1);
1914    }
1915
1916    #[test]
1917    fn unknown_schema_version_fails_typed() {
1918        let s = SIMPLE.replace("schema_version = 1", "schema_version = 2");
1919        let err = DistributionContract::parse_toml_str(&s).unwrap_err();
1920        assert!(matches!(err, DistError::UnsupportedVersion { found: 2 }));
1921    }
1922
1923    #[test]
1924    fn duplicate_target_is_rejected() {
1925        let s = format!("{SIMPLE}\n[[targets]]\ntriple = \"x86_64-unknown-linux-gnu\"\n[targets.asset]\nkind = \"direct\"\nasset = \"a\"\ninstall = \"b\"\n[targets.checksum]\nsidecar = \"{{asset}}.sha256\"\n");
1926        let err = DistributionContract::parse_toml_str(&s).unwrap_err();
1927        assert!(matches!(err, DistError::DuplicateTarget(_)));
1928    }
1929
1930    #[test]
1931    fn duplicate_alias_is_rejected() {
1932        let s = r#"
1933schema_version = 1
1934[product]
1935id = "p"
1936[[targets]]
1937triple = "x86_64-unknown-linux-gnu"
1938aliases = ["same"]
1939[targets.asset]
1940kind = "direct"
1941asset = "a"
1942install = "b"
1943[targets.checksum]
1944sidecar = "{asset}.sha256"
1945[[targets]]
1946triple = "aarch64-apple-darwin"
1947aliases = ["same"]
1948[targets.asset]
1949kind = "direct"
1950asset = "a"
1951install = "b"
1952[targets.checksum]
1953sidecar = "{asset}.sha256"
1954"#;
1955        let err = DistributionContract::parse_toml_str(s).unwrap_err();
1956        assert!(matches!(err, DistError::DuplicateAlias(_)));
1957    }
1958
1959    #[test]
1960    fn alias_colliding_with_triple_is_rejected() {
1961        let s = r#"
1962schema_version = 1
1963[product]
1964id = "p"
1965[[targets]]
1966triple = "x86_64-unknown-linux-gnu"
1967aliases = ["aarch64-apple-darwin"]
1968[targets.asset]
1969kind = "direct"
1970asset = "a"
1971install = "b"
1972[targets.checksum]
1973sidecar = "{asset}.sha256"
1974[[targets]]
1975triple = "aarch64-apple-darwin"
1976aliases = []
1977[targets.asset]
1978kind = "direct"
1979asset = "a"
1980install = "b"
1981[targets.checksum]
1982sidecar = "{asset}.sha256"
1983"#;
1984        let err = DistributionContract::parse_toml_str(s).unwrap_err();
1985        assert!(matches!(err, DistError::DuplicateAlias(_)));
1986    }
1987
1988    #[test]
1989    fn unsupported_target_lookup_fails_without_guessing() {
1990        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
1991        let err = c.resolve("riscv64-unknown-linux-gnu").unwrap_err();
1992        assert!(matches!(err, DistError::UnknownTarget(_)));
1993        // Alias lookup works; wrong alias does not guess.
1994        assert!(c.resolve("linux-x64").is_ok());
1995        assert!(c.resolve("linux-arm64").is_err());
1996    }
1997
1998    #[test]
1999    fn bound_never_splits_a_character_or_panics() {
2000        // `bound` is the single chokepoint for every `DistError`, so a byte
2001        // bound applied with `String::truncate` would abort the process on any
2002        // caller-supplied detail that straddles the boundary.
2003        // `MAX_DETAIL_LEN - 1` and `MAX_DETAIL_LEN` place the byte bound
2004        // inside the two-byte character, which is where a byte-indexed
2005        // `truncate` panics.
2006        for padding in [
2007            MAX_DETAIL_LEN - 1,
2008            MAX_DETAIL_LEN,
2009            MAX_DETAIL_LEN + 5,
2010            MAX_DETAIL_LEN * 3,
2011        ] {
2012            let detail = format!("{}é", "x".repeat(padding));
2013            assert!(
2014                detail.len() > MAX_DETAIL_LEN,
2015                "fixture must exceed the bound"
2016            );
2017            let bounded = bound(detail.clone());
2018            assert!(bounded.len() <= MAX_DETAIL_LEN, "bound is not a byte bound");
2019            assert!(detail.starts_with(&bounded), "bound must be a prefix");
2020            let rendered = DistError::invalid(detail).to_string();
2021            assert!(rendered.starts_with("invalid distribution contract: "));
2022        }
2023        // The reachable path: an unknown target name is caller-supplied.
2024        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
2025        let unknown = format!("{}é", "riscv64-unknown-linux-gnu-".repeat(12));
2026        assert!(c.resolve(&unknown).is_err());
2027    }
2028
2029    #[test]
2030    fn unknown_placeholder_is_rejected() {
2031        let s = SIMPLE.replace("{product}-{version}-{target}", "{product}-{env}-x");
2032        let err = DistributionContract::parse_toml_str(&s).unwrap_err();
2033        assert!(matches!(err, DistError::UnknownPlaceholder(_)));
2034    }
2035
2036    #[test]
2037    fn malformed_template_grammar_is_rejected_during_parse() {
2038        for bad in [
2039            "{product",
2040            "product}",
2041            "{}",
2042            "{product{version}}",
2043            "{ bad}",
2044            "{{product}}",
2045            "file name",
2046            "{asset}",
2047        ] {
2048            let source = SIMPLE.replace(
2049                "asset = \"{product}-{version}-{target}\"",
2050                &format!("asset = \"{bad}\""),
2051            );
2052            assert!(
2053                DistributionContract::parse_toml_str(&source).is_err(),
2054                "accepted malformed template {bad:?}"
2055            );
2056        }
2057    }
2058
2059    #[test]
2060    fn repeated_known_placeholders_remain_valid() {
2061        let source = SIMPLE.replace(
2062            "asset = \"{product}-{version}-{target}\"",
2063            "asset = \"{product}-{product}-{version}\"",
2064        );
2065        let contract = DistributionContract::parse_toml_str(&source).unwrap();
2066        let expanded = contract
2067            .expand("x86_64-unknown-linux-gnu", "1.2.3")
2068            .unwrap();
2069        match expanded.assets {
2070            ExpandedAssets::Direct(direct) => {
2071                assert_eq!(direct.asset_file, "eggsact-eggsact-1.2.3")
2072            }
2073            _ => panic!("expected direct"),
2074        }
2075    }
2076
2077    #[test]
2078    fn bundle_expansion_rejects_release_asset_and_sidecar_collisions() {
2079        let contract = bundle_with("same", "same", "app", "helper", "{asset}.sha256")
2080            .expect_err("identical raw assets should fail early");
2081        assert!(matches!(
2082            contract,
2083            DistError::NameCollision {
2084                namespace: NameNamespace::ReleaseFiles,
2085                ..
2086            }
2087        ));
2088
2089        let contract =
2090            bundle_with("{version}", "1.2.3", "app", "helper", "{asset}.sha256").unwrap();
2091        assert!(matches!(
2092            contract.expand("x86_64-unknown-linux-gnu", "1.2.3"),
2093            Err(DistError::NameCollision {
2094                namespace: NameNamespace::ReleaseFiles,
2095                ..
2096            })
2097        ));
2098
2099        let contract = bundle_with("one", "two", "app", "helper", "constant.sha256").unwrap();
2100        assert!(matches!(
2101            contract.expand("x86_64-unknown-linux-gnu", "1.2.3"),
2102            Err(DistError::NameCollision {
2103                namespace: NameNamespace::ReleaseFiles,
2104                ..
2105            })
2106        ));
2107
2108        let contract = bundle_with("first", "second", "app", "helper", "first").unwrap();
2109        assert!(matches!(
2110            contract.expand("x86_64-unknown-linux-gnu", "1.2.3"),
2111            Err(DistError::NameCollision {
2112                namespace: NameNamespace::ReleaseFiles,
2113                ..
2114            })
2115        ));
2116    }
2117
2118    #[test]
2119    fn direct_and_archive_asset_sidecar_collisions_are_rejected() {
2120        let direct = SIMPLE.replace(
2121            "sidecar = \"{asset}.sha256\"",
2122            "sidecar = \"{product}-{version}-{target}\"",
2123        );
2124        let contract = DistributionContract::parse_toml_str(&direct).unwrap();
2125        assert!(matches!(
2126            contract.expand("x86_64-unknown-linux-gnu", "1.2.3"),
2127            Err(DistError::NameCollision {
2128                namespace: NameNamespace::ReleaseFiles,
2129                ..
2130            })
2131        ));
2132
2133        let archive = ARCHIVE.replace("sidecar = \"{asset}.sha256\"", "sidecar = \"{asset}\"");
2134        let contract = DistributionContract::parse_toml_str(&archive).unwrap();
2135        assert!(matches!(
2136            contract.expand("aarch64-apple-darwin", "1.2.3"),
2137            Err(DistError::NameCollision {
2138                namespace: NameNamespace::ReleaseFiles,
2139                ..
2140            })
2141        ));
2142    }
2143
2144    #[test]
2145    fn bundle_and_archive_install_names_must_be_unique_and_portable() {
2146        let contract = bundle_with("one", "two", "same", "same", "{asset}.sha256")
2147            .expect_err("identical raw install names should fail early");
2148        assert!(matches!(
2149            contract,
2150            DistError::NameCollision {
2151                namespace: NameNamespace::InstallNames,
2152                ..
2153            }
2154        ));
2155
2156        let contract = bundle_with("one", "two", "App", "app", "{asset}.sha256")
2157            .expect_err("ASCII case-only raw install names should fail early");
2158        assert!(matches!(
2159            contract,
2160            DistError::NameCollision {
2161                namespace: NameNamespace::InstallNames,
2162                ..
2163            }
2164        ));
2165
2166        let contract = bundle_with("one", "two", "{version}", "APP", "{asset}.sha256").unwrap();
2167        assert!(matches!(
2168            contract.expand("x86_64-unknown-linux-gnu", "app"),
2169            Err(DistError::NameCollision {
2170                namespace: NameNamespace::InstallNames,
2171                ..
2172            })
2173        ));
2174
2175        let contract = bundle_with(
2176            "one",
2177            "two",
2178            "member-{version}",
2179            "member-1.2.3",
2180            "{asset}.sha256",
2181        )
2182        .unwrap();
2183        assert!(matches!(
2184            contract.expand("x86_64-unknown-linux-gnu", "1.2.3"),
2185            Err(DistError::NameCollision {
2186                namespace: NameNamespace::InstallNames,
2187                ..
2188            })
2189        ));
2190
2191        let contract = archive_with("tool", "tool").expect_err("duplicate archive install name");
2192        assert!(matches!(
2193            contract,
2194            DistError::NameCollision {
2195                namespace: NameNamespace::InstallNames,
2196                ..
2197            }
2198        ));
2199        let contract = archive_with("Tool", "tool")
2200            .expect_err("ASCII case-only raw archive install names should fail early");
2201        assert!(matches!(
2202            contract,
2203            DistError::NameCollision {
2204                namespace: NameNamespace::InstallNames,
2205                ..
2206            }
2207        ));
2208        let contract = archive_with("{version}", "TOOL").unwrap();
2209        assert!(matches!(
2210            contract.expand("aarch64-apple-darwin", "tool"),
2211            Err(DistError::NameCollision {
2212                namespace: NameNamespace::InstallNames,
2213                ..
2214            })
2215        ));
2216    }
2217
2218    #[test]
2219    fn release_and_install_case_only_collisions_are_rejected() {
2220        let source = SIMPLE.replace(
2221            "sidecar = \"{asset}.sha256\"",
2222            "sidecar = \"EGGSACT-1.2.3-X86_64-UNKNOWN-LINUX-GNU\"",
2223        );
2224        let contract = DistributionContract::parse_toml_str(&source).unwrap();
2225        assert!(matches!(
2226            contract.expand("x86_64-unknown-linux-gnu", "1.2.3"),
2227            Err(DistError::NameCollision {
2228                namespace: NameNamespace::ReleaseFiles,
2229                ..
2230            })
2231        ));
2232
2233        let contract = bundle_with("one", "two", "{version}", "APP", "{asset}.sha256").unwrap();
2234        assert!(matches!(
2235            contract.expand("x86_64-unknown-linux-gnu", "app"),
2236            Err(DistError::NameCollision {
2237                namespace: NameNamespace::InstallNames,
2238                ..
2239            })
2240        ));
2241    }
2242
2243    #[test]
2244    fn missing_alias_input_fails() {
2245        let c = DistributionContract::parse_toml_str(
2246            &SIMPLE.replace("install = \"{product}\"", "install = \"{alias}\""),
2247        )
2248        .unwrap();
2249        // Lookup via triple leaves `{alias}` without input.
2250        let err = c.expand("x86_64-unknown-linux-gnu", "1.0.0").unwrap_err();
2251        assert!(matches!(err, DistError::MissingInput(_)));
2252        // Lookup via the alias supplies it.
2253        let ok = c.expand("linux-x64", "1.0.0").unwrap();
2254        match ok.assets {
2255            ExpandedAssets::Direct(d) => assert_eq!(d.install_name, "linux-x64"),
2256            _ => panic!("expected direct"),
2257        }
2258    }
2259
2260    #[test]
2261    fn direct_single_member_expansion() {
2262        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
2263        let e = c.expand("x86_64-unknown-linux-gnu", "1.2.6").unwrap();
2264        match e.assets {
2265            ExpandedAssets::Direct(d) => {
2266                assert_eq!(d.asset_file, "eggsact-1.2.6-x86_64-unknown-linux-gnu");
2267                assert_eq!(d.install_name, "eggsact");
2268                assert_eq!(
2269                    d.sidecar_file,
2270                    "eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256"
2271                );
2272            }
2273            _ => panic!("expected direct"),
2274        }
2275    }
2276
2277    #[test]
2278    fn multi_direct_bundle_expansion() {
2279        let c = DistributionContract::parse_toml_str(BUNDLE).unwrap();
2280        let e = c.expand("x86_64-unknown-linux-gnu", "0.9.0").unwrap();
2281        match e.assets {
2282            ExpandedAssets::Bundle(b) => {
2283                assert_eq!(b.entries.len(), 3);
2284                assert_eq!(
2285                    b.entries[0].asset_file,
2286                    "codegg-0.9.0-x86_64-unknown-linux-gnu"
2287                );
2288                assert_eq!(b.entries[1].install_name, "codegg-helper");
2289                assert_eq!(b.entries[2].asset_file, "codegg-manifest-0.9.0.json");
2290                assert!(b.entries[0].sidecar_file.ends_with(".sha256"));
2291            }
2292            _ => panic!("expected bundle"),
2293        }
2294    }
2295
2296    #[test]
2297    fn archive_asset_expansion() {
2298        let c = DistributionContract::parse_toml_str(ARCHIVE).unwrap();
2299        let e = c.expand("macos-arm64", "2.1.0").unwrap();
2300        assert_eq!(e.triple, "aarch64-apple-darwin");
2301        match e.assets {
2302            ExpandedAssets::Archive(a) => {
2303                assert_eq!(a.archive_file, "egress-2.1.0-aarch64-apple-darwin.tar.gz");
2304                assert_eq!(
2305                    a.sidecar_file,
2306                    "egress-2.1.0-aarch64-apple-darwin.tar.gz.sha256"
2307                );
2308                assert_eq!(a.members.len(), 2);
2309                assert_eq!(a.members[0].source, "egress");
2310                assert_eq!(a.members[1].source, "bin/egress-helper");
2311            }
2312            _ => panic!("expected archive"),
2313        }
2314    }
2315
2316    #[test]
2317    fn archive_member_absolute_path_is_rejected() {
2318        let s = ARCHIVE.replace("source = \"egress\"", "source = \"/egress\"");
2319        let err = DistributionContract::parse_toml_str(&s).unwrap_err();
2320        assert!(matches!(err, DistError::InvalidMemberPath(_)));
2321    }
2322
2323    #[test]
2324    fn archive_member_traversal_is_rejected() {
2325        for bad in ["../evil", "a/../../b", "a/../b", "bin/..", ".", ".."] {
2326            let s = ARCHIVE.replace("source = \"egress\"", &format!("source = \"{bad}\""));
2327            let err = DistributionContract::parse_toml_str(&s).unwrap_err();
2328            assert!(matches!(err, DistError::InvalidMemberPath(_)), "{bad}");
2329        }
2330    }
2331
2332    #[test]
2333    fn duplicate_normalized_archive_members_rejected() {
2334        let s = ARCHIVE.replace("source = \"bin/egress-helper\"", "source = \"egress\"");
2335        let err = DistributionContract::parse_toml_str(&s).unwrap_err();
2336        assert!(matches!(err, DistError::InvalidInput(_)));
2337        // ASCII case collisions are rejected at parse time too. Keying this
2338        // check on the exact source instead would let such a contract parse
2339        // and expand, and then be refused by `ArchiveMemberInventory::new`
2340        // — an archive contract that can never be validated.
2341        let cased = ARCHIVE.replace("source = \"bin/egress-helper\"", "source = \"EGRESS\"");
2342        let err = DistributionContract::parse_toml_str(&cased).unwrap_err();
2343        assert!(
2344            matches!(&err, DistError::InvalidInput(detail) if detail.contains("case-colliding")),
2345            "{err}"
2346        );
2347        assert!(DistributionContract::parse_toml_str(ARCHIVE).is_ok());
2348    }
2349
2350    #[test]
2351    fn expanded_release_names_are_acceptable_to_every_supported_platform() {
2352        // The release id is opaque but lands in artifact file names, so the
2353        // alphabet it may use has to be the intersection of the consumer's
2354        // release-name rules and every filesystem Eggpack targets.
2355        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
2356        for good in [
2357            "1.2.3",
2358            "v1.2.3-rc.1",
2359            "1.2.3-rc.1+build.5",
2360            "nightly_2026-10-05",
2361        ] {
2362            let e = c.expand("x86_64-unknown-linux-gnu", good).unwrap();
2363            let ExpandedAssets::Direct(direct) = e.assets else {
2364                panic!("expected direct");
2365            };
2366            for name in [
2367                &direct.asset_file,
2368                &direct.sidecar_file,
2369                &direct.install_name,
2370            ] {
2371                assert!(
2372                    name.chars().all(|c| is_safe_name_char(c) || c == '+'),
2373                    "release id {good} expanded to unportable name {name}"
2374                );
2375            }
2376        }
2377        // `:` is rejected by `eggpack-manifest` as an unsafe artifact file
2378        // name; `* ? " < > |` and spaces cannot be materialized on Windows at
2379        // all. Neither may reach an expanded name.
2380        for bad in [
2381            "1.0.0:beta",
2382            "1.0.0*",
2383            "1.0.0?",
2384            "1.0.0\"x",
2385            "1.0.0<x",
2386            "1.0.0>x",
2387            "1.0.0|x",
2388            "1.0.0 x",
2389            "a/b",
2390            "a\\b",
2391            "",
2392            "../evil",
2393        ] {
2394            assert!(
2395                c.expand("x86_64-unknown-linux-gnu", bad).is_err(),
2396                "release id {bad:?} must fail closed"
2397            );
2398        }
2399    }
2400
2401    #[test]
2402    fn checksum_sidecar_naming_is_explicit() {
2403        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
2404        let e = c.expand("linux-x64", "1.0.0").unwrap();
2405        match e.assets {
2406            ExpandedAssets::Direct(d) => {
2407                assert!(d.sidecar_file.contains(&d.asset_file));
2408                assert!(!d.sidecar_file.contains("signature"));
2409            }
2410            _ => panic!("expected direct"),
2411        }
2412    }
2413
2414    #[test]
2415    fn product_version_is_opaque_but_filesystem_safe() {
2416        let c = DistributionContract::parse_toml_str(SIMPLE).unwrap();
2417        // Opaque: dotted versions pass through unchanged.
2418        let e = c.expand("x86_64-unknown-linux-gnu", "1.2.6-rc.1").unwrap();
2419        match e.assets {
2420            ExpandedAssets::Direct(d) => assert!(d.asset_file.contains("1.2.6-rc.1")),
2421            _ => panic!("expected direct"),
2422        }
2423        // Unsafe versions fail instead of escaping.
2424        assert!(c.expand("x86_64-unknown-linux-gnu", "../evil").is_err());
2425        assert!(c.expand("x86_64-unknown-linux-gnu", "a/b").is_err());
2426        assert!(c.expand("x86_64-unknown-linux-gnu", "").is_err());
2427    }
2428
2429    #[test]
2430    fn deterministic_round_trip_golden() {
2431        for fixture in [SIMPLE, BUNDLE, ARCHIVE] {
2432            let c = DistributionContract::parse_toml_str(fixture).unwrap();
2433            let rendered = c.to_toml_string().unwrap();
2434            let reparsed = DistributionContract::parse_toml_str(&rendered).unwrap();
2435            assert_eq!(c, reparsed);
2436            // Golden stability: rendering twice yields identical bytes.
2437            assert_eq!(rendered, reparsed.to_toml_string().unwrap());
2438        }
2439    }
2440
2441    #[test]
2442    fn unknown_fields_are_rejected() {
2443        let s = SIMPLE.replace(
2444            "[product]\nid = \"eggsact\"",
2445            "[product]\nid = \"eggsact\"\ntypo_field = 1",
2446        );
2447        assert!(DistributionContract::parse_toml_str(&s).is_err());
2448    }
2449}