Skip to main content

pmcp_package/oci/
pack.rs

1//! `pack_server`/`pack_agent`/`pack_team`/`pack_workflow` — serialize each
2//! package type into a local [`OciLayout`] (RESEARCH System Architecture
3//! Diagram, pack() steps 1-5):
4//!
5//! 1. Serialize each logical layer to bytes via [`canonicalize`] (deterministic).
6//! 2. `layout.write_blob()` each → a content-addressed `Descriptor` with the
7//!    correct vendor `MediaType`.
8//! 3. Build an `oci_spec::image::ImageManifest` (empty config + layer
9//!    descriptors + `artifactType`).
10//! 4. Canonicalize the manifest via `olpc-cjson`.
11//! 5. `sha256(canonical manifest bytes)` — stored as the manifest blob's own
12//!    content-addressed digest AND returned as the function's
13//!    [`ManifestDigest`] (identity key). One hash, one source of truth —
14//!    no separate re-derivation of "the" manifest digest.
15//!
16//! The `ServerPackage` binary is a SEPARATE [`BinaryMode`] parameter to
17//! `pack_server`, never a field read off the struct (cross-AI review: binary
18//! payloads are OCI layers, not typed-struct fields) — it becomes either an
19//! `MT_SERVER_BOOTSTRAP` layer (embedded bytes) or an `MT_SERVER_BINARY_REF`
20//! layer (a digest the target environment resolves), never both.
21
22use crate::digest::{canonicalize, ManifestDigest};
23use crate::error::{PackageError, Result};
24use crate::oci::config_validation::{
25    parse_declared_config_slots_in, parse_document, validate_config_slot_agreement,
26    validate_config_slot_placeholders_in, validate_no_undeclared_env_refs_in,
27};
28use crate::oci::layout::OciLayout;
29use crate::oci::media_types::{
30    empty_config_descriptor, vendor_media_type, ANNOTATION_ATTESTATION_ISSUER,
31    ANNOTATION_ATTESTATION_PAYLOAD_TYPE, ANNOTATION_ATTESTATION_SUBJECT, ARTIFACT_TYPE_SERVER,
32    EMPTY_CONFIG_BLOB, MT_ATTESTATION, MT_EMPTY_CONFIG, MT_SERVER_BINARY_REF, MT_SERVER_BOOTSTRAP,
33    MT_SERVER_CEDAR_POLICY_SET, MT_SERVER_CONFIG, MT_SERVER_CONFIG_SLOTS,
34    MT_SERVER_DEPLOY_DESCRIPTOR, MT_SERVER_ENVELOPE, MT_SERVER_OPENAPI_SPEC,
35    MT_SERVER_TOOL_METADATA,
36};
37use crate::oci::SingleLayerPackage;
38use crate::package::{AgentPackage, BinaryRef, ServerPackage, TeamPackage, WorkflowManifest};
39use oci_spec::image::{
40    Descriptor, ImageManifest, ImageManifestBuilder, MediaType, ANNOTATION_TITLE, SCHEMA_VERSION,
41};
42use serde::{Deserialize, Serialize};
43use std::collections::HashMap;
44
45/// `ServerPackage` fields NOT covered by the deploy/cedar/tools/config-slots
46/// layers — `name`, `version` and the top-level `digest` — packed as their own
47/// small JSON layer ([`MT_SERVER_ENVELOPE`]) so every field round-trips
48/// losslessly by plain serialize/deserialize. `pub(super)` so `oci::unpack`
49/// (a sibling module) can reconstruct a `ServerPackage` from it.
50///
51/// The binary reference is deliberately NOT a field here (D-08): it lives in
52/// its own [`MT_SERVER_BINARY_REF`] layer, so "which binary" is one fact in
53/// one place rather than a struct field that could disagree with a layer.
54#[derive(Debug, Serialize, Deserialize)]
55pub(super) struct ServerEnvelope {
56    pub(super) name: String,
57    pub(super) version: semver::Version,
58    pub(super) digest: Option<ManifestDigest>,
59}
60
61/// How a packed server names its binary — exactly one of two mutually
62/// exclusive shapes (D-05, D-06). A package always carries one binary layer;
63/// which of the two it is decides whether the package is self-contained or
64/// resolved by the target environment.
65///
66/// [`BinaryMode::Referenced`]'s `digest` is taken VERBATIM from the caller and
67/// is NON-optional: `pmcp-package` never contacts a registry to derive or
68/// confirm it (milestone Decision 2 forbids a registry client), and a
69/// referenced binary with no digest would be an instruction to run an
70/// unpinned binary. The canonical producer in this repo is
71/// `cargo-pmcp`'s `deployment::targets::aws_lambda::artifact`, which builds it
72/// via [`ManifestDigest::from_bytes`] against the release `.sha256` sidecar.
73///
74/// Note that a bare-hex sidecar (`<64 hex chars>` with no prefix) is NOT a
75/// valid digest string — [`ManifestDigest::parse`] requires the `sha256:`
76/// prefix, so prepend it before parsing.
77///
78/// # Examples
79///
80/// Both arms, side by side — a self-contained package that carries its binary,
81/// and a Shape A pure-config package that only names one:
82///
83/// ```
84/// use pmcp_package::digest::ManifestDigest;
85/// use pmcp_package::oci::BinaryMode;
86///
87/// // Self-contained: the compiled bootstrap's bytes travel inside the package.
88/// let bootstrap: Vec<u8> = b"\x7fELF...compiled-bootstrap-bytes".to_vec();
89/// let embedded = BinaryMode::Embedded(&bootstrap);
90/// assert!(matches!(embedded, BinaryMode::Embedded(bytes) if bytes == bootstrap));
91///
92/// // Pure config: the package carries no bytes at all, only a pinned digest
93/// // the target environment resolves for itself.
94/// let referenced = BinaryMode::Referenced {
95///     digest: ManifestDigest::from_bytes(b"pmcp-openapi-server-v1.0.0-aarch64"),
96///     media_type: "application/x-lambda-bootstrap; arch=arm64".to_string(),
97/// };
98/// match referenced {
99///     BinaryMode::Referenced { digest, media_type } => {
100///         assert!(digest.as_str().starts_with("sha256:"));
101///         assert_eq!(media_type, "application/x-lambda-bootstrap; arch=arm64");
102///     },
103///     BinaryMode::Embedded(_) => unreachable!("constructed as Referenced"),
104/// }
105/// ```
106#[derive(Debug, Clone)]
107pub enum BinaryMode<'a> {
108    /// The binary's bytes are embedded in the package as an
109    /// [`MT_SERVER_BOOTSTRAP`] layer. The package is self-contained.
110    Embedded(&'a [u8]),
111    /// The binary is NOT embedded: the package records only its digest and
112    /// media type in an [`MT_SERVER_BINARY_REF`] layer, and the target
113    /// environment resolves the bytes for itself.
114    Referenced {
115        /// Content digest of the binary the target environment must run.
116        digest: ManifestDigest,
117        /// Descriptive media-type hint for that binary (e.g.
118        /// `application/x-lambda-bootstrap; arch=arm64`).
119        media_type: String,
120    },
121}
122
123/// The author's server config file, carried into the package VERBATIM.
124///
125/// `bytes` are written to the [`MT_SERVER_CONFIG`] layer byte-for-byte and are
126/// never re-derived from a parsed struct — packing must not rewrite,
127/// templatize, normalize or reformat what the author wrote. `file_name` is
128/// recorded in the layer descriptor's `org.opencontainers.image.title`
129/// annotation so unpack can restore it under its original name.
130///
131/// Distinct from [`OpenApiSpecFile`] on purpose: two types rather than one
132/// shared "named blob" means a caller cannot transpose the config and the spec.
133#[derive(Debug, Clone, Copy)]
134pub struct ConfigFile<'a> {
135    /// The config file's original name, e.g. `london-tube.toml`.
136    pub file_name: &'a str,
137    /// The config file's exact bytes.
138    pub bytes: &'a [u8],
139}
140
141/// An OpenAPI-backed server's spec file, carried into the package VERBATIM.
142///
143/// The spec sibling of [`ConfigFile`], with the same verbatim-bytes and
144/// original-file-name contract, written to the [`MT_SERVER_OPENAPI_SPEC`]
145/// layer.
146///
147/// [`MT_SERVER_OPENAPI_SPEC`]: crate::oci::media_types::MT_SERVER_OPENAPI_SPEC
148#[derive(Debug, Clone, Copy)]
149pub struct OpenApiSpecFile<'a> {
150    /// The spec file's original name, e.g. `openapi.yaml`.
151    pub file_name: &'a str,
152    /// The spec file's exact bytes.
153    pub bytes: &'a [u8],
154}
155
156/// A platform-issued attestation ABOUT this package, carried into it VERBATIM.
157///
158/// `bytes` are written to the [`MT_ATTESTATION`] layer byte-for-byte and are
159/// NEVER deserialized, parsed, sniffed or re-derived by this crate — the
160/// attestation format is the issuing platform's, not this crate's. The three
161/// metadata fields are recorded as LAYER-descriptor annotations
162/// ([`ANNOTATION_ATTESTATION_SUBJECT`], [`ANNOTATION_ATTESTATION_ISSUER`],
163/// [`ANNOTATION_ATTESTATION_PAYLOAD_TYPE`]) so that reading metadata never
164/// requires reading the payload.
165///
166/// `subject` is the `sha256:<hex>` manifest digest of the UNATTESTED package
167/// this attestation is about — not the digest of the package that carries it.
168/// See [`pack_server`]'s "two digests" section.
169///
170/// Distinct from [`ConfigFile`] and [`OpenApiSpecFile`] on purpose, for the
171/// same reason those two are distinct from each other: three types rather than
172/// one shared "named blob" type means a caller cannot transpose them.
173///
174/// [`MT_ATTESTATION`]: crate::oci::media_types::MT_ATTESTATION
175/// [`ANNOTATION_ATTESTATION_SUBJECT`]: crate::oci::media_types::ANNOTATION_ATTESTATION_SUBJECT
176/// [`ANNOTATION_ATTESTATION_ISSUER`]: crate::oci::media_types::ANNOTATION_ATTESTATION_ISSUER
177/// [`ANNOTATION_ATTESTATION_PAYLOAD_TYPE`]: crate::oci::media_types::ANNOTATION_ATTESTATION_PAYLOAD_TYPE
178#[derive(Debug, Clone, Copy)]
179pub struct AttestationFile<'a> {
180    /// The attestation payload's exact bytes, carried opaquely.
181    pub bytes: &'a [u8],
182    /// `sha256:<hex>` manifest digest of the UNATTESTED package this
183    /// attestation is about.
184    pub subject: &'a str,
185    /// Who issued the attestation.
186    pub issuer: &'a str,
187    /// The payload's own media type (e.g. a report schema, or a signed
188    /// envelope).
189    pub payload_type: &'a str,
190}
191
192/// One layer's finished BYTES, plus everything needed either to write it or
193/// merely to describe it — an in-memory layer plan, private to this module.
194///
195/// It exists so byte production can happen strictly BEFORE the first
196/// `write_blob`. Without it, every descriptor `pack_server` assembles would
197/// come out of a writing call, and the pack-time attestation-subject gate
198/// (which needs the would-be unattested manifest digest) could not run until
199/// the layers it is meant to gate were already on disk.
200///
201/// Deliberately NOT a public type and NOT a staging directory: a heavier
202/// two-phase `OciLayout` API was considered during cross-AI review and
203/// rejected. This is a plain in-memory vector element and nothing more.
204struct PlannedLayer {
205    /// The vendor (or standard) media type this layer's descriptor carries.
206    media_type: MediaType,
207    /// The layer's exact bytes, already canonicalized where canonicalization
208    /// applies and left verbatim where it does not.
209    bytes: Vec<u8>,
210    /// Annotations to attach to the resulting LAYER descriptor, if any.
211    annotations: Option<HashMap<String, String>>,
212}
213
214impl PlannedLayer {
215    /// The descriptor this layer WOULD have, computed without touching the
216    /// filesystem.
217    ///
218    /// Equal by construction to what [`write_planned_layer`] returns for the
219    /// same plan: both route through the shared [`annotate`] helper over
220    /// [`OciLayout::describe_blob`]/[`OciLayout::write_blob`], whose own
221    /// equality is pinned by a test in `layout.rs`.
222    fn describe(&self) -> Descriptor {
223        annotate(
224            OciLayout::describe_blob(self.media_type.clone(), &self.bytes),
225            self.annotations.as_ref(),
226        )
227    }
228}
229
230/// Attach `annotations` to `descriptor`, if there are any.
231///
232/// Shared by the describing and the writing path so the two cannot drift into
233/// annotating differently — which would make the two manifests differ by more
234/// than their layer vectors and silently break the pack-time subject gate.
235///
236/// Unlike the index-descriptor annotations set in [`finalize_pack`] — which are
237/// applied AFTER `write_manifest` has already computed the manifest digest and
238/// therefore do NOT feed it — a LAYER descriptor's annotations live inside the
239/// manifest that `canonicalize` then hashes, so these annotations DO feed the
240/// manifest digest. Renaming the config file, or swapping an attestation's
241/// claimed subject, changes the package's identity.
242fn annotate(
243    mut descriptor: Descriptor,
244    annotations: Option<&HashMap<String, String>>,
245) -> Descriptor {
246    if let Some(annotations) = annotations {
247        descriptor.set_annotations(Some(annotations.clone()));
248    }
249    descriptor
250}
251
252/// Write one planned layer's bytes to `layout` and return its descriptor.
253///
254/// The ONE writing path for a server package's layers, called only after every
255/// gate in [`validate_pack_preconditions`] has returned `Ok`.
256fn write_planned_layer(layout: &OciLayout, planned: &PlannedLayer) -> Result<Descriptor> {
257    let descriptor = layout.write_blob(planned.media_type.clone(), &planned.bytes)?;
258    Ok(annotate(descriptor, planned.annotations.as_ref()))
259}
260
261/// Plan a STRUCT layer: the typed value serialized through the crate's one
262/// canonicalizer.
263fn plan_struct_layer<T: Serialize>(media_type: &str, value: &T) -> Result<PlannedLayer> {
264    Ok(PlannedLayer {
265        media_type: vendor_media_type(media_type),
266        bytes: canonicalize(value)?,
267        annotations: None,
268    })
269}
270
271/// Plan a VERBATIM-bytes layer carrying `annotations` on its descriptor.
272///
273/// Raw bytes, never `canonicalize` — the crate rule is to digest what was
274/// stored, never re-derive it from a parsed struct.
275fn plan_annotated_layer(
276    media_type: &str,
277    annotations: HashMap<String, String>,
278    bytes: &[u8],
279) -> PlannedLayer {
280    PlannedLayer {
281        media_type: vendor_media_type(media_type),
282        bytes: bytes.to_vec(),
283        annotations: Some(annotations),
284    }
285}
286
287/// Plan the layer for a named vendor-content file, recording the author's
288/// original file name in the descriptor's standard
289/// `org.opencontainers.image.title` annotation.
290///
291/// One mechanism, not two: a thin caller of [`plan_annotated_layer`] supplying
292/// the single-entry title map, where the attestation supplies a three-entry
293/// map.
294fn plan_named_file_layer(media_type: &str, file_name: &str, bytes: &[u8]) -> PlannedLayer {
295    plan_annotated_layer(
296        media_type,
297        HashMap::from([(ANNOTATION_TITLE.to_string(), file_name.to_string())]),
298        bytes,
299    )
300}
301
302/// Plan the attestation layer: the payload VERBATIM, with the subject, issuer
303/// and payload media type on the LAYER descriptor's annotations (and therefore
304/// inside the manifest digest).
305fn plan_attestation_layer(attestation: AttestationFile<'_>) -> PlannedLayer {
306    plan_annotated_layer(
307        MT_ATTESTATION,
308        HashMap::from([
309            (
310                ANNOTATION_ATTESTATION_SUBJECT.to_string(),
311                attestation.subject.to_string(),
312            ),
313            (
314                ANNOTATION_ATTESTATION_ISSUER.to_string(),
315                attestation.issuer.to_string(),
316            ),
317            (
318                ANNOTATION_ATTESTATION_PAYLOAD_TYPE.to_string(),
319                attestation.payload_type.to_string(),
320            ),
321        ]),
322        attestation.bytes,
323    )
324}
325
326/// Plan the one binary layer this package carries, per [`BinaryMode`] — the
327/// bytes-producing sibling of the writing path.
328///
329/// Embedded bytes travel verbatim. A reference is a STRUCT layer: the existing
330/// [`BinaryRef`] wire type serialized via `canonicalize`, keeping the wire
331/// payload's `Option<ManifestDigest>` tolerance while the API type
332/// [`BinaryMode::Referenced`] stays non-optional.
333fn plan_binary_layer(binary: &BinaryMode<'_>) -> Result<PlannedLayer> {
334    match binary {
335        BinaryMode::Embedded(bootstrap) => Ok(PlannedLayer {
336            media_type: vendor_media_type(MT_SERVER_BOOTSTRAP),
337            bytes: (*bootstrap).to_vec(),
338            annotations: None,
339        }),
340        BinaryMode::Referenced { digest, media_type } => {
341            let binary_ref = BinaryRef {
342                digest: Some(digest.clone()),
343                media_type: media_type.clone(),
344            };
345            plan_struct_layer(MT_SERVER_BINARY_REF, &binary_ref)
346        },
347    }
348}
349
350/// Every layer a `pack_server` call will write, produced as BYTES before
351/// anything reaches the filesystem.
352///
353/// The attestation is held SEPARATELY rather than appended to `unattested`, so
354/// the pack-time subject gate reads the unattested layer vector directly
355/// instead of filtering a mixed one by media type. The two manifests the gate
356/// compares can then differ only in their layer vectors — which is exactly the
357/// difference the subject digest is about.
358struct ServerLayerPlan {
359    /// Every layer EXCEPT the attestation, in deterministic push order.
360    unattested: Vec<PlannedLayer>,
361    /// The attestation layer, when the caller supplied one.
362    attestation: Option<PlannedLayer>,
363}
364
365/// Produce every layer's bytes for a server pack. Pure: no filesystem access,
366/// no `OciLayout` parameter, nothing observable outside the returned plan.
367fn plan_server_layers(
368    package: &ServerPackage,
369    binary: &BinaryMode<'_>,
370    config: Option<ConfigFile<'_>>,
371    spec: Option<OpenApiSpecFile<'_>>,
372    attestation: Option<AttestationFile<'_>>,
373) -> Result<ServerLayerPlan> {
374    let envelope = ServerEnvelope {
375        name: package.name.clone(),
376        version: package.version.clone(),
377        digest: package.digest.clone(),
378    };
379
380    // Push order is deterministic so the manifest bytes (and therefore the
381    // manifest digest) are reproducible. It is NOT a read-order contract:
382    // the optional layers make position meaningless, and `unpack_server`
383    // locates every layer by media type.
384    let mut unattested = vec![
385        plan_binary_layer(binary)?,
386        plan_struct_layer(MT_SERVER_ENVELOPE, &envelope)?,
387        plan_struct_layer(MT_SERVER_DEPLOY_DESCRIPTOR, &package.deploy)?,
388        plan_struct_layer(MT_SERVER_CEDAR_POLICY_SET, &package.policies)?,
389        plan_struct_layer(MT_SERVER_TOOL_METADATA, &package.tools)?,
390        plan_struct_layer(MT_SERVER_CONFIG_SLOTS, &package.config_slots)?,
391    ];
392
393    if let Some(config) = config {
394        unattested.push(plan_named_file_layer(
395            MT_SERVER_CONFIG,
396            config.file_name,
397            config.bytes,
398        ));
399    }
400
401    // The spec is planned after the config so the push order stays
402    // deterministic. Its bytes stay RAW — never through `canonicalize` and
403    // never parsed: one media type carries both JSON and YAML documents, and
404    // the format is evident from the file-name annotation (D-16).
405    if let Some(spec) = spec {
406        unattested.push(plan_named_file_layer(
407            MT_SERVER_OPENAPI_SPEC,
408            spec.file_name,
409            spec.bytes,
410        ));
411    }
412
413    Ok(ServerLayerPlan {
414        unattested,
415        attestation: attestation.map(plan_attestation_layer),
416    })
417}
418
419/// Every gate [`pack_server`] runs BEFORE its first `write_blob`, so a rejected
420/// pack adds neither a blob nor an index entry — which is what makes "a
421/// resolved secret never travels in a layer" a property of the filesystem and
422/// not merely of the return value.
423///
424/// That invariant holds LITERALLY, for every gate including the
425/// attestation-subject one. `pack_server` produces every layer's bytes first
426/// ([`plan_server_layers`], which touches nothing on disk), runs this function
427/// over the resulting plan, and only then walks the plan writing blobs. A
428/// refused pack therefore leaves the destination layout byte-for-byte as it
429/// found it, which
430/// `negative.rs::a_refused_pack_leaves_the_destination_layout_byte_for_byte_unchanged`
431/// asserts over the FULL recursive file list rather than over the attestation
432/// blob alone.
433///
434/// Extracted from `pack_server` rather than inlined so that function stays
435/// under the repo's cognitive-complexity ceiling (CLAUDE.md: "Cognitive
436/// complexity ≤25 per function", enforced in CI by
437/// `pmat quality-gate --checks complexity`); inlined, the arms below push
438/// `pack_server` over it. Each gate is its own named free function for the
439/// same reason — growing THIS function inline is how that PR-blocking gate
440/// fires next.
441///
442/// # Errors
443///
444/// Returns [`PackageError::ConfigSlotViolation`] when the config document's
445/// `[[config_slots]]` block disagrees with `package.config_slots`, when a
446/// slot-declared value key holds a resolved literal rather than an environment
447/// reference, when the config defers a slot-addressable key to the environment
448/// that NO slot declares, or when a package that ships NO config file
449/// nonetheless declares a slot naming a `config_key`. Returns
450/// [`PackageError::Serialize`] when the
451/// config document is not parseable TOML. Returns
452/// [`PackageError::MalformedDigest`] or
453/// [`PackageError::AttestationSubjectMismatch`] per
454/// [`reject_an_attestation_subject_naming_another_package`].
455///
456/// [`PackageError::MalformedDigest`]: crate::error::PackageError::MalformedDigest
457/// [`PackageError::AttestationSubjectMismatch`]: crate::error::PackageError::AttestationSubjectMismatch
458fn validate_pack_preconditions(
459    package: &ServerPackage,
460    config: Option<ConfigFile<'_>>,
461    attestation: Option<AttestationFile<'_>>,
462    unattested_layers: &[PlannedLayer],
463) -> Result<()> {
464    reject_attestation_annotations_that_break_canonical_json(attestation)?;
465    reject_an_attestation_subject_naming_another_package(
466        attestation,
467        unattested_layers,
468        ARTIFACT_TYPE_SERVER,
469    )?;
470    // The document gates run only when a config file is present: an embedded,
471    // pre-built package has no config document to read declarations out of,
472    // and every pre-0.2 server package is exactly that shape.
473    let Some(config) = config else {
474        // No config file: a slot may still be declared (the keyless embedded
475        // shape every pre-0.2 package has), but a slot naming a `config_key`
476        // points into a config document this package does not ship — a claim
477        // nothing could validate at pack time and nothing could fill at
478        // deploy time. Refusing it here is the mirror of the "a value slot
479        // must name the config key it fills" rule on the with-config path.
480        return reject_config_keys_without_a_config(package);
481    };
482    // One parse feeds all three gates — the `_in` variants take the document.
483    let document = parse_document(config.bytes)?;
484    let declared = parse_declared_config_slots_in(&document)?;
485    validate_config_slot_agreement(&declared, &package.config_slots)?;
486    validate_config_slot_placeholders_in(&document, &package.config_slots)?;
487    // The CONFIG -> SLOT direction. The two gates above both start from the
488    // declared slot list, so a config declaring NO slots satisfies both
489    // trivially; this one starts from the document and is what makes the pair
490    // of questions symmetric.
491    validate_no_undeclared_env_refs_in(&document, &package.config_slots)
492}
493
494/// The no-config half of [`validate_pack_preconditions`]: refuse a package that
495/// ships no config document while declaring a slot that names a `config_key`.
496///
497/// # Errors
498///
499/// Returns [`PackageError::ConfigSlotViolation`] naming the offending key.
500fn reject_config_keys_without_a_config(package: &ServerPackage) -> Result<()> {
501    for slot in &package.config_slots {
502        if let Some(config_key) = slot.config_key.as_deref() {
503            return Err(PackageError::ConfigSlotViolation {
504                key: config_key.to_string(),
505                reason: "the package slot names a config key, but the package ships no \
506                         config file for that key to address — pack with the config \
507                         document, or drop the slot's config_key"
508                    .to_string(),
509            });
510        }
511    }
512    Ok(())
513}
514
515/// Gate A: refuse an attestation attached to a team whose references are not
516/// all resolved (D-09).
517///
518/// # Why — "attestation implies resolved", the `cargo build --locked` analogue
519///
520/// An attestation's subject is a DIGEST, and a digest is a claim about exactly
521/// which code was examined. If that digest covers a package holding a
522/// `ComponentRef::Range`, two environments with the same package digest run
523/// DIFFERENT code — dev resolves `london-tube@^1.2` to 1.3.0 while prod
524/// resolves the same range to the 1.2.0 it already has. The attestation would
525/// then attest nothing about what actually runs, while this crate ships a
526/// verification path implying otherwise. A reader meeting this refusal deserves
527/// that reason at the refusal, which is why it is written here.
528///
529/// # Scoped to the CLAIM, not to the format
530///
531/// The gate is VACUOUS when no attestation is supplied, and that is the whole
532/// design: D-09 is *attestation implies resolved*, NOT *teams must always be
533/// pinned*. A team holding ranges is a legal package — it is what capture
534/// produces before resolution — and it must keep packing unattested. Guarding
535/// unconditionally would break every existing unattested team pack.
536///
537/// # The ONE-LEVEL DEPTH LIMIT, restated here and not only on the helper
538///
539/// `TeamMember.agent` pins an agent BY DIGEST. That digest covers the agent
540/// package's own contents, including its `connectors: Vec<ComponentRef>`, which
541/// may themselves be ranges. The team package holds only the digest, and
542/// milestone Decision 2 forbids this crate a registry client, so nothing here
543/// can resolve a referenced package offline to look inside it.
544///
545/// A team that passes this gate is resolved AT ITS OWN LEVEL. It is NOT
546/// transitively resolved and must never be read as such. Closing that
547/// transitively is platform ADMISSION POLICY — requiring every pinned component
548/// to itself be attested — not SDK work. The limit is pinned as visible
549/// behaviour by
550/// `negative.rs::attestation_resolved::an_attested_team_whose_pinned_agent_itself_holds_a_range_still_packs`,
551/// and it is also inside the error text a caller sees, so it cannot be missed
552/// by someone who never opens these docs.
553///
554/// # Why there is no server-path equivalent — a fact about the type
555///
556/// This gate is VACUOUS on the server path, so `pack_server` deliberately does
557/// not call it. `ServerPackage`'s fields are `name`, `version`, `digest`,
558/// `deploy`, `policies`, `tools` and `config_slots` — not one of them is a
559/// `ComponentRef`, so there is no unresolved reference a server package could
560/// hold. Its absence there is a fact about the type rather than an omission;
561/// do NOT "fix" the apparent asymmetry by adding a no-op call on the server
562/// path.
563///
564/// # Errors
565///
566/// Propagates [`TeamPackage::validate_all_pinned`]'s
567/// [`PackageError::InvalidReference`] unchanged, which already names the
568/// offending component, its `component_type` and the depth limit. No new error
569/// variant exists for this case, deliberately: an attestation over an
570/// unresolved package IS an invalid reference.
571///
572/// [`PackageError::InvalidReference`]: crate::error::PackageError::InvalidReference
573fn reject_an_attestation_over_an_unresolved_team(
574    package: &TeamPackage,
575    attestation: Option<AttestationFile<'_>>,
576) -> Result<()> {
577    if attestation.is_none() {
578        return Ok(());
579    }
580    package.validate_all_pinned()
581}
582
583/// The first byte offset at which `value` carries a C0 control character, with
584/// the character itself.
585///
586/// C0 (U+0000–U+001F) is exactly the range RFC 8259 forbids unescaped inside a
587/// JSON string. DEL (U+007F) and every other non-ASCII code point are legal
588/// unescaped and are deliberately NOT rejected — over-refusing an issuer that
589/// happens to be non-ASCII would be a bug of its own.
590fn first_control_character(value: &str) -> Option<(usize, char)> {
591    value
592        .char_indices()
593        .find(|(_, character)| (*character as u32) < 0x20)
594}
595
596/// Refuse an attestation whose issuer or payload-type value cannot survive this
597/// crate's canonical JSON form.
598///
599/// # Why this gate exists
600///
601/// `canonicalize` is OLPC/TUF Canonical JSON, which escapes ONLY `"` and `\`
602/// and writes every other character — including C0 control characters —
603/// LITERALLY. That is correct for its own spec and wrong for RFC 8259, so a
604/// control character in ANY string reaching the manifest produces manifest bytes
605/// that no JSON parser will read back. The package packs cleanly, its digest
606/// verifies (the digest is over the bytes as stored), and then `unpack_server`
607/// — and every other OCI tool — fails on the manifest.
608///
609/// Found by `tests/attestation_opacity.rs`'s adversarial-annotation property,
610/// which generated `issuer = "\0"` and observed a package that packed and could
611/// not be unpacked. Refusing at pack time is the fix that keeps an unreadable
612/// artifact from being produced at all.
613///
614/// # Why only issuer and payload-type
615///
616/// `subject` is validated more strictly one gate later:
617/// [`reject_an_attestation_subject_naming_another_package`] parses it as
618/// `sha256:<64 hex>`, a form that admits no control character. Duplicating the
619/// weaker check here would only change which of two refusals a caller sees.
620///
621/// # Known wider blind spot, stated rather than left to be found
622///
623/// The same canonical-JSON hazard applies to every OTHER string this crate
624/// canonicalizes: a `ConfigFile`/`OpenApiSpecFile` `file_name` (which becomes
625/// the standard `org.opencontainers.image.title` annotation) and every `String`
626/// inside `ServerPackage` itself. Those values come from the packaging author's
627/// own filesystem and source, not from an untrusted platform-issued
628/// attestation, so they are a different trust class and are deliberately out of
629/// this gate's scope rather than silently assumed safe.
630///
631/// # Errors
632///
633/// Returns [`PackageError::AttestationAnnotationInvalid`] naming the annotation
634/// key and the offending code point. It never reproduces the value.
635///
636/// [`PackageError::AttestationAnnotationInvalid`]: crate::error::PackageError::AttestationAnnotationInvalid
637fn reject_attestation_annotations_that_break_canonical_json(
638    attestation: Option<AttestationFile<'_>>,
639) -> Result<()> {
640    let Some(attestation) = attestation else {
641        return Ok(());
642    };
643    for (key, value) in [
644        (ANNOTATION_ATTESTATION_ISSUER, attestation.issuer),
645        (
646            ANNOTATION_ATTESTATION_PAYLOAD_TYPE,
647            attestation.payload_type,
648        ),
649    ] {
650        if let Some((offset, character)) = first_control_character(value) {
651            return Err(PackageError::AttestationAnnotationInvalid {
652                annotation: key.to_string(),
653                reason: format!(
654                    "the value carries the control character U+{:04X} at byte offset {offset}; \
655                     canonical JSON writes control characters literally, so the manifest would \
656                     not be parseable JSON",
657                    character as u32
658                ),
659            });
660        }
661    }
662    Ok(())
663}
664
665/// The pack-time half of D-02's two-ended subject check: refuse an attestation
666/// whose `subject` does not name the package it is being packed into.
667///
668/// The comparison is against the would-be UNATTESTED manifest digest — the
669/// digest this same package would have had if packed with no attestation at
670/// all — because that is what an attestation's subject means (D-01's two-digest
671/// consequence). Comparing against the ATTESTED digest instead could never
672/// match, and "fixing" it that way is one of the two regressions
673/// `roundtrip.rs`'s two-digest test exists to block.
674///
675/// Runs BEFORE the first `write_blob`, so an attestation attached to the wrong
676/// package is unrepresentable in a produced layout rather than merely reported
677/// after one is on disk.
678///
679/// # The accepted cost, stated rather than discovered
680///
681/// On an ATTESTED pack the manifest is canonicalized TWICE: once dry here, and
682/// once for real in [`finalize_pack`]. D-02 accepts that. An unattested pack is
683/// unaffected — the `else` below returns immediately and the manifest is
684/// canonicalized exactly once, as it always was.
685///
686/// # Errors
687///
688/// Returns [`PackageError::MalformedDigest`] when `subject` is not a
689/// well-formed `sha256:<64 hex>` string, and
690/// [`PackageError::AttestationSubjectMismatch`] when it is well-formed but
691/// names a different package. Neither error carries any attestation payload
692/// material — see that variant's rustdoc for the rule.
693///
694/// [`PackageError::MalformedDigest`]: crate::error::PackageError::MalformedDigest
695/// [`PackageError::AttestationSubjectMismatch`]: crate::error::PackageError::AttestationSubjectMismatch
696fn reject_an_attestation_subject_naming_another_package(
697    attestation: Option<AttestationFile<'_>>,
698    unattested_layers: &[PlannedLayer],
699    artifact_type: &str,
700) -> Result<()> {
701    let Some(attestation) = attestation else {
702        return Ok(());
703    };
704    // Parsed, not string-compared: a subject that is not a well-formed digest
705    // is a malformed claim, and reporting it as a MISMATCH would tell an
706    // operator to go looking for the wrong package.
707    let supplied = ManifestDigest::parse(attestation.subject)?;
708    let computed = would_be_unattested_manifest_digest(unattested_layers, artifact_type)?;
709    if supplied == computed {
710        return Ok(());
711    }
712    Err(PackageError::AttestationSubjectMismatch {
713        supplied: supplied.as_str().to_string(),
714        computed: computed.as_str().to_string(),
715    })
716}
717
718/// The manifest digest this package WOULD have if packed with no attestation:
719/// describe every non-attestation layer, assemble the manifest through the
720/// SAME helper [`finalize_pack`] uses, canonicalize with the crate's ONE
721/// canonicalizer, and hash.
722///
723/// Every step is the dry twin of a step `pack_server` performs for real, which
724/// is why the result is comparable at all:
725/// [`OciLayout::describe_blob`] mirrors `write_blob`,
726/// [`assemble_manifest`] IS the builder chain `finalize_pack` runs, and
727/// [`crate::oci::media_types::empty_config_descriptor`] returns exactly the
728/// descriptor `finalize_pack`'s empty-config `write_blob` produces (both hash
729/// the same two fixed bytes). A bespoke hash or a hand-rolled serialization
730/// here would not equal the digest `finalize_pack` later stores.
731///
732/// `artifact_type` is a PARAMETER rather than a constant because two package
733/// kinds now carry attestations (D-08): a server pack passes
734/// [`ARTIFACT_TYPE_SERVER`] and a team pack passes `P::ARTIFACT_TYPE`
735/// (`ARTIFACT_TYPE_TEAM`). It must be the SAME value the matching
736/// [`finalize_pack`] call will use, or the dry manifest differs from the real
737/// one in a field that is inside the hash and the comparison silently stops
738/// meaning anything.
739fn would_be_unattested_manifest_digest(
740    unattested_layers: &[PlannedLayer],
741    artifact_type: &str,
742) -> Result<ManifestDigest> {
743    let layers: Vec<Descriptor> = unattested_layers
744        .iter()
745        .map(PlannedLayer::describe)
746        .collect();
747    let manifest = assemble_manifest(empty_config_descriptor(), layers, artifact_type)?;
748    Ok(ManifestDigest::from_bytes(&canonicalize(&manifest)?))
749}
750
751/// Pack `package` plus its binary (embedded or referenced) and its optional
752/// verbatim config/spec files into `layout` as a local OCI artifact. Returns
753/// the canonical manifest digest.
754///
755/// `config` and `spec` are both optional because an embedded, pre-built server
756/// package has neither: they exist for the Shape A pure-config servers, whose
757/// entire identity is their config (plus, for OpenAPI, their spec).
758///
759/// # The spec layer is OPTIONAL, and its absence is a declaration
760///
761/// Passing `spec: None` is the CALLER'S declaration that this server is
762/// curated-only — it mirrors `pmcp-openapi-server`'s `--spec: Option<PathBuf>`,
763/// where a server boots and serves its curated tools with no OpenAPI document
764/// at all. It is never a default that quietly drops an author's spec: when
765/// `spec` is `Some`, the bytes are always written to their own
766/// [`MT_SERVER_OPENAPI_SPEC`] layer, VERBATIM and unparsed, under the author's
767/// original file name. There is no absence marker (D-14) — an absent spec is
768/// simply an absent layer.
769///
770/// [`MT_SERVER_OPENAPI_SPEC`]: crate::oci::media_types::MT_SERVER_OPENAPI_SPEC
771///
772/// # The attestation layer is OPTIONAL, and it carries TWO digests
773///
774/// Passing `attestation: Some(..)` writes the payload bytes VERBATIM to their
775/// own [`MT_ATTESTATION`] layer — never canonicalized, never parsed — with the
776/// subject, issuer and payload media type recorded as annotations on that
777/// LAYER's descriptor. `None` writes no layer at all; absence is exactly the
778/// layer's absence, with no marker (D-14).
779///
780/// The accepted consequence, stated here rather than discovered later: an
781/// attested package's own manifest digest NECESSARILY DIFFERS from the
782/// unattested digest the attestation names as its subject. The attestation
783/// layer (and its annotations) sit inside the manifest whose canonical bytes
784/// are hashed, so adding the attestation changes the hash. Two digests exist,
785/// and that is deliberate.
786///
787/// The rejected alternative was to exclude the attestation layer from the
788/// canonical digest. That would make the two digests equal, at the cost of
789/// weakening [`crate::digest::verify()`] into verifying everything EXCEPT the
790/// one layer an attacker would most want to swap.
791///
792/// [`MT_ATTESTATION`]: crate::oci::media_types::MT_ATTESTATION
793///
794/// # The subject is CHECKED, not trusted
795///
796/// The subject arrives from the issuing platform, not from this repo, so it is
797/// verified rather than recorded: this function computes the would-be
798/// unattested manifest digest and REFUSES to pack when the supplied subject
799/// names anything else — before writing a single blob. See
800/// `reject_an_attestation_subject_naming_another_package`, which also states
801/// the accepted cost (an attested pack canonicalizes the manifest twice).
802///
803/// `unpack_server` re-derives the same digest INDEPENDENTLY rather than
804/// trusting that this gate ran, because a layout can arrive from anywhere.
805///
806/// # Errors
807///
808/// Returns [`PackageError::Layout`] if the `ImageManifest` fails to build or
809/// if any blob/index write fails. Returns [`PackageError::Serialize`] if a
810/// layer fails to canonicalize.
811///
812/// When `config` is `Some`, returns [`PackageError::ConfigSlotViolation`]
813/// BEFORE writing anything if the config's `[[config_slots]]` declaration block
814/// disagrees with `package.config_slots` in either direction (D-01: the shipped
815/// config is the source of truth), if a slot-declared value key holds a
816/// resolved literal rather than a `${VAR}` / `env:VAR` reference (D-04), or if
817/// the config holds a `${VAR}` / `env:VAR` reference at a slot-addressable key
818/// that no slot declares — the CONFIG -> SLOT direction, without which a
819/// package under-reports what a target environment must supply. See
820/// [`crate::oci::config_validation`].
821///
822/// When `config` is `None`, returns [`PackageError::ConfigSlotViolation`] if
823/// any package slot carries a `config_key`: the key names a path inside a
824/// config document this package does not ship, a claim nothing can validate or
825/// fill. Keyless slots (the pre-0.2 embedded shape) remain legal without a
826/// config.
827///
828/// When `attestation` is `Some`, returns [`PackageError::MalformedDigest`]
829/// BEFORE writing anything if its `subject` is not a well-formed
830/// `sha256:<64 hex>` string, or
831/// [`PackageError::AttestationSubjectMismatch`] if the subject is well-formed
832/// but does not equal this package's would-be unattested manifest digest. Both
833/// carry digest strings only, never attestation payload material.
834///
835/// When `attestation` is `Some`, also returns
836/// [`PackageError::AttestationAnnotationInvalid`] BEFORE writing anything if
837/// its `issuer` or `payload_type` carries a C0 control character. Canonical
838/// JSON writes control characters literally, so packing one would produce a
839/// manifest that is not parseable JSON — a package that packs and can never be
840/// unpacked. See `reject_attestation_annotations_that_break_canonical_json`.
841///
842/// [`PackageError::Serialize`]: crate::error::PackageError::Serialize
843/// [`PackageError::ConfigSlotViolation`]: crate::error::PackageError::ConfigSlotViolation
844/// [`PackageError::MalformedDigest`]: crate::error::PackageError::MalformedDigest
845/// [`PackageError::AttestationSubjectMismatch`]: crate::error::PackageError::AttestationSubjectMismatch
846/// [`PackageError::AttestationAnnotationInvalid`]: crate::error::PackageError::AttestationAnnotationInvalid
847///
848/// # Examples
849///
850/// Pack a Shape A pure-config server — a referenced binary plus the author's
851/// verbatim `config.toml` — and read the config back byte-for-byte:
852///
853/// ```
854/// use pmcp_package::digest::ManifestDigest;
855/// use pmcp_package::oci::{pack_server, unpack_server, BinaryMode, ConfigFile, OciLayout};
856/// # use pmcp_package::package::*;
857/// # use std::collections::BTreeMap;
858/// # fn deploy() -> DeployDescriptor {
859/// #     DeployDescriptor {
860/// #         target: TargetSection { target_type: "pmcp-run".into(), version: "1.0.0".into() },
861/// #         metadata: None,
862/// #         aws: AwsSection { region: "us-east-1".into() },
863/// #         server: ServerSection {
864/// #             name: "london-tube".into(), memory_mb: Some(1024), timeout_seconds: 30,
865/// #             memory: None, cpu: None, ingress: None, allow_unauthenticated: None, binary: None,
866/// #         },
867/// #         environment: BTreeMap::new(),
868/// #         secrets: BTreeMap::new(),
869/// #         auth: AuthSection {
870/// #             enabled: false, provider: "none".into(), callback_urls: vec![],
871/// #             cognito: None, dcr: None, groups: None, scopes: None,
872/// #         },
873/// #         observability: ObservabilitySection {
874/// #             log_retention_days: 30, enable_xray: true, create_dashboard: true, alarms: None,
875/// #         },
876/// #         composition: None, assets: None, iam: None, gcp: None, layout: None,
877/// #     }
878/// # }
879/// let package = ServerPackage {
880///     name: "london-tube".to_string(),
881///     version: semver::Version::parse("1.0.0").unwrap(),
882///     digest: None,
883///     deploy: deploy(),
884///     policies: CedarPolicySet(vec![]),
885///     tools: vec![],
886///     config_slots: vec![],
887/// };
888///
889/// let dir = tempfile::tempdir().unwrap();
890/// let layout = OciLayout::create(dir.path()).unwrap();
891///
892/// let config_toml = b"name = \"london-tube\"\n";
893/// pack_server(
894///     &package,
895///     BinaryMode::Referenced {
896///         digest: ManifestDigest::from_bytes(b"pmcp-openapi-server-v1.0.0"),
897///         media_type: "application/x-lambda-bootstrap; arch=arm64".to_string(),
898///     },
899///     Some(ConfigFile { file_name: "london-tube.toml", bytes: config_toml }),
900///     // Curated-only: this server carries no OpenAPI spec.
901///     None,
902///     // Unattested: this server carries no attestation.
903///     None,
904///     &layout,
905/// )
906/// .unwrap();
907///
908/// let unpacked = unpack_server(&layout).unwrap();
909/// let config = unpacked.config.unwrap();
910/// assert_eq!(config.file_name, "london-tube.toml");
911/// assert_eq!(config.bytes, config_toml);
912/// assert_eq!(unpacked.spec, None);
913/// assert_eq!(unpacked.attestation, None);
914/// ```
915pub fn pack_server(
916    package: &ServerPackage,
917    binary: BinaryMode<'_>,
918    config: Option<ConfigFile<'_>>,
919    spec: Option<OpenApiSpecFile<'_>>,
920    attestation: Option<AttestationFile<'_>>,
921    layout: &OciLayout,
922) -> Result<ManifestDigest> {
923    // 1. BYTES. Nothing here touches the filesystem, which is what lets every
924    //    gate below — including the attestation-subject gate, which needs the
925    //    would-be unattested manifest digest — run before the first write.
926    let plan = plan_server_layers(package, &binary, config, spec, attestation)?;
927
928    // 2. GATES. Any refusal returns here, with the destination layout still
929    //    byte-for-byte as it was found.
930    validate_pack_preconditions(package, config, attestation, &plan.unattested)?;
931
932    // 3. WRITES. The attestation goes LAST so the push order stays
933    //    deterministic. As with every other layer, that order is explicitly
934    //    NOT a read-order contract — `unpack_server` locates every layer by
935    //    media type, so a re-ordered manifest reads identically.
936    let mut layers = Vec::with_capacity(plan.unattested.len() + 1);
937    for planned in plan.unattested.iter().chain(plan.attestation.iter()) {
938        layers.push(write_planned_layer(layout, planned)?);
939    }
940
941    finalize_pack(
942        layout,
943        layers,
944        ARTIFACT_TYPE_SERVER,
945        &package.name,
946        &package.version,
947    )
948}
949
950/// Every gate a [`pack_single_layer`] call runs BEFORE its first `write_blob`
951/// — the single-layer sibling of [`validate_pack_preconditions`], carrying the
952/// same "a rejected pack adds neither a blob nor an index entry" invariant.
953///
954/// It holds the two KIND-NEUTRAL attestation gates, called in the same order
955/// and through the SAME two functions the server path uses: no second copy of
956/// either check exists, and a fix applied to one is a fix applied to both.
957///
958/// # Errors
959///
960/// Returns [`PackageError::AttestationAnnotationInvalid`],
961/// [`PackageError::MalformedDigest`] or
962/// [`PackageError::AttestationSubjectMismatch`] per the two gates it calls.
963///
964/// [`PackageError::AttestationAnnotationInvalid`]: crate::error::PackageError::AttestationAnnotationInvalid
965/// [`PackageError::MalformedDigest`]: crate::error::PackageError::MalformedDigest
966/// [`PackageError::AttestationSubjectMismatch`]: crate::error::PackageError::AttestationSubjectMismatch
967fn validate_single_layer_pack_preconditions(
968    attestation: Option<AttestationFile<'_>>,
969    unattested_layers: &[PlannedLayer],
970    artifact_type: &str,
971) -> Result<()> {
972    reject_attestation_annotations_that_break_canonical_json(attestation)?;
973    reject_an_attestation_subject_naming_another_package(
974        attestation,
975        unattested_layers,
976        artifact_type,
977    )
978}
979
980/// Pack any single-layer package (agent/team/workflow) into `layout`:
981/// serialize it to one canonical-JSON config layer under its vendor media
982/// type, optionally append a verbatim attestation layer, then wrap the result
983/// in a manifest with the kind's `artifactType`. The per-kind constants come
984/// from the [`SingleLayerPackage`] impl — one path, no per-kind copy-paste.
985/// Returns the canonical manifest digest.
986///
987/// # Attestation carriage covers SERVER and TEAM packages only (D-08)
988///
989/// This helper takes `attestation` because all three single-layer kinds route
990/// through it, but only [`pack_team`] EXPOSES the parameter. [`pack_agent`] and
991/// [`pack_workflow`] pass `None` and their public signatures are unchanged.
992///
993/// The reason is stated here, at the shared helper, because this is exactly
994/// where a later reader is tempted to "finish the job" by exposing it on all
995/// three: **the unit that ships to production is a team, and an agent is a
996/// team of one in its essence.** An agent that needs an attestation is wrapped
997/// as a team of one and attested there; it does not get its own carriage path.
998/// `pack_workflow` is out for the same reason — a workflow is a captured
999/// resolution of a team, not an independently shipped unit.
1000///
1001/// The consequence to preserve: ONE mechanism, not two. The team path reuses
1002/// the server path's [`plan_attestation_layer`], [`write_planned_layer`],
1003/// [`reject_attestation_annotations_that_break_canonical_json`] and
1004/// [`reject_an_attestation_subject_naming_another_package`] verbatim, with no
1005/// kind dispatch anywhere and no team-specific attestation media type.
1006///
1007/// # Errors
1008///
1009/// Returns [`PackageError::Layout`] if the `ImageManifest` fails to build or if
1010/// any blob/index write fails, [`PackageError::Serialize`] if the package fails
1011/// to canonicalize, and any gate error from
1012/// [`validate_single_layer_pack_preconditions`].
1013///
1014/// [`PackageError::Serialize`]: crate::error::PackageError::Serialize
1015fn pack_single_layer<P: SingleLayerPackage>(
1016    package: &P,
1017    attestation: Option<AttestationFile<'_>>,
1018    layout: &OciLayout,
1019) -> Result<ManifestDigest> {
1020    // 1. BYTES. Nothing here touches the filesystem — the same ordering
1021    //    `pack_server` uses, and what lets the subject gate below compute the
1022    //    would-be unattested manifest digest before the first write.
1023    let unattested = [plan_struct_layer(P::LAYER_MEDIA_TYPE, package)?];
1024    let attestation_layer = attestation.map(plan_attestation_layer);
1025
1026    // 2. GATES. Any refusal returns here, with the destination layout still
1027    //    byte-for-byte as it was found.
1028    validate_single_layer_pack_preconditions(attestation, &unattested, P::ARTIFACT_TYPE)?;
1029
1030    // 3. WRITES. The attestation goes LAST so the push order stays
1031    //    deterministic. As on the server path that order is explicitly NOT a
1032    //    read-order contract — every layer is located by media type.
1033    let mut layers = Vec::with_capacity(unattested.len() + 1);
1034    for planned in unattested.iter().chain(attestation_layer.iter()) {
1035        layers.push(write_planned_layer(layout, planned)?);
1036    }
1037
1038    finalize_pack(
1039        layout,
1040        layers,
1041        P::ARTIFACT_TYPE,
1042        package.name(),
1043        package.version(),
1044    )
1045}
1046
1047/// Pack an `AgentPackage` into `layout` as a single-layer local OCI artifact.
1048/// Returns the canonical manifest digest.
1049///
1050/// An agent package carries NO attestation, by decision rather than by
1051/// omission: see `pack_single_layer`'s "attestation carriage covers server
1052/// and team packages only" section for why, and what to do instead (wrap the
1053/// agent as a team of one).
1054pub fn pack_agent(package: &AgentPackage, layout: &OciLayout) -> Result<ManifestDigest> {
1055    pack_single_layer(package, None, layout)
1056}
1057
1058/// Pack a `TeamPackage` into `layout` as a local OCI artifact — one config
1059/// layer, plus an OPTIONAL attestation layer. Returns the canonical manifest
1060/// digest.
1061///
1062/// # The attestation layer is OPTIONAL, and it carries TWO digests
1063///
1064/// Exactly as on [`pack_server`], and through the same code: `Some` writes the
1065/// payload bytes VERBATIM to their own [`MT_ATTESTATION`] layer — never
1066/// canonicalized, never parsed — with subject, issuer and payload media type as
1067/// annotations on that LAYER's descriptor. `None` writes no layer at all, and
1068/// absence is exactly the layer's absence with no marker (D-14).
1069///
1070/// An attested team's own manifest digest therefore NECESSARILY DIFFERS from
1071/// the unattested digest its attestation names as a subject (D-01). See
1072/// [`pack_server`]'s "two digests" section for the full reasoning and the
1073/// rejected alternative.
1074///
1075/// [`MT_ATTESTATION`]: crate::oci::media_types::MT_ATTESTATION
1076///
1077/// # An attestation implies a RESOLVED team (D-09)
1078///
1079/// Attaching an attestation to a team holding any `ComponentRef::Range` is
1080/// refused BEFORE the first write, naming the offending component and its
1081/// component type. Packing that same team WITHOUT an attestation still
1082/// succeeds — the guard is scoped to the CLAIM, not to the format.
1083///
1084/// The guard is ONE LEVEL DEEP: it covers this team's own four reference
1085/// surfaces and cannot see inside a pinned component's own references. See
1086/// `reject_an_attestation_over_an_unresolved_team` for why, and for what a
1087/// passing pack does and does not prove.
1088///
1089/// # Errors
1090///
1091/// Returns [`PackageError::InvalidReference`] when an attestation is supplied
1092/// over a team whose references are not all pinned,
1093/// [`PackageError::AttestationAnnotationInvalid`] when its `issuer` or
1094/// `payload_type` carries a C0 control character,
1095/// [`PackageError::MalformedDigest`] when its `subject` is not a well-formed
1096/// `sha256:<64 hex>` string, and [`PackageError::AttestationSubjectMismatch`]
1097/// when the subject is well-formed but names another package — all BEFORE
1098/// anything is written. Also returns [`PackageError::Layout`] or
1099/// [`PackageError::Serialize`] on a write or canonicalization failure.
1100///
1101/// [`PackageError::InvalidReference`]: crate::error::PackageError::InvalidReference
1102/// [`PackageError::AttestationAnnotationInvalid`]: crate::error::PackageError::AttestationAnnotationInvalid
1103/// [`PackageError::MalformedDigest`]: crate::error::PackageError::MalformedDigest
1104/// [`PackageError::AttestationSubjectMismatch`]: crate::error::PackageError::AttestationSubjectMismatch
1105/// [`PackageError::Serialize`]: crate::error::PackageError::Serialize
1106pub fn pack_team(
1107    package: &TeamPackage,
1108    attestation: Option<AttestationFile<'_>>,
1109    layout: &OciLayout,
1110) -> Result<ManifestDigest> {
1111    // Gate A runs here rather than inside `validate_single_layer_pack_preconditions`
1112    // because it needs a `&TeamPackage` to inspect four `ComponentRef` surfaces,
1113    // and that helper is generic over every single-layer kind — hosting it there
1114    // would mean a kind-dispatch hook on `SingleLayerPackage` whose agent and
1115    // workflow impls could never run. The pre-write invariant is unaffected:
1116    // this function writes nothing of its own before delegating, so a Gate-A
1117    // refusal still leaves the destination layout byte-for-byte as it was found.
1118    //
1119    // It also runs FIRST because it is the cheapest of the three gates: it reads
1120    // the typed team's own reference surfaces and needs no dry manifest digest
1121    // at all, unlike the subject gate that follows.
1122    reject_an_attestation_over_an_unresolved_team(package, attestation)?;
1123    pack_single_layer(package, attestation, layout)
1124}
1125
1126/// Pack a `WorkflowManifest` into `layout` as a single-layer local OCI
1127/// artifact. Returns the canonical manifest digest.
1128///
1129/// A workflow manifest carries NO attestation, by decision rather than by
1130/// omission: see `pack_single_layer`'s "attestation carriage covers server
1131/// and team packages only" section.
1132pub fn pack_workflow(package: &WorkflowManifest, layout: &OciLayout) -> Result<ManifestDigest> {
1133    pack_single_layer(package, None, layout)
1134}
1135
1136/// Build the `ImageManifest` for a package: OCI schema version, the standard
1137/// `ImageManifest` media type, the kind's `artifactType`, the (non-null)
1138/// empty-config descriptor and the layer descriptors.
1139///
1140/// Pure — it writes nothing — and deliberately the ONE place the builder chain
1141/// lives. [`finalize_pack`] calls it with the descriptors it just WROTE, and
1142/// [`would_be_unattested_manifest_digest`] calls it with descriptors it merely
1143/// DESCRIBED. Sharing the helper is what guarantees the two manifests can
1144/// differ only in their layer vectors; a second copy of the chain would let
1145/// them drift in `artifactType`, media type or config and silently invalidate
1146/// the pack-time subject comparison.
1147///
1148/// # Errors
1149///
1150/// Returns [`PackageError::Layout`] if the builder rejects the combination.
1151fn assemble_manifest(
1152    config: Descriptor,
1153    layers: Vec<Descriptor>,
1154    artifact_type: &str,
1155) -> Result<ImageManifest> {
1156    ImageManifestBuilder::default()
1157        .schema_version(SCHEMA_VERSION)
1158        .media_type(MediaType::ImageManifest)
1159        .artifact_type(MediaType::Other(artifact_type.to_string()))
1160        .config(config)
1161        .layers(layers)
1162        .build()
1163        .map_err(|e| PackageError::Layout {
1164            reason: format!("failed to build ImageManifest: {e}"),
1165        })
1166}
1167
1168/// Shared steps 3-6: write the standard empty-config blob, build the
1169/// `ImageManifest` (config + `layers` + `artifact_type`), store it under its
1170/// OWN canonical-bytes digest (step 4-5 — this IS the returned
1171/// [`ManifestDigest`], not a separate re-derivation), record it in
1172/// `index.json` with `name`/`version` annotations, and return that digest.
1173fn finalize_pack(
1174    layout: &OciLayout,
1175    layers: Vec<Descriptor>,
1176    artifact_type: &str,
1177    name: &str,
1178    version: &semver::Version,
1179) -> Result<ManifestDigest> {
1180    let config_descriptor =
1181        layout.write_blob(MediaType::from(MT_EMPTY_CONFIG), EMPTY_CONFIG_BLOB)?;
1182
1183    let manifest = assemble_manifest(config_descriptor, layers, artifact_type)?;
1184
1185    // Canonicalize (not plain serde_json) so the stored blob's own
1186    // content-addressed digest doubles as the identity digest —
1187    // one hash, one source of truth (RESEARCH steps 4-5).
1188    let manifest_bytes = canonicalize(&manifest)?;
1189    let mut manifest_descriptor = layout.write_manifest(&manifest_bytes)?;
1190
1191    let annotations = HashMap::from([
1192        ("name".to_string(), name.to_string()),
1193        ("version".to_string(), version.to_string()),
1194    ]);
1195    manifest_descriptor.set_annotations(Some(annotations));
1196
1197    let manifest_digest = ManifestDigest::try_from(manifest_descriptor.digest())?;
1198
1199    let mut index = layout.read_index()?;
1200    let mut manifests = index.manifests().clone();
1201    manifests.push(manifest_descriptor);
1202    index.set_manifests(manifests);
1203    layout.write_index(&index)?;
1204
1205    Ok(manifest_digest)
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use super::*;
1211    use crate::oci::media_types::{
1212        MT_EMPTY_CONFIG, MT_SERVER_BINARY_REF, MT_SERVER_BOOTSTRAP, MT_SERVER_OPENAPI_SPEC,
1213    };
1214    use crate::oci::unpack::tests_support::sample_server_package;
1215
1216    #[test]
1217    fn pack_server_writes_bootstrap_layer_with_vendor_media_type() {
1218        let dir = tempfile::tempdir().unwrap();
1219        let layout = OciLayout::create(dir.path()).unwrap();
1220        let (package, bootstrap) = sample_server_package();
1221
1222        pack_server(
1223            &package,
1224            BinaryMode::Embedded(&bootstrap),
1225            None,
1226            None,
1227            None,
1228            &layout,
1229        )
1230        .unwrap();
1231
1232        let index = layout.read_index().unwrap();
1233        let manifest_descriptor = &index.manifests()[0];
1234        let manifest = layout.read_manifest(manifest_descriptor).unwrap();
1235        assert_eq!(
1236            manifest.layers()[0].media_type().to_string(),
1237            MT_SERVER_BOOTSTRAP
1238        );
1239        assert_eq!(manifest.layers()[0].size(), bootstrap.len() as u64);
1240    }
1241
1242    #[test]
1243    fn pack_server_referenced_writes_binary_ref_layer_and_no_bootstrap_layer() {
1244        let dir = tempfile::tempdir().unwrap();
1245        let layout = OciLayout::create(dir.path()).unwrap();
1246        let (package, _bootstrap) = sample_server_package();
1247
1248        pack_server(
1249            &package,
1250            BinaryMode::Referenced {
1251                digest: ManifestDigest::from_bytes(b"referenced-binary"),
1252                media_type: "application/x-lambda-bootstrap; arch=arm64".to_string(),
1253            },
1254            None,
1255            None,
1256            None,
1257            &layout,
1258        )
1259        .unwrap();
1260
1261        let index = layout.read_index().unwrap();
1262        let manifest = layout.read_manifest(&index.manifests()[0]).unwrap();
1263        let media_types: Vec<String> = manifest
1264            .layers()
1265            .iter()
1266            .map(|l| l.media_type().to_string())
1267            .collect();
1268        assert!(media_types.iter().any(|m| m == MT_SERVER_BINARY_REF));
1269        assert!(!media_types.iter().any(|m| m == MT_SERVER_BOOTSTRAP));
1270    }
1271
1272    #[test]
1273    fn pack_server_writes_the_supplied_spec_as_its_own_annotated_layer() {
1274        let dir = tempfile::tempdir().unwrap();
1275        let layout = OciLayout::create(dir.path()).unwrap();
1276        let (package, bootstrap) = sample_server_package();
1277
1278        pack_server(
1279            &package,
1280            BinaryMode::Embedded(&bootstrap),
1281            None,
1282            Some(OpenApiSpecFile {
1283                file_name: "openapi.yaml",
1284                bytes: b"openapi: 3.1.0",
1285            }),
1286            None,
1287            &layout,
1288        )
1289        .unwrap();
1290
1291        let index = layout.read_index().unwrap();
1292        let manifest = layout.read_manifest(&index.manifests()[0]).unwrap();
1293        let spec_layer = manifest
1294            .layers()
1295            .iter()
1296            .find(|l| l.media_type().to_string() == MT_SERVER_OPENAPI_SPEC)
1297            .expect("a supplied spec must become its own layer");
1298        assert_eq!(spec_layer.size(), b"openapi: 3.1.0".len() as u64);
1299        assert_eq!(
1300            spec_layer
1301                .annotations()
1302                .as_ref()
1303                .and_then(|a| a.get(ANNOTATION_TITLE))
1304                .map(String::as_str),
1305            Some("openapi.yaml"),
1306            "the author's file name must ride in the descriptor's title annotation"
1307        );
1308    }
1309
1310    #[test]
1311    fn pack_server_writes_no_spec_layer_when_the_caller_supplies_none() {
1312        let dir = tempfile::tempdir().unwrap();
1313        let layout = OciLayout::create(dir.path()).unwrap();
1314        let (package, bootstrap) = sample_server_package();
1315
1316        pack_server(
1317            &package,
1318            BinaryMode::Embedded(&bootstrap),
1319            None,
1320            None,
1321            None,
1322            &layout,
1323        )
1324        .unwrap();
1325
1326        let index = layout.read_index().unwrap();
1327        let manifest = layout.read_manifest(&index.manifests()[0]).unwrap();
1328        assert!(
1329            !manifest
1330                .layers()
1331                .iter()
1332                .any(|l| l.media_type().to_string() == MT_SERVER_OPENAPI_SPEC),
1333            "absence of a spec is the absence of the layer — never an absence marker (D-14)"
1334        );
1335    }
1336
1337    #[test]
1338    fn pack_uses_standard_non_null_empty_config_descriptor() {
1339        let dir = tempfile::tempdir().unwrap();
1340        let layout = OciLayout::create(dir.path()).unwrap();
1341        let (package, bootstrap) = sample_server_package();
1342
1343        pack_server(
1344            &package,
1345            BinaryMode::Embedded(&bootstrap),
1346            None,
1347            None,
1348            None,
1349            &layout,
1350        )
1351        .unwrap();
1352
1353        let index = layout.read_index().unwrap();
1354        let manifest = layout.read_manifest(&index.manifests()[0]).unwrap();
1355        assert_eq!(manifest.config().media_type().to_string(), MT_EMPTY_CONFIG);
1356        assert_eq!(manifest.config().size(), 2);
1357    }
1358
1359    #[test]
1360    fn packing_the_same_package_twice_yields_an_identical_manifest_digest() {
1361        let (package, bootstrap) = sample_server_package();
1362
1363        let dir_a = tempfile::tempdir().unwrap();
1364        let layout_a = OciLayout::create(dir_a.path()).unwrap();
1365        let digest_a = pack_server(
1366            &package,
1367            BinaryMode::Embedded(&bootstrap),
1368            None,
1369            None,
1370            None,
1371            &layout_a,
1372        )
1373        .unwrap();
1374
1375        let dir_b = tempfile::tempdir().unwrap();
1376        let layout_b = OciLayout::create(dir_b.path()).unwrap();
1377        let digest_b = pack_server(
1378            &package,
1379            BinaryMode::Embedded(&bootstrap),
1380            None,
1381            None,
1382            None,
1383            &layout_b,
1384        )
1385        .unwrap();
1386
1387        assert_eq!(
1388            digest_a, digest_b,
1389            ": packing identical input must yield an identical digest"
1390        );
1391    }
1392
1393    #[test]
1394    fn index_json_records_manifest_with_name_and_version_annotations() {
1395        let dir = tempfile::tempdir().unwrap();
1396        let layout = OciLayout::create(dir.path()).unwrap();
1397        let (package, bootstrap) = sample_server_package();
1398
1399        pack_server(
1400            &package,
1401            BinaryMode::Embedded(&bootstrap),
1402            None,
1403            None,
1404            None,
1405            &layout,
1406        )
1407        .unwrap();
1408
1409        let index = layout.read_index().unwrap();
1410        let annotations = index.manifests()[0].annotations().as_ref().unwrap();
1411        assert_eq!(annotations.get("name"), Some(&package.name));
1412        assert_eq!(
1413            annotations.get("version"),
1414            Some(&package.version.to_string())
1415        );
1416    }
1417}