Skip to main content

varve_core/
deposit.rs

1//! Deposit — how a layer comes into being (REQ-DEPOSIT-001).
2//!
3//! One auditable step, run by CI: assemble the layer manifest (an OCI image
4//! index) from the pinned per-tool artifacts, embed the release counter and
5//! issued-at inside the payload, sign it into a DSSE envelope with the
6//! PulseEngine root key, and write the same directory-shaped OCI image
7//! layout that `varve archive` produces — so a fresh deposit and an archived
8//! core are byte-compatible, and both install through the one pipeline.
9//! Hand-edited layer manifests do not exist: this module is the only writer.
10
11use std::path::Path;
12
13use crate::install::VerifyError;
14use crate::layer::LayerId;
15use crate::store::manifest_digest;
16use crate::verify::sign_layer_manifest_with;
17
18/// An RFC 3339 timestamp, not merely a date. `epoch_days` accepts a bare
19/// `YYYY-MM-DD` because it only needs day resolution; a manifest's issued-at
20/// must carry a time, since it lands verbatim in the SBOM's `metadata.timestamp`
21/// where a bare date is invalid (REQ-PRODUCER-001).
22fn is_rfc3339(s: &str) -> bool {
23    let Some((date, time)) = s.split_once('T') else {
24        return false;
25    };
26    if crate::rollback::epoch_days(date).is_none() {
27        return false;
28    }
29    // hh:mm:ss, then an optional fraction, then Z or a numeric offset.
30    let b = time.as_bytes();
31    if b.len() < 9 || b[2] != b':' || b[5] != b':' {
32        return false;
33    }
34    if !b[..8].iter().enumerate().all(|(i, c)| {
35        if i == 2 || i == 5 {
36            *c == b':'
37        } else {
38            c.is_ascii_digit()
39        }
40    }) {
41        return false;
42    }
43    let rest = &time[8..];
44    rest == "Z" || rest.ends_with('Z') || rest.contains('+') || rest.matches('-').count() == 1
45}
46
47/// What to deposit: the layer identity and the tools that make it up.
48#[derive(Debug, Clone)]
49pub struct DepositSpec {
50    pub layer: LayerId,
51    /// `qualified` | `rolling` — recorded verbatim in the annotations.
52    pub channel: String,
53    /// Monotonic per-line release counter (DD-005). The depositor owns
54    /// monotonicity; clients enforce it.
55    pub counter: u64,
56    /// RFC 3339 issued-at, supplied by the caller (CI knows the time; this
57    /// library does not sample clocks).
58    pub issued_at: String,
59    /// (tool name, tool version, binary bytes) triples.
60    pub tools: Vec<DepositTool>,
61    /// Layers composed into this one (REQ-COMPOSE-001).
62    pub includes: Vec<DepositInclude>,
63}
64
65/// One composed layer, as the depositor names it.
66#[derive(Debug, Clone, Default)]
67pub struct DepositInclude {
68    pub digest: String,
69    pub realm: Option<String>,
70    pub layer: Option<String>,
71}
72
73#[derive(Debug, Clone)]
74pub struct DepositTool {
75    pub name: String,
76    pub version: String,
77    /// Target triple this binary is built for; `None` claims
78    /// platform-independence (scripts, data). New deposits should stamp it.
79    pub platform: Option<String>,
80    /// What this payload BUILDS FOR, when that differs from what runs it
81    /// (REQ-SDKTARGET-001). `platform` is the machine that executes these
82    /// bytes; `target` is the machine the artefacts they produce will run on.
83    /// A compiler you invoke declares none and is unchanged by this field.
84    pub target: Option<String>,
85    pub bytes: Vec<u8>,
86    /// Where the bytes came from — recorded INSIDE the signed payload so
87    /// downstream lockfiles (Bazel registries) inherit the signature anchor
88    /// (REQ-BAZEL-001).
89    pub source: Option<ToolSource>,
90    /// Runner contract for portable wasm entries (REQ-RUNNER-001): the tool
91    /// (from the SAME layer) that executes this entry, prefix args, and an
92    /// optional per-user-argument flag (kilnd's --wasi-arg shape).
93    pub runner: Option<RunnerSpec>,
94    /// Payload kind (REQ-KIND-001). `None` or `Tool` deposits no kind
95    /// annotation — pre-kind and tool layers keep byte-identical payloads.
96    pub kind: Option<crate::kind::PayloadKind>,
97    /// What this payload needs from the host's libc (REQ-LIBCSTATED-001),
98    /// measured from its ELF by the producer. `None` deposits no annotation,
99    /// so a payload nothing could measure makes no claim.
100    pub libc: Option<String>,
101    /// The absolute path a tree-shaped payload was BUILT for, signed into the
102    /// manifest as `eu.pulseengine.varve.sdk.prefix` (REQ-SDK-001 clause 4).
103    ///
104    /// It is the relocation BUDGET, so it has to be attributable rather than
105    /// guessed: `export-sdk` refuses a destination longer than this, and a
106    /// consumer must not be able to talk varve into trying. Only a tree payload
107    /// has one — see `check_identities` for why depositing it on anything else
108    /// is refused rather than ignored.
109    pub sdk_prefix: Option<String>,
110    /// What a `docs` payload IS — `html|rustdoc|pdf|markdown|reqif` — signed
111    /// into the manifest as `eu.pulseengine.varve.docs.format`
112    /// (REQ-LAYERDOCS-001).
113    ///
114    /// Signed rather than inferred because it decides how the payload is
115    /// OPENED. A consumer that guessed from the file name could be handed a
116    /// tarball of HTML and told it was a PDF; worse, the guess would usually
117    /// be right, so the one case where it is not would arrive as a puzzle.
118    /// Only a `docs` payload has one, and depositing it on anything else is
119    /// refused rather than ignored — an annotation nothing reads is how a
120    /// field goes inert.
121    pub docs_format: Option<String>,
122    /// The file inside a `docs` payload a reader starts at, signed as
123    /// `eu.pulseengine.varve.docs.entry`. Absent for a single-file format,
124    /// where the payload IS the entry.
125    pub docs_entry: Option<String>,
126    /// The human label shown when choosing between documents, signed as
127    /// `eu.pulseengine.varve.docs.title`. Optional: `name` is always the
128    /// handle a command takes.
129    pub docs_title: Option<String>,
130    /// The payload this document documents, by name, signed as
131    /// `eu.pulseengine.varve.docs.documents` (REQ-LAYERDOCS-001 clause 2).
132    ///
133    /// What lets a reader ask for "the rustdoc of varve-core" instead of
134    /// guessing which of several documents that is. `check_docs_metadata`
135    /// refuses a name matching no payload of this layer: a typo signs exactly
136    /// as cleanly as the right name, and would then answer every such question
137    /// with "nothing documents that".
138    pub docs_documents: Option<String>,
139    /// The operator's opt-in to a `zephyr-module`'s pip requirement files,
140    /// signed as `eu.pulseengine.varve.zephyr.allow-pip` (REQ-ZMODEXPORT-001
141    /// clause 5).
142    ///
143    /// A module whose `zephyr/module.yml` declares `package-managers: pip`
144    /// adds a Python dependency to every build that uses it, which varve does
145    /// not distribute and does not need. The deposit refuses such a module
146    /// unless this names EXACTLY the declared files; `None` is no opt-in, and
147    /// `Some(vec![])` is the explicit opt-in for `pip` declared with no files.
148    /// Only a `zephyr-module` may carry it.
149    pub zephyr_allow_pip: Option<Vec<String>>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
153#[serde(deny_unknown_fields)]
154pub struct RunnerSpec {
155    pub tool: String,
156    #[serde(default)]
157    pub args: Vec<String>,
158    #[serde(rename = "arg-prefix", default)]
159    pub arg_prefix: Option<String>,
160}
161
162/// Upstream provenance of a deposited tool.
163#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
164#[serde(deny_unknown_fields)]
165pub struct ToolSource {
166    /// e.g. "pulseengine/rivet"
167    pub repo: String,
168    /// e.g. "v0.32.0"
169    pub release: String,
170    /// The release asset AS DOWNLOADED, e.g. "rivet-v0.32.0-<triple>.tar.gz"
171    pub asset: String,
172    /// sha256 of that asset (the bytes Bazel will hash), bare hex or
173    /// sha256:-prefixed.
174    pub sha256: String,
175    /// WHICH mechanism vouched for these bytes (REQ-INGEST-001 clause 2).
176    /// `None` on a spec written before the requirement; a layer deposited that
177    /// way reads as `unrecorded`, never as verified.
178    #[serde(default)]
179    pub proof: Option<crate::ingest::IngestProof>,
180    /// The identity that vouched — the cosign certificate identity, or the
181    /// attestation's `buildSignerURI`.
182    #[serde(rename = "proof-signer", default)]
183    pub proof_signer: Option<String>,
184    /// What that mechanism ASSERTED, in one line. For `unverified` this is the
185    /// operator's recorded reason, and it is mandatory: see
186    /// `DepositError::UnverifiedWithoutReason`.
187    #[serde(rename = "proof-asserts", default)]
188    pub proof_asserts: Option<String>,
189    /// The key that actually signed, where that is not the same fact as
190    /// `proof-signer` (an OpenPGP subkey under the certificate's primary).
191    #[serde(rename = "proof-signing-key", default)]
192    pub proof_signing_key: Option<String>,
193    /// The upstream repository's DECLARED SPDX license (REQ-SBOMFIELDS-001
194    /// clause 5) — GitHub's statement, recorded at deposit, never a concluded
195    /// audit of what the binary bundles. `None` on a spec written before the
196    /// requirement, or where GitHub itself has nothing to say; absence must
197    /// not read as "no license".
198    #[serde(default)]
199    pub license: Option<String>,
200    /// The file name of a CycloneDX SBOM upstream published in the SAME
201    /// release this payload came from (REQ-SBOMFIELDS-001 clause 4), relative
202    /// to that release — paired with `sbom_sha256`.
203    #[serde(default)]
204    pub sbom: Option<String>,
205    /// The sha256 (bare hex) of `sbom` as the producer fetched it.
206    #[serde(rename = "sbom-sha256", default)]
207    pub sbom_sha256: Option<String>,
208}
209
210/// How a deposit treats a destination that is not empty (REQ-NODESTROY-001).
211#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
212pub struct DepositOptions {
213    /// Overwrite a layout that already carries referrers, destroying them.
214    /// Deliberate and stated — the point of the guard is that the destructive
215    /// case must be ASKED for, not stumbled into.
216    pub force: bool,
217}
218
219/// A completed deposit.
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct DepositOutcome {
222    /// Digest of the manifest payload — what pins reference.
223    pub digest: String,
224    pub layer: LayerId,
225    pub counter: u64,
226}
227
228/// A deposit described as a file (CI-authored TOML) rather than flags —
229/// the shape the deposit workflow and the Bazel extension both read.
230#[derive(Debug, serde::Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct DepositFileSpec {
233    pub layer: String,
234    pub channel: String,
235    pub counter: u64,
236    #[serde(default, rename = "tool")]
237    pub tools: Vec<SpecTool>,
238    /// Layers this one composes (REQ-COMPOSE-001). Without this a composed
239    /// layer could not be PRODUCED at all — only hand-authored.
240    #[serde(default, rename = "include")]
241    pub includes: Vec<SpecInclude>,
242}
243
244/// A layer composed into this one: named by the digest of its signed manifest,
245/// plus the realm whose trust root is authoritative for it.
246#[derive(Debug, serde::Deserialize)]
247#[serde(deny_unknown_fields)]
248pub struct SpecInclude {
249    /// `sha256:<hex>` of the included layer's signed manifest.
250    pub digest: String,
251    /// The realm that verifies it. Absent = this layer's own realm.
252    #[serde(default)]
253    pub realm: Option<String>,
254    /// The included layer's identifier, so errors can name it before it is
255    /// fetched.
256    #[serde(default)]
257    pub layer: Option<String>,
258}
259
260#[derive(Debug, serde::Deserialize)]
261#[serde(deny_unknown_fields)]
262pub struct SpecTool {
263    pub name: String,
264    pub version: String,
265    #[serde(default)]
266    pub platform: Option<String>,
267    /// `target` — what this payload BUILDS FOR (REQ-SDKTARGET-001 clause 1).
268    /// Absent for anything whose output runs on the machine that ran it.
269    #[serde(default)]
270    pub target: Option<String>,
271    /// Binary path, absolute or relative to the spec file's directory.
272    pub path: String,
273    #[serde(default)]
274    pub source: Option<ToolSource>,
275    #[serde(default)]
276    pub runner: Option<RunnerSpec>,
277    /// Payload kind (REQ-KIND-001): tool|crate|wit|zephyr-module|sdk|
278    /// wasm-component|vsix. Absent = tool.
279    #[serde(default)]
280    pub kind: Option<String>,
281    /// `sdk-prefix` — the absolute path this tree was built for (REQ-SDK-001
282    /// clause 4). Required to make an `sdk` exportable at all: without it there
283    /// is no relocation budget, so `varve export-sdk` has nothing to patch.
284    #[serde(rename = "sdk-prefix", default)]
285    pub sdk_prefix: Option<String>,
286    /// `docs-format` — what this documentation IS (REQ-LAYERDOCS-001).
287    /// Required to make a `docs` payload exportable at all: without it
288    /// `varve export-docs` does not know whether it is unpacking a site or
289    /// handing over one file.
290    #[serde(rename = "docs-format", default)]
291    pub docs_format: Option<String>,
292    /// `docs-entry` — the starting file inside a tree-shaped document.
293    #[serde(rename = "docs-entry", default)]
294    pub docs_entry: Option<String>,
295    /// `docs-title` — the label a human reads when choosing.
296    #[serde(rename = "docs-title", default)]
297    pub docs_title: Option<String>,
298    /// `docs-documents` — the payload this document documents, by name.
299    #[serde(rename = "docs-documents", default)]
300    pub docs_documents: Option<String>,
301    /// `allow-pip` — the requirement files of a `zephyr-module` the operator
302    /// accepts as a Python dependency (REQ-ZMODEXPORT-001 clause 5). Must name
303    /// exactly the files the module's `zephyr/module.yml` declares.
304    #[serde(rename = "allow-pip", default)]
305    pub zephyr_allow_pip: Option<Vec<String>>,
306    /// `libc` — what this payload needs from the host (REQ-LIBCSTATED-001).
307    /// MEASURED by the producer from the ELF, never declared by hand: a
308    /// hand-written floor is a claim, and this annotation exists because the
309    /// layer was already making one.
310    #[serde(default)]
311    pub libc: Option<String>,
312}
313
314pub fn parse_deposit_spec(toml_text: &str) -> Result<DepositFileSpec, DepositError> {
315    toml::from_str(toml_text).map_err(|e| DepositError::Spec(e.to_string()))
316}
317
318impl SpecInclude {
319    /// The composed-layer reference this spec entry describes.
320    ///
321    /// Beside `SpecTool::into_deposit_tool` and for the same reason: the CLI
322    /// used to map these inline, so a test could only exercise the mapping by
323    /// copying it — and a copy agrees with itself no matter what the CLI does.
324    pub fn into_deposit_include(self) -> DepositInclude {
325        DepositInclude {
326            digest: self.digest,
327            realm: self.realm,
328            layer: self.layer,
329        }
330    }
331}
332
333impl SpecTool {
334    /// The payload this spec entry describes, with its bytes read from `base`.
335    ///
336    /// The ONE conversion from a spec file to what `deposit` signs. It used to
337    /// live inline in the CLI, which left the producer's own tests unable to
338    /// run the path a spec it wrote would actually take — and a producer that
339    /// wrote no `kind` and no `docs-format` for a document went unnoticed,
340    /// because every test of the deposit fed it a hand-written spec.
341    pub fn into_deposit_tool(self, base: &Path) -> Result<DepositTool, DepositError> {
342        let path = base.join(&self.path);
343        let bytes = std::fs::read(&path).map_err(|e| {
344            DepositError::Spec(format!("cannot read tool binary {}: {e}", path.display()))
345        })?;
346        let kind = self
347            .kind
348            .as_deref()
349            .map(str::parse)
350            .transpose()
351            .map_err(|e: crate::kind::UnknownKind| DepositError::Spec(e.to_string()))?;
352        // RE-MEASURED from the bytes just read, and not merely copied from the
353        // spec. The producer measures too — but `varve deposit --spec` signs
354        // whatever spec it is handed, so a rule enforced only in the producer
355        // is enforced where it cannot act (REQ-LIBCSTATED-001 clause 1). A
356        // declaration that disagrees with the bytes is REFUSED rather than
357        // corrected: silently replacing it would hide that someone wrote a
358        // portability floor by hand.
359        let measured = crate::elf::linkage(&bytes).map(|l| l.as_str().to_string());
360        if let Some(declared) = &self.libc {
361            // `None` measured means nothing about these bytes is measurable, so
362            // the declaration cannot be checked at all — absence of evidence is
363            // not a portability guarantee (clause 4).
364            let measured_desc = measured
365                .clone()
366                .unwrap_or_else(|| "nothing measurable in these bytes".to_string());
367            if measured.as_deref() != Some(declared.as_str()) {
368                return Err(DepositError::LibcDeclaredNotMeasured {
369                    name: self.name.clone(),
370                    declared: declared.clone(),
371                    measured: measured_desc,
372                });
373            }
374        }
375        Ok(DepositTool {
376            name: self.name,
377            version: self.version,
378            platform: self.platform,
379            target: self.target,
380            bytes,
381            source: self.source,
382            runner: self.runner,
383            kind,
384            // RE-MEASURED here, from the bytes this function already read, and
385            // not merely copied from the spec. The producer measures too — but
386            // `varve deposit --spec` signs whatever spec it is handed, so a
387            // rule enforced only in the producer is enforced where it cannot
388            // act (REQ-LIBCSTATED-001 clause 1). A declaration that disagrees
389            // with the bytes is refused rather than corrected: silently
390            // replacing it would hide that someone wrote a floor by hand.
391            libc: measured,
392            sdk_prefix: self.sdk_prefix,
393            docs_format: self.docs_format,
394            docs_entry: self.docs_entry,
395            docs_title: self.docs_title,
396            docs_documents: self.docs_documents,
397            zephyr_allow_pip: self.zephyr_allow_pip,
398        })
399    }
400}
401
402impl From<crate::archive::LayoutWriteError> for DepositError {
403    fn from(e: crate::archive::LayoutWriteError) -> Self {
404        match e {
405            crate::archive::LayoutWriteError::Io { path, source } => {
406                DepositError::Io { path, source }
407            }
408            crate::archive::LayoutWriteError::WouldDestroy(d) => {
409                DepositError::WouldDestroySignedWork(d)
410            }
411        }
412    }
413}
414
415#[derive(Debug, thiserror::Error)]
416pub enum DepositError {
417    #[error(
418        "the envelope this deposit just signed does not verify against the key that signed \
419         it — refusing to publish an artifact no consumer could accept"
420    )]
421    SelfVerifyFailed,
422    #[error(
423        "channel {channel:?} is not one a pin can name — use `qualified` or `rolling`. \
424         Signing it would produce a layer no varve.toml could ever select."
425    )]
426    BadChannel { channel: String },
427    #[error(
428        "issued-at {issued_at:?} is not an RFC 3339 timestamp (e.g. 2026-08-01T00:00:00Z). \
429         It is signed into the manifest and drives staleness and the SBOM timestamp, so it \
430         cannot be corrected afterwards."
431    )]
432    BadIssuedAt { issued_at: String },
433    #[error("deposit spec is not valid: {0}")]
434    Spec(String),
435    /// REQ-NODESTROY-001. `deposit` writes the WHOLE layout, `index.json`
436    /// included, so a second deposit into a directory that has had evidence
437    /// attached dropped all of it and reported success. Documentation warned
438    /// about this in three topics and guarded nothing.
439    #[error(transparent)]
440    WouldDestroySignedWork(#[from] crate::referrers::WouldDestroy),
441    #[error(
442        "deposit has no tools and composes no layers — an empty layer is not a toolchain. \
443         (A layer that carries only `[[include]]` entries is a COMPOSITION and is accepted: \
444         it says that other realms' layers belong together, which is what a pin naming one \
445         layer needs in order to reach two toolchains.)"
446    )]
447    NoTools,
448    #[error(
449        "tool '{name}' is deposited twice for platform {platform} (versions {first} and \
450         {second}) — a tool is DISPATCHED BY NAME (`varve run {name}`, `varve which {name}`, the \
451         argv[0] shims), so one name must resolve to exactly one binary per platform. Deposit the \
452         other version as a separate layer, or give it a distinct name."
453    )]
454    DuplicateTool {
455        name: String,
456        platform: String,
457        first: String,
458        second: String,
459    },
460    #[error(
461        "payload '{name}' version {version} is deposited twice for platform {platform} — a layer \
462         may hold several VERSIONS of one name, but not one version twice: the two would be the \
463         same payload, and only one set of bytes could land."
464    )]
465    DuplicatePayload {
466        name: String,
467        version: String,
468        platform: String,
469    },
470    #[error(
471        "payload '{name}' is kind {kind} and carries `sdk-prefix` — only a tree payload (sdk) is \
472         relocated, so the prefix would be signed into the manifest, ignored by every adapter, \
473         and believed. Drop it, or deposit this payload as kind = \"sdk\"."
474    )]
475    SdkPrefixOnNonTree { name: String, kind: String },
476    #[error(
477        "payload '{name}' is kind {kind} and carries `docs-format` — only a `docs` payload is \
478         opened by format, so it would be signed into the manifest, read by nothing, and \
479         believed. Drop it, or deposit this payload as kind = \"docs\"."
480    )]
481    DocsFormatOnNonDocs { name: String, kind: String },
482    #[error(
483        "payload {name:?} declares libc {declared:?} and its own bytes say {measured:?}. A \
484         portability floor is a MEASUREMENT, not a label: it is signed into the layer and a \
485         consumer reads it to decide whether these bytes will start on their machine, so a \
486         declared one is a claim nobody checked — the thing this field exists to replace. Drop \
487         `libc` from the spec and let the deposit measure it, or deposit the bytes the \
488         declaration describes."
489    )]
490    LibcDeclaredNotMeasured {
491        name: String,
492        declared: String,
493        measured: String,
494    },
495    #[error(
496        "docs '{name}' version {version} declares no `docs-format` — what the payload IS. \
497         Without it `varve export-docs` cannot tell a site from a single file, so the layer \
498         would install and verify and the document could never be opened. Add \
499         `docs-format = \"html\"` (or rustdoc|pdf|markdown|reqif) to the [[tool]] table."
500    )]
501    DocsFormatMissing { name: String, version: String },
502    #[error(
503        "docs '{name}' declares format '{format}', which varve does not know. The vocabulary is \
504         closed on purpose: a format varve cannot open is one no consumer can act on, and \
505         signing the claim anyway would put a promise in the manifest that nothing keeps. \
506         Known: html, rustdoc, pdf, markdown, reqif."
507    )]
508    DocsFormatUnknown { name: String, format: String },
509    #[error(
510        "docs '{name}' says it documents '{documents}', and this layer carries no payload by \
511         that name that is not itself documentation. It carries: {carried}. A wrong name signs \
512         as cleanly as a right one and would answer every `varve export-docs --for {documents}` \
513         with nothing, so it is refused here, where every payload of the layer is visible. \
514         A document of a payload in a COMPOSED layer cannot be checked at deposit and is not \
515         accepted yet."
516    )]
517    DocsDocumentsDangling {
518        name: String,
519        documents: String,
520        carried: String,
521    },
522    #[error(
523        "payload '{name}' is kind {kind} and carries `docs-documents` — only a `docs` payload \
524         documents something, so it would be signed, read by nothing, and believed. Drop it, \
525         or deposit this payload as kind = \"docs\"."
526    )]
527    DocsDocumentsOnNonDocs { name: String, kind: String },
528    /// A `zephyr-module` the deposit cannot accept (REQ-ZMODEXPORT-001
529    /// clauses 1 and 5). Transparent: the message is the module checker's own,
530    /// which names the payload and what to do.
531    #[error(transparent)]
532    ZephyrModule(#[from] crate::zephyrmodule::ZephyrModuleError),
533    #[error(
534        "payload '{name}' is kind {kind} and carries `allow-pip` — only a `zephyr-module` has \
535         pip requirement files to accept, so it would be signed into the manifest, read by \
536         nothing, and believed. Drop it, or deposit this payload as kind = \"zephyr-module\"."
537    )]
538    ZephyrAllowPipOnNonModule { name: String, kind: String },
539    #[error(
540        "sdk '{name}' version {version} declares no `sdk-prefix` — the absolute path it was \
541         BUILT for. Without it `varve export-sdk` has no relocation budget and no path to \
542         patch, so the layer would install and verify and could never be exported. Add \
543         `sdk-prefix = \"/opt/poky/4.0\"` (the path the SDK was built for) to the [[tool]] table."
544    )]
545    SdkPrefixMissing { name: String, version: String },
546    #[error(
547        "sdk '{name}' declares sdk-prefix {prefix:?}, which is not absolute — the prefix is the \
548         path PATCHED INTO the SDK's binaries, and a relative one there would resolve against \
549         whatever directory a compiler happens to run in"
550    )]
551    SdkPrefixNotAbsolute { name: String, prefix: String },
552    #[error(
553        "payload '{name}' from {repo} declares proof = \"unverified\" and records no reason — \
554         \"we could not verify this\" must never be the silent path. Nothing vouched for these \
555         bytes, so the only thing that can travel with them is WHY you shipped them anyway: set \
556         `proof-asserts` on [tool.source] to the operator's justification, which is signed into \
557         the layer where `varve inspect` and every consumer will see it."
558    )]
559    UnverifiedWithoutReason { name: String, repo: String },
560    #[error(
561        "payload '{name}' from {repo} declares proof = \"unverified\" and also names \
562         proof-signer {signer:?} — nothing vouched for these bytes, so naming an identity that \
563         did would be signed, attributable and false. Drop the signer, or declare the mechanism \
564         that actually established it."
565    )]
566    UnverifiedNamesASigner {
567        name: String,
568        repo: String,
569        signer: String,
570    },
571    #[error(
572        "payload '{name}' from {repo} declares proof = \"{proof}\" and a blank proof-signer \
573         ({signer:?}) — the signer is WHO established that proof, and a blank one is signed into \
574         the layer as a verified claim with nobody behind it. Name the identity the mechanism \
575         actually established, or drop the field: an absent signer is absent, not empty."
576    )]
577    ProofSignerBlank {
578        name: String,
579        repo: String,
580        proof: &'static str,
581        signer: String,
582    },
583    #[error(
584        "payload '{name}' from {repo} carries ingestion-proof detail ({detail}) but declares no \
585         `proof` mechanism — the detail would be signed into the layer with nothing saying HOW \
586         it was established, which makes it attributable and believed rather than checkable. \
587         Declare `proof = \"cosign-sums\" | \"build-provenance\" | \"pgp-sums\" | \"upstream-sums\" | \"unverified\"`, or drop the \
588         detail."
589    )]
590    ProofDetailWithoutMechanism {
591        name: String,
592        repo: String,
593        detail: &'static str,
594    },
595    #[error(
596        "payload '{name}' from {repo} declares sbom-sha256 {sha256:?}, which is not 64 hex \
597         characters — this is signed into the layer as a digest a reader will compare bytes \
598         against, so a malformed one would be believed and never match anything. Record the \
599         SBOM's actual sha256, or drop both `sbom` and `sbom-sha256`."
600    )]
601    SbomSha256Malformed {
602        name: String,
603        repo: String,
604        sha256: String,
605    },
606    #[error(
607        "payload '{name}' from {repo} declares {detail} but not its partner — `sbom` (the file \
608         name) and `sbom-sha256` (its digest) are recorded together or not at all, so a \
609         reference without a checkable digest, or a digest with nothing to name, is never \
610         signed in half."
611    )]
612    SbomFieldIncomplete {
613        name: String,
614        repo: String,
615        detail: &'static str,
616    },
617    #[error(transparent)]
618    Sign(#[from] VerifyError),
619    #[error("io error at {path}: {source}")]
620    Io {
621        path: String,
622        #[source]
623        source: std::io::Error,
624    },
625}
626
627/// How a platform reads in an error when the entry claims none.
628fn platform_label(platform: Option<&String>) -> String {
629    platform
630        .cloned()
631        .unwrap_or_else(|| "any (unstamped)".to_string())
632}
633
634/// Refuse only TRUE duplicates, under the identity of REQ-STORE-002 clause 1
635/// (clause 3).
636///
637/// A `tool` is dispatched by name, so its identity is (name, platform) and two
638/// versions of one tool in one layer is a genuine error — `varve run synth`
639/// would have no answer. Every other kind is held, not dispatched: its identity
640/// is (name, version, platform), so `serde@1.0.200` beside `serde@1.0.210` is
641/// the ORDINARY shape of a dependency graph and must be accepted. varve's own
642/// Cargo.lock has 14 names at more than one version; refusing them meant varve
643/// could not express its own dependency graph as a layer.
644fn check_identities(tools: &[&DepositTool]) -> Result<(), DepositError> {
645    // (name, platform, target) -> the version already seen, for dispatchable
646    // payloads.
647    let mut dispatched: std::collections::BTreeMap<(&str, Option<&String>, Option<&String>), &str> =
648        std::collections::BTreeMap::new();
649    // (name, version, platform, target) -> seen, for everything else.
650    //
651    // The TARGET belongs in the identity (REQ-SDKTARGET-001 clause 3) because
652    // for a cross-toolchain the platform is the same for every target: it
653    // describes the machine that runs the compiler, not the machine its output
654    // runs on. Without it, the four toolchains a Zephyr realm wants are one
655    // identity four times over and the layer is refused.
656    let mut held: std::collections::BTreeSet<(&str, &str, Option<&String>, Option<&String>)> =
657        std::collections::BTreeSet::new();
658    for tool in tools {
659        let dispatchable = tool.kind.unwrap_or_default().is_dispatchable();
660        let platform = tool.platform.as_ref();
661        let target = tool.target.as_ref();
662        if dispatchable {
663            if let Some(first) = dispatched.insert((&tool.name, platform, target), &tool.version) {
664                return Err(DepositError::DuplicateTool {
665                    name: tool.name.clone(),
666                    platform: platform_label(platform),
667                    first: first.to_string(),
668                    second: tool.version.clone(),
669                });
670            }
671        } else if !held.insert((&tool.name, &tool.version, platform, target)) {
672            return Err(DepositError::DuplicatePayload {
673                name: tool.name.clone(),
674                version: tool.version.clone(),
675                platform: match target {
676                    Some(t) => format!("{} target {t}", platform_label(platform)),
677                    None => platform_label(platform),
678                },
679            });
680        }
681    }
682    Ok(())
683}
684
685/// The relocation budget must be present exactly where it can be acted on, and
686/// absent everywhere else (REQ-SDK-001 clause 4).
687///
688/// Both directions are refusals rather than warnings, at the PRODUCING end. An
689/// `sdk-prefix` on a payload nobody relocates is signed, ignored and believed;
690/// an `sdk` without one installs and verifies and can never be exported, which
691/// the consumer discovers on the far side of an air gap. Neither is repairable
692/// without re-depositing, because the annotation lives inside the signature.
693/// Signed annotations for a `docs` payload (REQ-LAYERDOCS-001).
694pub const ANN_DOCS_FORMAT: &str = "eu.pulseengine.varve.docs.format";
695pub const ANN_DOCS_ENTRY: &str = "eu.pulseengine.varve.docs.entry";
696pub const ANN_DOCS_TITLE: &str = "eu.pulseengine.varve.docs.title";
697pub const ANN_DOCS_DOCUMENTS: &str = "eu.pulseengine.varve.docs.documents";
698
699/// A docs payload must say what it is, and nothing else may.
700///
701/// Both directions are refused, for the same reason `sdk-prefix` is. A `docs`
702/// payload with no format cannot be exported — the exporter would not know
703/// whether to unpack a site or hand over one file — so the absence is caught
704/// while the manifest can still be fixed. And a format on a payload that is
705/// not documentation is an annotation nothing will ever read, which is
706/// precisely how a field ships inert.
707fn check_docs_metadata(tools: &[&DepositTool]) -> Result<(), DepositError> {
708    for tool in tools {
709        let is_docs = tool.kind == Some(crate::kind::PayloadKind::Docs);
710        match (&tool.docs_format, is_docs) {
711            (Some(_), false) => {
712                return Err(DepositError::DocsFormatOnNonDocs {
713                    name: tool.name.clone(),
714                    kind: tool.kind.unwrap_or_default().as_str().to_string(),
715                });
716            }
717            (None, true) => {
718                return Err(DepositError::DocsFormatMissing {
719                    name: tool.name.clone(),
720                    version: tool.version.clone(),
721                });
722            }
723            // The vocabulary is closed. A format varve does not know is one it
724            // cannot open, and accepting it would sign a claim about the
725            // payload that no consumer can act on.
726            (Some(f), true) if crate::layerspec::DocsFormat::parse(f).is_none() => {
727                return Err(DepositError::DocsFormatUnknown {
728                    name: tool.name.clone(),
729                    format: f.clone(),
730                });
731            }
732            _ => {}
733        }
734        // An entry on a non-docs payload is the same inert-annotation problem.
735        if tool.docs_entry.is_some() && !is_docs {
736            return Err(DepositError::DocsFormatOnNonDocs {
737                name: tool.name.clone(),
738                kind: tool.kind.unwrap_or_default().as_str().to_string(),
739            });
740        }
741        if let Some(documents) = &tool.docs_documents {
742            if !is_docs {
743                return Err(DepositError::DocsDocumentsOnNonDocs {
744                    name: tool.name.clone(),
745                    kind: tool.kind.unwrap_or_default().as_str().to_string(),
746                });
747            }
748            // Only a payload that is NOT documentation can be documented —
749            // otherwise a document could satisfy this check by naming itself.
750            let documentable = |t: &DepositTool| t.kind != Some(crate::kind::PayloadKind::Docs);
751            if !tools
752                .iter()
753                .any(|t| documentable(t) && &t.name == documents)
754            {
755                let mut carried: Vec<&str> = tools
756                    .iter()
757                    .filter(|t| documentable(t))
758                    .map(|t| t.name.as_str())
759                    .collect();
760                carried.sort_unstable();
761                carried.dedup();
762                return Err(DepositError::DocsDocumentsDangling {
763                    name: tool.name.clone(),
764                    documents: documents.clone(),
765                    carried: if carried.is_empty() {
766                        "nothing but documentation".to_string()
767                    } else {
768                        carried.join(", ")
769                    },
770                });
771            }
772        }
773    }
774    Ok(())
775}
776
777/// A `zephyr-module` must be a module, and must not quietly bring Python
778/// (REQ-ZMODEXPORT-001 clauses 1 and 5).
779///
780/// Decided here, on the BYTES being signed, and not only in the producer: the
781/// producer checks what it fetched, but `varve deposit --spec` signs whatever
782/// archive a spec names, and a rule enforced only upstream of that is enforced
783/// where it cannot act. The opt-in is also refused on a payload that is not a
784/// module, for the reason `sdk-prefix` is: an annotation nothing reads is how a
785/// field ships inert.
786fn check_zephyr_modules(tools: &[&DepositTool]) -> Result<(), DepositError> {
787    for tool in tools {
788        let is_module = tool.kind == Some(crate::kind::PayloadKind::ZephyrModule);
789        if !is_module {
790            if tool.zephyr_allow_pip.is_some() {
791                return Err(DepositError::ZephyrAllowPipOnNonModule {
792                    name: tool.name.clone(),
793                    kind: tool.kind.unwrap_or_default().as_str().to_string(),
794                });
795            }
796            continue;
797        }
798        crate::zephyrmodule::check_deposit(
799            &tool.name,
800            &tool.bytes,
801            tool.zephyr_allow_pip.as_deref(),
802        )?;
803    }
804    Ok(())
805}
806
807fn check_sdk_prefixes(tools: &[&DepositTool]) -> Result<(), DepositError> {
808    for tool in tools {
809        let is_tree = tool.kind == Some(crate::kind::PayloadKind::Sdk);
810        match (&tool.sdk_prefix, is_tree) {
811            (Some(_), false) => {
812                return Err(DepositError::SdkPrefixOnNonTree {
813                    name: tool.name.clone(),
814                    kind: tool.kind.unwrap_or_default().as_str().to_string(),
815                });
816            }
817            (None, true) => {
818                return Err(DepositError::SdkPrefixMissing {
819                    name: tool.name.clone(),
820                    version: tool.version.clone(),
821                });
822            }
823            (Some(prefix), true) if !prefix.starts_with('/') => {
824                return Err(DepositError::SdkPrefixNotAbsolute {
825                    name: tool.name.clone(),
826                    prefix: prefix.clone(),
827                });
828            }
829            _ => {}
830        }
831    }
832    Ok(())
833}
834
835/// The ingestion proof must be sayable, or not said at all (REQ-INGEST-001
836/// clause 3), checked at the PRODUCING end for the same reason
837/// `check_sdk_prefixes` is: everything below is immutable the moment it is
838/// signed.
839///
840/// This function does NOT require a proof to be present. A crate ingested from
841/// crates.io and a layer deposited before this requirement both legitimately
842/// carry none, and they read as `unrecorded` rather than as verified. What it
843/// refuses are the three shapes that would be signed and BELIEVED:
844///
845/// * `unverified` with no recorded reason — the silent path the requirement
846///   exists to close;
847/// * `unverified` naming a signer — an identity credited with vouching for
848///   bytes nothing vouched for;
849/// * proof detail with no mechanism — a claim with no account of how it was
850///   established.
851///
852/// Refusing a MISSING proof is the assembler's job, not this one's: only the
853/// assembler knows it went looking for a mechanism and found none.
854fn check_ingest_proofs(tools: &[&DepositTool]) -> Result<(), DepositError> {
855    for tool in tools {
856        let Some(source) = &tool.source else { continue };
857        match source.proof {
858            Some(crate::ingest::IngestProof::Unverified) => {
859                if source
860                    .proof_asserts
861                    .as_ref()
862                    .is_none_or(|r| r.trim().is_empty())
863                {
864                    return Err(DepositError::UnverifiedWithoutReason {
865                        name: tool.name.clone(),
866                        repo: source.repo.clone(),
867                    });
868                }
869                if let Some(signer) = source
870                    .proof_signer
871                    .as_ref()
872                    .or(source.proof_signing_key.as_ref())
873                {
874                    return Err(DepositError::UnverifiedNamesASigner {
875                        name: tool.name.clone(),
876                        repo: source.repo.clone(),
877                        signer: signer.clone(),
878                    });
879                }
880            }
881            // Every other mechanism DID establish something, so it must say
882            // who. A blank identity here is not "unrecorded" — `None` is; this
883            // is a signed claim of provenance with nobody behind it.
884            Some(proof) => {
885                // A blank signer, or a blank signing key, is a claim with
886                // nobody behind it.
887                for named in [&source.proof_signer, &source.proof_signing_key]
888                    .into_iter()
889                    .flatten()
890                {
891                    if named.trim().is_empty() {
892                        return Err(DepositError::ProofSignerBlank {
893                            name: tool.name.clone(),
894                            repo: source.repo.clone(),
895                            proof: proof.as_str(),
896                            signer: named.clone(),
897                        });
898                    }
899                }
900            }
901            None => {
902                let detail = match (
903                    &source.proof_signer,
904                    &source.proof_asserts,
905                    &source.proof_signing_key,
906                ) {
907                    (_, _, Some(_)) => Some("proof-signing-key"),
908                    (Some(_), Some(_), None) => Some("proof-signer and proof-asserts"),
909                    (Some(_), None, None) => Some("proof-signer"),
910                    (None, Some(_), None) => Some("proof-asserts"),
911                    (None, None, None) => None,
912                };
913                if let Some(detail) = detail {
914                    return Err(DepositError::ProofDetailWithoutMechanism {
915                        name: tool.name.clone(),
916                        repo: source.repo.clone(),
917                        detail,
918                    });
919                }
920            }
921        }
922    }
923    Ok(())
924}
925
926/// The upstream SBOM reference must be a checkable pair, or absent entirely
927/// (REQ-SBOMFIELDS-001 clauses 4 and 6).
928///
929/// `sbom-sha256` is signed into the layer as a digest a consumer will compare
930/// bytes against, so a malformed one — not 64 hex characters — is refused
931/// here rather than signed and never matching anything. And `sbom` /
932/// `sbom-sha256` travel together: a name with no digest cannot be checked,
933/// and a digest naming nothing is unreadable, so either both are present or
934/// neither is — never a default, which is exactly the silent upgrade clause 6
935/// forbids for a layer that carries neither.
936fn check_sbom_fields(tools: &[&DepositTool]) -> Result<(), DepositError> {
937    for tool in tools {
938        let Some(source) = &tool.source else { continue };
939        if let Some(sha) = &source.sbom_sha256
940            && (sha.len() != 64 || !sha.chars().all(|c| c.is_ascii_hexdigit()))
941        {
942            return Err(DepositError::SbomSha256Malformed {
943                name: tool.name.clone(),
944                repo: source.repo.clone(),
945                sha256: sha.clone(),
946            });
947        }
948        let detail = match (&source.sbom, &source.sbom_sha256) {
949            (Some(_), None) => Some("sbom"),
950            (None, Some(_)) => Some("sbom-sha256"),
951            _ => None,
952        };
953        if let Some(detail) = detail {
954            return Err(DepositError::SbomFieldIncomplete {
955                name: tool.name.clone(),
956                repo: source.repo.clone(),
957                detail,
958            });
959        }
960    }
961    Ok(())
962}
963
964/// Assemble, sign, and write a layer as an OCI image layout at `dest`,
965/// refusing a destination that already carries signed work (REQ-NODESTROY-001).
966pub fn deposit(
967    spec: &DepositSpec,
968    signing_key: &[u8],
969    key_id: &str,
970    dest: &Path,
971) -> Result<DepositOutcome, DepositError> {
972    deposit_with_options(spec, signing_key, key_id, dest, &DepositOptions::default())
973}
974
975/// `deposit`, with the destructive case available to callers that ask for it.
976pub fn deposit_with_options(
977    spec: &DepositSpec,
978    signing_key: &[u8],
979    key_id: &str,
980    dest: &Path,
981    options: &DepositOptions,
982) -> Result<DepositOutcome, DepositError> {
983    let signer = crate::verify::FileSigner::new_unchecked(signing_key, key_id)?;
984    deposit_with_signer(spec, &signer, dest, options)
985}
986
987/// `deposit_with_options` with any [`crate::verify::RealmSigner`]: the key may
988/// live somewhere other than a file (REQ-SIGNERSEAM-001).
989pub fn deposit_with_signer(
990    spec: &DepositSpec,
991    signer: &dyn crate::verify::RealmSigner,
992    dest: &Path,
993    options: &DepositOptions,
994) -> Result<DepositOutcome, DepositError> {
995    // FIRST, before anything is validated or signed. `write_oci_layout` runs
996    // the same guard — it is the single writer, and clause 4 lives there — but
997    // asking here too means a deposit that would destroy signed work is
998    // refused before a key is even read, rather than after a signature exists
999    // for an artifact that will not be written (REQ-NODESTROY-001).
1000    crate::referrers::guard(dest, options.force)?;
1001    // Empty means EMPTY — no payloads and nothing composed. A layer that
1002    // carries only includes is not empty: it is a composition, which is the
1003    // whole shape of a realm whose job is to say that two other realms' layers
1004    // belong together (REQ-COVALENT-001 clause 1). A pin names exactly one
1005    // layer, so composing is the only way one pin reaches two toolchains, and
1006    // a composition that also shipped binaries would be a fourth place tools
1007    // are defined. Refusing it here made that realm unbuildable while the
1008    // manifest, the planner and the docs all described it.
1009    if spec.tools.is_empty() && spec.includes.is_empty() {
1010        return Err(DepositError::NoTools);
1011    }
1012    let mut tools: Vec<&DepositTool> = spec.tools.iter().collect();
1013    // Sorted by the FULL identity, so the payload order is deterministic even
1014    // when one name appears at several versions — the digest is the identity a
1015    // pin freezes against, and it must not depend on spec order.
1016    tools.sort_by(|a, b| {
1017        (&a.name, &a.version, &a.platform).cmp(&(&b.name, &b.version, &b.platform))
1018    });
1019    check_identities(&tools)?;
1020    check_sdk_prefixes(&tools)?;
1021    check_docs_metadata(&tools)?;
1022    check_zephyr_modules(&tools)?;
1023    check_ingest_proofs(&tools)?;
1024    check_sbom_fields(&tools)?;
1025
1026    // Assemble the payload deterministically: sorted tools, fixed key order
1027    // (serde_json sorts map keys), no timestamps beyond the caller-supplied
1028    // issued-at. Identical specs must produce identical digests — the digest
1029    // is the identity a pin freezes against.
1030    let entries: Vec<serde_json::Value> = tools
1031        .iter()
1032        .map(|tool| {
1033            let mut annotations = serde_json::Map::new();
1034            annotations.insert("eu.pulseengine.tool".into(), tool.name.clone().into());
1035            annotations.insert(
1036                "eu.pulseengine.tool.version".into(),
1037                tool.version.clone().into(),
1038            );
1039            if let Some(platform) = &tool.platform {
1040                annotations.insert(
1041                    crate::platform::ANN_PLATFORM.into(),
1042                    platform.clone().into(),
1043                );
1044            }
1045            // Beside the platform, never instead of it: the platform is the
1046            // slot a consumer resolves by, and this is what the bytes in that
1047            // slot actually need (REQ-LIBCSTATED-001).
1048            if let Some(libc) = &tool.libc {
1049                annotations.insert(crate::platform::ANN_LIBC.into(), libc.clone().into());
1050            }
1051            // Clause 2: signed, so a consumer resolves by target rather than
1052            // by a name the producer happened to choose.
1053            if let Some(target) = &tool.target {
1054                annotations.insert(crate::platform::ANN_TARGET.into(), target.clone().into());
1055            }
1056            if let Some(source) = &tool.source {
1057                annotations.insert(
1058                    crate::bazel::ANN_SRC_REPO.into(),
1059                    source.repo.clone().into(),
1060                );
1061                annotations.insert(
1062                    crate::bazel::ANN_SRC_RELEASE.into(),
1063                    source.release.clone().into(),
1064                );
1065                annotations.insert(
1066                    crate::bazel::ANN_SRC_ASSET.into(),
1067                    source.asset.clone().into(),
1068                );
1069                annotations.insert(
1070                    crate::bazel::ANN_SRC_SHA256.into(),
1071                    source.sha256.clone().into(),
1072                );
1073                // WHICH mechanism vouched for these bytes, and what it
1074                // asserted (REQ-INGEST-001 clause 2) — inside the signed
1075                // payload, so a consumer can tell a cosign-signed tool from an
1076                // attested one without leaving the layer.
1077                //
1078                // Stamped only when the spec declares it. An absent annotation
1079                // is the pre-requirement layer and reads as `unrecorded`;
1080                // synthesising a default here would silently upgrade every
1081                // payload deposited by an older spec to a claim nobody made,
1082                // and would change the signed bytes of layers that carry no
1083                // proof at all (the crate deposits, whose ingestion is
1084                // crates.io and not a release page).
1085                if let Some(proof) = source.proof {
1086                    annotations.insert(crate::ingest::ANN_PROOF.into(), proof.as_str().into());
1087                }
1088                if let Some(signer) = &source.proof_signer {
1089                    annotations.insert(
1090                        crate::ingest::ANN_PROOF_SIGNER.into(),
1091                        signer.clone().into(),
1092                    );
1093                }
1094                if let Some(asserts) = &source.proof_asserts {
1095                    annotations.insert(
1096                        crate::ingest::ANN_PROOF_ASSERTS.into(),
1097                        asserts.clone().into(),
1098                    );
1099                }
1100                if let Some(key) = &source.proof_signing_key {
1101                    annotations.insert(
1102                        crate::ingest::ANN_PROOF_SIGNING_KEY.into(),
1103                        key.clone().into(),
1104                    );
1105                }
1106                // REQ-SBOMFIELDS-001 clauses 4–6: stamped only when the spec
1107                // declares them. Absent is a layer deposited before the
1108                // requirement (or a repo/release that genuinely carries
1109                // neither), and it must read as `unrecorded` rather than as
1110                // a license nobody declared or an SBOM nobody published —
1111                // synthesising either here would be exactly the silent
1112                // upgrade clause 6 forbids.
1113                if let Some(license) = &source.license {
1114                    annotations.insert(crate::ingest::ANN_LICENSE.into(), license.clone().into());
1115                }
1116                if let Some(sbom) = &source.sbom {
1117                    annotations.insert(crate::ingest::ANN_SBOM.into(), sbom.clone().into());
1118                }
1119                if let Some(sha) = &source.sbom_sha256 {
1120                    annotations.insert(crate::ingest::ANN_SBOM_SHA256.into(), sha.clone().into());
1121                }
1122            }
1123            // Stamp the payload kind only when it is non-default: a `tool`
1124            // (or unspecified) entry carries no kind annotation, so pre-kind
1125            // tool layers keep byte-identical signed payloads (REQ-KIND-001).
1126            if let Some(kind) = tool.kind
1127                && kind != crate::kind::PayloadKind::Tool
1128            {
1129                annotations.insert(crate::kind::ANN_KIND.into(), kind.as_str().into());
1130            }
1131            // The relocation budget, inside the signature (REQ-SDK-001
1132            // clause 4). `check_identities` has already refused it on a kind
1133            // that is not a tree, so an entry carrying it is one `export-sdk`
1134            // can act on.
1135            if let Some(prefix) = &tool.sdk_prefix {
1136                annotations.insert(
1137                    crate::sdkexport::ANN_SDK_PREFIX.into(),
1138                    prefix.clone().into(),
1139                );
1140            }
1141            // What this document IS and where a reader starts, inside the
1142            // signature (REQ-LAYERDOCS-001). `check_docs_metadata` has
1143            // already refused a format on a payload that is not
1144            // documentation, and refused a docs payload without one, so an
1145            // entry carrying these is one `export-docs` can act on.
1146            if let Some(format) = &tool.docs_format {
1147                annotations.insert(ANN_DOCS_FORMAT.into(), format.clone().into());
1148            }
1149            if let Some(entry) = &tool.docs_entry {
1150                annotations.insert(ANN_DOCS_ENTRY.into(), entry.clone().into());
1151            }
1152            if let Some(title) = &tool.docs_title {
1153                annotations.insert(ANN_DOCS_TITLE.into(), title.clone().into());
1154            }
1155            if let Some(documents) = &tool.docs_documents {
1156                annotations.insert(ANN_DOCS_DOCUMENTS.into(), documents.clone().into());
1157            }
1158            // The operator's pip opt-in, inside the signature, so `varve
1159            // inspect` shows what the module was accepted WITH
1160            // (REQ-ZMODEXPORT-001 clause 5). `check_zephyr_modules` has already
1161            // refused it unless it names exactly what the module declares.
1162            if let Some(allow) = &tool.zephyr_allow_pip {
1163                annotations.insert(
1164                    crate::zephyrmodule::ANN_ALLOW_PIP.into(),
1165                    crate::zephyrmodule::allow_pip_to_annotation(allow).into(),
1166                );
1167            }
1168            if let Some(runner) = &tool.runner {
1169                annotations.insert(crate::bazel::ANN_RUNNER.into(), runner.tool.clone().into());
1170                if !runner.args.is_empty() {
1171                    annotations.insert(
1172                        crate::bazel::ANN_RUNNER_ARGS.into(),
1173                        runner.args.join(" ").into(),
1174                    );
1175                }
1176                if let Some(prefix) = &runner.arg_prefix {
1177                    annotations.insert(
1178                        crate::bazel::ANN_RUNNER_ARG_PREFIX.into(),
1179                        prefix.clone().into(),
1180                    );
1181                }
1182            }
1183            serde_json::json!({
1184                "mediaType": "application/vnd.oci.image.manifest.v1+json",
1185                "digest": manifest_digest(&tool.bytes),
1186                "size": tool.bytes.len(),
1187                "annotations": annotations,
1188            })
1189        })
1190        .collect();
1191    // Composed layers are entries too: a `layer`-kind reference whose digest is
1192    // the included layer's SIGNED MANIFEST digest. Emitting them here is what
1193    // makes the composition part of the signed payload — and what lets a
1194    // composed layer be produced at all rather than hand-authored.
1195    let mut entries = entries;
1196    for inc in &spec.includes {
1197        let mut annotations = serde_json::Map::new();
1198        annotations.insert(
1199            crate::kind::ANN_KIND.into(),
1200            crate::kind::PayloadKind::Layer.as_str().into(),
1201        );
1202        if let Some(realm) = &inc.realm {
1203            annotations.insert(
1204                crate::compose::ANN_INCLUDE_REALM.into(),
1205                realm.clone().into(),
1206            );
1207        }
1208        if let Some(layer) = &inc.layer {
1209            annotations.insert(
1210                crate::compose::ANN_INCLUDE_LAYER.into(),
1211                layer.clone().into(),
1212            );
1213        }
1214        entries.push(serde_json::json!({
1215            "mediaType": "application/vnd.oci.image.index.v1+json",
1216            "digest": inc.digest,
1217            "size": 0,
1218            "annotations": annotations,
1219        }));
1220    }
1221    // Validate BEFORE signing. Everything below becomes immutable the moment it
1222    // is signed, so a bad value here is not a mistake you can correct — it is a
1223    // released artifact nobody can use (REQ-PRODUCER-001).
1224    if spec.channel.parse::<crate::pin::Channel>().is_err() {
1225        return Err(DepositError::BadChannel {
1226            channel: spec.channel.clone(),
1227        });
1228    }
1229    if !is_rfc3339(&spec.issued_at) {
1230        return Err(DepositError::BadIssuedAt {
1231            issued_at: spec.issued_at.clone(),
1232        });
1233    }
1234    let payload_json = serde_json::json!({
1235        "schemaVersion": 2,
1236        "mediaType": "application/vnd.oci.image.index.v1+json",
1237        "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
1238        "annotations": {
1239            "eu.pulseengine.varve.layer": spec.layer.to_string(),
1240            "eu.pulseengine.varve.line": spec.layer.line().to_string(),
1241            "eu.pulseengine.varve.channel": spec.channel,
1242            "eu.pulseengine.varve.counter": spec.counter.to_string(),
1243            "org.opencontainers.image.created": spec.issued_at,
1244        },
1245        "manifests": entries,
1246    });
1247    let payload = serde_json::to_vec_pretty(&payload_json).expect("payload serializes");
1248    let envelope = sign_layer_manifest_with(&payload, signer)?;
1249    // Read our own work back before publishing it. The cheapest possible guard
1250    // against emitting a release artifact nobody can verify — and the last
1251    // point at which it is still correctable (REQ-PRODUCER-001).
1252    let public = signer.public_key();
1253    match crate::verify::dsse_verify_typed(
1254        envelope.as_bytes(),
1255        crate::verify::LAYER_PAYLOAD_TYPE,
1256        &public,
1257    ) {
1258        Ok(back) if back == payload => {}
1259        _ => return Err(DepositError::SelfVerifyFailed),
1260    }
1261
1262    let blobs: Vec<(String, Vec<u8>)> = tools
1263        .iter()
1264        .map(|tool| (manifest_digest(&tool.bytes), tool.bytes.clone()))
1265        .collect();
1266    crate::archive::write_oci_layout(
1267        &payload,
1268        envelope.as_bytes(),
1269        &blobs,
1270        &spec.layer.to_string(),
1271        &spec.channel,
1272        // A deposit carries every platform the producer built, so it makes no
1273        // single-platform claim — unlike an archive (varve#80).
1274        None,
1275        dest,
1276        options.force,
1277    )
1278    .map_err(DepositError::from)?;
1279
1280    Ok(DepositOutcome {
1281        digest: manifest_digest(&payload),
1282        layer: spec.layer.clone(),
1283        counter: spec.counter,
1284    })
1285}
1286
1287#[cfg(test)]
1288mod producer_tests {
1289    use super::*;
1290
1291    // rivet: verifies REQ-PRODUCER-001
1292    #[test]
1293    fn a_channel_no_pin_could_name_is_refused_before_signing() {
1294        // `--channel stable` signed happily and produced a layer no varve.toml
1295        // could ever select, exit 0. The enum is shared with the pin parser so
1296        // the two cannot drift.
1297        assert!("qualified".parse::<crate::pin::Channel>().is_ok());
1298        assert!("rolling".parse::<crate::pin::Channel>().is_ok());
1299        for bad in ["stable", "Qualified", "", "beta"] {
1300            assert!(
1301                bad.parse::<crate::pin::Channel>().is_err(),
1302                "{bad} must be refused"
1303            );
1304        }
1305    }
1306
1307    // rivet: verifies REQ-NODESTROY-001
1308    #[test]
1309    fn a_deposit_that_would_drop_a_referrer_is_refused_before_a_byte_is_written() {
1310        use crate::verify::generate_root_keypair;
1311        let (sk, _) = generate_root_keypair();
1312        let tmp = tempfile::tempdir().unwrap();
1313        let dest = tmp.path().join("layout");
1314        let spec = super::tests::spec();
1315        deposit(&spec, &sk, "k", &dest).unwrap();
1316        // Evidence attached after the deposit — the append-only half of the
1317        // producer pipeline.
1318        let status = crate::linestatus::LineStatus {
1319            min_counter: None,
1320            line: "2026.08".into(),
1321            counter: 1,
1322            issued_at: "2026-08-07T00:00:00Z".into(),
1323            support_until: None,
1324            yanked: Default::default(),
1325            known_problems: Vec::new(),
1326        };
1327        crate::linestatus::attach_to_layout(
1328            &dest,
1329            &"2026.08".parse().unwrap(),
1330            status.sign(&sk, "k").unwrap().as_bytes(),
1331        )
1332        .unwrap();
1333
1334        let index_before = std::fs::read(dest.join("index.json")).unwrap();
1335        let err = deposit(&spec, &sk, "k", &dest).expect_err("must refuse");
1336        assert!(
1337            matches!(&err, DepositError::WouldDestroySignedWork { .. }),
1338            "got: {err}"
1339        );
1340        let msg = err.to_string();
1341        assert!(
1342            msg.contains("line-status") && msg.contains("2026.08"),
1343            "{msg}"
1344        );
1345        assert!(msg.contains("varve attach-status"), "{msg}");
1346        assert_eq!(
1347            index_before,
1348            std::fs::read(dest.join("index.json")).unwrap(),
1349            "a refused deposit must not have touched the layout"
1350        );
1351
1352        // …and --force is the deliberate way through, because sometimes the
1353        // operator really does mean to start the directory over.
1354        deposit_with_options(&spec, &sk, "k", &dest, &DepositOptions { force: true })
1355            .expect("--force overrides the guard");
1356        assert!(
1357            crate::linestatus::read_any_from_layout(&dest)
1358                .unwrap()
1359                .is_none(),
1360            "--force is destructive on purpose — the referrer is gone"
1361        );
1362    }
1363
1364    // rivet: verifies REQ-NODESTROY-001
1365    #[test]
1366    fn depositing_into_a_fresh_or_previously_clean_directory_still_works() {
1367        // The guard must fire on ATTACHED work only. A guard that also refused
1368        // a directory holding nothing but a previous clean deposit would break
1369        // every idempotent CI re-run, and a guard that gets switched off
1370        // protects nobody.
1371        use crate::verify::generate_root_keypair;
1372        let (sk, _) = generate_root_keypair();
1373        let tmp = tempfile::tempdir().unwrap();
1374        let dest = tmp.path().join("layout");
1375        let spec = super::tests::spec();
1376        let first = deposit(&spec, &sk, "k", &dest).unwrap();
1377        let second = deposit(&spec, &sk, "k", &dest).expect("a clean layout may be re-deposited");
1378        assert_eq!(first.digest, second.digest);
1379    }
1380
1381    // rivet: verifies REQ-PRODUCER-001
1382    #[test]
1383    fn issued_at_must_be_a_timestamp_not_merely_a_date() {
1384        // A bare date passed `epoch_days` (which needs only day resolution) but
1385        // lands verbatim in the SBOM's metadata.timestamp, where it is invalid
1386        // and uncorrectable after signing.
1387        assert!(is_rfc3339("2026-08-01T00:00:00Z"));
1388        assert!(is_rfc3339("2026-08-01T12:34:56.789Z"));
1389        assert!(is_rfc3339("2026-08-01T12:34:56+02:00"));
1390        for bad in [
1391            "2026-10-01",
1392            "not-a-date",
1393            "",
1394            "2026-08-01T",
1395            "2026-13-01T00:00:00Z",
1396        ] {
1397            assert!(!is_rfc3339(bad), "{bad} must be refused");
1398        }
1399    }
1400}
1401
1402#[cfg(test)]
1403mod libc_enforcement_tests {
1404    use super::*;
1405
1406    /// A real ELF64 header with a `PT_INTERP` naming glibc, built field by
1407    /// field so the test states what it depends on.
1408    fn glibc_elf() -> Vec<u8> {
1409        const PHOFF: usize = 64;
1410        const INTERP: &[u8] = b"/lib64/ld-linux-x86-64.so.2\0";
1411        let interp_off = PHOFF + 56;
1412        let mut v = vec![0u8; interp_off + INTERP.len()];
1413        v[..4].copy_from_slice(&[0x7F, b'E', b'L', b'F']);
1414        v[4] = 2; // ELFCLASS64
1415        v[5] = 1; // little-endian
1416        v[16..18].copy_from_slice(&2u16.to_le_bytes()); // e_type = ET_EXEC
1417        v[18..20].copy_from_slice(&0x3Eu16.to_le_bytes()); // x86-64
1418        v[32..40].copy_from_slice(&(PHOFF as u64).to_le_bytes());
1419        v[54..56].copy_from_slice(&56u16.to_le_bytes()); // e_phentsize
1420        v[56..58].copy_from_slice(&1u16.to_le_bytes()); // e_phnum
1421        v[PHOFF..PHOFF + 4].copy_from_slice(&3u32.to_le_bytes()); // PT_INTERP
1422        v[PHOFF + 8..PHOFF + 16].copy_from_slice(&(interp_off as u64).to_le_bytes());
1423        v[PHOFF + 32..PHOFF + 40].copy_from_slice(&(INTERP.len() as u64).to_le_bytes());
1424        v[interp_off..].copy_from_slice(INTERP);
1425        v
1426    }
1427
1428    fn spec_tool(dir: &std::path::Path, libc: Option<&str>) -> SpecTool {
1429        std::fs::write(dir.join("tool"), glibc_elf()).unwrap();
1430        SpecTool {
1431            name: "ordeal".into(),
1432            version: "1.0.0".into(),
1433            platform: Some("x86_64-unknown-linux-gnu".into()),
1434            target: None,
1435            path: "tool".into(),
1436            source: None,
1437            runner: None,
1438            kind: None,
1439            sdk_prefix: None,
1440            docs_format: None,
1441            docs_entry: None,
1442            docs_title: None,
1443            docs_documents: None,
1444            zephyr_allow_pip: None,
1445            libc: libc.map(str::to_string),
1446        }
1447    }
1448
1449    /// Clause 1: the floor is MEASURED, never taken on the spec's word.
1450    ///
1451    /// This is the gap an independent review found: the producer measured, and
1452    /// `varve deposit --spec` signed whatever it was handed, so the rule was
1453    /// enforced where it could not act. A hand-written `libc = "static"` over
1454    /// a glibc binary used to sign; now it is refused, and the refusal names
1455    /// both numbers so the operator can see which one is the lie.
1456    ///
1457    /// It is also the mechanical detector for this release's own falsification
1458    /// criterion — "a payload carrying static whose binary has a PT_INTERP".
1459    // rivet: verifies REQ-LIBCSTATED-001
1460    #[test]
1461    fn a_declared_libc_the_bytes_contradict_is_refused() {
1462        let tmp = tempfile::tempdir().unwrap();
1463        let err = spec_tool(tmp.path(), Some("static"))
1464            .into_deposit_tool(tmp.path())
1465            .expect_err("a hand-declared floor the bytes contradict must not sign");
1466        let msg = err.to_string();
1467        assert!(
1468            msg.contains("\"static\""),
1469            "the declaration is not named: {msg}"
1470        );
1471        assert!(
1472            msg.contains("\"glibc\""),
1473            "the measurement is not named: {msg}"
1474        );
1475        assert!(
1476            matches!(err, DepositError::LibcDeclaredNotMeasured { .. }),
1477            "{err:?}"
1478        );
1479    }
1480
1481    /// Measuring is the normal path: no declaration, and the floor still
1482    /// reaches the tool because the bytes were read.
1483    // rivet: verifies REQ-LIBCSTATED-001
1484    #[test]
1485    fn an_undeclared_floor_is_measured_from_the_bytes() {
1486        let tmp = tempfile::tempdir().unwrap();
1487        let tool = spec_tool(tmp.path(), None)
1488            .into_deposit_tool(tmp.path())
1489            .expect("an undeclared floor is measured, not refused");
1490        assert_eq!(tool.libc.as_deref(), Some("glibc"));
1491    }
1492
1493    /// A declaration that AGREES is accepted — the rule is "measured", not
1494    /// "never written down". A producer-written spec carries the measurement
1495    /// it just made, and must not be refused for doing so.
1496    // rivet: verifies REQ-LIBCSTATED-001
1497    #[test]
1498    fn a_declaration_that_matches_the_bytes_is_accepted() {
1499        let tmp = tempfile::tempdir().unwrap();
1500        let tool = spec_tool(tmp.path(), Some("glibc"))
1501            .into_deposit_tool(tmp.path())
1502            .expect("the producer's own spec must still deposit");
1503        assert_eq!(tool.libc.as_deref(), Some("glibc"));
1504    }
1505
1506    /// Declaring a floor for bytes nothing can measure is refused too.
1507    ///
1508    /// The tempting alternative is to drop the declaration silently. That
1509    /// would let `libc = "static"` on a shell script pass unnoticed, which is
1510    /// the same unchecked claim in a quieter form.
1511    // rivet: verifies REQ-LIBCSTATED-001
1512    #[test]
1513    fn a_floor_declared_for_unmeasurable_bytes_is_refused() {
1514        let tmp = tempfile::tempdir().unwrap();
1515        std::fs::write(tmp.path().join("tool"), b"#!/bin/sh\nexec true\n").unwrap();
1516        let mut t = spec_tool(tmp.path(), Some("static"));
1517        std::fs::write(tmp.path().join("tool"), b"#!/bin/sh\nexec true\n").unwrap();
1518        t.libc = Some("static".into());
1519        let err = t
1520            .into_deposit_tool(tmp.path())
1521            .expect_err("an unverifiable declaration must not sign");
1522        assert!(
1523            err.to_string().contains("nothing measurable"),
1524            "the refusal must say the claim could not be checked: {err}"
1525        );
1526    }
1527}
1528
1529#[cfg(test)]
1530mod tests {
1531    use super::*;
1532    use crate::archive::OciLayoutSource;
1533    use crate::install::{InstallPolicy, install};
1534    use crate::pin::Pin;
1535    use crate::rollback::HighWaterMarks;
1536    use crate::store::Store;
1537    use crate::verify::{PinnedKeyVerifier, generate_root_keypair};
1538
1539    pub(super) fn spec() -> DepositSpec {
1540        DepositSpec {
1541            includes: Vec::new(),
1542            layer: "2026.08.0".parse().unwrap(),
1543            channel: "qualified".into(),
1544            counter: 1,
1545            issued_at: "2026-08-07T00:00:00Z".into(),
1546            tools: vec![
1547                DepositTool {
1548                    name: "synth".into(),
1549                    version: "0.45.0".into(),
1550                    platform: None,
1551                    target: None,
1552                    bytes: b"synth-bytes".to_vec(),
1553                    source: None,
1554                    runner: None,
1555                    kind: None,
1556                    sdk_prefix: None,
1557                    docs_format: None,
1558                    docs_entry: None,
1559                    docs_title: None,
1560                    docs_documents: None,
1561                    zephyr_allow_pip: None,
1562                    libc: None,
1563                },
1564                DepositTool {
1565                    name: "rivet".into(),
1566                    version: "0.32.0".into(),
1567                    platform: None,
1568                    target: None,
1569                    bytes: b"rivet-bytes".to_vec(),
1570                    source: None,
1571                    runner: None,
1572                    kind: None,
1573                    sdk_prefix: None,
1574                    docs_format: None,
1575                    docs_entry: None,
1576                    docs_title: None,
1577                    docs_documents: None,
1578                    zephyr_allow_pip: None,
1579                    libc: None,
1580                },
1581            ],
1582        }
1583    }
1584
1585    // rivet: verifies REQ-DEPOSIT-001
1586    #[test]
1587    fn a_deposit_round_trips_through_the_standard_install_pipeline() {
1588        let (sk, pk) = generate_root_keypair();
1589        let tmp = tempfile::tempdir().unwrap();
1590        let dest = tmp.path().join("deposit");
1591        let outcome = deposit(&spec(), &sk, "varve-root-1", &dest).unwrap();
1592        assert_eq!(outcome.layer.to_string(), "2026.08.0");
1593
1594        // Standard layout markers present.
1595        assert!(dest.join("oci-layout").is_file());
1596        assert!(dest.join("index.json").is_file());
1597
1598        // Install from the deposit exactly as from an archive.
1599        let pin = Pin::parse(
1600            "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.08.0\"\n",
1601            "varve.toml",
1602        )
1603        .unwrap();
1604        let root = tmp.path().join("fresh");
1605        let store = Store::at(&root);
1606        let mut marks = HighWaterMarks::load(&root).unwrap();
1607        let verifier = PinnedKeyVerifier::from_public_key_bytes(&pk).unwrap();
1608        let policy = InstallPolicy {
1609            index: None,
1610            now: "2026-08-07T00:00:00Z",
1611            staleness_threshold_days: 90,
1612            platform: "test-platform",
1613        };
1614        let installed = install(
1615            &pin,
1616            &OciLayoutSource::at(&dest),
1617            &verifier,
1618            &store,
1619            &mut marks,
1620            &policy,
1621        )
1622        .unwrap();
1623        assert_eq!(installed.digest, outcome.digest);
1624        assert_eq!(installed.counter, 1);
1625        let entry = store.get(&installed.digest).unwrap().unwrap();
1626        let checked =
1627            crate::reverify::verify_installed(&store, &entry, &verifier, "test-platform").unwrap();
1628        assert_eq!(checked, 2);
1629    }
1630
1631    // rivet: verifies REQ-DEPOSIT-001
1632    #[test]
1633    fn the_payload_records_layer_line_channel_counter_and_tool_versions() {
1634        let (sk, _) = generate_root_keypair();
1635        let tmp = tempfile::tempdir().unwrap();
1636        let dest = tmp.path().join("deposit");
1637        let outcome = deposit(&spec(), &sk, "varve-root-1", &dest).unwrap();
1638        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
1639        let payload = std::fs::read(dest.join("blobs/sha256").join(hex)).unwrap();
1640        let json: serde_json::Value = serde_json::from_slice(&payload).unwrap();
1641        let ann = &json["annotations"];
1642        assert_eq!(ann["eu.pulseengine.varve.layer"], "2026.08.0");
1643        assert_eq!(ann["eu.pulseengine.varve.line"], "2026.08");
1644        assert_eq!(ann["eu.pulseengine.varve.channel"], "qualified");
1645        assert_eq!(ann["eu.pulseengine.varve.counter"], "1");
1646        assert_eq!(
1647            ann["org.opencontainers.image.created"],
1648            "2026-08-07T00:00:00Z"
1649        );
1650        let entries = json["manifests"].as_array().unwrap();
1651        assert_eq!(entries.len(), 2);
1652        assert!(entries.iter().any(|e| {
1653            e["annotations"]["eu.pulseengine.tool"] == "synth"
1654                && e["annotations"]["eu.pulseengine.tool.version"] == "0.45.0"
1655        }));
1656    }
1657
1658    // rivet: verifies REQ-DEPOSIT-001
1659    #[test]
1660    fn identical_specs_deposit_identical_digests() {
1661        let (sk, _) = generate_root_keypair();
1662        let tmp = tempfile::tempdir().unwrap();
1663        let a = deposit(&spec(), &sk, "varve-root-1", &tmp.path().join("a")).unwrap();
1664        let b = deposit(&spec(), &sk, "varve-root-1", &tmp.path().join("b")).unwrap();
1665        assert_eq!(
1666            a.digest, b.digest,
1667            "the payload is deterministic — the digest IS the identity"
1668        );
1669    }
1670
1671    // rivet: verifies REQ-DEPOSIT-001
1672    #[test]
1673    fn empty_and_duplicate_tool_lists_are_refused() {
1674        let (sk, _) = generate_root_keypair();
1675        let tmp = tempfile::tempdir().unwrap();
1676        let mut empty = spec();
1677        empty.tools.clear();
1678        assert!(matches!(
1679            deposit(&empty, &sk, "k", &tmp.path().join("x")).unwrap_err(),
1680            DepositError::NoTools
1681        ));
1682        let mut dup = spec();
1683        dup.tools[1].name = "synth".into();
1684        let err = deposit(&dup, &sk, "k", &tmp.path().join("y")).unwrap_err();
1685        assert!(
1686            matches!(&err, DepositError::DuplicateTool { name, .. } if name == "synth"),
1687            "got: {err}"
1688        );
1689    }
1690
1691    /// A tool whose bytes arrived through a NAMED ingestion mechanism
1692    /// (REQ-INGEST-001).
1693    fn ingested(name: &str, repo: &str, proof: crate::ingest::IngestProof) -> DepositTool {
1694        let mut tool = payload(name, "1.0.0", None, Some("x86_64-unknown-linux-gnu"));
1695        tool.source = Some(ToolSource {
1696            repo: repo.into(),
1697            release: "v1.0.0".into(),
1698            asset: format!("{name}-v1.0.0-x86_64-unknown-linux-gnu.tar.gz"),
1699            sha256: "a".repeat(64),
1700            proof: Some(proof),
1701            proof_signer: match proof {
1702                crate::ingest::IngestProof::Unverified => None,
1703                _ => Some(format!(
1704                    "https://github.com/{repo}/.github/workflows/release.yml@refs/tags/v1.0.0"
1705                )),
1706            },
1707            proof_signing_key: None,
1708            proof_asserts: Some(match proof {
1709                crate::ingest::IngestProof::CosignSums => {
1710                    "SHA256SUMS.txt signed for this repo".to_string()
1711                }
1712                crate::ingest::IngestProof::BuildProvenance => {
1713                    "built from source commit deadbeef".to_string()
1714                }
1715                crate::ingest::IngestProof::PgpSums => {
1716                    "the publisher holding OpenPGP key 0123 signed the digest list".to_string()
1717                }
1718                crate::ingest::IngestProof::UpstreamSums => {
1719                    "transcribed from sha256.sum, which upstream publishes and                      does not sign"
1720                        .to_string()
1721                }
1722                crate::ingest::IngestProof::Unverified => {
1723                    "NOTHING — operator opt-in: needed for the 2026.09 bring-up".to_string()
1724                }
1725            }),
1726            license: None,
1727            sbom: None,
1728            sbom_sha256: None,
1729        });
1730        tool
1731    }
1732
1733    /// `ingested`, with an upstream-declared license and SBOM reference
1734    /// (REQ-SBOMFIELDS-001 clauses 4 and 5).
1735    fn with_sbom_fields(
1736        mut tool: DepositTool,
1737        license: Option<&str>,
1738        sbom: Option<(&str, &str)>,
1739    ) -> DepositTool {
1740        let source = tool.source.as_mut().expect("ingested() sets a source");
1741        source.license = license.map(str::to_string);
1742        if let Some((name, sha256)) = sbom {
1743            source.sbom = Some(name.to_string());
1744            source.sbom_sha256 = Some(sha256.to_string());
1745        }
1746        tool
1747    }
1748
1749    // rivet: verifies REQ-INGEST-001
1750    #[test]
1751    fn the_mechanism_that_vouched_for_each_payload_is_inside_the_signed_layer() {
1752        // Clause 2. A consumer must be able to tell a cosign-signed tool from
1753        // an attested one WITHOUT leaving the layer, so the mechanism and what
1754        // it asserted are annotations on the payload entry — inside the DSSE
1755        // payload, uncorrectable after signing, exactly like the kind and the
1756        // source digests beside them.
1757        use crate::ingest::{ANN_PROOF, ANN_PROOF_ASSERTS, ANN_PROOF_SIGNER, IngestProof};
1758        let (sk, _) = generate_root_keypair();
1759        let tmp = tempfile::tempdir().unwrap();
1760        let mut spec = spec();
1761        spec.tools = vec![
1762            ingested("rivet", "pulseengine/rivet", IngestProof::CosignSums),
1763            ingested(
1764                "wasm-tools",
1765                "bytecodealliance/wasm-tools",
1766                IngestProof::BuildProvenance,
1767            ),
1768            ingested(
1769                "wit-bindgen",
1770                "bytecodealliance/wit-bindgen",
1771                IngestProof::Unverified,
1772            ),
1773        ];
1774        let outcome = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap();
1775        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
1776        let bytes = std::fs::read(tmp.path().join("d/blobs/sha256").join(hex)).unwrap();
1777        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1778        let entries = json["manifests"].as_array().unwrap();
1779        let by_name = |n: &str| {
1780            entries
1781                .iter()
1782                .find(|e| e["annotations"]["eu.pulseengine.tool"] == n)
1783                .unwrap_or_else(|| panic!("{n} is not in the payload"))
1784                .clone()
1785        };
1786
1787        let rivet = by_name("rivet");
1788        assert_eq!(rivet["annotations"][ANN_PROOF], "cosign-sums");
1789        assert_eq!(
1790            rivet["annotations"][ANN_PROOF_SIGNER],
1791            "https://github.com/pulseengine/rivet/.github/workflows/release.yml@refs/tags/v1.0.0"
1792        );
1793
1794        let wasm_tools = by_name("wasm-tools");
1795        assert_eq!(
1796            wasm_tools["annotations"][ANN_PROOF], "build-provenance",
1797            "an attested tool must not read as a cosign-signed one"
1798        );
1799        assert_eq!(
1800            wasm_tools["annotations"][ANN_PROOF_ASSERTS],
1801            "built from source commit deadbeef"
1802        );
1803
1804        let wit_bindgen = by_name("wit-bindgen");
1805        assert_eq!(wit_bindgen["annotations"][ANN_PROOF], "unverified");
1806        assert!(
1807            wit_bindgen["annotations"][ANN_PROOF_SIGNER].is_null(),
1808            "nothing vouched for it, so no signer may be named"
1809        );
1810        assert!(
1811            wit_bindgen["annotations"][ANN_PROOF_ASSERTS]
1812                .as_str()
1813                .unwrap()
1814                .contains("2026.09 bring-up"),
1815            "the recorded opt-in reason travels with the payload"
1816        );
1817    }
1818
1819    /// REQ-SIGNEDSUMS-001 clause 1: the key that actually signed is recorded
1820    /// SEPARATELY from the identity, as its own signed annotation.
1821    // rivet: verifies REQ-SIGNEDSUMS-001
1822    #[test]
1823    fn the_signing_key_is_its_own_signed_annotation_beside_the_signer() {
1824        use crate::ingest::{ANN_PROOF_SIGNER, ANN_PROOF_SIGNING_KEY, IngestProof};
1825        let (sk, _) = generate_root_keypair();
1826        let tmp = tempfile::tempdir().unwrap();
1827        let mut spec = spec();
1828        let mut pgp = ingested("rust", "o/rust", IngestProof::PgpSums);
1829        pgp.source.as_mut().unwrap().proof_signer = Some("openpgp:aaaa (Rust)".into());
1830        pgp.source.as_mut().unwrap().proof_signing_key = Some("bbbb".into());
1831        spec.tools = vec![
1832            pgp,
1833            ingested("rivet", "pulseengine/rivet", IngestProof::CosignSums),
1834        ];
1835        let outcome = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap();
1836        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
1837        let bytes = std::fs::read(tmp.path().join("d/blobs/sha256").join(hex)).unwrap();
1838        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1839        let entry = |n: &str| {
1840            json["manifests"]
1841                .as_array()
1842                .unwrap()
1843                .iter()
1844                .find(|e| e["annotations"]["eu.pulseengine.tool"] == n)
1845                .unwrap()
1846                .clone()
1847        };
1848        let rust = entry("rust");
1849        assert_eq!(rust["annotations"][ANN_PROOF_SIGNER], "openpgp:aaaa (Rust)");
1850        assert_eq!(rust["annotations"][ANN_PROOF_SIGNING_KEY], "bbbb");
1851        assert!(
1852            entry("rivet")["annotations"][ANN_PROOF_SIGNING_KEY].is_null(),
1853            "a mechanism with no separate signing key records none"
1854        );
1855    }
1856
1857    /// A signing key with no mechanism, or a blank one, would be signed and
1858    /// believed with nothing behind it.
1859    // rivet: verifies REQ-SIGNEDSUMS-001
1860    #[test]
1861    fn a_signing_key_without_a_proof_or_a_blank_one_is_refused() {
1862        use crate::ingest::IngestProof;
1863        let (sk, _) = generate_root_keypair();
1864        let tmp = tempfile::tempdir().unwrap();
1865        let mut spec = spec();
1866        let mut bare = ingested("rust", "o/rust", IngestProof::PgpSums);
1867        let source = bare.source.as_mut().unwrap();
1868        source.proof = None;
1869        source.proof_signer = None;
1870        source.proof_asserts = None;
1871        source.proof_signing_key = Some("bbbb".into());
1872        spec.tools = vec![bare];
1873        let err = deposit(&spec, &sk, "k", &tmp.path().join("a")).unwrap_err();
1874        assert!(
1875            matches!(&err, DepositError::ProofDetailWithoutMechanism { detail, .. } if detail.contains("proof-signing-key")),
1876            "{err}"
1877        );
1878
1879        let mut blank = ingested("rust", "o/rust", IngestProof::PgpSums);
1880        blank.source.as_mut().unwrap().proof_signing_key = Some("  ".into());
1881        spec.tools = vec![blank];
1882        let err = deposit(&spec, &sk, "k", &tmp.path().join("b")).unwrap_err();
1883        assert!(
1884            matches!(err, DepositError::ProofSignerBlank { .. }),
1885            "{err}"
1886        );
1887    }
1888
1889    // rivet: verifies REQ-INGEST-001
1890    #[test]
1891    fn an_unproven_payload_may_not_be_signed_in_silently() {
1892        // Clause 3, at the signing end. `unverified` is a real, sayable state —
1893        // but only WITH the recorded reason. A bare `proof = "unverified"` and
1894        // no `proof-asserts` is the silent path the requirement forbids, and it
1895        // is refused before a key is read rather than published and believed.
1896        use crate::ingest::IngestProof;
1897        let (sk, _) = generate_root_keypair();
1898        let tmp = tempfile::tempdir().unwrap();
1899        let mut spec = spec();
1900        let mut tool = ingested(
1901            "wit-bindgen",
1902            "bytecodealliance/wit-bindgen",
1903            IngestProof::Unverified,
1904        );
1905        tool.source.as_mut().unwrap().proof_asserts = None;
1906        spec.tools = vec![tool];
1907        let err = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap_err();
1908        assert!(
1909            matches!(&err, DepositError::UnverifiedWithoutReason { name, .. } if name == "wit-bindgen"),
1910            "got: {err}"
1911        );
1912
1913        // …and a signer named for a mechanism that vouched for nothing is a
1914        // claim of provenance where there is none.
1915        let mut spec = super::tests::spec();
1916        let mut tool = ingested(
1917            "wit-bindgen",
1918            "bytecodealliance/wit-bindgen",
1919            IngestProof::Unverified,
1920        );
1921        tool.source.as_mut().unwrap().proof_signer = Some("https://github.com/someone/".into());
1922        spec.tools = vec![tool];
1923        let err = deposit(&spec, &sk, "k", &tmp.path().join("e")).unwrap_err();
1924        assert!(
1925            matches!(&err, DepositError::UnverifiedNamesASigner { name, .. } if name == "wit-bindgen"),
1926            "got: {err}"
1927        );
1928    }
1929
1930    /// A blank signer is meaningless under EVERY mechanism, not only under
1931    /// `unverified`.
1932    ///
1933    /// The producer once emitted `proof-signer = ""` for an unverified payload,
1934    /// which this check caught only because the unverified branch refuses ANY
1935    /// signer. One branch over — a real mechanism with a blank identity — the
1936    /// same bytes would have been signed as "cosign verified this, by nobody
1937    /// named", and nothing looked. `Some("")` must never read as "unrecorded":
1938    /// an absent signer is `None`.
1939    // rivet: verifies REQ-INGEST-001
1940    #[test]
1941    fn a_mechanism_that_names_a_blank_signer_is_refused() {
1942        let tmp = tempfile::tempdir().unwrap();
1943        let (sk, _pk) = crate::generate_root_keypair();
1944        for (n, (proof, blank)) in [
1945            (crate::ingest::IngestProof::CosignSums, ""),
1946            (crate::ingest::IngestProof::BuildProvenance, "   "),
1947            (crate::ingest::IngestProof::PgpSums, " "),
1948            (crate::ingest::IngestProof::UpstreamSums, "\t"),
1949        ]
1950        .into_iter()
1951        .enumerate()
1952        {
1953            let mut spec = super::tests::spec();
1954            let mut tool = ingested("wit-bindgen", "bytecodealliance/wit-bindgen", proof);
1955            tool.source.as_mut().unwrap().proof_signer = Some(blank.into());
1956            spec.tools = vec![tool];
1957            let err = deposit(&spec, &sk, "k", &tmp.path().join(format!("blank{n}"))).unwrap_err();
1958            assert!(
1959                matches!(&err, DepositError::ProofSignerBlank { name, .. } if name == "wit-bindgen"),
1960                "{proof:?} with signer {blank:?} got: {err}"
1961            );
1962        }
1963    }
1964
1965    // rivet: verifies REQ-INGEST-001
1966    #[test]
1967    fn proof_detail_without_a_mechanism_is_refused_rather_than_signed() {
1968        // The other direction: `proof-signer` / `proof-asserts` with no
1969        // `proof` would land a signer and a claim in the signed payload with
1970        // nothing saying HOW it was established — attributable, believed, and
1971        // meaningless. Same shape of refusal as an sdk-prefix on a non-tree.
1972        let (sk, _) = generate_root_keypair();
1973        let tmp = tempfile::tempdir().unwrap();
1974        let mut spec = spec();
1975        let mut tool = ingested(
1976            "wasm-tools",
1977            "bytecodealliance/wasm-tools",
1978            crate::ingest::IngestProof::BuildProvenance,
1979        );
1980        tool.source.as_mut().unwrap().proof = None;
1981        spec.tools = vec![tool];
1982        let err = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap_err();
1983        assert!(
1984            matches!(&err, DepositError::ProofDetailWithoutMechanism { name, .. } if name == "wasm-tools"),
1985            "got: {err}"
1986        );
1987    }
1988
1989    // rivet: verifies REQ-INGEST-001
1990    #[test]
1991    fn a_layer_deposited_before_this_requirement_reads_as_unrecorded_not_as_verified() {
1992        // The compatibility promise. Every layer already published carries no
1993        // proof annotation, and the absent case must NOT read as "verified" —
1994        // that would silently upgrade every pre-REQ-INGEST-001 payload to a
1995        // claim nobody made. Absent is its own state: `unrecorded`.
1996        use crate::ingest::IngestProof;
1997        use crate::manifest::ManifestEntry;
1998        let entry = ManifestEntry {
1999            digest: "sha256:abc".into(),
2000            annotations: Default::default(),
2001        };
2002        assert_eq!(entry.ingest_proof(), Ok(None));
2003        assert_eq!(IngestProof::label(None), "unrecorded");
2004
2005        let mut entry = entry;
2006        entry
2007            .annotations
2008            .insert(crate::ingest::ANN_PROOF.into(), "build-provenance".into());
2009        assert_eq!(entry.ingest_proof(), Ok(Some(IngestProof::BuildProvenance)));
2010        // The proof this build writes for an unsigned upstream digest list
2011        // must read back, not fall into the unknown branch.
2012        entry
2013            .annotations
2014            .insert(crate::ingest::ANN_PROOF.into(), "upstream-sums".into());
2015        assert_eq!(entry.ingest_proof(), Ok(Some(IngestProof::UpstreamSums)));
2016        // And the signed digest list (REQ-SIGNEDSUMS-001), likewise.
2017        entry
2018            .annotations
2019            .insert(crate::ingest::ANN_PROOF.into(), "pgp-sums".into());
2020        assert_eq!(entry.ingest_proof(), Ok(Some(IngestProof::PgpSums)));
2021        // An unknown mechanism is reported verbatim, never guessed into a
2022        // known one — a newer varve may mint mechanisms this build has not
2023        // heard of, and quietly reading one as `cosign-sums` would be a lie.
2024        entry
2025            .annotations
2026            .insert(crate::ingest::ANN_PROOF.into(), "notary-v2".into());
2027        assert_eq!(
2028            entry.ingest_proof(),
2029            Err(crate::ingest::UnknownProof("notary-v2".into()))
2030        );
2031    }
2032
2033    // rivet: verifies REQ-SBOMFIELDS-001
2034    #[test]
2035    fn a_declared_license_and_upstream_sbom_become_exactly_those_three_annotations() {
2036        // Clauses 4 and 5: present in the spec, present as signed annotations
2037        // — and nothing else is stamped alongside them.
2038        use crate::ingest::{ANN_LICENSE, ANN_SBOM, ANN_SBOM_SHA256};
2039        let (sk, _) = generate_root_keypair();
2040        let tmp = tempfile::tempdir().unwrap();
2041        let mut spec = spec();
2042        let tool = with_sbom_fields(
2043            ingested(
2044                "rivet",
2045                "pulseengine/rivet",
2046                crate::ingest::IngestProof::CosignSums,
2047            ),
2048            Some("Apache-2.0"),
2049            Some(("rivet-v1.0.0.cdx.json", &"b".repeat(64))),
2050        );
2051        spec.tools = vec![tool];
2052        let outcome = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap();
2053        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
2054        let bytes = std::fs::read(tmp.path().join("d/blobs/sha256").join(hex)).unwrap();
2055        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2056        let entry = json["manifests"].as_array().unwrap()[0].clone();
2057        assert_eq!(entry["annotations"][ANN_LICENSE], "Apache-2.0");
2058        assert_eq!(entry["annotations"][ANN_SBOM], "rivet-v1.0.0.cdx.json");
2059        assert_eq!(entry["annotations"][ANN_SBOM_SHA256], "b".repeat(64));
2060    }
2061
2062    // rivet: verifies REQ-SBOMFIELDS-001
2063    #[test]
2064    fn a_spec_without_license_or_sbom_signs_none_of_the_three_annotations() {
2065        // Clause 6: absence must stay absence — no default, no
2066        // "NOASSERTION" the deposit itself invents.
2067        use crate::ingest::{ANN_LICENSE, ANN_SBOM, ANN_SBOM_SHA256};
2068        let (sk, _) = generate_root_keypair();
2069        let tmp = tempfile::tempdir().unwrap();
2070        let mut spec = spec();
2071        spec.tools = vec![ingested(
2072            "rivet",
2073            "pulseengine/rivet",
2074            crate::ingest::IngestProof::CosignSums,
2075        )];
2076        let outcome = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap();
2077        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
2078        let bytes = std::fs::read(tmp.path().join("d/blobs/sha256").join(hex)).unwrap();
2079        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2080        let entry = json["manifests"].as_array().unwrap()[0].clone();
2081        assert!(entry["annotations"][ANN_LICENSE].is_null());
2082        assert!(entry["annotations"][ANN_SBOM].is_null());
2083        assert!(entry["annotations"][ANN_SBOM_SHA256].is_null());
2084    }
2085
2086    /// A malformed digest must be refused BEFORE signing, not signed as a
2087    /// claim nothing can ever match.
2088    // rivet: verifies REQ-SBOMFIELDS-001
2089    #[test]
2090    fn a_malformed_sbom_sha256_is_refused_rather_than_signed() {
2091        let (sk, _) = generate_root_keypair();
2092        let tmp = tempfile::tempdir().unwrap();
2093        for bad in ["not-hex-at-all", &"a".repeat(63), &"a".repeat(65), ""] {
2094            let mut spec = spec();
2095            spec.tools = vec![with_sbom_fields(
2096                ingested(
2097                    "rivet",
2098                    "pulseengine/rivet",
2099                    crate::ingest::IngestProof::CosignSums,
2100                ),
2101                None,
2102                Some(("rivet-v1.0.0.cdx.json", bad)),
2103            )];
2104            let err =
2105                deposit(&spec, &sk, "k", &tmp.path().join(format!("d{}", bad.len()))).unwrap_err();
2106            assert!(
2107                matches!(&err, DepositError::SbomSha256Malformed { name, .. } if name == "rivet"),
2108                "{bad:?} got: {err}"
2109            );
2110        }
2111    }
2112
2113    /// `sbom` and `sbom-sha256` travel together; either one alone is a
2114    /// reference that cannot be checked, or a digest naming nothing.
2115    // rivet: verifies REQ-SBOMFIELDS-001
2116    #[test]
2117    fn sbom_and_its_digest_are_refused_when_only_one_is_present() {
2118        let (sk, _) = generate_root_keypair();
2119        let tmp = tempfile::tempdir().unwrap();
2120        let mut name_only = ingested(
2121            "rivet",
2122            "pulseengine/rivet",
2123            crate::ingest::IngestProof::CosignSums,
2124        );
2125        name_only.source.as_mut().unwrap().sbom = Some("rivet-v1.0.0.cdx.json".into());
2126        let mut spec_a = spec();
2127        spec_a.tools = vec![name_only];
2128        let err = deposit(&spec_a, &sk, "k", &tmp.path().join("a")).unwrap_err();
2129        assert!(
2130            matches!(&err, DepositError::SbomFieldIncomplete { detail, .. } if *detail == "sbom"),
2131            "got: {err}"
2132        );
2133
2134        let mut digest_only = ingested(
2135            "rivet",
2136            "pulseengine/rivet",
2137            crate::ingest::IngestProof::CosignSums,
2138        );
2139        digest_only.source.as_mut().unwrap().sbom_sha256 = Some("c".repeat(64));
2140        let mut spec_b = spec();
2141        spec_b.tools = vec![digest_only];
2142        let err = deposit(&spec_b, &sk, "k", &tmp.path().join("b")).unwrap_err();
2143        assert!(
2144            matches!(&err, DepositError::SbomFieldIncomplete { detail, .. } if *detail == "sbom-sha256"),
2145            "got: {err}"
2146        );
2147    }
2148
2149    /// One entry of a given kind, at a given version and platform.
2150    fn payload(
2151        name: &str,
2152        version: &str,
2153        kind: Option<crate::kind::PayloadKind>,
2154        platform: Option<&str>,
2155    ) -> DepositTool {
2156        DepositTool {
2157            name: name.into(),
2158            version: version.into(),
2159            platform: platform.map(str::to_string),
2160            target: None,
2161            bytes: format!("{name}-{version}-bytes").into_bytes(),
2162            source: None,
2163            runner: None,
2164            kind,
2165            sdk_prefix: None,
2166            docs_format: None,
2167            docs_entry: None,
2168            docs_title: None,
2169            docs_documents: None,
2170            zephyr_allow_pip: None,
2171            libc: None,
2172        }
2173    }
2174
2175    /// Two cross-toolchains for one host, same name and version, different
2176    /// targets: two payloads, not a duplicate.
2177    ///
2178    /// The identity rule was (name, version, platform), and for a
2179    /// cross-toolchain the platform is IDENTICAL across targets — it is the
2180    /// machine running the compiler, not the one the output runs on. So the
2181    /// four arm/riscv/xtensa/arc toolchains a realm wants were one identity
2182    /// four times over, and the deposit refused the layer.
2183    // rivet: verifies REQ-SDKTARGET-001
2184    #[test]
2185    fn two_targets_of_one_sdk_are_two_payloads_not_a_duplicate() {
2186        let tmp = tempfile::tempdir().unwrap();
2187        let (sk, _pk) = crate::generate_root_keypair();
2188        let sdk = |target: &str| {
2189            let mut t = payload(
2190                "zephyr-sdk",
2191                "1.0.1",
2192                Some(crate::kind::PayloadKind::Sdk),
2193                Some("x86_64-unknown-linux-gnu"),
2194            );
2195            t.target = Some(target.to_string());
2196            t.sdk_prefix = Some("/opt/zephyr-sdk-1.0.1".into());
2197            t.bytes = format!("{target}-bytes").into_bytes();
2198            t
2199        };
2200        let mut spec = tests::spec();
2201        spec.tools = vec![sdk("arm-zephyr-eabi"), sdk("riscv64-zephyr-elf")];
2202        let layout = tmp.path().join("ok");
2203        let outcome = deposit(&spec, &sk, "k", &layout).expect("two targets are two payloads");
2204
2205        // Clause 2: the target is IN the signed manifest, so a consumer can
2206        // resolve by it rather than by a name the producer chose.
2207        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
2208        let bytes = std::fs::read(layout.join("blobs/sha256").join(hex)).unwrap();
2209        let manifest: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2210        let entries = manifest["manifests"].as_array().unwrap();
2211        let targets: Vec<&str> = entries
2212            .iter()
2213            .filter_map(|e| e["annotations"][crate::platform::ANN_TARGET].as_str())
2214            .collect();
2215        assert_eq!(targets, vec!["arm-zephyr-eabi", "riscv64-zephyr-elf"]);
2216
2217        // …and one target deposited twice is still a duplicate: extending the
2218        // identity must not open a hole in the rule it extends.
2219        let mut dup = spec;
2220        dup.tools = vec![sdk("arm-zephyr-eabi"), sdk("arm-zephyr-eabi")];
2221        let err = deposit(&dup, &sk, "k", &tmp.path().join("dup")).unwrap_err();
2222        assert!(
2223            matches!(&err, DepositError::DuplicatePayload { name, .. } if name == "zephyr-sdk"),
2224            "got: {err}"
2225        );
2226    }
2227
2228    // rivet: verifies REQ-STORE-002
2229    #[test]
2230    fn two_versions_of_one_crate_are_a_layer_not_a_duplicate() {
2231        // THE reported defect (varve#69), at the function that raised it.
2232        // `deposit` keyed on (name, platform) and ignored version and kind, so
2233        // serde 1.0.200 beside serde 1.0.210 was refused as "duplicate tool
2234        // name 'serde'" — and varve could not express its own dependency graph
2235        // (252 packages, 14 names at more than one version) as a layer.
2236        use crate::kind::PayloadKind;
2237        let (sk, _) = generate_root_keypair();
2238        let tmp = tempfile::tempdir().unwrap();
2239        let mut spec = spec();
2240        spec.tools = vec![
2241            payload("serde", "1.0.200", Some(PayloadKind::Crate), None),
2242            payload("serde", "1.0.210", Some(PayloadKind::Crate), None),
2243        ];
2244        let outcome = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap();
2245
2246        // Both versions are in the SIGNED payload, each under its own digest.
2247        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
2248        let payload_bytes = std::fs::read(tmp.path().join("d/blobs/sha256").join(hex)).unwrap();
2249        let json: serde_json::Value = serde_json::from_slice(&payload_bytes).unwrap();
2250        let entries = json["manifests"].as_array().unwrap();
2251        assert_eq!(entries.len(), 2);
2252        let versions: Vec<&str> = entries
2253            .iter()
2254            .map(|e| {
2255                e["annotations"]["eu.pulseengine.tool.version"]
2256                    .as_str()
2257                    .unwrap()
2258            })
2259            .collect();
2260        assert_eq!(versions, vec!["1.0.200", "1.0.210"]);
2261        assert_ne!(
2262            entries[0]["digest"], entries[1]["digest"],
2263            "two versions are two artifacts"
2264        );
2265    }
2266
2267    // rivet: verifies REQ-VSIX-001
2268    #[test]
2269    fn extensions_deposit_as_vsix_entries_at_several_versions() {
2270        // Clause 1: the kind reaches the SIGNED payload as `vsix`, spelled that
2271        // way — the annotation is what a consumer's `export-vsix` keys on, and
2272        // it is inside the DSSE payload, so it cannot be corrected afterwards.
2273        // Clause 4: an extension is not dispatched by name, so its identity is
2274        // (name, version) and two versions of one extension is a layer, not a
2275        // duplicate — the same rule REQ-STORE-002 established for crates,
2276        // reached here through `is_dispatchable` rather than a second list.
2277        use crate::kind::PayloadKind;
2278        let (sk, _) = generate_root_keypair();
2279        let tmp = tempfile::tempdir().unwrap();
2280        let mut spec = spec();
2281        spec.tools = vec![
2282            payload(
2283                "rust-lang.rust-analyzer",
2284                "0.3.2260",
2285                Some(PayloadKind::Vsix),
2286                None,
2287            ),
2288            payload(
2289                "rust-lang.rust-analyzer",
2290                "0.3.2300",
2291                Some(PayloadKind::Vsix),
2292                None,
2293            ),
2294            payload(
2295                "vadimcn.vscode-lldb",
2296                "1.11.4",
2297                Some(PayloadKind::Vsix),
2298                None,
2299            ),
2300        ];
2301        let outcome = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap();
2302
2303        let hex = outcome.digest.strip_prefix("sha256:").unwrap();
2304        let payload_bytes = std::fs::read(tmp.path().join("d/blobs/sha256").join(hex)).unwrap();
2305        let json: serde_json::Value = serde_json::from_slice(&payload_bytes).unwrap();
2306        let entries = json["manifests"].as_array().unwrap();
2307        assert_eq!(entries.len(), 3, "all three extensions must be signed in");
2308        for e in entries {
2309            assert_eq!(
2310                e["annotations"][crate::kind::ANN_KIND],
2311                "vsix",
2312                "every entry must carry the vsix kind in the SIGNED payload"
2313            );
2314        }
2315        let ids: Vec<(&str, &str)> = entries
2316            .iter()
2317            .map(|e| {
2318                (
2319                    e["annotations"]["eu.pulseengine.tool"].as_str().unwrap(),
2320                    e["annotations"]["eu.pulseengine.tool.version"]
2321                        .as_str()
2322                        .unwrap(),
2323                )
2324            })
2325            .collect();
2326        assert_eq!(
2327            ids,
2328            vec![
2329                ("rust-lang.rust-analyzer", "0.3.2260"),
2330                ("rust-lang.rust-analyzer", "0.3.2300"),
2331                ("vadimcn.vscode-lldb", "1.11.4"),
2332            ]
2333        );
2334        assert_ne!(
2335            entries[0]["digest"], entries[1]["digest"],
2336            "two versions of one extension are two artifacts"
2337        );
2338
2339        // …and one version deposited twice is still a true duplicate.
2340        let mut dup = spec;
2341        dup.tools = vec![
2342            payload("pub.ext", "1.0.0", Some(PayloadKind::Vsix), None),
2343            payload("pub.ext", "1.0.0", Some(PayloadKind::Vsix), None),
2344        ];
2345        let err = deposit(&dup, &sk, "k", &tmp.path().join("e")).unwrap_err();
2346        assert!(
2347            matches!(&err, DepositError::DuplicatePayload { name, version, .. }
2348                     if name == "pub.ext" && version == "1.0.0"),
2349            "got: {err}"
2350        );
2351    }
2352
2353    // rivet: verifies REQ-STORE-002
2354    #[test]
2355    fn a_tool_may_not_appear_twice_under_one_name_however_its_versions_differ() {
2356        // Clause 1's other half, and the reason the rule is not simply
2357        // "(name, version)": dispatch is BY NAME. `varve run synth` must have
2358        // exactly one answer, so two versions of one TOOL in one layer is a
2359        // real error — and the error must name both versions, or the depositor
2360        // cannot tell which two entries collided.
2361        use crate::kind::PayloadKind;
2362        let (sk, _) = generate_root_keypair();
2363        let tmp = tempfile::tempdir().unwrap();
2364        let mut spec = spec();
2365        spec.tools = vec![
2366            payload("synth", "0.45.0", Some(PayloadKind::Tool), None),
2367            payload("synth", "0.46.0", None, None), // absent kind == tool
2368        ];
2369        let err = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap_err();
2370        let msg = err.to_string();
2371        assert!(
2372            matches!(&err, DepositError::DuplicateTool { name, .. } if name == "synth"),
2373            "got: {err}"
2374        );
2375        assert!(msg.contains("0.45.0") && msg.contains("0.46.0"), "{msg}");
2376        // The identity includes the platform, so the verdict must name it —
2377        // otherwise a depositor of a cross-platform layer is told two entries
2378        // collide without being told on WHICH platform they do.
2379        assert!(
2380            msg.contains("any"),
2381            "an unstamped entry is any-platform: {msg}"
2382        );
2383        let mut stamped = spec;
2384        for tool in &mut stamped.tools {
2385            tool.platform = Some("x86_64-unknown-linux-gnu".into());
2386        }
2387        let msg = deposit(&stamped, &sk, "k", &tmp.path().join("e"))
2388            .unwrap_err()
2389            .to_string();
2390        assert!(msg.contains("x86_64-unknown-linux-gnu"), "{msg}");
2391    }
2392
2393    // rivet: verifies REQ-STORE-002
2394    #[test]
2395    fn one_version_deposited_twice_is_still_refused_and_the_error_names_it() {
2396        // Clause 3: relaxing the check must refuse only TRUE duplicates. Two
2397        // entries with ONE identity are the same payload twice — only one set
2398        // of bytes could land, so this stays an error, and the message carries
2399        // the version the old one lacked.
2400        use crate::kind::PayloadKind;
2401        let (sk, _) = generate_root_keypair();
2402        let tmp = tempfile::tempdir().unwrap();
2403        let mut spec = spec();
2404        spec.tools = vec![
2405            payload("serde", "1.0.200", Some(PayloadKind::Crate), None),
2406            payload("serde", "1.0.200", Some(PayloadKind::Crate), None),
2407        ];
2408        let err = deposit(&spec, &sk, "k", &tmp.path().join("d")).unwrap_err();
2409        let msg = err.to_string();
2410        assert!(
2411            matches!(&err, DepositError::DuplicatePayload { name, version, .. }
2412                if name == "serde" && version == "1.0.200"),
2413            "got: {err}"
2414        );
2415        assert!(msg.contains("serde") && msg.contains("1.0.200"), "{msg}");
2416    }
2417
2418    // rivet: verifies REQ-STORE-002
2419    #[test]
2420    fn platform_still_separates_identities_for_both_rules() {
2421        // Clause 1 keeps `platform` in BOTH keys. The same tool for two
2422        // platforms is the ordinary cross-platform layer (install filters to
2423        // one), and the same crate for two platforms must likewise be allowed —
2424        // dropping platform from the key would refuse layers that install fine.
2425        use crate::kind::PayloadKind;
2426        let (sk, _) = generate_root_keypair();
2427        let tmp = tempfile::tempdir().unwrap();
2428        let mut spec = spec();
2429        spec.tools = vec![
2430            payload("synth", "0.45.0", None, Some("aarch64-apple-darwin")),
2431            payload("synth", "0.45.0", None, Some("x86_64-unknown-linux-gnu")),
2432            payload(
2433                "serde",
2434                "1.0.200",
2435                Some(PayloadKind::Crate),
2436                Some("aarch64-apple-darwin"),
2437            ),
2438            payload(
2439                "serde",
2440                "1.0.200",
2441                Some(PayloadKind::Crate),
2442                Some("x86_64-unknown-linux-gnu"),
2443            ),
2444        ];
2445        deposit(&spec, &sk, "k", &tmp.path().join("d")).expect(
2446            "distinct platforms, distinct
2447             identities",
2448        );
2449    }
2450
2451    // rivet: verifies REQ-STORE-002
2452    #[test]
2453    fn the_signed_digest_does_not_depend_on_the_order_versions_are_listed_in() {
2454        // The payload is sorted by the FULL identity now that one name can
2455        // appear more than once. Sorting by (name, platform) alone left two
2456        // versions of one name in spec order, so the same layer deposited from
2457        // a reordered spec would have produced a DIFFERENT digest — and the
2458        // digest is the identity a pin freezes against.
2459        use crate::kind::PayloadKind;
2460        let (sk, _) = generate_root_keypair();
2461        let tmp = tempfile::tempdir().unwrap();
2462        let a_first = vec![
2463            payload("serde", "1.0.200", Some(PayloadKind::Crate), None),
2464            payload("serde", "1.0.210", Some(PayloadKind::Crate), None),
2465        ];
2466        let b_first: Vec<DepositTool> = a_first.iter().rev().cloned().collect();
2467        let mut s1 = spec();
2468        s1.tools = a_first;
2469        let mut s2 = spec();
2470        s2.tools = b_first;
2471        assert_eq!(
2472            deposit(&s1, &sk, "k", &tmp.path().join("a"))
2473                .unwrap()
2474                .digest,
2475            deposit(&s2, &sk, "k", &tmp.path().join("b"))
2476                .unwrap()
2477                .digest,
2478        );
2479    }
2480
2481    // rivet: verifies REQ-SIGNERSEAM-001
2482    #[test]
2483    fn deposit_through_a_non_file_signer_is_byte_identical_and_self_verifies() {
2484        let (sk, _) = generate_root_keypair();
2485        let tmp = tempfile::tempdir().unwrap();
2486        let by_key = deposit(&spec(), &sk, "mock-1", &tmp.path().join("a")).unwrap();
2487
2488        let mock = crate::verify::testsigner::CountingSigner::new(&sk);
2489        let by_signer = deposit_with_signer(
2490            &spec(),
2491            &mock,
2492            &tmp.path().join("b"),
2493            &DepositOptions::default(),
2494        )
2495        .unwrap();
2496        assert_eq!(mock.calls(), 1, "one manifest, one signature");
2497        assert_eq!(by_key.digest, by_signer.digest);
2498    }
2499}