Skip to main content

eggpack_manifest/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Bounded schema-v1 evidence for finalized Eggpack release bytes."]
4#![doc = "This crate parses and serializes data only; it does not access files, networks, or trust authorities."]
5
6use serde::{Deserialize, Serialize};
7use std::{collections::HashSet, fmt};
8
9/// The only manifest schema version currently supported.
10pub const SCHEMA_V1: u32 = 1;
11/// Maximum encoded JSON document size.
12pub const MAX_DOCUMENT_BYTES: usize = 1_048_576;
13/// Maximum target records.
14pub const MAX_TARGETS: usize = 256;
15/// Maximum records in any bundle/archive member list.
16pub const MAX_RECORDS: usize = 256;
17/// Maximum evidence references per manifest.
18pub const MAX_EVIDENCE_REFERENCES: usize = 64;
19const MAX_ID: usize = 128;
20const MAX_NAME: usize = 255;
21const MAX_REVISION: usize = 128;
22const MAX_EVIDENCE: usize = 256;
23
24/// Validation, parsing, or serialization failure.
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum ManifestError {
28    /// Input is malformed or violates a structural/semantic invariant.
29    Invalid(String),
30    /// The manifest declares an unsupported schema version.
31    UnsupportedVersion(u32),
32    /// JSON exceeds the documented input bound.
33    TooLarge,
34}
35
36impl fmt::Display for ManifestError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Self::Invalid(s) => write!(f, "invalid release manifest: {s}"),
40            Self::UnsupportedVersion(v) => write!(f, "unsupported manifest schema version: {v}"),
41            Self::TooLarge => f.write_str("release manifest exceeds the 1 MiB limit"),
42        }
43    }
44}
45impl std::error::Error for ManifestError {}
46fn invalid(s: impl Into<String>) -> ManifestError {
47    ManifestError::Invalid(s.into())
48}
49
50/// Why a SHA-256 hex digest string was refused.
51///
52/// ADR-0006 (Option A) fixes one acceptance set for the whole workspace:
53/// exactly 64 lowercase hexadecimal characters, and not the all-zeros
54/// placeholder that no real file digest can produce.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Sha256Error {
57    /// The digest is not exactly 64 characters long.
58    Length,
59    /// The digest contains a character that is not lowercase hexadecimal.
60    NotLowercaseHex,
61    /// The digest is the all-zeros placeholder, which is never a real digest.
62    AllZeros,
63}
64
65impl Sha256Error {
66    /// Bounded, single-line reason phrase for this refusal.
67    pub fn reason(self) -> &'static str {
68        match self {
69            Self::Length => "must be 64 characters",
70            Self::NotLowercaseHex => "must be lowercase hexadecimal",
71            Self::AllZeros => "must not be the all-zeros digest",
72        }
73    }
74}
75
76impl fmt::Display for Sha256Error {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.write_str(self.reason())
79    }
80}
81impl std::error::Error for Sha256Error {}
82
83/// The all-zeros placeholder digest. No byte sequence hashes to it.
84const ALL_ZEROS_SHA256: &str = "0000000000000000000000000000000000000000000000000000000000000000";
85
86/// Validate one SHA-256 hex digest against the canonical acceptance set.
87///
88/// This is the **single** SHA-256 hex acceptance rule in the workspace. The
89/// crate that owns the evidence schema owns the rule, and `eggpack-core`,
90/// `eggpack-ci`, and `eggpack-github` all consume it instead of restating it.
91///
92/// The accepted set is exactly 64 lowercase hexadecimal characters, minus the
93/// all-zeros placeholder, which can only mean "no digest was computed" and
94/// which no legitimate producer emits (ADR-0006).
95///
96/// A digest is an integrity fact about bytes. Acceptance here says nothing
97/// about authenticity, provenance, or publisher identity.
98pub fn validate_sha256_hex(digest: &str) -> Result<(), Sha256Error> {
99    if digest.len() != 64 {
100        return Err(Sha256Error::Length);
101    }
102    if !digest
103        .bytes()
104        .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
105    {
106        return Err(Sha256Error::NotLowercaseHex);
107    }
108    if digest == ALL_ZEROS_SHA256 {
109        return Err(Sha256Error::AllZeros);
110    }
111    Ok(())
112}
113fn bounded(s: &str, max: usize, label: &str) -> Result<(), ManifestError> {
114    if s.is_empty() || s.len() > max || s.chars().any(char::is_control) {
115        return Err(invalid(format!("invalid {label}")));
116    }
117    Ok(())
118}
119
120/// Top-level immutable evidence for one finalized product release.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(deny_unknown_fields)]
123pub struct ReleaseManifest {
124    /// Schema version, currently exactly `1`.
125    pub schema_version: u32,
126    /// Stable opaque product identifier.
127    pub product_id: String,
128    /// Opaque release identifier.
129    pub release_id: String,
130    /// Immutable source revision associated with the release.
131    pub source_revision: String,
132    /// Canonical target records, emitted in lexical triple order.
133    pub targets: Vec<TargetRecord>,
134    /// Optional bounded evidence identity strings; these make no trust claim.
135    #[serde(default, skip_serializing_if = "Vec::is_empty")]
136    pub evidence_references: Vec<String>,
137}
138
139/// Finalized artifact facts for one canonical target.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct TargetRecord {
143    /// Canonical target triple.
144    pub target: String,
145    /// Explicit direct, bundle, or archive representation.
146    pub form: ArtifactForm,
147}
148
149/// Discriminated artifact layout. Nested records retain semantic relationships.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
152pub enum ArtifactForm {
153    /// One release artifact corresponding to one installed file.
154    Direct {
155        /// Artifact facts.
156        artifact: ArtifactRecord,
157        /// Installed filename.
158        install: String,
159    },
160    /// Several independently downloadable files, each paired with its install identity.
161    Bundle {
162        /// Paired bundle entries.
163        entries: Vec<BundleRecord>,
164    },
165    /// One archive artifact and its required logical members.
166    Archive {
167        /// Archive byte facts.
168        artifact: ArtifactRecord,
169        /// Required archive members.
170        members: Vec<ArchiveMemberRecord>,
171    },
172}
173
174/// Exact byte facts for one emitted artifact or logical member.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(deny_unknown_fields)]
177pub struct ArtifactRecord {
178    /// Safe flat release filename.
179    pub name: String,
180    /// Exact non-zero byte size.
181    pub size: u64,
182    /// Lowercase 64-character SHA-256 hexadecimal digest.
183    pub sha256: String,
184}
185
186/// A bundle artifact and its corresponding install name.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(deny_unknown_fields)]
189pub struct BundleRecord {
190    /// Bundle artifact facts.
191    pub artifact: ArtifactRecord,
192    /// Safe flat install identity associated with this artifact.
193    pub install: String,
194}
195
196/// A required archive member with source and install identities preserved.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(deny_unknown_fields)]
199pub struct ArchiveMemberRecord {
200    /// Normalized relative source path inside the archive.
201    pub source: String,
202    /// Safe flat install identity.
203    pub install: String,
204    /// Exact member byte facts.
205    pub bytes: ByteEvidence,
206}
207
208/// Exact size and digest evidence for an archive member, whose identity is
209/// supplied by its source and install fields.
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(deny_unknown_fields)]
212pub struct ByteEvidence {
213    /// Exact non-zero byte size.
214    pub size: u64,
215    /// Lowercase 64-character SHA-256 hexadecimal digest.
216    pub sha256: String,
217}
218
219impl ReleaseManifest {
220    /// Find exactly one canonical target record. This never resolves aliases or guesses.
221    pub fn target(&self, canonical_triple: &str) -> Result<&TargetRecord, ManifestError> {
222        self.validate()?;
223        self.targets
224            .iter()
225            .find(|t| t.target == canonical_triple)
226            .ok_or_else(|| invalid("canonical target not found"))
227    }
228    /// Parse strict schema-v1 JSON and validate all bounds and relationships.
229    pub fn from_json(input: &str) -> Result<Self, ManifestError> {
230        if input.len() > MAX_DOCUMENT_BYTES {
231            return Err(ManifestError::TooLarge);
232        }
233        let value: Self = serde_json::from_str(input).map_err(|e| invalid(format!("JSON: {e}")))?;
234        value.validate()?;
235        Ok(value)
236    }
237
238    /// Validate a manifest without performing I/O.
239    pub fn validate(&self) -> Result<(), ManifestError> {
240        if self.schema_version != SCHEMA_V1 {
241            return Err(ManifestError::UnsupportedVersion(self.schema_version));
242        }
243        bounded(&self.product_id, MAX_ID, "product id")?;
244        bounded(&self.release_id, MAX_ID, "release id")?;
245        bounded(&self.source_revision, MAX_REVISION, "source revision")?;
246        if self.targets.is_empty() || self.targets.len() > MAX_TARGETS {
247            return Err(invalid("target count out of bounds"));
248        }
249        if self.evidence_references.len() > MAX_EVIDENCE_REFERENCES {
250            return Err(invalid("evidence reference count out of bounds"));
251        }
252        let mut target_seen = HashSet::new();
253        let mut release_names = HashSet::new();
254        for t in &self.targets {
255            bounded(&t.target, MAX_ID, "target")?;
256            if !target_seen.insert(t.target.as_str()) {
257                return Err(invalid("duplicate canonical target"));
258            }
259            let mut installs = HashSet::new();
260            match &t.form {
261                ArtifactForm::Direct { artifact, install } => {
262                    artifact.validate(&mut release_names)?;
263                    valid_name(install, "install name", &mut installs)?;
264                }
265                ArtifactForm::Bundle { entries } => {
266                    if entries.is_empty() || entries.len() > MAX_RECORDS {
267                        return Err(invalid("bundle entry count out of bounds"));
268                    }
269                    let mut seen = HashSet::new();
270                    for e in entries {
271                        e.artifact.validate(&mut release_names)?;
272                        valid_name(&e.install, "install name", &mut installs)?;
273                        if !seen.insert(e.artifact.name.as_str()) {
274                            return Err(invalid("duplicate bundle artifact"));
275                        }
276                    }
277                }
278                ArtifactForm::Archive { artifact, members } => {
279                    artifact.validate(&mut release_names)?;
280                    if members.is_empty() || members.len() > MAX_RECORDS {
281                        return Err(invalid("archive member count out of bounds"));
282                    }
283                    let mut sources = HashSet::new();
284                    for m in members {
285                        valid_path(&m.source)?;
286                        valid_name(&m.install, "install name", &mut installs)?;
287                        m.bytes.validate()?;
288                        if !sources.insert(m.source.as_str()) {
289                            return Err(invalid("duplicate archive member source"));
290                        }
291                    }
292                }
293            }
294        }
295        for r in &self.evidence_references {
296            bounded(r, MAX_EVIDENCE, "evidence reference")?;
297        }
298        // The structural bounds above must imply the document bound: a document
299        // that this crate's own `from_json` would refuse is not a valid
300        // manifest, so `validate` rejects it here instead of letting `to_json`
301        // emit something no reader can parse back. Counting is bounded, so the
302        // serialized length cannot exceed the largest admissible document plus
303        // JSON punctuation and escapes.
304        self.check_document_bound()
305    }
306
307    /// Reject a manifest whose canonical serialization exceeds the document
308    /// bound accepted by `from_json`.
309    fn check_document_bound(&self) -> Result<(), ManifestError> {
310        let mut worst_case = self.clone();
311        // `to_json` serializes a canonical (sorted) copy; ordering cannot change
312        // the encoded length, so measuring this copy bounds the canonical one.
313        worst_case.targets.sort_by(|a, b| a.target.cmp(&b.target));
314        let encoded = serde_json::to_string(&worst_case)
315            .map_err(|e| invalid(format!("JSON serialization: {e}")))?;
316        if encoded.len() > MAX_DOCUMENT_BYTES {
317            return Err(ManifestError::TooLarge);
318        }
319        Ok(())
320    }
321
322    /// Serialize as deterministic compact JSON with canonical lexical ordering.
323    /// This is stable application serialization, not signing-grade canonical JSON.
324    pub fn to_json(&self) -> Result<String, ManifestError> {
325        self.validate()?;
326        let mut canonical = self.clone();
327        canonical.targets.sort_by(|a, b| a.target.cmp(&b.target));
328        for t in &mut canonical.targets {
329            match &mut t.form {
330                ArtifactForm::Bundle { entries } => entries.sort_by(|a, b| {
331                    (&a.artifact.name, &a.install).cmp(&(&b.artifact.name, &b.install))
332                }),
333                ArtifactForm::Archive { members, .. } => {
334                    members.sort_by(|a, b| (&a.source, &a.install).cmp(&(&b.source, &b.install)))
335                }
336                ArtifactForm::Direct { .. } => {}
337            }
338        }
339        serde_json::to_string(&canonical).map_err(|e| invalid(format!("JSON serialization: {e}")))
340    }
341}
342
343impl ArtifactRecord {
344    /// Decode validated lowercase SHA-256 hexadecimal evidence into bytes.
345    pub fn sha256_bytes(&self) -> Result<[u8; 32], ManifestError> {
346        decode_sha256(&self.sha256)
347    }
348    fn validate(&self, names: &mut HashSet<String>) -> Result<(), ManifestError> {
349        valid_name(&self.name, "artifact filename", names)?;
350        if self.size == 0 {
351            return Err(invalid("size must be non-zero"));
352        }
353        validate_sha256_hex(&self.sha256).map_err(|error| match error {
354            Sha256Error::AllZeros => invalid("sha256 must not be the all-zeros digest"),
355            _ => invalid("sha256 must be 64 lowercase hexadecimal characters"),
356        })?;
357        Ok(())
358    }
359}
360impl ByteEvidence {
361    /// Decode validated lowercase SHA-256 hexadecimal evidence into bytes.
362    pub fn sha256_bytes(&self) -> Result<[u8; 32], ManifestError> {
363        decode_sha256(&self.sha256)
364    }
365    fn validate(&self) -> Result<(), ManifestError> {
366        if self.size == 0 {
367            return Err(invalid("size must be non-zero"));
368        }
369        validate_sha256_hex(&self.sha256).map_err(|error| match error {
370            Sha256Error::AllZeros => invalid("sha256 must not be the all-zeros digest"),
371            _ => invalid("sha256 must be 64 lowercase hexadecimal characters"),
372        })?;
373        Ok(())
374    }
375}
376fn decode_sha256(hex: &str) -> Result<[u8; 32], ManifestError> {
377    validate_sha256_hex(hex).map_err(|error| match error {
378        Sha256Error::Length => invalid("sha256 must contain 64 lowercase hex characters"),
379        Sha256Error::AllZeros => invalid("sha256 must not be the all-zeros digest"),
380        Sha256Error::NotLowercaseHex => invalid("invalid lowercase sha256"),
381    })?;
382    let mut out = [0u8; 32];
383    for (i, pair) in hex.as_bytes().as_chunks::<2>().0.iter().enumerate() {
384        let digit = |b: u8| match b {
385            b'0'..=b'9' => Some(b - b'0'),
386            b'a'..=b'f' => Some(b - b'a' + 10),
387            _ => None,
388        };
389        out[i] = digit(pair[0])
390            .and_then(|h| digit(pair[1]).map(|l| (h << 4) | l))
391            .ok_or_else(|| invalid("invalid lowercase sha256"))?;
392    }
393    Ok(out)
394}
395fn valid_name(name: &str, label: &str, names: &mut HashSet<String>) -> Result<(), ManifestError> {
396    bounded(name, MAX_NAME, label)?;
397    if name == "."
398        || name == ".."
399        || name.contains('/')
400        || name.contains('\\')
401        || name.contains(':')
402    {
403        return Err(invalid(format!("unsafe {label}")));
404    }
405    if !names.insert(name.to_ascii_lowercase()) {
406        return Err(invalid(format!(
407            "duplicate or ASCII-case-colliding {label}"
408        )));
409    }
410    Ok(())
411}
412fn valid_path(p: &str) -> Result<(), ManifestError> {
413    bounded(p, 1024, "archive member path")?;
414    if p.starts_with('/')
415        || p.contains('\\')
416        || p.contains(':')
417        || p.split('/').any(|c| c.is_empty() || c == "." || c == "..")
418    {
419        return Err(invalid("unsafe archive member path"));
420    }
421    Ok(())
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    fn artifact(name: &str) -> ArtifactRecord {
428        ArtifactRecord {
429            name: name.into(),
430            size: 3,
431            sha256: "ab".repeat(32),
432        }
433    }
434    /// A manifest that satisfies every structural bound must still serialize
435    /// inside the document bound: `from_json` refuses a larger document, so a
436    /// document that violates the bound without being readable back would be a
437    /// valid manifest only until it was written.
438    #[test]
439    fn a_valid_manifest_always_fits_the_document_bound() {
440        let members: Vec<ArchiveMemberRecord> = (0..MAX_RECORDS)
441            .map(|index| ArchiveMemberRecord {
442                source: format!("bin/member-{index:04}-{}", "p".repeat(MAX_NAME - 14)),
443                install: format!("member-{index:04}"),
444                bytes: ByteEvidence {
445                    size: 3,
446                    sha256: "ab".repeat(32),
447                },
448            })
449            .collect();
450        let worst_case = ReleaseManifest {
451            schema_version: 1,
452            product_id: "e".repeat(MAX_ID),
453            release_id: "r".repeat(MAX_ID),
454            source_revision: "a".repeat(MAX_REVISION),
455            targets: (0..MAX_TARGETS)
456                .map(|index| TargetRecord {
457                    target: format!("x86_64-unknown-linux-gnu-{index:03}"),
458                    form: ArtifactForm::Archive {
459                        artifact: artifact(&format!("a-{index:03}-{}", "n".repeat(MAX_NAME - 6))),
460                        members: members.clone(),
461                    },
462                })
463                .collect(),
464            evidence_references: (0..MAX_EVIDENCE_REFERENCES)
465                .map(|index| format!("refs/{index:03}-{}", "e".repeat(MAX_EVIDENCE - 10)))
466                .collect(),
467        };
468        assert!(
469            worst_case.validate().is_err(),
470            "this fixture must exceed the document bound for the assertion to mean anything"
471        );
472        // A document that cannot be read back is rejected at validation, so
473        // `to_json` never emits one.
474        assert!(matches!(
475            worst_case.validate(),
476            Err(ManifestError::TooLarge)
477        ));
478        assert!(worst_case.to_json().is_err());
479        // The serialized form parses.
480        let ok = manifest(ArtifactForm::Direct {
481            artifact: artifact("app"),
482            install: "app".into(),
483        });
484        let text = ok.to_json().unwrap();
485        assert!(ReleaseManifest::from_json(&text).is_ok());
486    }
487
488    fn manifest(form: ArtifactForm) -> ReleaseManifest {
489        ReleaseManifest {
490            schema_version: 1,
491            product_id: "eggsact".into(),
492            release_id: "1.0.0".into(),
493            source_revision: "a".repeat(40),
494            targets: vec![TargetRecord {
495                target: "x86_64-unknown-linux-gnu".into(),
496                form,
497            }],
498            evidence_references: vec![],
499        }
500    }
501    fn multi_target(forms: Vec<(&str, ArtifactForm)>) -> ReleaseManifest {
502        let mut m = manifest(forms[0].1.clone());
503        m.targets = forms
504            .into_iter()
505            .map(|(target, form)| TargetRecord {
506                target: target.into(),
507                form,
508            })
509            .collect();
510        m
511    }
512    #[test]
513    fn direct_round_trip_stable() {
514        let m = manifest(ArtifactForm::Direct {
515            artifact: artifact("eggsact"),
516            install: "eggsact".into(),
517        });
518        let j = m.to_json().unwrap();
519        let expected = format!(
520            r#"{{"schema_version":1,"product_id":"eggsact","release_id":"1.0.0","source_revision":"{}","targets":[{{"target":"x86_64-unknown-linux-gnu","form":{{"kind":"direct","artifact":{{"name":"eggsact","size":3,"sha256":"{}"}},"install":"eggsact"}}}}]}}"#,
521            "a".repeat(40),
522            "ab".repeat(32)
523        );
524        assert_eq!(j, expected);
525        assert_eq!(
526            ReleaseManifest::from_json(&j).unwrap().to_json().unwrap(),
527            j
528        );
529    }
530    #[test]
531    fn bundle_pairing_round_trip() {
532        let m = manifest(ArtifactForm::Bundle {
533            entries: vec![
534                BundleRecord {
535                    artifact: artifact("helper"),
536                    install: "helper-bin".into(),
537                },
538                BundleRecord {
539                    artifact: artifact("main"),
540                    install: "main-bin".into(),
541                },
542            ],
543        });
544        assert_eq!(
545            ReleaseManifest::from_json(&m.to_json().unwrap()).unwrap(),
546            m
547        );
548    }
549    #[test]
550    fn archive_relationship_round_trip() {
551        let m = manifest(ArtifactForm::Archive {
552            artifact: artifact("release.tar"),
553            members: vec![ArchiveMemberRecord {
554                source: "bin/tool".into(),
555                install: "tool".into(),
556                bytes: ByteEvidence {
557                    size: 3,
558                    sha256: "ab".repeat(32),
559                },
560            }],
561        });
562        assert_eq!(
563            ReleaseManifest::from_json(&m.to_json().unwrap()).unwrap(),
564            m
565        );
566    }
567    #[test]
568    fn rejects_unknown_fields_version_and_bad_digest_or_size() {
569        let m = manifest(ArtifactForm::Direct {
570            artifact: artifact("a"),
571            install: "a".into(),
572        });
573        let j = m.to_json().unwrap();
574        assert!(ReleaseManifest::from_json(
575            &j.replace("\"schema_version\":1", "\"schema_version\":2")
576        )
577        .is_err());
578        assert!(ReleaseManifest::from_json(
579            &j.replace("\"schema_version\":1", "\"schema_version\":1,\"extra\":0")
580        )
581        .is_err());
582        assert!(ReleaseManifest::from_json(&j.replace(&"ab".repeat(32), "xx")).is_err());
583        assert!(ReleaseManifest::from_json(&j.replace("\"size\":3", "\"size\":0")).is_err());
584    }
585    #[test]
586    fn rejects_case_collision_and_crossed_install() {
587        let mut m = manifest(ArtifactForm::Bundle {
588            entries: vec![
589                BundleRecord {
590                    artifact: artifact("App"),
591                    install: "one".into(),
592                },
593                BundleRecord {
594                    artifact: artifact("app"),
595                    install: "two".into(),
596                },
597            ],
598        });
599        assert!(m.validate().is_err());
600        m = manifest(ArtifactForm::Bundle {
601            entries: vec![
602                BundleRecord {
603                    artifact: artifact("one"),
604                    install: "same".into(),
605                },
606                BundleRecord {
607                    artifact: artifact("two"),
608                    install: "same".into(),
609                },
610            ],
611        });
612        assert!(m.validate().is_err());
613    }
614    #[test]
615    fn direct_install_names_are_target_local_like_eggsact_contract() {
616        let m = multi_target(vec![
617            (
618                "x86_64-unknown-linux-gnu",
619                ArtifactForm::Direct {
620                    artifact: artifact("eggsact-linux"),
621                    install: "eggsact".into(),
622                },
623            ),
624            (
625                "aarch64-apple-darwin",
626                ArtifactForm::Direct {
627                    artifact: artifact("eggsact-macos"),
628                    install: "eggsact".into(),
629                },
630            ),
631        ]);
632        // Mirrors crates/eggpack-contract/tests/fixtures/simple-direct.toml.
633        assert!(m.validate().is_ok());
634    }
635    #[test]
636    fn archive_install_names_are_target_local_like_egress_contract() {
637        let archive = |filename: &str| ArtifactForm::Archive {
638            artifact: artifact(filename),
639            members: vec![
640                ArchiveMemberRecord {
641                    source: "egress".into(),
642                    install: "egress".into(),
643                    bytes: ByteEvidence {
644                        size: 3,
645                        sha256: "ab".repeat(32),
646                    },
647                },
648                ArchiveMemberRecord {
649                    source: "bin/egress-helper".into(),
650                    install: "egress-helper".into(),
651                    bytes: ByteEvidence {
652                        size: 4,
653                        sha256: "cd".repeat(32),
654                    },
655                },
656            ],
657        };
658        let m = multi_target(vec![
659            ("x86_64-unknown-linux-gnu", archive("egress-linux.tar")),
660            ("aarch64-apple-darwin", archive("egress-macos.tar")),
661        ]);
662        // Mirrors crates/eggpack-contract/tests/fixtures/egress-archive.toml.
663        assert!(m.validate().is_ok());
664    }
665    #[test]
666    fn bundle_install_names_are_target_local() {
667        let bundle = |main: &str, helper: &str| ArtifactForm::Bundle {
668            entries: vec![
669                BundleRecord {
670                    artifact: artifact(main),
671                    install: "app".into(),
672                },
673                BundleRecord {
674                    artifact: artifact(helper),
675                    install: "app-helper".into(),
676                },
677            ],
678        };
679        let m = multi_target(vec![
680            (
681                "x86_64-unknown-linux-gnu",
682                bundle("app-linux", "helper-linux"),
683            ),
684            ("aarch64-apple-darwin", bundle("app-macos", "helper-macos")),
685        ]);
686        assert!(m.validate().is_ok());
687    }
688    #[test]
689    fn install_collisions_remain_rejected_within_target() {
690        for installs in [["same", "same"], ["App", "app"]] {
691            let m = manifest(ArtifactForm::Bundle {
692                entries: vec![
693                    BundleRecord {
694                        artifact: artifact("one"),
695                        install: installs[0].into(),
696                    },
697                    BundleRecord {
698                        artifact: artifact("two"),
699                        install: installs[1].into(),
700                    },
701                ],
702            });
703            assert!(m.validate().is_err());
704        }
705
706        for installs in [["same", "same"], ["App", "app"]] {
707            let m = manifest(ArtifactForm::Archive {
708                artifact: artifact("release.tar"),
709                members: vec![
710                    ArchiveMemberRecord {
711                        source: "bin/one".into(),
712                        install: installs[0].into(),
713                        bytes: ByteEvidence {
714                            size: 3,
715                            sha256: "ab".repeat(32),
716                        },
717                    },
718                    ArchiveMemberRecord {
719                        source: "bin/two".into(),
720                        install: installs[1].into(),
721                        bytes: ByteEvidence {
722                            size: 3,
723                            sha256: "cd".repeat(32),
724                        },
725                    },
726                ],
727            });
728            assert!(m.validate().is_err());
729        }
730    }
731    #[test]
732    fn release_artifact_collisions_remain_manifest_global() {
733        for filenames in [["same", "same"], ["App.tar", "app.tar"]] {
734            let m = multi_target(vec![
735                (
736                    "x86_64-unknown-linux-gnu",
737                    ArtifactForm::Direct {
738                        artifact: artifact(filenames[0]),
739                        install: "app".into(),
740                    },
741                ),
742                (
743                    "aarch64-apple-darwin",
744                    ArtifactForm::Direct {
745                        artifact: artifact(filenames[1]),
746                        install: "app".into(),
747                    },
748                ),
749            ]);
750            assert!(m.validate().is_err());
751        }
752    }
753    #[test]
754    fn exact_target_and_sha_helpers_are_non_wire_additions() {
755        let m = manifest(ArtifactForm::Direct {
756            artifact: artifact("a"),
757            install: "a".into(),
758        });
759        let before = m.to_json().unwrap();
760        let target = m.target("x86_64-unknown-linux-gnu").unwrap();
761        if let ArtifactForm::Direct { artifact, .. } = &target.form {
762            assert_eq!(artifact.sha256_bytes().unwrap(), [0xab; 32]);
763        }
764        assert!(m.target("linux-x64").is_err());
765        assert_eq!(m.to_json().unwrap(), before);
766    }
767    #[test]
768    fn eggup_interoperability_manifest_fixtures_are_valid_v1() {
769        for fixture in [
770            include_str!(
771                "../../../plans/closure/eggup-interoperability/fixtures/direct-manifest.json"
772            ),
773            include_str!(
774                "../../../plans/closure/eggup-interoperability/fixtures/bundle-manifest.json"
775            ),
776            include_str!(
777                "../../../plans/closure/eggup-interoperability/fixtures/archive-manifest.json"
778            ),
779        ] {
780            let parsed = ReleaseManifest::from_json(fixture).unwrap();
781            assert_eq!(parsed.to_json().unwrap(), fixture.trim());
782        }
783        assert!(ReleaseManifest::from_json(include_str!(
784            "../../../plans/closure/eggup-interoperability/fixtures/unknown-schema.json"
785        ))
786        .is_err());
787        assert!(ReleaseManifest::from_json(include_str!(
788            "../../../plans/closure/eggup-interoperability/fixtures/corrupt-digest.json"
789        ))
790        .is_err());
791        assert!(ReleaseManifest::from_json(include_str!(
792            "../../../plans/closure/eggup-interoperability/fixtures/corrupt-size.json"
793        ))
794        .is_err());
795        let direct = ReleaseManifest::from_json(include_str!(
796            "../../../plans/closure/eggup-interoperability/fixtures/direct-manifest.json"
797        ))
798        .unwrap();
799        assert!(direct.target("x86_64-pc-windows-gnu").is_err());
800        assert_eq!(direct.product_id, "eggsact");
801        assert_eq!(direct.release_id, "1.2.6");
802        let bundle = ReleaseManifest::from_json(include_str!(
803            "../../../plans/closure/eggup-interoperability/fixtures/bundle-manifest.json"
804        ))
805        .unwrap();
806        match &bundle.target("x86_64-unknown-linux-gnu").unwrap().form {
807            ArtifactForm::Bundle { entries } => assert_eq!(entries.len(), 3),
808            _ => panic!("bundle fixture changed form"),
809        }
810        let archive = ReleaseManifest::from_json(include_str!(
811            "../../../plans/closure/eggup-interoperability/fixtures/archive-manifest.json"
812        ))
813        .unwrap();
814        match &archive.target("x86_64-unknown-linux-gnu").unwrap().form {
815            ArtifactForm::Archive { artifact, members } => {
816                assert_eq!(artifact.size, 3);
817                assert_eq!(members.len(), 2);
818                assert_eq!(members[0].source, "bin/egress-helper");
819            }
820            _ => panic!("archive fixture changed form"),
821        }
822        let projection: serde_json::Value = serde_json::from_str(include_str!(
823            "../../../plans/closure/eggup-interoperability/fixtures/projection-archive.json"
824        ))
825        .unwrap();
826        assert_eq!(projection["extraction_required"], true);
827        assert_eq!(projection["acquisition_units"].as_array().unwrap().len(), 1);
828        assert_eq!(projection["members"].as_array().unwrap().len(), 2);
829    }
830    #[test]
831    fn canonical_order_is_independent_of_input_order() {
832        let mut a = manifest(ArtifactForm::Bundle {
833            entries: vec![
834                BundleRecord {
835                    artifact: artifact("z"),
836                    install: "z".into(),
837                },
838                BundleRecord {
839                    artifact: artifact("a"),
840                    install: "a".into(),
841                },
842            ],
843        });
844        let mut b = a.clone();
845        if let ArtifactForm::Bundle { entries } = &mut b.targets[0].form {
846            entries.reverse();
847        }
848        assert_eq!(a.to_json().unwrap(), b.to_json().unwrap());
849        a.targets.reverse();
850    }
851
852    mod projection_fixture_consistency {
853        //! Pairwise direct, bundle, and archive projection/manifest validation.
854        //!
855        //! Projection fixtures are explicitly documentation/test evidence, not a
856        //! production wire format. This harness parses them into strict typed
857        //! structs and proves each projection is an exact pairwise projection
858        //! of its paired ReleaseManifest fixture. It also runs the detection-gap
859        //! negative matrix that would have failed against the original M001
860        //! checked-in `projection-bundle.json`.
861        use super::{
862            super::{ArtifactForm, ReleaseManifest},
863            *,
864        };
865
866        const DIRECT_MANIFEST: &str = include_str!(
867            "../../../plans/closure/eggup-interoperability/fixtures/direct-manifest.json"
868        );
869        const BUNDLE_MANIFEST: &str = include_str!(
870            "../../../plans/closure/eggup-interoperability/fixtures/bundle-manifest.json"
871        );
872        const ARCHIVE_MANIFEST: &str = include_str!(
873            "../../../plans/closure/eggup-interoperability/fixtures/archive-manifest.json"
874        );
875        const DIRECT_PROJECTION: &str = include_str!(
876            "../../../plans/closure/eggup-interoperability/fixtures/projection-direct.json"
877        );
878        const BUNDLE_PROJECTION: &str = include_str!(
879            "../../../plans/closure/eggup-interoperability/fixtures/projection-bundle.json"
880        );
881        const ARCHIVE_PROJECTION: &str = include_str!(
882            "../../../plans/closure/eggup-interoperability/fixtures/projection-archive.json"
883        );
884
885        const DIRECT_TARGET: &str = "x86_64-unknown-linux-gnu";
886        const BUNDLE_TARGET: &str = "x86_64-unknown-linux-gnu";
887        const ARCHIVE_TARGET: &str = "x86_64-unknown-linux-gnu";
888
889        #[derive(Debug, Clone, serde::Deserialize)]
890        #[serde(deny_unknown_fields)]
891        struct ReleaseIdentity {
892            product_id: String,
893            release_id: String,
894        }
895
896        #[derive(Debug, Clone, serde::Deserialize)]
897        #[serde(deny_unknown_fields)]
898        struct DirectAcquisitionUnit {
899            name: String,
900            exact_size: u64,
901            sha256: String,
902            member_id: String,
903            relative_destination: String,
904        }
905
906        #[derive(Debug, Clone, serde::Deserialize)]
907        #[serde(deny_unknown_fields)]
908        struct DirectProjection {
909            selected_target: String,
910            release_identity: ReleaseIdentity,
911            acquisition_units: Vec<DirectAcquisitionUnit>,
912            transaction_group: String,
913        }
914
915        #[derive(Debug, Clone, serde::Deserialize)]
916        #[serde(deny_unknown_fields)]
917        struct BundleAcquisitionUnit {
918            name: String,
919            exact_size: u64,
920            sha256: String,
921            member_id: String,
922            relative_destination: String,
923        }
924
925        #[derive(Debug, Clone, serde::Deserialize)]
926        #[serde(deny_unknown_fields)]
927        struct BundleProjection {
928            selected_target: String,
929            release_identity: ReleaseIdentity,
930            acquisition_units: Vec<BundleAcquisitionUnit>,
931            transaction_group: String,
932        }
933
934        #[derive(Debug, Clone, serde::Deserialize)]
935        #[serde(deny_unknown_fields)]
936        struct ArchiveAcquisitionUnit {
937            name: String,
938            exact_size: u64,
939            sha256: String,
940        }
941
942        #[derive(Debug, Clone, serde::Deserialize)]
943        #[serde(deny_unknown_fields)]
944        struct ArchiveProjectedMember {
945            source: String,
946            install: String,
947            size: u64,
948            sha256: String,
949        }
950
951        #[derive(Debug, Clone, serde::Deserialize)]
952        #[serde(deny_unknown_fields)]
953        struct ArchiveProjection {
954            selected_target: String,
955            acquisition_units: Vec<ArchiveAcquisitionUnit>,
956            members: Vec<ArchiveProjectedMember>,
957            extraction_required: bool,
958            transaction_group: String,
959        }
960
961        fn err<S: Into<String>>(s: S) -> String {
962            s.into()
963        }
964
965        fn check_direct_projection(
966            projection: &DirectProjection,
967            manifest: &ReleaseManifest,
968            target: &str,
969        ) -> Result<(), String> {
970            if projection.selected_target != target {
971                return Err(err(format!(
972                    "selected_target mismatch: {} != {target}",
973                    projection.selected_target
974                )));
975            }
976            if projection.release_identity.product_id != manifest.product_id {
977                return Err(err(format!(
978                    "release_identity.product_id {} != manifest {}",
979                    projection.release_identity.product_id, manifest.product_id
980                )));
981            }
982            if projection.release_identity.release_id != manifest.release_id {
983                return Err(err(format!(
984                    "release_identity.release_id {} != manifest {}",
985                    projection.release_identity.release_id, manifest.release_id
986                )));
987            }
988            let m_target = manifest
989                .target(target)
990                .map_err(|e| err(format!("target in manifest: {e}")))?;
991            let (m_artifact, m_install) = match &m_target.form {
992                ArtifactForm::Direct { artifact, install } => (artifact, install),
993                _ => return Err(err("manifest form is not direct")),
994            };
995            if projection.acquisition_units.len() != 1 {
996                return Err(err(format!(
997                    "direct projection must have exactly one acquisition unit, got {}",
998                    projection.acquisition_units.len()
999                )));
1000            }
1001            let unit = &projection.acquisition_units[0];
1002            if unit.name != m_artifact.name {
1003                return Err(err(format!(
1004                    "unit name {} != manifest {}",
1005                    unit.name, m_artifact.name
1006                )));
1007            }
1008            if unit.exact_size != m_artifact.size {
1009                return Err(err(format!(
1010                    "unit exact_size {} != manifest {}",
1011                    unit.exact_size, m_artifact.size
1012                )));
1013            }
1014            if unit.sha256 != m_artifact.sha256 {
1015                return Err(err(format!(
1016                    "unit sha256 {} != manifest {}",
1017                    unit.sha256, m_artifact.sha256
1018                )));
1019            }
1020            if unit.member_id != *m_install {
1021                return Err(err(format!(
1022                    "unit member_id {} != manifest install {m_install}",
1023                    unit.member_id
1024                )));
1025            }
1026            if unit.relative_destination != *m_install {
1027                return Err(err(format!(
1028                    "unit relative_destination {} != manifest install {m_install}",
1029                    unit.relative_destination
1030                )));
1031            }
1032            if projection.transaction_group != "one-artifact-set" {
1033                return Err(err(format!(
1034                    "transaction_group must be 'one-artifact-set', got {}",
1035                    projection.transaction_group
1036                )));
1037            }
1038            Ok(())
1039        }
1040
1041        fn check_bundle_projection(
1042            projection: &BundleProjection,
1043            manifest: &ReleaseManifest,
1044            target: &str,
1045        ) -> Result<(), String> {
1046            if projection.selected_target != target {
1047                return Err(err(format!(
1048                    "selected_target mismatch: {} != {target}",
1049                    projection.selected_target
1050                )));
1051            }
1052            if projection.release_identity.product_id != manifest.product_id {
1053                return Err(err(format!(
1054                    "release_identity.product_id {} != manifest {}",
1055                    projection.release_identity.product_id, manifest.product_id
1056                )));
1057            }
1058            if projection.release_identity.release_id != manifest.release_id {
1059                return Err(err(format!(
1060                    "release_identity.release_id {} != manifest {}",
1061                    projection.release_identity.release_id, manifest.release_id
1062                )));
1063            }
1064            let m_target = manifest
1065                .target(target)
1066                .map_err(|e| err(format!("target in manifest: {e}")))?;
1067            let m_entries: &Vec<BundleRecord> = match &m_target.form {
1068                ArtifactForm::Bundle { entries } => entries,
1069                _ => return Err(err("manifest form is not bundle")),
1070            };
1071            if projection.acquisition_units.len() != m_entries.len() {
1072                return Err(err(format!(
1073                    "acquisition unit count {} != manifest bundle entry count {}",
1074                    projection.acquisition_units.len(),
1075                    m_entries.len()
1076                )));
1077            }
1078            for m_entry in m_entries {
1079                let matched = projection.acquisition_units.iter().any(|u| {
1080                    u.name == m_entry.artifact.name
1081                        && u.exact_size == m_entry.artifact.size
1082                        && u.sha256 == m_entry.artifact.sha256
1083                        && u.member_id == m_entry.install
1084                        && u.relative_destination == m_entry.install
1085                });
1086                if !matched {
1087                    return Err(err(format!(
1088                        "no projection unit matches manifest entry {} (install {})",
1089                        m_entry.artifact.name, m_entry.install
1090                    )));
1091                }
1092            }
1093            for unit in &projection.acquisition_units {
1094                let matched = m_entries.iter().any(|e| {
1095                    e.artifact.name == unit.name
1096                        && e.artifact.size == unit.exact_size
1097                        && e.artifact.sha256 == unit.sha256
1098                        && e.install == unit.member_id
1099                        && e.install == unit.relative_destination
1100                });
1101                if !matched {
1102                    return Err(err(format!(
1103                        "projection unit {} has no paired manifest entry",
1104                        unit.name
1105                    )));
1106                }
1107            }
1108            if projection.transaction_group != "one-artifact-set" {
1109                return Err(err(format!(
1110                    "transaction_group must be 'one-artifact-set', got {}",
1111                    projection.transaction_group
1112                )));
1113            }
1114            Ok(())
1115        }
1116
1117        fn check_archive_projection(
1118            projection: &ArchiveProjection,
1119            manifest: &ReleaseManifest,
1120            target: &str,
1121        ) -> Result<(), String> {
1122            if projection.selected_target != target {
1123                return Err(err(format!(
1124                    "selected_target mismatch: {} != {target}",
1125                    projection.selected_target
1126                )));
1127            }
1128            let m_target = manifest
1129                .target(target)
1130                .map_err(|e| err(format!("target in manifest: {e}")))?;
1131            let (m_artifact, m_members) = match &m_target.form {
1132                ArtifactForm::Archive { artifact, members } => (artifact, members),
1133                _ => return Err(err("manifest form is not archive")),
1134            };
1135            if projection.acquisition_units.len() != 1 {
1136                return Err(err(format!(
1137                    "archive projection must have exactly one acquisition unit, got {}",
1138                    projection.acquisition_units.len()
1139                )));
1140            }
1141            let unit = &projection.acquisition_units[0];
1142            if unit.name != m_artifact.name {
1143                return Err(err(format!(
1144                    "acquisition unit name {} != manifest archive {}",
1145                    unit.name, m_artifact.name
1146                )));
1147            }
1148            if unit.exact_size != m_artifact.size {
1149                return Err(err(format!(
1150                    "acquisition unit exact_size {} != manifest {}",
1151                    unit.exact_size, m_artifact.size
1152                )));
1153            }
1154            if unit.sha256 != m_artifact.sha256 {
1155                return Err(err(format!(
1156                    "acquisition unit sha256 {} != manifest {}",
1157                    unit.sha256, m_artifact.sha256
1158                )));
1159            }
1160            if projection.members.len() != m_members.len() {
1161                return Err(err(format!(
1162                    "projected member count {} != manifest archive member count {}",
1163                    projection.members.len(),
1164                    m_members.len()
1165                )));
1166            }
1167            for m_member in m_members {
1168                let matched = projection.members.iter().any(|p| {
1169                    p.source == m_member.source
1170                        && p.install == m_member.install
1171                        && p.size == m_member.bytes.size
1172                        && p.sha256 == m_member.bytes.sha256
1173                });
1174                if !matched {
1175                    return Err(err(format!(
1176                        "no projected member matches manifest member source={} install={}",
1177                        m_member.source, m_member.install
1178                    )));
1179                }
1180            }
1181            for p in &projection.members {
1182                let matched = m_members.iter().any(|m| {
1183                    m.source == p.source
1184                        && m.install == p.install
1185                        && m.bytes.size == p.size
1186                        && m.bytes.sha256 == p.sha256
1187                });
1188                if !matched {
1189                    return Err(err(format!(
1190                        "projected member source={} install={} has no manifest member",
1191                        p.source, p.install
1192                    )));
1193                }
1194            }
1195            if !projection.extraction_required {
1196                return Err(err(
1197                    "archive projection must declare extraction_required=true before any Eggup ArtifactSet construction",
1198                ));
1199            }
1200            if !projection.transaction_group.contains("consumer-owned") {
1201                return Err(err(format!(
1202                    "archive transaction_group must reflect consumer-owned extraction, got {}",
1203                    projection.transaction_group
1204                )));
1205            }
1206            Ok(())
1207        }
1208
1209        fn bundle_projection_value() -> serde_json::Value {
1210            serde_json::from_str(BUNDLE_PROJECTION).expect("bundle projection is valid JSON")
1211        }
1212
1213        fn direct_projection_value() -> serde_json::Value {
1214            serde_json::from_str(DIRECT_PROJECTION).expect("direct projection is valid JSON")
1215        }
1216
1217        fn archive_projection_value() -> serde_json::Value {
1218            serde_json::from_str(ARCHIVE_PROJECTION).expect("archive projection is valid JSON")
1219        }
1220
1221        fn manifest_for(text: &str) -> ReleaseManifest {
1222            ReleaseManifest::from_json(text).expect("manifest fixture is valid v1")
1223        }
1224
1225        #[test]
1226        fn direct_projection_is_exact_pairwise_projection() {
1227            let projection: DirectProjection =
1228                serde_json::from_str(DIRECT_PROJECTION).expect("direct projection parses");
1229            let manifest = manifest_for(DIRECT_MANIFEST);
1230            check_direct_projection(&projection, &manifest, DIRECT_TARGET)
1231                .expect("checked-in direct projection must exactly project its manifest");
1232        }
1233
1234        #[test]
1235        fn bundle_projection_is_exact_pairwise_projection() {
1236            let projection: BundleProjection =
1237                serde_json::from_str(BUNDLE_PROJECTION).expect("bundle projection parses");
1238            let manifest = manifest_for(BUNDLE_MANIFEST);
1239            check_bundle_projection(&projection, &manifest, BUNDLE_TARGET)
1240                .expect("checked-in bundle projection must exactly project its manifest");
1241        }
1242
1243        #[test]
1244        fn archive_projection_is_exact_pairwise_projection() {
1245            let projection: ArchiveProjection =
1246                serde_json::from_str(ARCHIVE_PROJECTION).expect("archive projection parses");
1247            let manifest = manifest_for(ARCHIVE_MANIFEST);
1248            check_archive_projection(&projection, &manifest, ARCHIVE_TARGET)
1249                .expect("checked-in archive projection must exactly project its manifest");
1250        }
1251
1252        #[test]
1253        fn bundle_projection_rejects_substituting_eggsact_for_helper() {
1254            let mut value = bundle_projection_value();
1255            let units = value["acquisition_units"]
1256                .as_array_mut()
1257                .expect("acquisition_units array");
1258            let mut found = false;
1259            for unit in units.iter_mut() {
1260                if unit["name"] == "codegg-helper-2.4.0-x86_64-unknown-linux-gnu" {
1261                    unit["name"] = serde_json::json!("eggsact-2.4.0-x86_64-unknown-linux-gnu");
1262                    unit["member_id"] = serde_json::json!("eggsact");
1263                    unit["relative_destination"] = serde_json::json!("eggsact");
1264                    found = true;
1265                }
1266            }
1267            assert!(found, "mutated codegg-helper entry");
1268            let projection: BundleProjection =
1269                serde_json::from_value(value).expect("mutated projection still parses");
1270            let manifest = manifest_for(BUNDLE_MANIFEST);
1271            assert!(
1272                check_bundle_projection(&projection, &manifest, BUNDLE_TARGET).is_err(),
1273                "substituting eggsact for codegg-helper must be rejected"
1274            );
1275        }
1276
1277        #[test]
1278        fn bundle_projection_rejects_dropping_codegg_manifest_entry() {
1279            let mut value = bundle_projection_value();
1280            let units = value["acquisition_units"]
1281                .as_array_mut()
1282                .expect("acquisition_units array");
1283            let initial_len = units.len();
1284            units.retain(|u| u["name"] != "codegg-manifest-2.4.0.json");
1285            assert_eq!(
1286                units.len(),
1287                initial_len - 1,
1288                "dropped codegg-manifest entry"
1289            );
1290            let projection: BundleProjection =
1291                serde_json::from_value(value).expect("mutated projection still parses");
1292            let manifest = manifest_for(BUNDLE_MANIFEST);
1293            assert!(
1294                check_bundle_projection(&projection, &manifest, BUNDLE_TARGET).is_err(),
1295                "dropping codegg-manifest entry must be rejected"
1296            );
1297        }
1298
1299        #[test]
1300        fn bundle_projection_rejects_unrelated_fourth_unit() {
1301            let mut value = bundle_projection_value();
1302            value["acquisition_units"]
1303                .as_array_mut()
1304                .expect("acquisition_units array")
1305                .push(serde_json::json!({
1306                    "name": "unrelated-2.4.0-x86_64-unknown-linux-gnu",
1307                    "exact_size": 6,
1308                    "sha256": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
1309                    "member_id": "unrelated",
1310                    "relative_destination": "unrelated",
1311                }));
1312            let projection: BundleProjection =
1313                serde_json::from_value(value).expect("mutated projection still parses");
1314            let manifest = manifest_for(BUNDLE_MANIFEST);
1315            assert!(
1316                check_bundle_projection(&projection, &manifest, BUNDLE_TARGET).is_err(),
1317                "extra unrelated bundle unit must be rejected"
1318            );
1319        }
1320
1321        #[test]
1322        fn bundle_projection_rejects_crossed_destinations() {
1323            let mut value = bundle_projection_value();
1324            let units = value["acquisition_units"]
1325                .as_array_mut()
1326                .expect("acquisition_units array");
1327            let mut codegg_idx = None;
1328            let mut helper_idx = None;
1329            for (idx, unit) in units.iter().enumerate() {
1330                if unit["name"] == "codegg-2.4.0-x86_64-unknown-linux-gnu" {
1331                    codegg_idx = Some(idx);
1332                } else if unit["name"] == "codegg-helper-2.4.0-x86_64-unknown-linux-gnu" {
1333                    helper_idx = Some(idx);
1334                }
1335            }
1336            let codegg_idx = codegg_idx.expect("codegg unit");
1337            let helper_idx = helper_idx.expect("helper unit");
1338            let swapped_size = units[helper_idx]["exact_size"].clone();
1339            let swapped_digest = units[helper_idx]["sha256"].clone();
1340            units[codegg_idx]["exact_size"] = swapped_size.clone();
1341            units[codegg_idx]["sha256"] = swapped_digest.clone();
1342            units[helper_idx]["exact_size"] = units[helper_idx]["exact_size"].clone();
1343            units[helper_idx]["sha256"] = units[helper_idx]["sha256"].clone();
1344            // Now genuinely cross: codegg unit claims helper's facts, helper keeps its own,
1345            // so no manifest entry can match either unit.
1346            let helper_size = units[helper_idx]["exact_size"].clone();
1347            let helper_digest = units[helper_idx]["sha256"].clone();
1348            units[codegg_idx]["exact_size"] = helper_size;
1349            units[codegg_idx]["sha256"] = helper_digest;
1350            let _ = swapped_size;
1351            let _ = swapped_digest;
1352            let projection: BundleProjection =
1353                serde_json::from_value(value).expect("mutated projection still parses");
1354            let manifest = manifest_for(BUNDLE_MANIFEST);
1355            assert!(
1356                check_bundle_projection(&projection, &manifest, BUNDLE_TARGET).is_err(),
1357                "crossed bundle destination/digest must be rejected"
1358            );
1359        }
1360
1361        #[test]
1362        fn bundle_projection_rejects_duplicate_unit() {
1363            let mut value = bundle_projection_value();
1364            let units = value["acquisition_units"]
1365                .as_array_mut()
1366                .expect("acquisition_units array");
1367            let original = units[0].clone();
1368            units.push(original);
1369            let projection: BundleProjection =
1370                serde_json::from_value(value).expect("mutated projection still parses");
1371            let manifest = manifest_for(BUNDLE_MANIFEST);
1372            assert!(
1373                check_bundle_projection(&projection, &manifest, BUNDLE_TARGET).is_err(),
1374                "duplicate bundle unit must be rejected"
1375            );
1376        }
1377
1378        #[test]
1379        fn projection_rejects_wrong_selected_target() {
1380            let mut value = direct_projection_value();
1381            value["selected_target"] = serde_json::json!("x86_64-pc-windows-gnu");
1382            let projection: DirectProjection =
1383                serde_json::from_value(value).expect("mutated projection still parses");
1384            let manifest = manifest_for(DIRECT_MANIFEST);
1385            assert!(
1386                check_direct_projection(&projection, &manifest, DIRECT_TARGET).is_err(),
1387                "wrong selected target must be rejected"
1388            );
1389        }
1390
1391        #[test]
1392        fn archive_projection_rejects_crossed_member_relationship() {
1393            let mut value = archive_projection_value();
1394            let members = value["members"].as_array_mut().expect("members array");
1395            let mut egress_idx = None;
1396            let mut helper_idx = None;
1397            for (idx, member) in members.iter().enumerate() {
1398                if member["source"] == "egress" {
1399                    egress_idx = Some(idx);
1400                } else if member["source"] == "bin/egress-helper" {
1401                    helper_idx = Some(idx);
1402                }
1403            }
1404            let egress_idx = egress_idx.expect("egress member");
1405            let helper_idx = helper_idx.expect("helper member");
1406            let helper_install = members[helper_idx]["install"].clone();
1407            let helper_size = members[helper_idx]["size"].clone();
1408            let helper_digest = members[helper_idx]["sha256"].clone();
1409            members[egress_idx]["install"] = helper_install;
1410            members[egress_idx]["size"] = helper_size;
1411            members[egress_idx]["sha256"] = helper_digest;
1412            let projection: ArchiveProjection =
1413                serde_json::from_value(value).expect("mutated projection still parses");
1414            let manifest = manifest_for(ARCHIVE_MANIFEST);
1415            assert!(
1416                check_archive_projection(&projection, &manifest, ARCHIVE_TARGET).is_err(),
1417                "crossed archive member relationship must be rejected"
1418            );
1419        }
1420
1421        #[test]
1422        fn archive_projection_rejects_missing_extraction_required() {
1423            let mut value = archive_projection_value();
1424            value["extraction_required"] = serde_json::json!(false);
1425            let projection: ArchiveProjection =
1426                serde_json::from_value(value).expect("mutated projection still parses");
1427            let manifest = manifest_for(ARCHIVE_MANIFEST);
1428            assert!(
1429                check_archive_projection(&projection, &manifest, ARCHIVE_TARGET).is_err(),
1430                "archive projection without extraction_required=true must be rejected"
1431            );
1432        }
1433
1434        #[test]
1435        fn direct_projection_rejects_wrong_size_or_digest() {
1436            let mut value = direct_projection_value();
1437            let units = value["acquisition_units"]
1438                .as_array_mut()
1439                .expect("acquisition_units array");
1440            units[0]["exact_size"] = serde_json::json!(4);
1441            let projection: DirectProjection =
1442                serde_json::from_value(value).expect("mutated projection still parses");
1443            let manifest = manifest_for(DIRECT_MANIFEST);
1444            assert!(
1445                check_direct_projection(&projection, &manifest, DIRECT_TARGET).is_err(),
1446                "direct projection with mutated exact_size must be rejected"
1447            );
1448
1449            let mut value = direct_projection_value();
1450            let units = value["acquisition_units"]
1451                .as_array_mut()
1452                .expect("acquisition_units array");
1453            units[0]["sha256"] = serde_json::json!(
1454                "cb8379ac2098aa165029e3938a51da0bcecfc008fd6795f401178647f96c5b34"
1455            );
1456            let projection: DirectProjection =
1457                serde_json::from_value(value).expect("mutated projection still parses");
1458            let manifest = manifest_for(DIRECT_MANIFEST);
1459            assert!(
1460                check_direct_projection(&projection, &manifest, DIRECT_TARGET).is_err(),
1461                "direct projection with mutated sha256 must be rejected"
1462            );
1463        }
1464
1465        #[test]
1466        fn wrong_target_projection_fixture_is_negative_evidence() {
1467            let text = include_str!(
1468                "../../../plans/closure/eggup-interoperability/fixtures/wrong-target.json"
1469            );
1470            let value: serde_json::Value = serde_json::from_str(text).expect("wrong-target JSON");
1471            assert_eq!(value["selected_target"], "x86_64-pc-windows-gnu");
1472            assert_eq!(
1473                value["expected"],
1474                "no exact target match; no alias or nearest-target fallback"
1475            );
1476            let manifest = manifest_for(DIRECT_MANIFEST);
1477            assert!(
1478                manifest.target("x86_64-pc-windows-gnu").is_err(),
1479                "wrong-target fixture must remain an unsupported selection"
1480            );
1481        }
1482    }
1483
1484    #[test]
1485    fn m003l_sha256_acceptance_set_is_the_canonical_one() {
1486        // The canonical acceptance set: exactly 64 lowercase hexadecimal
1487        // characters, and not the all-zeros placeholder (ADR-0006).
1488        assert!(validate_sha256_hex(
1489            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90"
1490        )
1491        .is_ok());
1492        assert_eq!(
1493            validate_sha256_hex(&"0".repeat(64)),
1494            Err(Sha256Error::AllZeros)
1495        );
1496        assert_eq!(
1497            validate_sha256_hex(&"A".repeat(64)),
1498            Err(Sha256Error::NotLowercaseHex)
1499        );
1500        assert_eq!(
1501            validate_sha256_hex(&"g".repeat(64)),
1502            Err(Sha256Error::NotLowercaseHex)
1503        );
1504        assert_eq!(
1505            validate_sha256_hex(&"a".repeat(63)),
1506            Err(Sha256Error::Length)
1507        );
1508        assert_eq!(
1509            validate_sha256_hex(&"a".repeat(65)),
1510            Err(Sha256Error::Length)
1511        );
1512        assert_eq!(validate_sha256_hex(""), Err(Sha256Error::Length));
1513        // The document shape is unchanged, but the acceptance set tightened:
1514        // the all-zeros placeholder is no longer a usable evidence digest.
1515        assert!(ByteEvidence::validate(&ByteEvidence {
1516            size: 1,
1517            sha256: "0".repeat(64),
1518        })
1519        .is_err());
1520        assert!(ByteEvidence::validate(&ByteEvidence {
1521            size: 1,
1522            sha256: "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90".to_owned(),
1523        })
1524        .is_ok());
1525        // The reason phrases stay single-line and bounded.
1526        for error in [
1527            Sha256Error::Length,
1528            Sha256Error::NotLowercaseHex,
1529            Sha256Error::AllZeros,
1530        ] {
1531            let reason = error.reason();
1532            assert!(!reason.is_empty() && !reason.contains('\n'));
1533            assert!(reason.len() <= 64);
1534        }
1535    }
1536}