Skip to main content

eggpack_github/
lib.rs

1//! GitHub draft release staging adapter and local staging payload materializer.
2//!
3//! M003a owns two bounded capabilities: materialize a complete local staging
4//! payload from M004 finalization plus `ReleaseManifest` plus deterministic
5//! bootstrap generators, and reconcile that payload into a GitHub draft
6//! release through a provider-specific adapter. There is no publication
7//! authority, no tag creation/move/delete, and no `publish` endpoint.
8
9#![forbid(unsafe_code)]
10#![deny(missing_docs)]
11
12use eggpack_bootstrap::{BootstrapInstallPolicyV1, BootstrapSpec};
13use eggpack_contract::{DistributionContract, ExpandedAssets};
14use eggpack_manifest::ReleaseManifest;
15use serde::{Deserialize, Serialize};
16use std::collections::{BTreeMap, BTreeSet};
17use std::fmt;
18use std::path::{Component, Path, PathBuf};
19use std::sync::Mutex;
20
21const API_BASE: &str = "https://api.github.com";
22const UPLOAD_BASE: &str = "https://uploads.github.com";
23const API_VERSION: &str = "2026-03-10";
24const USER_AGENT: &str = "eggpack-github/0.1.0";
25const MAX_TAG_PEEL_DEPTH: usize = 8;
26const MAX_POLICY_JSON: usize = 256 * 1024;
27const RELEASE_IDENTITY_SCHEMA_VERSION: u32 = 1;
28const MAX_PAYLOAD_JSON: usize = 1_048_576;
29const MAX_BODY_NOTES: usize = 65_536;
30const MAX_TITLE: usize = 256;
31const MAX_NAME_SEGMENT: usize = 128;
32const FIXED_MANIFEST_NAME: &str = "release-manifest.json";
33const FIXED_POSIX_NAME: &str = "install.sh";
34const FIXED_POWERSHELL_NAME: &str = "install.ps1";
35/// Maximum upload read/write chunk, bounding per-asset transfer memory.
36const UPLOAD_CHUNK_BYTES: usize = 64 * 1024;
37/// GitHub's fixed page size for both the release and asset listings.
38const LIST_PAGE_SIZE: usize = 100;
39
40/// Bounded staging failure with redacted diagnostics.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct GithubError(String);
43
44impl fmt::Display for GithubError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.write_str(&self.0)
47    }
48}
49
50impl std::error::Error for GithubError {}
51
52fn fail(message: impl Into<String>) -> GithubError {
53    GithubError(message.into())
54}
55
56/// Finite producer mapping from an immutable source tag to manifest identity.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "snake_case")]
59pub enum ReleaseIdentityMode {
60    /// Preserve the historical opaque tag as the manifest release id.
61    ExactTag,
62    /// Map exactly `vMAJOR.MINOR.PATCH` to `MAJOR.MINOR.PATCH`.
63    VPrefixedStableSemver,
64}
65
66impl ReleaseIdentityMode {
67    /// Resolve the finite manifest identity for one validated source tag.
68    pub fn release_id(self, tag: &str) -> Result<String, GithubError> {
69        validate_tag(tag)?;
70        match self {
71            Self::ExactTag => Ok(tag.to_owned()),
72            Self::VPrefixedStableSemver => {
73                let version = tag
74                    .strip_prefix('v')
75                    .ok_or_else(|| fail("stable semantic tag must start with v"))?;
76                let parts: Vec<&str> = version.split('.').collect();
77                if parts.len() != 3
78                    || parts.iter().any(|part| {
79                        part.is_empty()
80                            || !part.bytes().all(|byte| byte.is_ascii_digit())
81                            || (part.len() > 1 && part.starts_with('0'))
82                            || part.parse::<u64>().is_err()
83                    })
84                {
85                    return Err(fail("tag is not v-prefixed stable semantic version"));
86                }
87                Ok(version.to_owned())
88            }
89        }
90    }
91}
92
93/// Strict draft staging policy.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96pub struct GitHubDraftPolicyV1 {
97    /// Schema version, exactly 1.
98    pub schema_version: u32,
99    /// GitHub repository owner.
100    pub owner: String,
101    /// GitHub repository name.
102    pub repository: String,
103    /// Exact existing tag to stage.
104    pub tag: String,
105    /// Version of the optional mapped-identity tuple; absent in legacy mode.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub release_identity_schema_version: Option<u32>,
108    /// Opt-in identity mode. Absent preserves historical exact-tag JSON.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub release_identity_mode: Option<ReleaseIdentityMode>,
111    /// Mapped manifest identity. Present exactly when the opt-in mode is used.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub release_id: Option<String>,
114    /// Checked-out source revision bound by runtime identity resolution.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub source_revision: Option<String>,
117    /// Draft release title.
118    pub title: String,
119    /// Bounded release notes body.
120    #[serde(default)]
121    pub body: String,
122    /// Prerelease intent.
123    #[serde(default)]
124    pub prerelease: bool,
125    /// Token environment variable name, allowlisted to `GITHUB_TOKEN`.
126    #[serde(default = "default_token_env")]
127    pub token_env: String,
128    /// Per-request timeout in seconds.
129    #[serde(default = "default_timeout_secs")]
130    pub request_timeout_secs: u64,
131    /// Maximum metadata response bytes.
132    #[serde(default = "default_max_metadata_bytes")]
133    pub max_metadata_bytes: usize,
134    /// Maximum bounded release-list pages.
135    #[serde(default = "default_max_list_pages")]
136    pub max_list_pages: u32,
137}
138
139fn default_token_env() -> String {
140    "GITHUB_TOKEN".to_owned()
141}
142
143fn default_timeout_secs() -> u64 {
144    30
145}
146
147fn default_max_metadata_bytes() -> usize {
148    1_000_000
149}
150
151fn default_max_list_pages() -> u32 {
152    16
153}
154
155impl GitHubDraftPolicyV1 {
156    /// Parse strict bounded JSON policy.
157    pub fn from_json(text: &str) -> Result<Self, GithubError> {
158        if text.len() > MAX_POLICY_JSON {
159            return Err(fail("github draft policy exceeds size bound"));
160        }
161        let value: Self =
162            serde_json::from_str(text).map_err(|_| fail("invalid github draft policy JSON"))?;
163        value.validate()?;
164        Ok(value)
165    }
166
167    /// Serialize deterministically after validation.
168    pub fn to_json(&self) -> Result<String, GithubError> {
169        self.validate()?;
170        serde_json::to_string(self).map_err(|_| fail("github draft policy encode failed"))
171    }
172
173    /// Validate all bounds and injection rules.
174    pub fn validate(&self) -> Result<(), GithubError> {
175        if self.schema_version != 1 {
176            return Err(fail("unsupported github draft policy version"));
177        }
178        validate_owner(&self.owner)?;
179        validate_repo(&self.repository)?;
180        validate_tag(&self.tag)?;
181        match (
182            self.release_identity_schema_version,
183            self.release_identity_mode,
184            self.release_id.as_deref(),
185            self.source_revision.as_deref(),
186        ) {
187            (None, None, None, None) => {}
188            (
189                Some(RELEASE_IDENTITY_SCHEMA_VERSION),
190                Some(mode),
191                Some(release_id),
192                Some(_revision),
193            ) if mode
194                .release_id(&self.tag)
195                .is_ok_and(|expected| expected == release_id) => {}
196            _ => {
197                return Err(fail(
198                    "draft identity envelope is incomplete or inconsistent",
199                ))
200            }
201        }
202        if let Some(revision) = self.source_revision.as_deref() {
203            if revision.len() != 40
204                || !revision
205                    .bytes()
206                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
207            {
208                return Err(fail("draft source revision is invalid"));
209            }
210        }
211        validate_title(&self.title)?;
212        validate_body(&self.body)?;
213        if self.token_env != "GITHUB_TOKEN" {
214            return Err(fail("token env must be GITHUB_TOKEN"));
215        }
216        if !(5..=120).contains(&self.request_timeout_secs) {
217            return Err(fail("request timeout out of bounds"));
218        }
219        if self.max_metadata_bytes == 0 || self.max_metadata_bytes > 8_000_000 {
220            return Err(fail("max metadata bytes out of bounds"));
221        }
222        if self.max_list_pages == 0 || self.max_list_pages > 32 {
223            return Err(fail("max list pages out of bounds"));
224        }
225        Ok(())
226    }
227
228    /// Exact release download origin for bootstrap installers.
229    pub fn download_origin(&self) -> String {
230        format!(
231            "https://github.com/{}/{}/releases/download/{}",
232            self.owner, self.repository, self.tag
233        )
234    }
235
236    /// Manifest id bound by this policy, preserving legacy exact-tag policy.
237    pub fn resolved_release_id(&self) -> &str {
238        self.release_id.as_deref().unwrap_or(&self.tag)
239    }
240}
241
242/// Semantic kind of one staged file.
243///
244/// M003d compatibility: the payload schema remains v1. `GeneratedDefault`
245/// payloads use exactly the M003a kind set, so existing v1 readers parse
246/// them unchanged. `ProductWrappers` payloads additionally use
247/// `ProductPosixWrapper` / `ProductPowershellWrapper`; v1 readers that do
248/// not know those variants reject such payloads (fail-closed) rather than
249/// silently reinterpreting them.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "snake_case")]
252pub enum StagingAssetKind {
253    /// Finalized M004 artifact bytes.
254    FinalizedArtifact,
255    /// Checksum sidecar for a finalized artifact.
256    ChecksumSidecar,
257    /// Standalone deterministic release manifest.
258    ReleaseManifest,
259    /// Deterministic POSIX installer.
260    PosixInstaller,
261    /// Deterministic PowerShell installer.
262    PowershellInstaller,
263    /// Consumer-owned POSIX wrapper copied exactly from the verified source
264    /// tree and staged as the public `install.sh` (M003d only).
265    ProductPosixWrapper,
266    /// Consumer-owned PowerShell wrapper copied exactly from the verified
267    /// source tree and staged as the public `install.ps1` (M003d only).
268    ProductPowershellWrapper,
269}
270
271/// One ordered staged file record.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(deny_unknown_fields)]
274pub struct StagingAsset {
275    /// Safe flat asset name.
276    pub name: String,
277    /// Local relative path under payload root (flat, equals name).
278    pub path: String,
279    /// Exact byte size.
280    pub size: u64,
281    /// Lowercase SHA-256 hex.
282    pub sha256: String,
283    /// Media type for upload.
284    pub media_type: String,
285    /// Semantic kind.
286    pub kind: StagingAssetKind,
287}
288
289/// Deterministic local staging payload.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(deny_unknown_fields)]
292pub struct StagingPayloadV1 {
293    /// Schema version, exactly 1.
294    pub schema_version: u32,
295    /// Product id from manifest.
296    pub product_id: String,
297    /// Release id from manifest.
298    pub release_id: String,
299    /// Source revision from manifest.
300    pub source_revision: String,
301    /// Repository owner.
302    pub owner: String,
303    /// Repository name.
304    pub repository: String,
305    /// Exact existing tag.
306    pub tag: String,
307    /// Draft title.
308    pub title: String,
309    /// Prerelease intent.
310    pub prerelease: bool,
311    /// Bounded release notes.
312    pub body: String,
313    /// Ordered asset records sorted by name.
314    pub assets: Vec<StagingAsset>,
315}
316
317impl StagingPayloadV1 {
318    /// Parse strict bounded JSON payload.
319    pub fn from_json(text: &str) -> Result<Self, GithubError> {
320        if text.len() > MAX_PAYLOAD_JSON {
321            return Err(fail("staging payload exceeds size bound"));
322        }
323        let value: Self =
324            serde_json::from_str(text).map_err(|_| fail("invalid staging payload JSON"))?;
325        value.validate()?;
326        Ok(value)
327    }
328
329    /// Serialize deterministically after validation.
330    pub fn to_json(&self) -> Result<String, GithubError> {
331        self.validate()?;
332        let mut canonical = self.clone();
333        canonical.assets.sort_by(|a, b| a.name.cmp(&b.name));
334        serde_json::to_string(&canonical).map_err(|_| fail("staging payload encode failed"))
335    }
336
337    /// Validate bounds, paths, digests, and ordering.
338    pub fn validate(&self) -> Result<(), GithubError> {
339        if self.schema_version != 1 {
340            return Err(fail("unsupported staging payload version"));
341        }
342        if self.product_id.is_empty()
343            || self.product_id.len() > MAX_NAME_SEGMENT
344            || self.release_id.is_empty()
345            || self.release_id.len() > MAX_NAME_SEGMENT
346            || self.source_revision.is_empty()
347            || self.source_revision.len() > MAX_NAME_SEGMENT
348        {
349            return Err(fail("staging payload identity out of bounds"));
350        }
351        validate_owner(&self.owner)?;
352        validate_repo(&self.repository)?;
353        validate_tag(&self.tag)?;
354        validate_title(&self.title)?;
355        validate_body(&self.body)?;
356        if self.assets.is_empty() || self.assets.len() > 1024 {
357            return Err(fail("staging payload asset count out of bounds"));
358        }
359        let mut seen = BTreeSet::new();
360        for asset in &self.assets {
361            validate_asset_name(&asset.name)?;
362            validate_relative_path(&asset.path)?;
363            if asset.path != asset.name {
364                return Err(fail("staging payload path must equal flat asset name"));
365            }
366            if asset.size == 0 {
367                return Err(fail("staging asset size must be non-zero"));
368            }
369            validate_sha256(&asset.sha256)?;
370            if asset.media_type.is_empty() || asset.media_type.len() > 128 {
371                return Err(fail("staging asset media type out of bounds"));
372            }
373            if !seen.insert(asset.name.to_ascii_lowercase()) {
374                return Err(fail("duplicate staging asset name"));
375            }
376        }
377        Ok(())
378    }
379}
380
381/// Bounded staging receipt (producer evidence, not an install receipt).
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
383#[serde(deny_unknown_fields)]
384pub struct GitHubDraftReceiptV1 {
385    /// Schema version, exactly 1.
386    pub schema_version: u32,
387    /// Repository owner.
388    pub owner: String,
389    /// Repository name.
390    pub repository: String,
391    /// Product release id.
392    pub release_id: String,
393    /// Exact tag.
394    pub tag: String,
395    /// Source revision.
396    pub source_revision: String,
397    /// GitHub numeric release id.
398    pub github_release_id: u64,
399    /// Draft state, always true.
400    pub draft: bool,
401    /// Immutable state, always false for staged drafts.
402    pub immutable: bool,
403    /// Ordered asset names.
404    pub assets: Vec<StagingAsset>,
405    /// True when the release was created by this invocation.
406    pub created: bool,
407    /// Count of uploaded assets.
408    pub uploaded: u32,
409    /// Count of reused exact assets.
410    pub reused: u32,
411}
412
413impl GitHubDraftReceiptV1 {
414    /// Parse strict bounded JSON receipt.
415    pub fn from_json(text: &str) -> Result<Self, GithubError> {
416        if text.len() > MAX_PAYLOAD_JSON {
417            return Err(fail("staging receipt exceeds size bound"));
418        }
419        let value: Self =
420            serde_json::from_str(text).map_err(|_| fail("invalid staging receipt JSON"))?;
421        value.validate()?;
422        Ok(value)
423    }
424
425    /// Serialize after validation.
426    pub fn to_json(&self) -> Result<String, GithubError> {
427        self.validate()?;
428        serde_json::to_string(self).map_err(|_| fail("staging receipt encode failed"))
429    }
430
431    /// Validate receipt shape.
432    pub fn validate(&self) -> Result<(), GithubError> {
433        if self.schema_version != 1 {
434            return Err(fail("unsupported staging receipt version"));
435        }
436        validate_owner(&self.owner)?;
437        validate_repo(&self.repository)?;
438        validate_tag(&self.tag)?;
439        if !self.draft || self.immutable {
440            return Err(fail("receipt must describe a mutable draft"));
441        }
442        if self.assets.is_empty() || self.assets.len() > 1024 {
443            return Err(fail("receipt asset count out of bounds"));
444        }
445        if self
446            .uploaded
447            .checked_add(self.reused)
448            .is_none_or(|total| total as usize != self.assets.len())
449        {
450            return Err(fail("receipt upload/reuse counts must cover assets"));
451        }
452        Ok(())
453    }
454}
455
456fn validate_owner(value: &str) -> Result<(), GithubError> {
457    if value.is_empty() || value.len() > 64 {
458        return Err(fail("owner out of bounds"));
459    }
460    if value.chars().any(char::is_control) {
461        return Err(fail("owner contains control characters"));
462    }
463    if !value
464        .bytes()
465        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
466    {
467        return Err(fail("owner contains unsupported characters"));
468    }
469    if value.starts_with('-') || value.ends_with('-') || value.contains("..") {
470        return Err(fail("owner has unsafe shape"));
471    }
472    Ok(())
473}
474
475fn validate_repo(value: &str) -> Result<(), GithubError> {
476    if value.is_empty() || value.len() > 64 {
477        return Err(fail("repository out of bounds"));
478    }
479    if value.chars().any(char::is_control) {
480        return Err(fail("repository contains control characters"));
481    }
482    if !value
483        .bytes()
484        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
485    {
486        return Err(fail("repository contains unsupported characters"));
487    }
488    if value.contains("..") {
489        return Err(fail("repository has unsafe shape"));
490    }
491    Ok(())
492}
493
494fn validate_tag(value: &str) -> Result<(), GithubError> {
495    // The canonical exact-tag safety rule is owned by `eggpack-core`; this
496    // crate keeps its own diagnostic wording for each refusal class.
497    eggpack_core::validate_exact_tag_safety(value).map_err(|error| {
498        fail(match error {
499            eggpack_core::ExactTagSafetyError::OutOfBounds => "tag out of bounds",
500            eggpack_core::ExactTagSafetyError::ControlCharacters => {
501                "tag contains control characters"
502            }
503            eggpack_core::ExactTagSafetyError::QueryOrInjectionCharacters => {
504                "tag contains query/injection characters"
505            }
506            eggpack_core::ExactTagSafetyError::UnsafePathShape => "tag has unsafe path shape",
507            eggpack_core::ExactTagSafetyError::UnsafeGitRefPath => {
508                "tag has unsafe git ref path shape"
509            }
510        })
511    })
512}
513
514fn validate_title(value: &str) -> Result<(), GithubError> {
515    if value.is_empty() || value.len() > MAX_TITLE {
516        return Err(fail("title out of bounds"));
517    }
518    if value.chars().any(char::is_control) {
519        return Err(fail("title contains control characters"));
520    }
521    Ok(())
522}
523
524fn validate_body(value: &str) -> Result<(), GithubError> {
525    if value.len() > MAX_BODY_NOTES {
526        return Err(fail("release notes exceed bound"));
527    }
528    if value.chars().any(|c| c == '\0') {
529        return Err(fail("release notes contain NUL"));
530    }
531    Ok(())
532}
533
534fn validate_asset_name(value: &str) -> Result<(), GithubError> {
535    if value.is_empty() || value.len() > 255 {
536        return Err(fail("asset name out of bounds"));
537    }
538    if value == "." || value == ".." {
539        return Err(fail("asset name is not a safe flat name"));
540    }
541    if value.contains('/') || value.contains('\\') {
542        return Err(fail("asset name must be flat"));
543    }
544    if value.chars().any(char::is_control) {
545        return Err(fail("asset name contains control characters"));
546    }
547    Ok(())
548}
549
550fn validate_relative_path(value: &str) -> Result<(), GithubError> {
551    if value.is_empty() || value.len() > 512 {
552        return Err(fail("staging path out of bounds"));
553    }
554    if Path::new(value).is_absolute() {
555        return Err(fail("staging path must be relative"));
556    }
557    if value.contains('\\') {
558        return Err(fail("staging path must use flat relative form"));
559    }
560    let path = Path::new(value);
561    for component in path.components() {
562        match component {
563            Component::Normal(_) => {}
564            _ => return Err(fail("staging path contains traversal")),
565        }
566    }
567    validate_asset_name(value)?;
568    Ok(())
569}
570
571fn validate_sha256(value: &str) -> Result<(), GithubError> {
572    // The SHA-256 hex acceptance set is owned by `eggpack-manifest`
573    // (ADR-0006); this crate applies it rather than restating it.
574    eggpack_manifest::validate_sha256_hex(value).map_err(|error| {
575        fail(match error {
576            eggpack_manifest::Sha256Error::AllZeros => "sha256 must not be the all-zeros digest",
577            _ => "sha256 must be 64 lowercase hex characters",
578        })
579    })
580}
581
582/// Read a credential from the environment without logging it.
583pub fn read_token(env_name: &str) -> Result<String, GithubError> {
584    if env_name != "GITHUB_TOKEN" {
585        return Err(fail("token env must be GITHUB_TOKEN"));
586    }
587    let value = std::env::var(env_name).map_err(|_| fail("github token is absent"))?;
588    if value.is_empty() || value.len() > 4096 || value.chars().any(char::is_control) {
589        return Err(fail("github token is absent"));
590    }
591    Ok(value)
592}
593
594/// Digest one staging file with the canonical producer file-digest helper.
595///
596/// The bytes are never held in memory: a finalized release bundle can be far
597/// larger than the process should grow to accommodate, and the rest of this
598/// crate already streams — `streamed_upload_body` and `verify_file` both read
599/// in `UPLOAD_CHUNK_BYTES` chunks. Peak memory here is therefore independent
600/// of artifact size.
601///
602/// The digest rule itself is owned by `eggpack-core`; this wrapper only keeps
603/// the crate's own staging diagnostic wording.
604fn digest_file(path: &Path) -> Result<(u64, String), GithubError> {
605    eggpack_core::file_digest(path).map_err(|error| fail(staging_digest_message(error)))
606}
607
608/// Map a canonical file-digest refusal to this crate's staging diagnostic.
609fn staging_digest_message(error: eggpack_core::DigestError) -> &'static str {
610    match error {
611        eggpack_core::DigestError::Unavailable => "staging file is unavailable",
612        eggpack_core::DigestError::NotRegularFile | eggpack_core::DigestError::Empty => {
613            "staging file must be a non-empty regular file"
614        }
615        eggpack_core::DigestError::OpenFailed | eggpack_core::DigestError::ReadFailed => {
616            "staging file cannot be read"
617        }
618        eggpack_core::DigestError::SizeOverflow => "staging file size exceeds the platform bound",
619        eggpack_core::DigestError::ChangedDuringRead => "staging file changed during read",
620    }
621}
622
623fn reject_symlink_dir(path: &Path, label: &str) -> Result<(), GithubError> {
624    let metadata =
625        std::fs::symlink_metadata(path).map_err(|_| fail(format!("{label} is unavailable")))?;
626    if metadata.file_type().is_symlink() || !metadata.is_dir() {
627        return Err(fail(format!("{label} is not a real directory")));
628    }
629    Ok(())
630}
631
632fn ensure_absent_private_dir(path: &Path, label: &str) -> Result<(), GithubError> {
633    if std::fs::symlink_metadata(path).is_ok() {
634        return Err(fail(format!("{label} must be absent")));
635    }
636    let parent = path
637        .parent()
638        .filter(|p| !p.as_os_str().is_empty())
639        .map(PathBuf::from)
640        .unwrap_or_else(|| PathBuf::from("."));
641    reject_symlink_dir(&parent, "output parent")?;
642    std::fs::create_dir(path).map_err(|_| fail(format!("{label} could not be created")))?;
643    #[cfg(unix)]
644    {
645        use std::os::unix::fs::PermissionsExt;
646        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
647            .map_err(|_| fail(format!("{label} permissions could not be restricted")))?;
648    }
649    Ok(())
650}
651
652/// Materialize a complete deterministic staging payload.
653///
654/// The finalized root is revalidated against the contract and manifest; exact
655/// finalized assets are copied into a private staging directory alongside a
656/// standalone `release-manifest.json` and deterministic bootstrap installers.
657///
658/// This is the generated-default installer presentation. It is the same
659/// single implementation that serves
660/// [`prepare_staging_payload_with_presentation`], with the presentation
661/// selected as an argument.
662#[allow(clippy::too_many_arguments)]
663pub fn prepare_staging_payload(
664    contract: &DistributionContract,
665    manifest: &ReleaseManifest,
666    finalized_root: &Path,
667    policy: &GitHubDraftPolicyV1,
668    install_policy: &BootstrapInstallPolicyV1,
669    output_dir: &Path,
670) -> Result<StagingPayloadV1, GithubError> {
671    prepare_staging_payload_with_presentation_inner(
672        contract,
673        manifest,
674        finalized_root,
675        policy,
676        install_policy,
677        &InstallerPresentationV1::generated_default(),
678        None,
679        output_dir,
680    )
681}
682
683/// Materialize a staging payload with an explicit installer presentation.
684///
685/// The presentation selects only the installer surface. Every other step —
686/// validation, inventory construction, sidecars, installers, digest loop,
687/// canonical sort, and payload assembly — is one implementation, shared with
688/// [`prepare_staging_payload`].
689#[allow(clippy::too_many_arguments)]
690pub fn prepare_staging_payload_with_presentation(
691    contract: &DistributionContract,
692    manifest: &ReleaseManifest,
693    finalized_root: &Path,
694    policy: &GitHubDraftPolicyV1,
695    install_policy: &BootstrapInstallPolicyV1,
696    presentation: &InstallerPresentationV1,
697    source_root: &Path,
698    output_dir: &Path,
699) -> Result<StagingPayloadV1, GithubError> {
700    prepare_staging_payload_with_presentation_inner(
701        contract,
702        manifest,
703        finalized_root,
704        policy,
705        install_policy,
706        presentation,
707        Some(source_root),
708        output_dir,
709    )
710}
711
712// ---------------------------------------------------------------------------
713// M003d — installer presentation policy and static draft template.
714// ---------------------------------------------------------------------------
715
716/// Maximum product wrapper source bytes (1 MiB per wrapper, M003d section 6).
717pub const MAX_WRAPPER_BYTES: u64 = 1024 * 1024;
718const MAX_PRESENTATION_JSON: usize = 64 * 1024;
719const MAX_TEMPLATE_JSON: usize = 64 * 1024;
720const MAX_TITLE_PREFIX: usize = 128;
721
722/// Strict versioned staging installer policy owned by the staging layer.
723///
724/// - `GeneratedDefault` preserves M003a behavior byte-for-byte: generated
725///   exact-release installers are staged as the public `install.sh` /
726///   `install.ps1`.
727/// - `ProductWrappers` stages four installer assets: consumer-owned wrapper
728///   bytes copied exactly as the public `install.sh` / `install.ps1`, plus
729///   Eggpack-generated exact installers under configured non-colliding
730///   names (eggsact: `install-exact.sh` / `install-exact.ps1`).
731#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
732#[serde(deny_unknown_fields)]
733pub struct InstallerPresentationV1 {
734    /// Schema version, exactly 1.
735    pub schema_version: u32,
736    /// Presentation mode.
737    pub mode: InstallerPresentationModeV1,
738}
739
740/// Installer presentation mode.
741#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
742#[serde(rename_all = "snake_case", deny_unknown_fields)]
743pub enum InstallerPresentationModeV1 {
744    /// Generated exact installers are the public install surface.
745    GeneratedDefault,
746    /// Product-owned wrappers are the public install surface.
747    ProductWrappers(ProductWrapperSourcesV1),
748}
749
750/// Product wrapper source configuration (M003d section 6).
751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
752#[serde(deny_unknown_fields)]
753pub struct ProductWrapperSourcesV1 {
754    /// Repository-relative POSIX wrapper source (staged as `install.sh`).
755    pub posix_source: String,
756    /// Repository-relative PowerShell wrapper source (staged as `install.ps1`).
757    pub powershell_source: String,
758    /// Staged asset name for the generated exact POSIX installer.
759    pub generated_posix_name: String,
760    /// Staged asset name for the generated exact PowerShell installer.
761    pub generated_powershell_name: String,
762}
763
764impl InstallerPresentationV1 {
765    /// Generated-default presentation (M003a behavior).
766    pub fn generated_default() -> Self {
767        Self {
768            schema_version: 1,
769            mode: InstallerPresentationModeV1::GeneratedDefault,
770        }
771    }
772
773    /// Parse a strict bounded JSON presentation document.
774    pub fn from_json(text: &str) -> Result<Self, GithubError> {
775        if text.len() > MAX_PRESENTATION_JSON {
776            return Err(fail("installer presentation exceeds size bound"));
777        }
778        let value: Self =
779            serde_json::from_str(text).map_err(|_| fail("invalid installer presentation JSON"))?;
780        value.validate()?;
781        Ok(value)
782    }
783
784    /// Serialize deterministically after validation.
785    pub fn to_json(&self) -> Result<String, GithubError> {
786        self.validate()?;
787        serde_json::to_string(self).map_err(|_| fail("installer presentation encode failed"))
788    }
789
790    /// Validate schema version, wrapper paths, and generated names.
791    pub fn validate(&self) -> Result<(), GithubError> {
792        if self.schema_version != 1 {
793            return Err(fail("unsupported installer presentation version"));
794        }
795        match &self.mode {
796            InstallerPresentationModeV1::GeneratedDefault => Ok(()),
797            InstallerPresentationModeV1::ProductWrappers(sources) => {
798                validate_wrapper_source_path(&sources.posix_source)?;
799                validate_wrapper_source_path(&sources.powershell_source)?;
800                if sources.posix_source == sources.powershell_source {
801                    return Err(fail("product wrapper sources must be distinct files"));
802                }
803                validate_generated_installer_name(&sources.generated_posix_name)?;
804                validate_generated_installer_name(&sources.generated_powershell_name)?;
805                if sources
806                    .generated_posix_name
807                    .eq_ignore_ascii_case(&sources.generated_powershell_name)
808                {
809                    return Err(fail("generated installer names must not collide"));
810                }
811                Ok(())
812            }
813        }
814    }
815}
816
817fn validate_wrapper_source_path(path: &str) -> Result<(), GithubError> {
818    if path.is_empty() || path.len() > 512 || path.contains('\0') || path.contains('\\') {
819        return Err(fail("wrapper source is not a bounded relative path"));
820    }
821    if path.starts_with('/') || path.contains(':') {
822        return Err(fail("wrapper source escapes its root"));
823    }
824    if path.split('/').any(|segment| {
825        segment.is_empty() || segment == "." || segment == ".." || segment.len() > 128
826    }) {
827        return Err(fail("wrapper source escapes its root"));
828    }
829    if path.chars().any(char::is_control) {
830        return Err(fail("wrapper source contains control characters"));
831    }
832    Ok(())
833}
834
835fn validate_generated_installer_name(name: &str) -> Result<(), GithubError> {
836    validate_asset_name(name)?;
837    let lower = name.to_ascii_lowercase();
838    if lower == FIXED_MANIFEST_NAME || lower == FIXED_POSIX_NAME || lower == FIXED_POWERSHELL_NAME {
839        return Err(fail(
840            "generated installer name collides with a reserved staging name",
841        ));
842    }
843    Ok(())
844}
845
846/// Read one product wrapper source exactly (no interpolation, no execution).
847///
848/// The source root must be a real non-symlink directory; the resolved file
849/// must stay beneath it, be a regular non-symlink file, and fit the
850/// 1 MiB bound. Bytes are copied exactly.
851fn read_wrapper_source(source_root: &Path, relative: &str) -> Result<Vec<u8>, GithubError> {
852    reject_symlink_dir(source_root, "wrapper source root")?;
853    validate_wrapper_source_path(relative)?;
854    let path = source_root.join(relative);
855    let metadata =
856        std::fs::symlink_metadata(&path).map_err(|_| fail("wrapper source is unavailable"))?;
857    if metadata.file_type().is_symlink() || !metadata.is_file() {
858        return Err(fail("wrapper source must be a regular file"));
859    }
860    if metadata.len() == 0 || metadata.len() > MAX_WRAPPER_BYTES {
861        return Err(fail("wrapper source size out of bounds"));
862    }
863    let bytes = std::fs::read(&path).map_err(|_| fail("wrapper source cannot be read"))?;
864    if bytes.len() as u64 != metadata.len() {
865        return Err(fail("wrapper source changed during read"));
866    }
867    Ok(bytes)
868}
869
870/// Static reusable GitHub draft template (M003d section 4C).
871///
872/// Contains only identity-independent fields known before the future tag:
873/// owner/repository, fixed title prefix, bounded body/notes, prerelease
874/// flag, token environment, and transport bounds. It MUST NOT contain a
875/// release id, source revision, exact tag, GitHub release id, or digests.
876/// Runtime resolution appends the exact validated tag to the title prefix;
877/// no arbitrary string templating exists.
878#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
879#[serde(deny_unknown_fields)]
880pub struct GitHubDraftTemplateV1 {
881    /// Schema version, exactly 1.
882    pub schema_version: u32,
883    /// GitHub repository owner.
884    pub owner: String,
885    /// GitHub repository name.
886    pub repository: String,
887    /// Fixed title prefix; the exact tag is appended at resolve time.
888    pub title_prefix: String,
889    /// Bounded fixed release notes.
890    #[serde(default)]
891    pub body: String,
892    /// Prerelease intent.
893    #[serde(default)]
894    pub prerelease: bool,
895    /// Token environment variable name, allowlisted to `GITHUB_TOKEN`.
896    #[serde(default = "default_token_env")]
897    pub token_env: String,
898    /// Per-request timeout in seconds.
899    #[serde(default = "default_timeout_secs")]
900    pub request_timeout_secs: u64,
901    /// Maximum metadata response bytes.
902    #[serde(default = "default_max_metadata_bytes")]
903    pub max_metadata_bytes: usize,
904    /// Maximum bounded release-list pages.
905    #[serde(default = "default_max_list_pages")]
906    pub max_list_pages: u32,
907}
908
909impl GitHubDraftTemplateV1 {
910    /// Parse a strict bounded JSON template document.
911    pub fn from_json(text: &str) -> Result<Self, GithubError> {
912        if text.len() > MAX_TEMPLATE_JSON {
913            return Err(fail("github draft template exceeds size bound"));
914        }
915        let value: Self =
916            serde_json::from_str(text).map_err(|_| fail("invalid github draft template JSON"))?;
917        value.validate()?;
918        Ok(value)
919    }
920
921    /// Serialize deterministically after validation.
922    pub fn to_json(&self) -> Result<String, GithubError> {
923        self.validate()?;
924        serde_json::to_string(self).map_err(|_| fail("github draft template encode failed"))
925    }
926
927    /// Validate all bounds and injection rules.
928    pub fn validate(&self) -> Result<(), GithubError> {
929        if self.schema_version != 1 {
930            return Err(fail("unsupported github draft template version"));
931        }
932        validate_owner(&self.owner)?;
933        validate_repo(&self.repository)?;
934        if self.title_prefix.is_empty()
935            || self.title_prefix.len() > MAX_TITLE_PREFIX
936            || self.title_prefix.chars().any(char::is_control)
937        {
938            return Err(fail("draft title prefix out of bounds"));
939        }
940        validate_body(&self.body)?;
941        if self.token_env != "GITHUB_TOKEN" {
942            return Err(fail("token env must be GITHUB_TOKEN"));
943        }
944        if !(5..=120).contains(&self.request_timeout_secs) {
945            return Err(fail("request timeout out of bounds"));
946        }
947        if self.max_metadata_bytes == 0 || self.max_metadata_bytes > 8_000_000 {
948            return Err(fail("max metadata bytes out of bounds"));
949        }
950        if self.max_list_pages == 0 || self.max_list_pages > 32 {
951            return Err(fail("max list pages out of bounds"));
952        }
953        Ok(())
954    }
955
956    /// Resolve the static template against one exact validated tag.
957    ///
958    /// Uses the exact tag as-is (no product-specific transformation) and
959    /// appends it to the fixed title prefix. The tag itself is validated
960    /// with the same rules as [`GitHubDraftPolicyV1`].
961    pub fn resolve(&self, tag: &str) -> Result<GitHubDraftPolicyV1, GithubError> {
962        self.validate()?;
963        validate_tag(tag)?;
964        let title = format!("{}{}", self.title_prefix, tag);
965        validate_title(&title)?;
966        Ok(GitHubDraftPolicyV1 {
967            schema_version: 1,
968            owner: self.owner.clone(),
969            repository: self.repository.clone(),
970            tag: tag.to_owned(),
971            release_identity_schema_version: None,
972            release_identity_mode: None,
973            release_id: None,
974            source_revision: None,
975            title,
976            body: self.body.clone(),
977            prerelease: self.prerelease,
978            token_env: self.token_env.clone(),
979            request_timeout_secs: self.request_timeout_secs,
980            max_metadata_bytes: self.max_metadata_bytes,
981            max_list_pages: self.max_list_pages,
982        })
983    }
984
985    /// Resolve the static template with a checked-in finite identity mode.
986    pub fn resolve_with_identity(
987        &self,
988        tag: &str,
989        mode: ReleaseIdentityMode,
990        source_revision: &str,
991    ) -> Result<GitHubDraftPolicyV1, GithubError> {
992        let release_id = mode.release_id(tag)?;
993        let mut policy = self.resolve(tag)?;
994        if mode != ReleaseIdentityMode::ExactTag {
995            policy.release_identity_schema_version = Some(RELEASE_IDENTITY_SCHEMA_VERSION);
996            policy.release_identity_mode = Some(mode);
997            policy.release_id = Some(release_id);
998            policy.source_revision = Some(source_revision.to_owned());
999        }
1000        policy.validate()?;
1001        Ok(policy)
1002    }
1003}
1004
1005/// Materialize a staging payload for one installer presentation.
1006///
1007/// This is the single staging-payload builder. The presentation selects only
1008/// the installer surface; every other step — validation, inventory
1009/// construction, sidecars, installers, digest loop, canonical sort, and
1010/// payload assembly — is implemented exactly once.
1011#[allow(clippy::too_many_arguments)]
1012fn prepare_staging_payload_with_presentation_inner(
1013    contract: &DistributionContract,
1014    manifest: &ReleaseManifest,
1015    finalized_root: &Path,
1016    policy: &GitHubDraftPolicyV1,
1017    install_policy: &BootstrapInstallPolicyV1,
1018    presentation: &InstallerPresentationV1,
1019    source_root: Option<&Path>,
1020    output_dir: &Path,
1021) -> Result<StagingPayloadV1, GithubError> {
1022    presentation.validate()?;
1023    let (sources, source_root) = match &presentation.mode {
1024        InstallerPresentationModeV1::GeneratedDefault => (None, None),
1025        InstallerPresentationModeV1::ProductWrappers(sources) => (
1026            Some(sources),
1027            Some(source_root.ok_or_else(|| fail("product wrappers require a source root"))?),
1028        ),
1029    };
1030    // The generated exact installers are the public install surface in the
1031    // default presentation; product wrappers move them to distinct names.
1032    let (generated_posix_name, generated_powershell_name) = match sources {
1033        Some(sources) => (
1034            sources.generated_posix_name.clone(),
1035            sources.generated_powershell_name.clone(),
1036        ),
1037        None => (
1038            FIXED_POSIX_NAME.to_owned(),
1039            FIXED_POWERSHELL_NAME.to_owned(),
1040        ),
1041    };
1042    policy.validate()?;
1043    manifest
1044        .validate()
1045        .map_err(|_| fail("invalid release manifest"))?;
1046    if contract.product.id != manifest.product_id {
1047        return Err(fail("contract and manifest product mismatch"));
1048    }
1049    if policy.release_identity_mode.is_some() && manifest.release_id != policy.resolved_release_id()
1050    {
1051        return Err(fail(
1052            "manifest release id differs from draft identity policy",
1053        ));
1054    }
1055    if policy
1056        .source_revision
1057        .as_deref()
1058        .is_some_and(|revision| revision != manifest.source_revision)
1059    {
1060        return Err(fail(
1061            "manifest source revision differs from draft identity policy",
1062        ));
1063    }
1064    reject_symlink_dir(finalized_root, "finalized root")?;
1065
1066    // Collect expected inventory from contract expansion plus manifest facts.
1067    let mut expected: BTreeMap<String, (bool, u64, String)> = BTreeMap::new();
1068    for target in &manifest.targets {
1069        let expanded = contract
1070            .expand(&target.target, &manifest.release_id)
1071            .map_err(|_| fail("manifest target is not supported by contract"))?;
1072        match (&expanded.assets, &target.form) {
1073            (
1074                ExpandedAssets::Direct(direct),
1075                eggpack_manifest::ArtifactForm::Direct { artifact, .. },
1076            ) => {
1077                if direct.asset_file != artifact.name {
1078                    return Err(fail("contract and manifest direct asset differ"));
1079                }
1080                if expected
1081                    .insert(
1082                        artifact.name.clone(),
1083                        (true, artifact.size, artifact.sha256.clone()),
1084                    )
1085                    .is_some()
1086                {
1087                    return Err(fail("duplicate release asset name"));
1088                }
1089                if expected
1090                    .insert(direct.sidecar_file.clone(), (false, 0, String::new()))
1091                    .is_some()
1092                {
1093                    return Err(fail("duplicate release asset name"));
1094                }
1095            }
1096            (
1097                ExpandedAssets::Bundle(bundle),
1098                eggpack_manifest::ArtifactForm::Bundle { entries },
1099            ) => {
1100                if bundle.entries.len() != entries.len() {
1101                    return Err(fail("bundle contract and manifest entry counts differ"));
1102                }
1103                let mut expanded_map = BTreeMap::new();
1104                for entry in &bundle.entries {
1105                    if expanded_map
1106                        .insert(entry.asset_file.clone(), entry.sidecar_file.clone())
1107                        .is_some()
1108                    {
1109                        return Err(fail("duplicate bundle asset"));
1110                    }
1111                }
1112                for entry in entries {
1113                    let sidecar = expanded_map
1114                        .get(&entry.artifact.name)
1115                        .ok_or_else(|| fail("bundle contract and manifest entries differ"))?;
1116                    if expected
1117                        .insert(
1118                            entry.artifact.name.clone(),
1119                            (true, entry.artifact.size, entry.artifact.sha256.clone()),
1120                        )
1121                        .is_some()
1122                    {
1123                        return Err(fail("duplicate release asset name"));
1124                    }
1125                    if expected
1126                        .insert(sidecar.clone(), (false, 0, String::new()))
1127                        .is_some()
1128                    {
1129                        return Err(fail("duplicate release asset name"));
1130                    }
1131                }
1132            }
1133            (
1134                ExpandedAssets::Archive(archive),
1135                eggpack_manifest::ArtifactForm::Archive { artifact, .. },
1136            ) => {
1137                if archive.archive_file != artifact.name {
1138                    return Err(fail("contract and manifest archive filenames differ"));
1139                }
1140                if expected
1141                    .insert(
1142                        artifact.name.clone(),
1143                        (true, artifact.size, artifact.sha256.clone()),
1144                    )
1145                    .is_some()
1146                {
1147                    return Err(fail("duplicate release asset name"));
1148                }
1149                if expected
1150                    .insert(archive.sidecar_file.clone(), (false, 0, String::new()))
1151                    .is_some()
1152                {
1153                    return Err(fail("duplicate release asset name"));
1154                }
1155            }
1156            _ => return Err(fail("contract and manifest forms differ for target")),
1157        }
1158    }
1159
1160    // Auxiliary collision guard, extended with the generated exact-installer
1161    // names: neither contract assets nor generated names may collide
1162    // (case-insensitively) with reserved staging names or each other.
1163    let generated_names = [
1164        generated_posix_name.clone(),
1165        generated_powershell_name.clone(),
1166    ];
1167    for name in expected.keys() {
1168        let lower = name.to_ascii_lowercase();
1169        if lower == FIXED_MANIFEST_NAME
1170            || lower == FIXED_POSIX_NAME
1171            || lower == FIXED_POWERSHELL_NAME
1172            || generated_names
1173                .iter()
1174                .any(|generated| generated.to_ascii_lowercase() == lower)
1175        {
1176            return Err(fail("release asset collides with staging auxiliary name"));
1177        }
1178    }
1179
1180    // Inventory of the finalized root.
1181    let mut observed: BTreeMap<String, PathBuf> = BTreeMap::new();
1182    let entries =
1183        std::fs::read_dir(finalized_root).map_err(|_| fail("finalized root cannot be listed"))?;
1184    for entry in entries {
1185        let entry = entry.map_err(|_| fail("finalized root entry unavailable"))?;
1186        let file_type = entry
1187            .file_type()
1188            .map_err(|_| fail("finalized entry type unavailable"))?;
1189        if file_type.is_symlink() || !file_type.is_file() {
1190            return Err(fail("finalized root must contain only regular files"));
1191        }
1192        let name = entry.file_name().to_string_lossy().into_owned();
1193        validate_asset_name(&name)?;
1194        if observed.insert(name.clone(), entry.path()).is_some() {
1195            return Err(fail("duplicate finalized file"));
1196        }
1197    }
1198    let expected_names: BTreeSet<String> = expected.keys().cloned().collect();
1199    let observed_names: BTreeSet<String> = observed.keys().cloned().collect();
1200    if expected_names != observed_names {
1201        return Err(fail("finalized root files do not exactly match manifest"));
1202    }
1203
1204    // Verify artifact bytes and sidecar contents.
1205    for (name, (is_artifact, size, sha)) in &expected {
1206        let path = observed
1207            .get(name)
1208            .ok_or_else(|| fail("finalized file missing"))?;
1209        if *is_artifact {
1210            let (actual_size, actual_sha) = digest_file(path)?;
1211            if actual_size != *size || actual_sha != *sha {
1212                return Err(fail("finalized file differs from manifest"));
1213            }
1214        }
1215    }
1216    for (name, (is_artifact, _, _)) in &expected {
1217        if *is_artifact {
1218            continue;
1219        }
1220        // Sidecar: "<sha>  <file>\n" for its artifact sibling is validated
1221        // by locating the artifact that shares the sidecar stem. The exact
1222        // sidecar filename mapping comes from contract expansion; here we
1223        // verify content shape and matching digest without trusting names.
1224        let path = observed
1225            .get(name)
1226            .ok_or_else(|| fail("finalized file missing"))?;
1227        let text = std::fs::read_to_string(path).map_err(|_| fail("sidecar cannot be read"))?;
1228        if text.len() > 4096 {
1229            return Err(fail("sidecar exceeds bound"));
1230        }
1231        let trimmed = text.trim_end_matches(['\n', '\r']);
1232        let mut parts = trimmed.splitn(2, "  ");
1233        let sha = parts
1234            .next()
1235            .ok_or_else(|| fail("sidecar content invalid"))?;
1236        let file = parts
1237            .next()
1238            .ok_or_else(|| fail("sidecar content invalid"))?;
1239        validate_sha256(sha)?;
1240        validate_asset_name(file)?;
1241        let artifact_path = finalized_root.join(file);
1242        if !observed.contains_key(file) {
1243            return Err(fail("sidecar references unknown artifact"));
1244        }
1245        let (actual_size, actual_sha) = digest_file(&artifact_path)?;
1246        if actual_sha != sha {
1247            return Err(fail("sidecar digest differs from artifact"));
1248        }
1249        let _ = actual_size;
1250        // Require the `.sha256` suffix.
1251        // Contract expansion supplies the exact names, so this is
1252        // only a consistency check.
1253        if !name.ends_with(".sha256") {
1254            return Err(fail("sidecar filename invalid"));
1255        }
1256    }
1257
1258    ensure_absent_private_dir(output_dir, "staging output")?;
1259    let cleanup = |_: ()| {
1260        let _ = std::fs::remove_dir_all(output_dir);
1261    };
1262
1263    // Copy exact finalized assets.
1264    for (name, path) in &observed {
1265        let dest = output_dir.join(name);
1266        std::fs::copy(path, &dest).map_err(|_| {
1267            cleanup(());
1268            fail("staging copy failed")
1269        })?;
1270    }
1271
1272    // Standalone manifest handoff.
1273    let manifest_json = manifest
1274        .to_json()
1275        .map_err(|_| fail("manifest encode failed"))?;
1276    let manifest_path = output_dir.join(FIXED_MANIFEST_NAME);
1277    std::fs::write(&manifest_path, manifest_json.as_bytes()).map_err(|_| {
1278        cleanup(());
1279        fail("staging manifest write failed")
1280    })?;
1281    let roundtrip = ReleaseManifest::from_json(&manifest_json).map_err(|_| {
1282        cleanup(());
1283        fail("staging manifest roundtrip failed")
1284    })?;
1285    let roundtrip_json = roundtrip.to_json().map_err(|_| {
1286        cleanup(());
1287        fail("staging manifest roundtrip failed")
1288    })?;
1289    if roundtrip_json != manifest_json {
1290        cleanup(());
1291        return Err(fail("staging manifest does not decode to exact manifest"));
1292    }
1293
1294    // Deterministic bootstrap installers with exact-tag origin.
1295    let origin = policy.download_origin();
1296    let spec = BootstrapSpec {
1297        origin,
1298        fixture_http: false,
1299    };
1300    let posix =
1301        eggpack_bootstrap::render_posix_with_policy(contract, manifest, &spec, install_policy)
1302            .map_err(|_| {
1303                cleanup(());
1304                fail("posix installer generation failed")
1305            })?;
1306    let powershell =
1307        eggpack_bootstrap::render_powershell_with_policy(contract, manifest, &spec, install_policy)
1308            .map_err(|_| {
1309                cleanup(());
1310                fail("powershell installer generation failed")
1311            })?;
1312    // Exact-tag origin only; never latest/download.
1313    if posix.contains("latest/download") || powershell.contains("latest/download") {
1314        cleanup(());
1315        return Err(fail("installer uses unsupported latest origin"));
1316    }
1317    // The generated exact installers are staged under the presentation's
1318    // names. Product wrappers additionally become the public install surface
1319    // under the fixed names.
1320    let (posix_wrapper, powershell_wrapper) = match (sources, source_root) {
1321        (Some(sources), Some(source_root)) => {
1322            // Product wrappers are the public surface; generated exact
1323            // installers keep distinct non-colliding names as
1324            // qualified-bootstrap evidence.
1325            let posix_wrapper =
1326                read_wrapper_source(source_root, &sources.posix_source).map_err(|_| {
1327                    cleanup(());
1328                    fail("product posix wrapper is unavailable")
1329                })?;
1330            let powershell_wrapper = read_wrapper_source(source_root, &sources.powershell_source)
1331                .map_err(|_| {
1332                cleanup(());
1333                fail("product powershell wrapper is unavailable")
1334            })?;
1335            (Some(posix_wrapper), Some(powershell_wrapper))
1336        }
1337        _ => (None, None),
1338    };
1339    std::fs::write(output_dir.join(&generated_posix_name), posix.as_bytes()).map_err(|_| {
1340        cleanup(());
1341        fail("posix installer write failed")
1342    })?;
1343    std::fs::write(
1344        output_dir.join(&generated_powershell_name),
1345        powershell.as_bytes(),
1346    )
1347    .map_err(|_| {
1348        cleanup(());
1349        fail("powershell installer write failed")
1350    })?;
1351    if let (Some(posix_wrapper), Some(powershell_wrapper)) = (posix_wrapper, powershell_wrapper) {
1352        std::fs::write(output_dir.join(FIXED_POSIX_NAME), posix_wrapper.as_slice()).map_err(
1353            |_| {
1354                cleanup(());
1355                fail("product posix wrapper write failed")
1356            },
1357        )?;
1358        std::fs::write(
1359            output_dir.join(FIXED_POWERSHELL_NAME),
1360            powershell_wrapper.as_slice(),
1361        )
1362        .map_err(|_| {
1363            cleanup(());
1364            fail("product powershell wrapper write failed")
1365        })?;
1366    }
1367
1368    // Build deterministic payload records.
1369    let mut assets = Vec::new();
1370    let mut staged_names: BTreeSet<String> = BTreeSet::new();
1371    let mut staged_entries: Vec<(String, StagingAssetKind, String)> = Vec::new();
1372    for name in observed.keys() {
1373        let is_artifact = expected
1374            .get(name)
1375            .map(|(is_artifact, _, _)| *is_artifact)
1376            .unwrap_or(false);
1377        let (kind, media) = if is_artifact {
1378            (
1379                StagingAssetKind::FinalizedArtifact,
1380                "application/octet-stream".to_owned(),
1381            )
1382        } else {
1383            (StagingAssetKind::ChecksumSidecar, "text/plain".to_owned())
1384        };
1385        staged_entries.push((name.clone(), kind, media));
1386    }
1387    staged_entries.push((
1388        FIXED_MANIFEST_NAME.to_owned(),
1389        StagingAssetKind::ReleaseManifest,
1390        "application/json".to_owned(),
1391    ));
1392    staged_entries.push((
1393        generated_posix_name.clone(),
1394        StagingAssetKind::PosixInstaller,
1395        "text/x-shellscript".to_owned(),
1396    ));
1397    staged_entries.push((
1398        generated_powershell_name.clone(),
1399        StagingAssetKind::PowershellInstaller,
1400        "text/x-powershell".to_owned(),
1401    ));
1402    if sources.is_some() {
1403        staged_entries.push((
1404            FIXED_POSIX_NAME.to_owned(),
1405            StagingAssetKind::ProductPosixWrapper,
1406            "text/x-shellscript".to_owned(),
1407        ));
1408        staged_entries.push((
1409            FIXED_POWERSHELL_NAME.to_owned(),
1410            StagingAssetKind::ProductPowershellWrapper,
1411            "text/x-powershell".to_owned(),
1412        ));
1413    }
1414    for (name, kind, media) in staged_entries {
1415        if !staged_names.insert(name.to_ascii_lowercase()) {
1416            cleanup(());
1417            return Err(fail("duplicate staging asset name"));
1418        }
1419        let (size, sha) = digest_file(&output_dir.join(&name)).map_err(|_| {
1420            cleanup(());
1421            fail("staged file digest failed")
1422        })?;
1423        assets.push(StagingAsset {
1424            name: name.clone(),
1425            path: name,
1426            size,
1427            sha256: sha,
1428            media_type: media,
1429            kind,
1430        });
1431    }
1432    assets.sort_by(|a, b| a.name.cmp(&b.name));
1433
1434    let payload = StagingPayloadV1 {
1435        schema_version: 1,
1436        product_id: manifest.product_id.clone(),
1437        release_id: manifest.release_id.clone(),
1438        source_revision: manifest.source_revision.clone(),
1439        owner: policy.owner.clone(),
1440        repository: policy.repository.clone(),
1441        tag: policy.tag.clone(),
1442        title: policy.title.clone(),
1443        prerelease: policy.prerelease,
1444        body: policy.body.clone(),
1445        assets,
1446    };
1447    payload.validate().map_err(|_| {
1448        cleanup(());
1449        fail("staging payload invalid")
1450    })?;
1451    Ok(payload)
1452}
1453
1454// ---------------------------------------------------------------------------
1455// GitHub adapter
1456// ---------------------------------------------------------------------------
1457
1458/// Exact tag reference target.
1459#[derive(Debug, Clone, PartialEq, Eq)]
1460pub struct RefTarget {
1461    /// Commit or tag object SHA.
1462    pub sha: String,
1463    /// Object type (`commit` or `tag`).
1464    pub kind: String,
1465}
1466
1467/// Annotated tag object peeling step.
1468#[derive(Debug, Clone, PartialEq, Eq)]
1469pub struct TagObject {
1470    /// Peeled object SHA.
1471    pub object_sha: String,
1472    /// Peeled object type.
1473    pub object_type: String,
1474}
1475
1476/// Remote release summary.
1477#[derive(Debug, Clone, PartialEq, Eq)]
1478pub struct RemoteRelease {
1479    /// GitHub numeric release id.
1480    pub id: u64,
1481    /// Exact tag name.
1482    pub tag_name: String,
1483    /// Release title.
1484    pub name: String,
1485    /// Release notes.
1486    pub body: String,
1487    /// Draft state.
1488    pub draft: bool,
1489    /// Immutable state.
1490    pub immutable: bool,
1491    /// Prerelease intent.
1492    pub prerelease: bool,
1493    /// Upload URL template/host.
1494    pub upload_url: String,
1495}
1496
1497/// Remote release asset.
1498#[derive(Debug, Clone, PartialEq, Eq)]
1499pub struct RemoteAsset {
1500    /// GitHub numeric asset id.
1501    pub id: u64,
1502    /// Exact asset name.
1503    pub name: String,
1504    /// Exact byte size.
1505    pub size: u64,
1506    /// Asset state (`uploaded` or `starter`).
1507    pub state: String,
1508    /// Optional `sha256:<hex>` digest.
1509    pub digest: Option<String>,
1510}
1511
1512/// Provider transport seam for GitHub staging.
1513///
1514/// Production uses fixed `https://api.github.com` plus upload host
1515/// `https://uploads.github.com` through `eggfetch-core` with a lean profile
1516/// (no retries, no redirects). Tests inject a deterministic fixture.
1517pub trait GithubApi: Send + Sync {
1518    /// Fetch exact `refs/tags/<tag>` reference.
1519    fn get_ref(
1520        &self,
1521        owner: &str,
1522        repo: &str,
1523        tag: &str,
1524    ) -> impl std::future::Future<Output = Result<RefTarget, GithubError>> + Send;
1525    /// Fetch one annotated tag object by SHA.
1526    fn get_tag(
1527        &self,
1528        owner: &str,
1529        repo: &str,
1530        sha: &str,
1531    ) -> impl std::future::Future<Output = Result<TagObject, GithubError>> + Send;
1532    /// List releases for one page (1-indexed, `per_page=100`).
1533    fn list_releases(
1534        &self,
1535        owner: &str,
1536        repo: &str,
1537        page: u32,
1538    ) -> impl std::future::Future<Output = Result<Vec<RemoteRelease>, GithubError>> + Send;
1539    /// Create a new draft release for an exact existing tag.
1540    fn create_release(
1541        &self,
1542        owner: &str,
1543        repo: &str,
1544        tag: &str,
1545        title: &str,
1546        body: &str,
1547        prerelease: bool,
1548    ) -> impl std::future::Future<Output = Result<RemoteRelease, GithubError>> + Send;
1549    /// List all assets for one release.
1550    fn list_assets(
1551        &self,
1552        owner: &str,
1553        repo: &str,
1554        release_id: u64,
1555        page: u32,
1556    ) -> impl std::future::Future<Output = Result<Vec<RemoteAsset>, GithubError>> + Send;
1557    /// Upload one asset; 502/422 are reported as errors with `http_502` /
1558    /// `http_422_duplicate` prefixes so the caller can apply narrow recovery.
1559    #[allow(clippy::too_many_arguments)]
1560    fn upload_asset(
1561        &self,
1562        owner: &str,
1563        repo: &str,
1564        release_id: u64,
1565        name: &str,
1566        file: Box<dyn std::io::Read + Send>,
1567        length: u64,
1568        content_type: &str,
1569    ) -> impl std::future::Future<Output = Result<RemoteAsset, GithubError>> + Send;
1570    /// Delete one asset by id (only the narrow starter recovery may call this).
1571    fn delete_asset(
1572        &self,
1573        owner: &str,
1574        repo: &str,
1575        asset_id: u64,
1576    ) -> impl std::future::Future<Output = Result<(), GithubError>> + Send;
1577}
1578
1579trait ReadSeek: std::io::Read + std::io::Seek {
1580    fn source_len(&self) -> Result<u64, GithubError>;
1581}
1582impl ReadSeek for std::fs::File {
1583    fn source_len(&self) -> Result<u64, GithubError> {
1584        Ok(self
1585            .metadata()
1586            .map_err(|_| fail("staged file is unavailable"))?
1587            .len())
1588    }
1589}
1590impl<T: AsRef<[u8]> + Send> ReadSeek for std::io::Cursor<T> {
1591    fn source_len(&self) -> Result<u64, GithubError> {
1592        Ok(self.get_ref().as_ref().len() as u64)
1593    }
1594}
1595
1596fn is_http_502(error: &GithubError) -> bool {
1597    error.0.starts_with("http_502")
1598}
1599
1600fn is_http_422_duplicate(error: &GithubError) -> bool {
1601    error.0.starts_with("http_422_duplicate")
1602}
1603
1604fn validate_sha40(value: &str) -> Result<(), GithubError> {
1605    if value.len() != 40
1606        || !value
1607            .bytes()
1608            .all(|b| b.is_ascii_hexdigit() && (b.is_ascii_digit() || b.is_ascii_lowercase()))
1609    {
1610        // GitHub SHAs are lowercase hex; be strict but do not leak values.
1611        return Err(fail("remote SHA has invalid shape"));
1612    }
1613    Ok(())
1614}
1615
1616/// Verify an exact tag resolves to the payload source revision.
1617///
1618/// Lightweight tags must point directly at the revision. Annotated tags are
1619/// peeled with a bounded loop and must terminate at a commit with the exact
1620/// revision. No tag write endpoint exists.
1621pub async fn verify_tag_source(
1622    transport: &impl GithubApi,
1623    owner: &str,
1624    repo: &str,
1625    tag: &str,
1626    source_revision: &str,
1627) -> Result<(), GithubError> {
1628    let reference = transport.get_ref(owner, repo, tag).await?;
1629    if reference.kind == "commit" {
1630        validate_sha40(&reference.sha)?;
1631        if reference.sha != source_revision {
1632            return Err(fail("tag does not match source revision"));
1633        }
1634        return Ok(());
1635    }
1636    if reference.kind != "tag" {
1637        return Err(fail("tag reference has unexpected type"));
1638    }
1639    validate_sha40(&reference.sha)?;
1640    let mut current = reference.sha;
1641    for _ in 0..MAX_TAG_PEEL_DEPTH {
1642        let object = transport.get_tag(owner, repo, &current).await?;
1643        if object.object_type == "commit" {
1644            validate_sha40(&object.object_sha)?;
1645            if object.object_sha != source_revision {
1646                return Err(fail("tag does not match source revision"));
1647            }
1648            return Ok(());
1649        }
1650        if object.object_type != "tag" {
1651            return Err(fail("annotated tag did not resolve to a commit"));
1652        }
1653        validate_sha40(&object.object_sha)?;
1654        current = object.object_sha;
1655    }
1656    Err(fail("annotated tag depth exceeds bound"))
1657}
1658
1659fn find_exact_release(
1660    releases: &[RemoteRelease],
1661    tag: &str,
1662) -> Result<Option<RemoteRelease>, GithubError> {
1663    let mut matches = Vec::new();
1664    for release in releases {
1665        if release.tag_name == tag {
1666            matches.push(release.clone());
1667        }
1668    }
1669    if matches.len() > 1 {
1670        return Err(fail("duplicate same-tag release records"));
1671    }
1672    Ok(matches.into_iter().next())
1673}
1674
1675fn check_upload_url(
1676    url: &str,
1677    owner: &str,
1678    repository: &str,
1679    release_id: u64,
1680) -> Result<(), GithubError> {
1681    let normalized = url.strip_suffix("{?name,label}").unwrap_or(url);
1682    let parsed = url::Url::parse(normalized).map_err(|_| fail("upload URL is invalid"))?;
1683    if parsed.scheme() != "https"
1684        || parsed.host_str() != Some("uploads.github.com")
1685        || parsed.username() != ""
1686        || parsed.password().is_some()
1687        || parsed.port().is_some_and(|port| port != 443)
1688        || parsed.fragment().is_some()
1689        || parsed.path() != format!("/repos/{owner}/{repository}/releases/{release_id}/assets")
1690        || parsed.query().is_some()
1691    {
1692        return Err(fail("upload host is not the expected GitHub host"));
1693    }
1694    Ok(())
1695}
1696
1697fn upload_url(
1698    owner: &str,
1699    repository: &str,
1700    release_id: u64,
1701    name: &str,
1702) -> Result<String, GithubError> {
1703    validate_asset_name(name)?;
1704    let mut url = url::Url::parse(&format!(
1705        "{UPLOAD_BASE}/repos/{owner}/{repository}/releases/{release_id}/assets"
1706    ))
1707    .map_err(|_| fail("upload URL construction failed"))?;
1708    url.query_pairs_mut().append_pair("name", name);
1709    Ok(url.into())
1710}
1711
1712fn streamed_upload_body(
1713    file: Box<dyn std::io::Read + Send>,
1714    length: u64,
1715) -> Result<eggfetch_core::RequestBody, GithubError> {
1716    let length =
1717        usize::try_from(length).map_err(|_| fail("asset length exceeds platform bound"))?;
1718    Ok(eggfetch_core::RequestBody::from_stream(
1719        futures_util::stream::try_unfold(file, |mut file| async move {
1720            use std::io::Read;
1721            let mut chunk = vec![0; UPLOAD_CHUNK_BYTES];
1722            let count = file
1723                .read(&mut chunk)
1724                .map_err(|error| eggfetch_core::Error::Io(std::sync::Arc::new(error)))?;
1725            if count == 0 {
1726                Ok(None)
1727            } else {
1728                chunk.truncate(count);
1729                Ok(Some((bytes::Bytes::from(chunk), file)))
1730            }
1731        }),
1732        Some(length),
1733    ))
1734}
1735
1736/// Page through one listing endpoint, failing closed when the bound is hit.
1737///
1738/// A batch that is completely filled (`LIST_PAGE_SIZE`) may have more pages
1739/// behind it, so running out of pages while that is still true means the
1740/// listing was truncated. The caller would otherwise act on a partial view —
1741/// for releases, by concluding the target tag has no release and creating a
1742/// second one for a tag that already has one — so truncation is an explicit
1743/// error, never a short list. `label` names the listing in that message.
1744async fn list_all_pages<T, F, Fut>(
1745    max_pages: u32,
1746    label: &'static str,
1747    mut fetch: F,
1748) -> Result<Vec<T>, GithubError>
1749where
1750    F: FnMut(u32) -> Fut,
1751    Fut: std::future::Future<Output = Result<Vec<T>, GithubError>>,
1752{
1753    let mut all = Vec::new();
1754    for page in 1..=max_pages {
1755        let batch = fetch(page).await?;
1756        let full = batch.len() >= LIST_PAGE_SIZE;
1757        all.extend(batch);
1758        if !full {
1759            return Ok(all);
1760        }
1761        if page == max_pages {
1762            return Err(fail(match label {
1763                "asset" => "asset pagination bound exhausted",
1764                _ => "release pagination bound exhausted",
1765            }));
1766        }
1767    }
1768    Ok(all)
1769}
1770
1771async fn list_all_releases(
1772    transport: &impl GithubApi,
1773    policy: &GitHubDraftPolicyV1,
1774) -> Result<Vec<RemoteRelease>, GithubError> {
1775    list_all_pages(policy.max_list_pages, "release", |page| {
1776        transport.list_releases(&policy.owner, &policy.repository, page)
1777    })
1778    .await
1779}
1780
1781async fn list_all_assets(
1782    transport: &impl GithubApi,
1783    policy: &GitHubDraftPolicyV1,
1784    release_id: u64,
1785) -> Result<Vec<RemoteAsset>, GithubError> {
1786    list_all_pages(policy.max_list_pages, "asset", |page| {
1787        transport.list_assets(&policy.owner, &policy.repository, release_id, page)
1788    })
1789    .await
1790}
1791
1792fn verify_file(file: &mut dyn ReadSeek, expected: &StagingAsset) -> Result<(), GithubError> {
1793    use std::io::SeekFrom;
1794    if file.source_len()? != expected.size {
1795        return Err(fail("local asset size differs from payload"));
1796    }
1797    file.seek(SeekFrom::Start(0))
1798        .map_err(|_| fail("staged file cannot be read"))?;
1799    let mut hasher = sha2::Sha256::new();
1800    let mut buf = [0u8; UPLOAD_CHUNK_BYTES];
1801    loop {
1802        let count = file
1803            .read(&mut buf)
1804            .map_err(|_| fail("staged file cannot be read"))?;
1805        if count == 0 {
1806            break;
1807        }
1808        use sha2::Digest;
1809        hasher.update(&buf[..count]);
1810    }
1811    use sha2::Digest;
1812    let digest = hasher
1813        .finalize()
1814        .iter()
1815        .map(|b| format!("{b:02x}"))
1816        .collect::<String>();
1817    if digest != expected.sha256 {
1818        return Err(fail("local asset digest differs from payload"));
1819    }
1820    file.seek(SeekFrom::Start(0))
1821        .map_err(|_| fail("staged file cannot be read"))?;
1822    Ok(())
1823}
1824
1825/// Testable staging core with explicit local bytes.
1826pub async fn stage_with_bytes<F>(
1827    payload: &StagingPayloadV1,
1828    policy: &GitHubDraftPolicyV1,
1829    transport: &impl GithubApi,
1830    token: &str,
1831    mut bytes_for: F,
1832) -> Result<GitHubDraftReceiptV1, GithubError>
1833where
1834    F: FnMut(&str) -> Result<Vec<u8>, GithubError>,
1835{
1836    stage_with_source(payload, policy, transport, token, |name| {
1837        Ok(Box::new(std::io::Cursor::new(bytes_for(name)?)) as Box<dyn ReadSeek + Send>)
1838    })
1839    .await
1840}
1841
1842async fn stage_with_source<F>(
1843    payload: &StagingPayloadV1,
1844    policy: &GitHubDraftPolicyV1,
1845    transport: &impl GithubApi,
1846    token: &str,
1847    mut source_for: F,
1848) -> Result<GitHubDraftReceiptV1, GithubError>
1849where
1850    F: FnMut(&str) -> Result<Box<dyn ReadSeek + Send>, GithubError>,
1851{
1852    if token.is_empty() || token.len() > 4096 || token.chars().any(char::is_control) {
1853        return Err(fail("github token is absent"));
1854    }
1855    payload.validate()?;
1856    policy.validate()?;
1857    if payload.owner != policy.owner
1858        || payload.repository != policy.repository
1859        || payload.tag != policy.tag
1860        || (policy.release_identity_mode.is_some()
1861            && payload.release_id != policy.resolved_release_id())
1862        || policy
1863            .source_revision
1864            .as_deref()
1865            .is_some_and(|revision| revision != payload.source_revision)
1866        || payload.title != policy.title
1867        || payload.prerelease != policy.prerelease
1868        || payload.body != policy.body
1869    {
1870        return Err(fail("staging payload does not match draft policy"));
1871    }
1872
1873    verify_tag_source(
1874        transport,
1875        &policy.owner,
1876        &policy.repository,
1877        &policy.tag,
1878        &payload.source_revision,
1879    )
1880    .await?;
1881
1882    // A truncated release listing would hide the existing draft for this tag,
1883    // and staging would then try to create a second release for a tag that
1884    // already has one. Bound exhaustion fails closed here, exactly as it does
1885    // on the asset listing.
1886    let seen = list_all_releases(transport, policy).await?;
1887    let existing = find_exact_release(&seen, &policy.tag)?;
1888    let (release, created) = match existing {
1889        None => {
1890            let created = transport
1891                .create_release(
1892                    &policy.owner,
1893                    &policy.repository,
1894                    &policy.tag,
1895                    &policy.title,
1896                    &policy.body,
1897                    policy.prerelease,
1898                )
1899                .await?;
1900            if created.tag_name != policy.tag || !created.draft || created.immutable {
1901                return Err(fail("created release has unexpected state"));
1902            }
1903            (created, true)
1904        }
1905        Some(current) => {
1906            if !current.draft || current.immutable {
1907                return Err(fail("existing release is not a mutable draft"));
1908            }
1909            if current.tag_name != policy.tag {
1910                return Err(fail("existing draft tag mismatch"));
1911            }
1912            if current.name != policy.title
1913                || current.prerelease != policy.prerelease
1914                || current.body != policy.body
1915            {
1916                return Err(fail("existing draft title/prerelease/body mismatch"));
1917            }
1918            (current, false)
1919        }
1920    };
1921    check_upload_url(
1922        &release.upload_url,
1923        &policy.owner,
1924        &policy.repository,
1925        release.id,
1926    )?;
1927
1928    let mut expected: BTreeMap<String, &StagingAsset> = BTreeMap::new();
1929    for asset in &payload.assets {
1930        if expected.insert(asset.name.clone(), asset).is_some() {
1931            return Err(fail("duplicate payload asset name"));
1932        }
1933    }
1934
1935    let remote = list_all_assets(transport, policy, release.id).await?;
1936    {
1937        let mut names = BTreeSet::new();
1938        for asset in &remote {
1939            if !names.insert(asset.name.to_ascii_lowercase()) {
1940                return Err(fail("duplicate same-name remote asset"));
1941            }
1942            if !expected.contains_key(&asset.name) {
1943                return Err(fail("unexpected remote asset"));
1944            }
1945        }
1946    }
1947    let mut remote_by_name: BTreeMap<String, RemoteAsset> = BTreeMap::new();
1948    for asset in remote {
1949        remote_by_name.insert(asset.name.clone(), asset);
1950    }
1951
1952    let mut uploaded: u32 = 0;
1953    let mut reused: u32 = 0;
1954    for (name, local) in &expected {
1955        match remote_by_name.get(name) {
1956            None => {
1957                let mut file = source_for(name)?;
1958                verify_file(file.as_mut(), local)?;
1959                match transport
1960                    .upload_asset(
1961                        &policy.owner,
1962                        &policy.repository,
1963                        release.id,
1964                        name,
1965                        Box::new(file),
1966                        local.size,
1967                        &local.media_type,
1968                    )
1969                    .await
1970                {
1971                    Ok(record) => {
1972                        if record.name != *name {
1973                            return Err(fail("upload response renamed the asset"));
1974                        }
1975                        if record.state != "uploaded" {
1976                            return Err(fail("upload response state is not uploaded"));
1977                        }
1978                        if record.size != local.size {
1979                            return Err(fail("upload response size mismatch"));
1980                        }
1981                        if let Some(digest) = &record.digest {
1982                            if digest != &format!("sha256:{}", local.sha256) {
1983                                return Err(fail("upload response digest mismatch"));
1984                            }
1985                        }
1986                        uploaded = uploaded
1987                            .checked_add(1)
1988                            .ok_or_else(|| fail("upload count overflow"))?;
1989                    }
1990                    Err(error) => {
1991                        if is_http_422_duplicate(&error) {
1992                            return Err(fail("duplicate-name upload rejected"));
1993                        }
1994                        if is_http_502(&error) {
1995                            let after = list_all_assets(transport, policy, release.id).await?;
1996                            let starters: Vec<&RemoteAsset> = after
1997                                .iter()
1998                                .filter(|asset| {
1999                                    asset.name == *name
2000                                        && asset.state == "starter"
2001                                        && asset.size == 0
2002                                })
2003                                .collect();
2004                            if starters.len() == 1 {
2005                                transport
2006                                    .delete_asset(&policy.owner, &policy.repository, starters[0].id)
2007                                    .await?;
2008                            }
2009                            return Err(fail("upload failed with 502; starter cleaned when exact"));
2010                        }
2011                        return Err(error);
2012                    }
2013                }
2014            }
2015            Some(record) => {
2016                if record.state != "uploaded" {
2017                    return Err(fail("remote asset is not uploaded"));
2018                }
2019                if record.size != local.size {
2020                    return Err(fail("same-name remote asset size mismatch"));
2021                }
2022                match &record.digest {
2023                    Some(digest) if digest == &format!("sha256:{}", local.sha256) => {
2024                        reused = reused
2025                            .checked_add(1)
2026                            .ok_or_else(|| fail("reuse count overflow"))?;
2027                    }
2028                    _ => return Err(fail("same-name remote asset digest mismatch")),
2029                }
2030            }
2031        }
2032    }
2033
2034    let final_assets = list_all_assets(transport, policy, release.id).await?;
2035    {
2036        let mut names = BTreeSet::new();
2037        for asset in &final_assets {
2038            if !names.insert(asset.name.clone()) {
2039                return Err(fail("duplicate same-name remote asset"));
2040            }
2041        }
2042        if names.len() != expected.len() {
2043            return Err(fail("staged asset set is incomplete"));
2044        }
2045        for (name, local) in &expected {
2046            let record = final_assets
2047                .iter()
2048                .find(|asset| &asset.name == name)
2049                .ok_or_else(|| fail("staged asset missing after upload"))?;
2050            if record.state != "uploaded"
2051                || record.size != local.size
2052                || record.digest.as_deref() != Some(&format!("sha256:{}", local.sha256))
2053            {
2054                return Err(fail("staged asset evidence mismatch"));
2055            }
2056        }
2057    }
2058
2059    verify_tag_source(
2060        transport,
2061        &policy.owner,
2062        &policy.repository,
2063        &policy.tag,
2064        &payload.source_revision,
2065    )
2066    .await?;
2067
2068    let mut ordered = payload.assets.clone();
2069    ordered.sort_by(|a, b| a.name.cmp(&b.name));
2070    Ok(GitHubDraftReceiptV1 {
2071        schema_version: 1,
2072        owner: policy.owner.clone(),
2073        repository: policy.repository.clone(),
2074        release_id: payload.release_id.clone(),
2075        tag: policy.tag.clone(),
2076        source_revision: payload.source_revision.clone(),
2077        github_release_id: release.id,
2078        draft: true,
2079        immutable: false,
2080        assets: ordered,
2081        created,
2082        uploaded,
2083        reused,
2084    })
2085}
2086
2087/// Stage using a staging directory on disk.
2088pub async fn stage_with_dir(
2089    payload: &StagingPayloadV1,
2090    policy: &GitHubDraftPolicyV1,
2091    transport: &impl GithubApi,
2092    token: &str,
2093    staging_dir: &Path,
2094) -> Result<GitHubDraftReceiptV1, GithubError> {
2095    payload.validate()?;
2096    policy.validate()?;
2097    reject_symlink_dir(staging_dir, "staging directory")?;
2098    let mut files = BTreeMap::new();
2099    for asset in &payload.assets {
2100        let path = staging_dir.join(&asset.name);
2101        let metadata =
2102            std::fs::symlink_metadata(&path).map_err(|_| fail("staged file is unavailable"))?;
2103        if metadata.file_type().is_symlink() || !metadata.is_file() {
2104            return Err(fail("staged file must be a regular file"));
2105        }
2106        let mut file =
2107            std::fs::File::open(&path).map_err(|_| fail("staged file cannot be read"))?;
2108        if !file
2109            .metadata()
2110            .map_err(|_| fail("staged file is unavailable"))?
2111            .is_file()
2112        {
2113            return Err(fail("staged file must be a regular file"));
2114        }
2115        verify_file(&mut file, asset)?;
2116        files.insert(asset.name.clone(), file);
2117    }
2118    stage_with_source(payload, policy, transport, token, |name| {
2119        let file = files
2120            .remove(name)
2121            .ok_or_else(|| fail("staged file is unavailable"))?;
2122        Ok(Box::new(file) as Box<dyn ReadSeek + Send>)
2123    })
2124    .await
2125}
2126
2127// ---------------------------------------------------------------------------
2128// Production transport (eggfetch-core, lean profile)
2129// ---------------------------------------------------------------------------
2130
2131/// Production GitHub transport with fixed hosts.
2132///
2133/// Uses `eggfetch-core 0.4.0` with explicit lean features (`standard-http1`,
2134/// `tls-rustls`, `tls-native-roots`, `json`) rather than the default
2135/// retry/redirect policy. Retries are disabled and redirects are not followed;
2136/// 3xx responses fail closed. Bounded timeouts and body sizes apply to every
2137/// request. The `Debug` implementation redacts the credential.
2138pub struct EggfetchTransport {
2139    client: eggfetch_core::Client,
2140    token: String,
2141    timeout_secs: u64,
2142    max_metadata_bytes: usize,
2143}
2144
2145impl fmt::Debug for EggfetchTransport {
2146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2147        f.debug_struct("EggfetchTransport")
2148            .field("timeout_secs", &self.timeout_secs)
2149            .field("max_metadata_bytes", &self.max_metadata_bytes)
2150            .field("token", &"<redacted>")
2151            .finish_non_exhaustive()
2152    }
2153}
2154
2155impl EggfetchTransport {
2156    /// Create a production transport. The token is held in memory only and
2157    /// never serialized or logged.
2158    pub fn new(
2159        token: String,
2160        timeout_secs: u64,
2161        max_metadata_bytes: usize,
2162    ) -> Result<Self, GithubError> {
2163        if token.is_empty() || token.len() > 4096 || token.chars().any(char::is_control) {
2164            return Err(fail("github token is absent"));
2165        }
2166        if !(5..=120).contains(&timeout_secs) {
2167            return Err(fail("request timeout out of bounds"));
2168        }
2169        if max_metadata_bytes == 0 || max_metadata_bytes > 8_000_000 {
2170            return Err(fail("max metadata bytes out of bounds"));
2171        }
2172        let timeout = eggfetch_core::Timeout::from_secs(timeout_secs);
2173        let client = eggfetch_core::Client::builder()
2174            .user_agent(USER_AGENT)
2175            .timeout(timeout)
2176            .build();
2177        Ok(Self {
2178            client,
2179            token,
2180            timeout_secs,
2181            max_metadata_bytes,
2182        })
2183    }
2184
2185    fn auth(&self) -> Result<eggfetch_core::AuthScheme, GithubError> {
2186        eggfetch_core::AuthScheme::bearer(self.token.clone())
2187            .map_err(|_| fail("github token has invalid shape"))
2188    }
2189
2190    fn timeout(&self) -> eggfetch_core::Timeout {
2191        eggfetch_core::Timeout::from_secs(self.timeout_secs)
2192    }
2193
2194    async fn read_json<T: serde::de::DeserializeOwned>(
2195        &self,
2196        mut response: eggfetch_core::Response,
2197    ) -> Result<T, GithubError> {
2198        let status = response.status().as_u16();
2199        if (300..400).contains(&status) {
2200            return Err(fail("unexpected redirect; redirects are disabled"));
2201        }
2202        if !(200..300).contains(&status) {
2203            return match status {
2204                404 => Err(fail("github resource not found")),
2205                422 => Err(fail("http_422_duplicate: github rejected duplicate name")),
2206                502 => Err(fail("http_502: github reported a gateway failure")),
2207                _ => Err(fail("github request failed")),
2208            };
2209        }
2210        response
2211            .json::<T>()
2212            .await
2213            .map_err(|_| fail("github response decode failed"))
2214    }
2215}
2216
2217#[derive(Debug, Deserialize)]
2218struct ApiRefObject {
2219    sha: String,
2220    #[serde(rename = "type")]
2221    kind: String,
2222}
2223
2224#[derive(Debug, Deserialize)]
2225struct ApiRefResponse {
2226    object: ApiRefObject,
2227}
2228
2229#[derive(Debug, Deserialize)]
2230struct ApiTagObjectInner {
2231    sha: String,
2232    #[serde(rename = "type")]
2233    kind: String,
2234}
2235
2236#[derive(Debug, Deserialize)]
2237struct ApiTagResponse {
2238    object: ApiTagObjectInner,
2239}
2240
2241#[derive(Debug, Deserialize)]
2242struct ApiRelease {
2243    id: u64,
2244    tag_name: String,
2245    name: Option<String>,
2246    body: Option<String>,
2247    draft: bool,
2248    /// Optional in the REST payload: a response that omits the field means the
2249    /// release was not reported immutable. The default is required for
2250    /// compatibility — making it mandatory would fail every release read
2251    /// against an API that does not return it. Staging still fails closed:
2252    /// a reported `true` refuses the draft, and an unreported one is rejected
2253    /// by the upload call itself.
2254    #[serde(default)]
2255    immutable: bool,
2256    prerelease: bool,
2257    upload_url: String,
2258}
2259
2260#[derive(Debug, Deserialize)]
2261struct ApiAsset {
2262    id: u64,
2263    name: String,
2264    size: u64,
2265    state: String,
2266    digest: Option<String>,
2267}
2268
2269impl GithubApi for EggfetchTransport {
2270    async fn get_ref(&self, owner: &str, repo: &str, tag: &str) -> Result<RefTarget, GithubError> {
2271        let url = format!("{API_BASE}/repos/{owner}/{repo}/git/ref/tags/{tag}");
2272        let response = self
2273            .client
2274            .get(&url)
2275            .map_err(|_| fail("github request build failed"))?
2276            .header("Accept", "application/vnd.github+json")
2277            .header("X-GitHub-Api-Version", API_VERSION)
2278            .auth(self.auth()?)
2279            .timeout(self.timeout())
2280            .max_decoded_body_size(self.max_metadata_bytes)
2281            .send()
2282            .await
2283            .map_err(|_| fail("github tag lookup failed"))?;
2284        let body: ApiRefResponse = self.read_json(response).await?;
2285        Ok(RefTarget {
2286            sha: body.object.sha,
2287            kind: body.object.kind,
2288        })
2289    }
2290
2291    async fn get_tag(&self, owner: &str, repo: &str, sha: &str) -> Result<TagObject, GithubError> {
2292        let url = format!("{API_BASE}/repos/{owner}/{repo}/git/tags/{sha}");
2293        let response = self
2294            .client
2295            .get(&url)
2296            .map_err(|_| fail("github request build failed"))?
2297            .header("Accept", "application/vnd.github+json")
2298            .header("X-GitHub-Api-Version", API_VERSION)
2299            .auth(self.auth()?)
2300            .timeout(self.timeout())
2301            .max_decoded_body_size(self.max_metadata_bytes)
2302            .send()
2303            .await
2304            .map_err(|_| fail("github tag object lookup failed"))?;
2305        let body: ApiTagResponse = self.read_json(response).await?;
2306        Ok(TagObject {
2307            object_sha: body.object.sha,
2308            object_type: body.object.kind,
2309        })
2310    }
2311
2312    async fn list_releases(
2313        &self,
2314        owner: &str,
2315        repo: &str,
2316        page: u32,
2317    ) -> Result<Vec<RemoteRelease>, GithubError> {
2318        let url = format!("{API_BASE}/repos/{owner}/{repo}/releases?per_page=100&page={page}");
2319        let response = self
2320            .client
2321            .get(&url)
2322            .map_err(|_| fail("github request build failed"))?
2323            .header("Accept", "application/vnd.github+json")
2324            .header("X-GitHub-Api-Version", API_VERSION)
2325            .auth(self.auth()?)
2326            .timeout(self.timeout())
2327            .max_decoded_body_size(self.max_metadata_bytes)
2328            .send()
2329            .await
2330            .map_err(|_| fail("github release list failed"))?;
2331        let body: Vec<ApiRelease> = self.read_json(response).await?;
2332        Ok(body
2333            .into_iter()
2334            .map(|item| RemoteRelease {
2335                id: item.id,
2336                tag_name: item.tag_name,
2337                name: item.name.unwrap_or_default(),
2338                body: item.body.unwrap_or_default(),
2339                draft: item.draft,
2340                immutable: item.immutable,
2341                prerelease: item.prerelease,
2342                upload_url: item.upload_url,
2343            })
2344            .collect())
2345    }
2346
2347    async fn create_release(
2348        &self,
2349        owner: &str,
2350        repo: &str,
2351        tag: &str,
2352        title: &str,
2353        body: &str,
2354        prerelease: bool,
2355    ) -> Result<RemoteRelease, GithubError> {
2356        let url = format!("{API_BASE}/repos/{owner}/{repo}/releases");
2357        let request_body = serde_json::json!({
2358            "tag_name": tag,
2359            "name": title,
2360            "body": body,
2361            "draft": true,
2362            "prerelease": prerelease,
2363            "make_latest": "false",
2364        });
2365        let response = self
2366            .client
2367            .post(&url)
2368            .map_err(|_| fail("github request build failed"))?
2369            .header("Accept", "application/vnd.github+json")
2370            .header("X-GitHub-Api-Version", API_VERSION)
2371            .auth(self.auth()?)
2372            .timeout(self.timeout())
2373            .max_decoded_body_size(self.max_metadata_bytes)
2374            .json(&request_body)
2375            .map_err(|_| fail("github request encode failed"))?
2376            .send()
2377            .await
2378            .map_err(|_| fail("github release creation failed"))?;
2379        let item: ApiRelease = self.read_json(response).await?;
2380        Ok(RemoteRelease {
2381            id: item.id,
2382            tag_name: item.tag_name,
2383            name: item.name.unwrap_or_default(),
2384            body: item.body.unwrap_or_default(),
2385            draft: item.draft,
2386            immutable: item.immutable,
2387            prerelease: item.prerelease,
2388            upload_url: item.upload_url,
2389        })
2390    }
2391
2392    async fn list_assets(
2393        &self,
2394        owner: &str,
2395        repo: &str,
2396        release_id: u64,
2397        page: u32,
2398    ) -> Result<Vec<RemoteAsset>, GithubError> {
2399        let url = format!(
2400            "{API_BASE}/repos/{owner}/{repo}/releases/{release_id}/assets?per_page=100&page={page}"
2401        );
2402        let response = self
2403            .client
2404            .get(&url)
2405            .map_err(|_| fail("github request build failed"))?
2406            .header("Accept", "application/vnd.github+json")
2407            .header("X-GitHub-Api-Version", API_VERSION)
2408            .auth(self.auth()?)
2409            .timeout(self.timeout())
2410            .max_decoded_body_size(self.max_metadata_bytes)
2411            .send()
2412            .await
2413            .map_err(|_| fail("github asset list failed"))?;
2414        let body: Vec<ApiAsset> = self.read_json(response).await?;
2415        Ok(body
2416            .into_iter()
2417            .map(|item| RemoteAsset {
2418                id: item.id,
2419                name: item.name,
2420                size: item.size,
2421                state: item.state,
2422                digest: item.digest,
2423            })
2424            .collect())
2425    }
2426
2427    async fn upload_asset(
2428        &self,
2429        owner: &str,
2430        repo: &str,
2431        release_id: u64,
2432        name: &str,
2433        file: Box<dyn std::io::Read + Send>,
2434        length: u64,
2435        content_type: &str,
2436    ) -> Result<RemoteAsset, GithubError> {
2437        let url = upload_url(owner, repo, release_id, name)?;
2438        let body = streamed_upload_body(file, length)?;
2439        let response = self
2440            .client
2441            .post(&url)
2442            .map_err(|_| fail("github request build failed"))?
2443            .header("Accept", "application/vnd.github+json")
2444            .header("X-GitHub-Api-Version", API_VERSION)
2445            .header("Content-Type", content_type)
2446            .auth(self.auth()?)
2447            .timeout(self.timeout())
2448            .max_decoded_body_size(self.max_metadata_bytes)
2449            .body(body)
2450            .send()
2451            .await
2452            .map_err(|_| fail("github asset upload failed"))?;
2453        let status = response.status().as_u16();
2454        if status == 502 {
2455            return Err(fail("http_502: github reported a gateway failure"));
2456        }
2457        if status == 422 {
2458            return Err(fail("http_422_duplicate: github rejected duplicate name"));
2459        }
2460        if (300..400).contains(&status) {
2461            return Err(fail("unexpected redirect; redirects are disabled"));
2462        }
2463        if status != 201 {
2464            return Err(fail("github asset upload failed"));
2465        }
2466        let item: ApiAsset = self.read_json(response).await?;
2467        Ok(RemoteAsset {
2468            id: item.id,
2469            name: item.name,
2470            size: item.size,
2471            state: item.state,
2472            digest: item.digest,
2473        })
2474    }
2475
2476    async fn delete_asset(
2477        &self,
2478        owner: &str,
2479        repo: &str,
2480        asset_id: u64,
2481    ) -> Result<(), GithubError> {
2482        let url = format!("{API_BASE}/repos/{owner}/{repo}/releases/assets/{asset_id}");
2483        let response = self
2484            .client
2485            .delete(&url)
2486            .map_err(|_| fail("github request build failed"))?
2487            .header("Accept", "application/vnd.github+json")
2488            .header("X-GitHub-Api-Version", API_VERSION)
2489            .auth(self.auth()?)
2490            .timeout(self.timeout())
2491            .max_decoded_body_size(self.max_metadata_bytes)
2492            .send()
2493            .await
2494            .map_err(|_| fail("github asset delete failed"))?;
2495        let status = response.status().as_u16();
2496        if status != 204 {
2497            return Err(fail("github asset delete failed"));
2498        }
2499        Ok(())
2500    }
2501}
2502
2503// ---------------------------------------------------------------------------
2504// Deterministic fixture transport for tests
2505// ---------------------------------------------------------------------------
2506
2507#[derive(Debug, Clone)]
2508struct FixtureReleaseState {
2509    release: RemoteRelease,
2510}
2511
2512#[derive(Debug)]
2513struct FixtureInner {
2514    ref_sha: Option<String>,
2515    ref_kind: String,
2516    tag_objects: BTreeMap<String, (String, String)>,
2517    releases: Vec<FixtureReleaseState>,
2518    assets: BTreeMap<u64, Vec<RemoteAsset>>,
2519    asset_pages: BTreeMap<(u64, u32), Vec<RemoteAsset>>,
2520    next_release_id: u64,
2521    next_asset_id: u64,
2522    upload_rename_next: bool,
2523    upload_digest_mismatch_next: bool,
2524    upload_omit_digest_next: bool,
2525    upload_size_mismatch_next: bool,
2526    upload_fail_502_create_starter: bool,
2527    upload_fail_502_next: Option<String>,
2528    upload_fail_422_next: bool,
2529    create_calls: u32,
2530    upload_calls: u32,
2531    delete_calls: u32,
2532}
2533
2534/// Deterministic in-memory GitHub fixture: a test double, not an adapter.
2535///
2536/// It performs no network I/O.
2537/// `seed_*`, `set_*`, and `fail_*` define every remote result.
2538/// Tests use those injectors to model staging responses.
2539/// It implements `GithubApi`, but the trait cannot distinguish
2540/// it from the real transport.
2541/// A production caller could report staging success without
2542/// network traffic.
2543///
2544/// It is hidden from rendered docs but is not test-gated.
2545/// Production wiring is a defect even though it compiles.
2546/// Use only in `#[cfg(test)]` modules or test crates.
2547///
2548/// Fidelity limits: releases stay in seeded order.
2549/// The fixture applies no filtering.
2550/// `get_tag` resolves only explicitly registered tag objects.
2551#[doc(hidden)]
2552#[derive(Debug)]
2553pub struct FixtureGithub {
2554    inner: Mutex<FixtureInner>,
2555}
2556
2557impl FixtureGithub {
2558    /// Create a fixture with an exact lightweight tag.
2559    pub fn with_tag(commit_sha: &str) -> Self {
2560        Self {
2561            inner: Mutex::new(FixtureInner {
2562                ref_sha: Some(commit_sha.to_owned()),
2563                ref_kind: "commit".to_owned(),
2564                tag_objects: BTreeMap::new(),
2565                releases: Vec::new(),
2566                assets: BTreeMap::new(),
2567                asset_pages: BTreeMap::new(),
2568                next_release_id: 100,
2569                next_asset_id: 1000,
2570                upload_rename_next: false,
2571                upload_digest_mismatch_next: false,
2572                upload_omit_digest_next: false,
2573                upload_size_mismatch_next: false,
2574                upload_fail_502_create_starter: true,
2575                upload_fail_502_next: None,
2576                upload_fail_422_next: false,
2577                create_calls: 0,
2578                upload_calls: 0,
2579                delete_calls: 0,
2580            }),
2581        }
2582    }
2583
2584    /// Set the tag reference (for movement tests).
2585    pub fn set_ref(&self, sha: Option<String>, kind: &str) {
2586        let mut inner = self.inner.lock().unwrap();
2587        inner.ref_sha = sha;
2588        inner.ref_kind = kind.to_owned();
2589    }
2590
2591    /// Register an annotated tag peeling step.
2592    pub fn add_tag_object(&self, sha: &str, object_type: &str, object_sha: &str) {
2593        let mut inner = self.inner.lock().unwrap();
2594        inner.tag_objects.insert(
2595            sha.to_owned(),
2596            (object_type.to_owned(), object_sha.to_owned()),
2597        );
2598    }
2599
2600    /// Seed one existing release.
2601    pub fn seed_release(&self, release: RemoteRelease, assets: Vec<RemoteAsset>) {
2602        let mut inner = self.inner.lock().unwrap();
2603        let id = release.id;
2604        inner.releases.push(FixtureReleaseState { release });
2605        inner.assets.insert(id, assets);
2606        if id >= inner.next_release_id {
2607            inner.next_release_id = id + 1;
2608        }
2609    }
2610
2611    /// Override one remote asset-list page for pagination edge-case tests.
2612    pub fn set_asset_page(&self, release_id: u64, page: u32, assets: Vec<RemoteAsset>) {
2613        self.inner
2614            .lock()
2615            .unwrap()
2616            .asset_pages
2617            .insert((release_id, page), assets);
2618    }
2619
2620    /// Fail the next upload for `name` with 502.
2621    pub fn fail_upload_502_next(&self, name: &str, create_starter: bool) {
2622        let mut inner = self.inner.lock().unwrap();
2623        inner.upload_fail_502_next = Some(name.to_owned());
2624        inner.upload_fail_502_create_starter = create_starter;
2625    }
2626
2627    /// Fail the next upload with 422 duplicate.
2628    pub fn fail_upload_422_next(&self) {
2629        let mut inner = self.inner.lock().unwrap();
2630        inner.upload_fail_422_next = true;
2631    }
2632
2633    /// Rename the next uploaded asset.
2634    pub fn rename_next_upload(&self) {
2635        let mut inner = self.inner.lock().unwrap();
2636        inner.upload_rename_next = true;
2637    }
2638
2639    /// Return a wrong digest for the next upload.
2640    pub fn digest_mismatch_next(&self) {
2641        let mut inner = self.inner.lock().unwrap();
2642        inner.upload_digest_mismatch_next = true;
2643    }
2644
2645    /// Return a wrong size for the next upload.
2646    pub fn size_mismatch_next(&self) {
2647        let mut inner = self.inner.lock().unwrap();
2648        inner.upload_size_mismatch_next = true;
2649    }
2650
2651    /// Omit the digest field from the next upload response.
2652    ///
2653    /// Real uploads answer with a digest, so the fixture returns one by
2654    /// default; this models a response that leaves it out, which the staging
2655    /// core must still reject at its final inventory check.
2656    pub fn omit_digest_next(&self) {
2657        let mut inner = self.inner.lock().unwrap();
2658        inner.upload_omit_digest_next = true;
2659    }
2660
2661    /// Number of release creations.
2662    pub fn create_calls(&self) -> u32 {
2663        self.inner.lock().unwrap().create_calls
2664    }
2665
2666    /// Number of upload attempts.
2667    pub fn upload_calls(&self) -> u32 {
2668        self.inner.lock().unwrap().upload_calls
2669    }
2670
2671    /// Number of asset deletions.
2672    pub fn delete_calls(&self) -> u32 {
2673        self.inner.lock().unwrap().delete_calls
2674    }
2675
2676    /// Current assets for one release.
2677    pub fn assets_for(&self, release_id: u64) -> Vec<RemoteAsset> {
2678        self.inner
2679            .lock()
2680            .unwrap()
2681            .assets
2682            .get(&release_id)
2683            .cloned()
2684            .unwrap_or_default()
2685    }
2686}
2687
2688/// Build a fixture release record for [`FixtureGithub`].
2689///
2690/// Test-double helper: see that type's documentation.
2691#[doc(hidden)]
2692pub fn fixture_release(
2693    id: u64,
2694    tag: &str,
2695    title: &str,
2696    body: &str,
2697    prerelease: bool,
2698    draft: bool,
2699    immutable: bool,
2700) -> RemoteRelease {
2701    RemoteRelease {
2702        id,
2703        tag_name: tag.to_owned(),
2704        name: title.to_owned(),
2705        body: body.to_owned(),
2706        draft,
2707        immutable,
2708        prerelease,
2709        upload_url: format!("{UPLOAD_BASE}/repos/acme/widget/releases/{id}/assets{{?name,label}}"),
2710    }
2711}
2712
2713/// Build a fixture asset record for [`FixtureGithub`].
2714///
2715/// Test-double helper: see that type's documentation.
2716#[doc(hidden)]
2717pub fn fixture_asset(
2718    id: u64,
2719    name: &str,
2720    size: u64,
2721    state: &str,
2722    sha_hex: Option<&str>,
2723) -> RemoteAsset {
2724    RemoteAsset {
2725        id,
2726        name: name.to_owned(),
2727        size,
2728        state: state.to_owned(),
2729        digest: sha_hex.map(|hex| format!("sha256:{hex}")),
2730    }
2731}
2732
2733impl GithubApi for FixtureGithub {
2734    async fn get_ref(
2735        &self,
2736        _owner: &str,
2737        _repo: &str,
2738        _tag: &str,
2739    ) -> Result<RefTarget, GithubError> {
2740        let inner = self.inner.lock().unwrap();
2741        match &inner.ref_sha {
2742            None => Err(fail("github resource not found")),
2743            Some(sha) => Ok(RefTarget {
2744                sha: sha.clone(),
2745                kind: inner.ref_kind.clone(),
2746            }),
2747        }
2748    }
2749
2750    async fn get_tag(
2751        &self,
2752        _owner: &str,
2753        _repo: &str,
2754        sha: &str,
2755    ) -> Result<TagObject, GithubError> {
2756        let inner = self.inner.lock().unwrap();
2757        match inner.tag_objects.get(sha) {
2758            None => Err(fail("github resource not found")),
2759            Some((kind, object_sha)) => Ok(TagObject {
2760                object_sha: object_sha.clone(),
2761                object_type: kind.clone(),
2762            }),
2763        }
2764    }
2765
2766    async fn list_releases(
2767        &self,
2768        _owner: &str,
2769        _repo: &str,
2770        page: u32,
2771    ) -> Result<Vec<RemoteRelease>, GithubError> {
2772        let inner = self.inner.lock().unwrap();
2773        // Paged like the real endpoint rather than returning everything on
2774        // page 1: a listing that can never fill a page cannot exercise the
2775        // bound-exhaustion path at all.
2776        let all: Vec<RemoteRelease> = inner
2777            .releases
2778            .iter()
2779            .map(|state| state.release.clone())
2780            .collect();
2781        let start = (page.saturating_sub(1) as usize).saturating_mul(LIST_PAGE_SIZE);
2782        Ok(all.into_iter().skip(start).take(LIST_PAGE_SIZE).collect())
2783    }
2784
2785    async fn create_release(
2786        &self,
2787        owner: &str,
2788        repo: &str,
2789        tag: &str,
2790        title: &str,
2791        body: &str,
2792        prerelease: bool,
2793    ) -> Result<RemoteRelease, GithubError> {
2794        let mut inner = self.inner.lock().unwrap();
2795        inner.create_calls += 1;
2796        // GitHub answers `422 already_exists` for a tag that already has a
2797        // release. Accepting it here would let a caller create a second
2798        // release for one tag and report success, which is exactly what the
2799        // staging core must never do.
2800        if inner
2801            .releases
2802            .iter()
2803            .any(|state| state.release.tag_name == tag)
2804        {
2805            return Err(fail(
2806                "http_422_already_exists: github rejected duplicate release tag",
2807            ));
2808        }
2809        let id = inner.next_release_id;
2810        inner.next_release_id += 1;
2811        let release = RemoteRelease {
2812            id,
2813            tag_name: tag.to_owned(),
2814            name: title.to_owned(),
2815            body: body.to_owned(),
2816            draft: true,
2817            immutable: false,
2818            prerelease,
2819            upload_url: format!(
2820                "{UPLOAD_BASE}/repos/{owner}/{repo}/releases/{id}/assets{{?name,label}}"
2821            ),
2822        };
2823        inner.releases.push(FixtureReleaseState {
2824            release: release.clone(),
2825        });
2826        inner.assets.insert(id, Vec::new());
2827        Ok(release)
2828    }
2829
2830    async fn list_assets(
2831        &self,
2832        _owner: &str,
2833        _repo: &str,
2834        release_id: u64,
2835        page: u32,
2836    ) -> Result<Vec<RemoteAsset>, GithubError> {
2837        let inner = self.inner.lock().unwrap();
2838        if let Some(page_assets) = inner.asset_pages.get(&(release_id, page)) {
2839            return Ok(page_assets.clone());
2840        }
2841        let all = inner.assets.get(&release_id).cloned().unwrap_or_default();
2842        let start = (page.saturating_sub(1) as usize).saturating_mul(LIST_PAGE_SIZE);
2843        Ok(all.into_iter().skip(start).take(LIST_PAGE_SIZE).collect())
2844    }
2845
2846    async fn upload_asset(
2847        &self,
2848        _owner: &str,
2849        _repo: &str,
2850        release_id: u64,
2851        name: &str,
2852        mut file: Box<dyn std::io::Read + Send>,
2853        length: u64,
2854        _content_type: &str,
2855    ) -> Result<RemoteAsset, GithubError> {
2856        use std::io::Read;
2857        let mut bytes = Vec::new();
2858        file.read_to_end(&mut bytes)
2859            .map_err(|_| fail("fixture upload read failed"))?;
2860        if bytes.len() as u64 != length {
2861            return Err(fail("fixture upload length mismatch"));
2862        }
2863        let mut inner = self.inner.lock().unwrap();
2864        inner.upload_calls += 1;
2865        if inner.upload_fail_422_next {
2866            inner.upload_fail_422_next = false;
2867            return Err(fail("http_422_duplicate: github rejected duplicate name"));
2868        }
2869        if let Some(expected) = inner.upload_fail_502_next.clone() {
2870            if expected == name {
2871                inner.upload_fail_502_next = None;
2872                if inner.upload_fail_502_create_starter {
2873                    let id = inner.next_asset_id;
2874                    inner.next_asset_id += 1;
2875                    inner
2876                        .assets
2877                        .entry(release_id)
2878                        .or_default()
2879                        .push(RemoteAsset {
2880                            id,
2881                            name: name.to_owned(),
2882                            size: 0,
2883                            state: "starter".to_owned(),
2884                            digest: None,
2885                        });
2886                }
2887                return Err(fail("http_502: github reported a gateway failure"));
2888            }
2889        }
2890        use sha2::Digest;
2891        let digest: String = sha2::Sha256::digest(&bytes)
2892            .iter()
2893            .map(|b| format!("{b:02x}"))
2894            .collect();
2895        let id = inner.next_asset_id;
2896        inner.next_asset_id += 1;
2897        let record_name = if inner.upload_rename_next {
2898            inner.upload_rename_next = false;
2899            format!("{name}.renamed")
2900        } else {
2901            name.to_owned()
2902        };
2903        let size = if inner.upload_size_mismatch_next {
2904            inner.upload_size_mismatch_next = false;
2905            bytes.len() as u64 + 1
2906        } else {
2907            bytes.len() as u64
2908        };
2909        let digest_value = if inner.upload_digest_mismatch_next {
2910            inner.upload_digest_mismatch_next = false;
2911            Some("sha256:".to_owned() + &"0".repeat(64))
2912        } else if inner.upload_omit_digest_next {
2913            inner.upload_omit_digest_next = false;
2914            None
2915        } else {
2916            Some(format!("sha256:{digest}"))
2917        };
2918        let record = RemoteAsset {
2919            id,
2920            name: record_name,
2921            size,
2922            state: "uploaded".to_owned(),
2923            digest: digest_value,
2924        };
2925        inner
2926            .assets
2927            .entry(release_id)
2928            .or_default()
2929            .push(record.clone());
2930        Ok(record)
2931    }
2932
2933    async fn delete_asset(
2934        &self,
2935        _owner: &str,
2936        _repo: &str,
2937        asset_id: u64,
2938    ) -> Result<(), GithubError> {
2939        let mut inner = self.inner.lock().unwrap();
2940        inner.delete_calls += 1;
2941        for assets in inner.assets.values_mut() {
2942            if let Some(position) = assets.iter().position(|asset| asset.id == asset_id) {
2943                assets.remove(position);
2944                return Ok(());
2945            }
2946        }
2947        Err(fail("github asset delete failed"))
2948    }
2949}
2950
2951#[cfg(test)]
2952mod tests;
2953
2954/// M003l: the SHA-256 acceptance set is the canonical one, applied here
2955/// rather than restated.
2956#[cfg(test)]
2957mod m003l_rule_convergence_tests {
2958    use super::*;
2959
2960    #[test]
2961    fn sha256_acceptance_set_is_the_canonical_one() {
2962        const DIGESTS: &[&str] = &[
2963            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90",
2964            "0000000000000000000000000000000000000000000000000000000000000000",
2965            "A1B2C3D4E5F60718293A4B5C6D7E8F90A1B2C3D4E5F60718293A4B5C6D7E8F90",
2966            "g1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90",
2967            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9",
2968            "a1b2c3d4",
2969            "",
2970        ];
2971        for digest in DIGESTS {
2972            assert_eq!(
2973                validate_sha256(digest).is_ok(),
2974                eggpack_manifest::validate_sha256_hex(digest).is_ok(),
2975                "GitHub call site diverged for {digest:?}"
2976            );
2977        }
2978        // The all-zeros placeholder is refused.
2979        assert!(validate_sha256(&"0".repeat(64)).is_err());
2980        // A canonical digest is accepted.
2981        assert!(validate_sha256(
2982            "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90"
2983        )
2984        .is_ok());
2985    }
2986
2987    #[test]
2988    fn exact_tag_safety_is_the_canonical_one() {
2989        // Every character class the pre-convergence rule refused is still
2990        // refused, and the canonical rule adds the git-ref-path concerns.
2991        for tag in [
2992            "",
2993            "v1.2.3#",
2994            "v1.2.3@",
2995            "v1.2.3'",
2996            "v1.2.3\"",
2997            "v1.2.3`",
2998            "v1.2.3$",
2999            "v1.2.3?",
3000            "v1.2.3 ",
3001            "v1.2.3\\",
3002            "v1.2.3^",
3003            "v1.2.3:",
3004            "v1.2.3*",
3005            "v1.2.3[",
3006            "v1.2.3~",
3007            "v1.2.3.",
3008            "v1..2.3",
3009            "/v1.2.3",
3010            "v1.2.3/",
3011            "release/v1.2.3.lock",
3012        ] {
3013            assert!(
3014                validate_tag(tag).is_err(),
3015                "GitHub accepted an unsafe tag {tag:?}"
3016            );
3017        }
3018        // A canonical version tag and a multi-segment tag stay accepted.
3019        assert!(validate_tag("v1.2.3").is_ok());
3020        assert!(validate_tag("release/v1.2.3").is_ok());
3021    }
3022}
3023
3024/// M003n: the staging payload has exactly one builder.
3025///
3026/// Both public entry points and both installer presentations are covered by
3027/// byte-exact evidence, so a divergence between the presentation-specific
3028/// work and the shared algorithm fails loudly.
3029#[cfg(test)]
3030mod m003n_consolidation_tests {
3031    use super::*;
3032    use eggpack_manifest::{ArtifactForm, ArtifactRecord, ReleaseManifest, TargetRecord};
3033
3034    /// Byte-exact golden for the generated-default staging payload.
3035    const M003N_GOLDEN_GENERATED_DEFAULT: &str = r#"{"schema_version":1,"product_id":"eggsact","release_id":"1.2.6","source_revision":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","owner":"acme","repository":"widget","tag":"v1.2.3","title":"widget 1.2.3","prerelease":false,"body":"notes","assets":[{"name":"eggsact-1.2.6-aarch64-apple-darwin","path":"eggsact-1.2.6-aarch64-apple-darwin","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-aarch64-apple-darwin.sha256","path":"eggsact-1.2.6-aarch64-apple-darwin.sha256","size":101,"sha256":"4f071dece3fa37c30e0dd043b1a797ac4ad3a667797416b86021874a38b796a2","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","size":105,"sha256":"c9529680b9d3bff4dc33c13385829307e2d18683c5dd23f0e62075d8bfd8c706","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"install.ps1","path":"install.ps1","size":2409,"sha256":"a58fd2089f7f93d77b49b095be040eb5d1ac0c6d3fcd6d8795a0f37e8b36c00c","media_type":"text/x-powershell","kind":"powershell_installer"},{"name":"install.sh","path":"install.sh","size":2990,"sha256":"d31c315d6a2ada9087f6206437b427765cad3333c5fc1358df3faadfe9fdd8ce","media_type":"text/x-shellscript","kind":"posix_installer"},{"name":"release-manifest.json","path":"release-manifest.json","size":587,"sha256":"6fdc51ab9a646b8b219eeba7b83ced5768ea704d1317dbb47d2fc07bf26dd9dd","media_type":"application/json","kind":"release_manifest"}]}"#;
3036
3037    /// Byte-exact golden for the product-wrappers staging payload.
3038    const M003N_GOLDEN_PRODUCT_WRAPPERS: &str = r#"{"schema_version":1,"product_id":"eggsact","release_id":"1.2.6","source_revision":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","owner":"acme","repository":"widget","tag":"v1.2.3","title":"widget 1.2.3","prerelease":false,"body":"notes","assets":[{"name":"eggsact-1.2.6-aarch64-apple-darwin","path":"eggsact-1.2.6-aarch64-apple-darwin","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-aarch64-apple-darwin.sha256","path":"eggsact-1.2.6-aarch64-apple-darwin.sha256","size":101,"sha256":"4f071dece3fa37c30e0dd043b1a797ac4ad3a667797416b86021874a38b796a2","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu","size":4,"sha256":"230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5","media_type":"application/octet-stream","kind":"finalized_artifact"},{"name":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","path":"eggsact-1.2.6-x86_64-unknown-linux-gnu.sha256","size":105,"sha256":"c9529680b9d3bff4dc33c13385829307e2d18683c5dd23f0e62075d8bfd8c706","media_type":"text/plain","kind":"checksum_sidecar"},{"name":"install-exact.ps1","path":"install-exact.ps1","size":2409,"sha256":"a58fd2089f7f93d77b49b095be040eb5d1ac0c6d3fcd6d8795a0f37e8b36c00c","media_type":"text/x-powershell","kind":"powershell_installer"},{"name":"install-exact.sh","path":"install-exact.sh","size":2990,"sha256":"d31c315d6a2ada9087f6206437b427765cad3333c5fc1358df3faadfe9fdd8ce","media_type":"text/x-shellscript","kind":"posix_installer"},{"name":"install.ps1","path":"install.ps1","size":37,"sha256":"3f078877b9c699b15c410e783e6bb6ca3da1b7881ac673f12ebaf7440adc9c64","media_type":"text/x-powershell","kind":"product_powershell_wrapper"},{"name":"install.sh","path":"install.sh","size":31,"sha256":"61a73587bfb5acdc2e718bfad3797b35f971cfa40d053d187792b07b6e095ffe","media_type":"text/x-shellscript","kind":"product_posix_wrapper"},{"name":"release-manifest.json","path":"release-manifest.json","size":587,"sha256":"6fdc51ab9a646b8b219eeba7b83ced5768ea704d1317dbb47d2fc07bf26dd9dd","media_type":"application/json","kind":"release_manifest"}]}"#;
3039
3040    fn temp_root(label: &str) -> PathBuf {
3041        use std::sync::atomic::{AtomicU64, Ordering};
3042        static NEXT: AtomicU64 = AtomicU64::new(0);
3043        loop {
3044            let id = NEXT.fetch_add(1, Ordering::Relaxed);
3045            let path = std::env::temp_dir().join(format!(
3046                "eggpack-gh-m003n-{label}-{}-{id}",
3047                std::process::id()
3048            ));
3049            match std::fs::create_dir(&path) {
3050                Ok(()) => return path,
3051                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
3052                Err(error) => panic!("create temp: {error}"),
3053            }
3054        }
3055    }
3056
3057    fn sha_hex(bytes: &[u8]) -> String {
3058        use sha2::Digest;
3059        sha2::Sha256::digest(bytes)
3060            .iter()
3061            .map(|b| format!("{b:02x}"))
3062            .collect()
3063    }
3064
3065    fn test_policy() -> GitHubDraftPolicyV1 {
3066        GitHubDraftPolicyV1 {
3067            schema_version: 1,
3068            owner: "acme".to_owned(),
3069            repository: "widget".to_owned(),
3070            tag: "v1.2.3".to_owned(),
3071            release_identity_schema_version: None,
3072            release_identity_mode: None,
3073            release_id: None,
3074            source_revision: None,
3075            title: "widget 1.2.3".to_owned(),
3076            body: "notes".to_owned(),
3077            prerelease: false,
3078            token_env: "GITHUB_TOKEN".to_owned(),
3079            request_timeout_secs: 30,
3080            max_metadata_bytes: 1_000_000,
3081            max_list_pages: 5,
3082        }
3083    }
3084
3085    fn direct_contract() -> DistributionContract {
3086        DistributionContract::parse_toml_str(include_str!(
3087            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
3088        ))
3089        .unwrap()
3090    }
3091
3092    fn direct_manifest(release: &str, source: &str) -> ReleaseManifest {
3093        let mk = |target: &str| TargetRecord {
3094            target: target.to_owned(),
3095            form: ArtifactForm::Direct {
3096                artifact: ArtifactRecord {
3097                    name: format!("eggsact-{release}-{target}"),
3098                    size: 4,
3099                    sha256: sha_hex(b"body"),
3100                },
3101                install: "eggsact".to_owned(),
3102            },
3103        };
3104        ReleaseManifest {
3105            schema_version: 1,
3106            product_id: "eggsact".to_owned(),
3107            release_id: release.to_owned(),
3108            source_revision: source.to_owned(),
3109            targets: vec![mk("aarch64-apple-darwin"), mk("x86_64-unknown-linux-gnu")],
3110            evidence_references: Vec::new(),
3111        }
3112    }
3113
3114    fn write_finalized_root(
3115        contract: &DistributionContract,
3116        manifest: &ReleaseManifest,
3117        root: &Path,
3118    ) {
3119        std::fs::create_dir(root).unwrap();
3120        let mut files: BTreeMap<String, bool> = BTreeMap::new();
3121        for target in &manifest.targets {
3122            let expanded = contract
3123                .expand(&target.target, &manifest.release_id)
3124                .unwrap();
3125            match expanded.assets {
3126                ExpandedAssets::Direct(direct) => {
3127                    files.insert(direct.asset_file, true);
3128                    files.insert(direct.sidecar_file, false);
3129                }
3130                ExpandedAssets::Bundle(bundle) => {
3131                    for entry in bundle.entries.into_iter() {
3132                        files.insert(entry.asset_file, true);
3133                        files.insert(entry.sidecar_file, false);
3134                    }
3135                }
3136                ExpandedAssets::Archive(archive) => {
3137                    files.insert(archive.archive_file, true);
3138                    files.insert(archive.sidecar_file, false);
3139                }
3140            }
3141        }
3142        for (name, is_artifact) in files {
3143            if is_artifact {
3144                std::fs::write(root.join(&name), b"body").unwrap();
3145            } else {
3146                let artifact = name.strip_suffix(".sha256").unwrap().to_owned();
3147                let content = format!("{}  {artifact}\n", sha_hex(b"body"));
3148                std::fs::write(root.join(&name), content).unwrap();
3149            }
3150        }
3151    }
3152
3153    fn wrapper_presentation() -> InstallerPresentationV1 {
3154        InstallerPresentationV1 {
3155            schema_version: 1,
3156            mode: InstallerPresentationModeV1::ProductWrappers(ProductWrapperSourcesV1 {
3157                posix_source: "packaging/install.sh".to_owned(),
3158                powershell_source: "packaging/install.ps1".to_owned(),
3159                generated_posix_name: "install-exact.sh".to_owned(),
3160                generated_powershell_name: "install-exact.ps1".to_owned(),
3161            }),
3162        }
3163    }
3164
3165    fn write_wrapper_sources(root: &Path, posix: &[u8], powershell: &[u8]) {
3166        std::fs::create_dir_all(root.join("packaging")).unwrap();
3167        std::fs::write(root.join("packaging/install.sh"), posix).unwrap();
3168        std::fs::write(root.join("packaging/install.ps1"), powershell).unwrap();
3169    }
3170
3171    /// The staged file inventory of one materialized payload, with the exact
3172    /// bytes of every staged file.
3173    fn staged_inventory(staged: &Path) -> BTreeMap<String, Vec<u8>> {
3174        let mut inventory = BTreeMap::new();
3175        for entry in std::fs::read_dir(staged).unwrap() {
3176            let entry = entry.unwrap();
3177            let name = entry.file_name().to_string_lossy().into_owned();
3178            let bytes = std::fs::read(entry.path()).unwrap();
3179            inventory.insert(name, bytes);
3180        }
3181        inventory
3182    }
3183
3184    /// Materialize the generated-default payload.
3185    fn materialize_default(
3186        parent: &Path,
3187        contract: &DistributionContract,
3188        manifest: &ReleaseManifest,
3189        policy: &GitHubDraftPolicyV1,
3190        install_policy: &BootstrapInstallPolicyV1,
3191        finalized: &Path,
3192        label: &str,
3193    ) -> (StagingPayloadV1, PathBuf) {
3194        let staged = parent.join(label);
3195        let payload = prepare_staging_payload(
3196            contract,
3197            manifest,
3198            finalized,
3199            policy,
3200            install_policy,
3201            &staged,
3202        )
3203        .unwrap();
3204        (payload, staged)
3205    }
3206
3207    /// Materialize the product-wrappers payload.
3208    fn materialize_wrappers(
3209        parent: &Path,
3210        contract: &DistributionContract,
3211        manifest: &ReleaseManifest,
3212        policy: &GitHubDraftPolicyV1,
3213        install_policy: &BootstrapInstallPolicyV1,
3214        finalized: &Path,
3215        label: &str,
3216    ) -> (StagingPayloadV1, PathBuf) {
3217        let source_root = parent.join("consumer");
3218        write_wrapper_sources(
3219            &source_root,
3220            b"#!/bin/sh\n# product wrapper v1\n",
3221            b"# product wrapper v1\r\nWrite-Host hi\r\n",
3222        );
3223        let staged = parent.join(label);
3224        let payload = prepare_staging_payload_with_presentation(
3225            contract,
3226            manifest,
3227            finalized,
3228            policy,
3229            install_policy,
3230            &wrapper_presentation(),
3231            &source_root,
3232            &staged,
3233        )
3234        .unwrap();
3235        (payload, staged)
3236    }
3237
3238    #[test]
3239    fn m003n_generated_default_payload_matches_golden() {
3240        let contract = direct_contract();
3241        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
3242        let install_policy = BootstrapInstallPolicyV1::empty();
3243        let policy = test_policy();
3244        let parent = temp_root("golden-default");
3245        let finalized = parent.join("finalized");
3246        write_finalized_root(&contract, &manifest, &finalized);
3247        let (payload, staged) = materialize_default(
3248            &parent,
3249            &contract,
3250            &manifest,
3251            &policy,
3252            &install_policy,
3253            &finalized,
3254            "staging",
3255        );
3256        assert_eq!(payload.to_json().unwrap(), M003N_GOLDEN_GENERATED_DEFAULT);
3257        // The staged files are the golden ones, byte for byte.
3258        let inventory = staged_inventory(&staged);
3259        assert_eq!(inventory.len(), 7);
3260        assert_eq!(
3261            inventory.get("install.sh").map(|b| b.len()),
3262            Some(2990),
3263            "the generated POSIX installer changed size"
3264        );
3265        std::fs::remove_dir_all(parent).unwrap();
3266    }
3267
3268    #[test]
3269    fn m003n_product_wrappers_payload_matches_golden() {
3270        let contract = direct_contract();
3271        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
3272        let install_policy = BootstrapInstallPolicyV1::empty();
3273        let policy = test_policy();
3274        let parent = temp_root("golden-wrappers");
3275        let finalized = parent.join("finalized");
3276        write_finalized_root(&contract, &manifest, &finalized);
3277        let (payload, staged) = materialize_wrappers(
3278            &parent,
3279            &contract,
3280            &manifest,
3281            &policy,
3282            &install_policy,
3283            &finalized,
3284            "staging",
3285        );
3286        assert_eq!(payload.to_json().unwrap(), M003N_GOLDEN_PRODUCT_WRAPPERS);
3287        let inventory = staged_inventory(&staged);
3288        assert_eq!(inventory.len(), 9);
3289        assert_eq!(inventory.get("install.sh").map(|b| b.len()), Some(31));
3290        assert_eq!(
3291            inventory.get("install-exact.sh").map(|b| b.len()),
3292            Some(2990)
3293        );
3294        std::fs::remove_dir_all(parent).unwrap();
3295    }
3296
3297    #[test]
3298    fn m003n_both_staging_entry_points_produce_byte_identical_payloads() {
3299        let contract = direct_contract();
3300        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
3301        let install_policy = BootstrapInstallPolicyV1::empty();
3302        let policy = test_policy();
3303        let parent = temp_root("entry-points");
3304        let finalized = parent.join("finalized");
3305        write_finalized_root(&contract, &manifest, &finalized);
3306        let (legacy, legacy_dir) = materialize_default(
3307            &parent,
3308            &contract,
3309            &manifest,
3310            &policy,
3311            &install_policy,
3312            &finalized,
3313            "legacy",
3314        );
3315        let modern_dir = parent.join("modern");
3316        let modern = prepare_staging_payload_with_presentation(
3317            &contract,
3318            &manifest,
3319            &finalized,
3320            &policy,
3321            &install_policy,
3322            &InstallerPresentationV1::generated_default(),
3323            &parent,
3324            &modern_dir,
3325        )
3326        .unwrap();
3327        // The two entry points are one implementation: byte-identical
3328        // payloads and byte-identical staged files.
3329        assert_eq!(
3330            legacy.to_json().unwrap(),
3331            modern.to_json().unwrap(),
3332            "the two staging entry points diverged"
3333        );
3334        let legacy_files = staged_inventory(&legacy_dir);
3335        let modern_files = staged_inventory(&modern_dir);
3336        assert_eq!(
3337            legacy_files.keys().collect::<Vec<_>>(),
3338            modern_files.keys().collect::<Vec<_>>(),
3339            "the two staging entry points staged different files"
3340        );
3341        for (name, bytes) in &legacy_files {
3342            assert_eq!(
3343                bytes,
3344                modern_files.get(name).unwrap(),
3345                "staged bytes differ for {name}"
3346            );
3347        }
3348        std::fs::remove_dir_all(parent).unwrap();
3349    }
3350
3351    #[test]
3352    fn m003n_shared_algorithm_regions_are_identical_across_presentations() {
3353        let contract = direct_contract();
3354        let manifest = direct_manifest("1.2.6", &"a".repeat(40));
3355        let install_policy = BootstrapInstallPolicyV1::empty();
3356        let policy = test_policy();
3357        let parent = temp_root("shared-regions");
3358        let finalized = parent.join("finalized");
3359        write_finalized_root(&contract, &manifest, &finalized);
3360        let (default_payload, default_dir) = materialize_default(
3361            &parent,
3362            &contract,
3363            &manifest,
3364            &policy,
3365            &install_policy,
3366            &finalized,
3367            "default",
3368        );
3369        let (wrappers_payload, wrappers_dir) = materialize_wrappers(
3370            &parent,
3371            &contract,
3372            &manifest,
3373            &policy,
3374            &install_policy,
3375            &finalized,
3376            "wrappers",
3377        );
3378        // The payload metadata is presentation-independent.
3379        assert_eq!(default_payload.product_id, wrappers_payload.product_id);
3380        assert_eq!(default_payload.release_id, wrappers_payload.release_id);
3381        assert_eq!(
3382            default_payload.source_revision,
3383            wrappers_payload.source_revision
3384        );
3385        assert_eq!(default_payload.owner, wrappers_payload.owner);
3386        assert_eq!(default_payload.repository, wrappers_payload.repository);
3387        assert_eq!(default_payload.tag, wrappers_payload.tag);
3388        assert_eq!(default_payload.title, wrappers_payload.title);
3389        assert_eq!(default_payload.prerelease, wrappers_payload.prerelease);
3390        assert_eq!(default_payload.body, wrappers_payload.body);
3391        // Every non-installer asset is identical: the same name, path, size,
3392        // digest, media type, and kind.
3393        let shared = |payload: &StagingPayloadV1| {
3394            payload
3395                .assets
3396                .iter()
3397                .filter(|asset| {
3398                    !matches!(
3399                        asset.kind,
3400                        StagingAssetKind::PosixInstaller
3401                            | StagingAssetKind::PowershellInstaller
3402                            | StagingAssetKind::ProductPosixWrapper
3403                            | StagingAssetKind::ProductPowershellWrapper
3404                    )
3405                })
3406                .map(|asset| {
3407                    (
3408                        asset.name.clone(),
3409                        asset.path.clone(),
3410                        asset.size,
3411                        asset.sha256.clone(),
3412                        asset.media_type.clone(),
3413                        format!("{:?}", asset.kind),
3414                    )
3415                })
3416                .collect::<Vec<_>>()
3417        };
3418        assert_eq!(
3419            shared(&default_payload),
3420            shared(&wrappers_payload),
3421            "the shared inventory regions diverged across presentations"
3422        );
3423        // The staged finalized assets and the standalone manifest are the
3424        // same bytes in both presentations.
3425        let default_files = staged_inventory(&default_dir);
3426        let wrappers_files = staged_inventory(&wrappers_dir);
3427        for (name, bytes) in &default_files {
3428            if name == "install.sh" || name == "install.ps1" {
3429                continue;
3430            }
3431            assert_eq!(
3432                bytes,
3433                wrappers_files.get(name).unwrap(),
3434                "shared staged bytes differ for {name}"
3435            );
3436        }
3437        std::fs::remove_dir_all(parent).unwrap();
3438    }
3439}