Skip to main content

varve_core/
attestcarry.rs

1//! Carrying attestations with the layer (REQ-ATTEST-002).
2//!
3//! v0.22.0 shipped BINDING — `sign-attestation` / `check-attestation` — and a
4//! review found REQ-ATTEST-001 marked verified with this half unimplemented.
5//! Binding says "this attestation belongs to that layer". Carriage is what
6//! makes the claim reach anyone: attestations attached to a deposit layout as
7//! referrer artifacts, surviving `archive` and an offline install, and
8//! reported by `varve verify`.
9//!
10//! Why it matters more than it sounds: registries DO publish this evidence and
11//! mirroring tools DROP it. bandersnatch and Verdaccio carry no attestations,
12//! and every Bazel Central Registry attestation URL points at github.com — so
13//! the moment a consumer crosses an air gap they receive the bytes without the
14//! evidence about them, and no error says so. A layer that travels without its
15//! attestations is not less trustworthy; it is less ACCOUNTABLE, and the
16//! consumer cannot tell the difference from the inside.
17//!
18//! Two blobs travel per attestation: the signed STATEMENT (varve's assertion
19//! about the attestation) and the attestation BYTES themselves, verbatim. varve
20//! never re-signs another party's judgement — re-signing would launder it under
21//! this root and an assessor could no longer tell who asserted what (DD-021).
22//!
23//! The referrer machinery is line-status's (REQ-STATUS-DIST-001) rather than a
24//! second shape, with one deliberate difference: a line has exactly one status,
25//! so attaching REPLACES; a layer has many attestations, so attaching ADDS and
26//! is keyed by the statement's own digest.
27
28use std::path::Path;
29
30use crate::attest::{AttestError, AttestationStatement};
31
32/// Artifact type for a carried attestation statement.
33pub const STATEMENT_ARTIFACT_TYPE: &str = crate::attest::PAYLOAD_TYPE;
34
35/// Artifact type for the attested bytes travelling verbatim beside it.
36pub const ATTESTATION_ARTIFACT_TYPE: &str =
37    "application/vnd.pulseengine.varve.attestation-bytes.v1";
38
39/// Annotation linking carried bytes back to the statement about them.
40pub const ANN_STATEMENT: &str = "eu.pulseengine.varve.attests";
41
42#[derive(Debug, thiserror::Error)]
43pub enum CarryError {
44    #[error(transparent)]
45    Attest(#[from] AttestError),
46    #[error("io error at {path}")]
47    Io {
48        path: String,
49        #[source]
50        source: std::io::Error,
51    },
52    #[error("{path}: {reason}")]
53    Layout { path: String, reason: String },
54    #[error(
55        "layer {layer} carries an attestation statement whose attested bytes are not present in \
56         the layout (statement {statement}, expected blob {digest}). The statement travelled and \
57         the evidence did not — which is exactly the mirror-boundary failure carriage exists to \
58         prevent."
59    )]
60    OrphanStatement {
61        layer: String,
62        statement: String,
63        digest: String,
64    },
65    #[error(
66        "layer {layer}: the layout index names an attestation blob '{digest}', which is not a \
67         sha256 content address — refusing to resolve it as a path"
68    )]
69    MalformedDigest { layer: String, digest: String },
70    #[error(transparent)]
71    Source(#[from] crate::source::SourceError),
72}
73
74/// One attestation as it sits in a layout.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct CarriedAttestation {
77    /// Digest of the signed statement envelope.
78    pub statement_digest: String,
79    /// The statement envelope bytes.
80    pub statement: Vec<u8>,
81    /// The attested bytes, verbatim as the producer emitted them.
82    pub bytes: Vec<u8>,
83}
84
85/// What `verify` reports about one carried attestation.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct AttestationReport {
88    pub kind: String,
89    pub producer: String,
90    /// Whether the statement verifies against the trust root AND still binds
91    /// to this layer and these bytes.
92    pub binds: bool,
93    /// Why not, when it does not.
94    pub reason: Option<String>,
95    /// The passthrough policy of the session that SIGNED the statement
96    /// (REQ-PASSTHROUGH-001 clause 4): empty for a pure session, and for a
97    /// statement that did not verify (nothing it says can be trusted).
98    pub ambient_tools: Vec<String>,
99}
100
101fn io(path: &Path, source: std::io::Error) -> CarryError {
102    CarryError::Io {
103        path: path.display().to_string(),
104        source,
105    }
106}
107
108fn blob_path(layout: &Path, digest: &str) -> std::path::PathBuf {
109    layout
110        .join("blobs")
111        .join("sha256")
112        .join(digest.strip_prefix("sha256:").unwrap_or(digest))
113}
114
115/// Is `digest` a well-formed `sha256:<64 hex>` content address?
116///
117/// UNTRUSTED-INPUT GUARD. Every digest in a layout's `index.json` is a string
118/// a mirror wrote, and `blob_path` turns it into a PATH COMPONENT: an entry
119/// reading `sha256:../../../../etc/whatever` would escape the layout, and the
120/// caller then WRITES a file named after it into the installed layer root. A
121/// content address is precisely the value that must never be taken on faith by
122/// the code that resolves it.
123fn is_content_address(digest: &str) -> bool {
124    digest
125        .strip_prefix("sha256:")
126        .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
127}
128
129/// Attach an attestation to a deposit layout: both blobs, plus two referrer
130/// entries. Idempotent — re-attaching the same statement replaces its entries
131/// rather than duplicating them, so a re-run CI step stays clean.
132pub fn attach(
133    layout: &Path,
134    statement_envelope: &[u8],
135    attested_bytes: &[u8],
136) -> Result<String, CarryError> {
137    let st_digest = crate::store::manifest_digest(statement_envelope);
138    let bytes_digest = crate::store::manifest_digest(attested_bytes);
139
140    let dir = layout.join("blobs").join("sha256");
141    std::fs::create_dir_all(&dir).map_err(|e| io(&dir, e))?;
142    for (digest, content) in [
143        (&st_digest, statement_envelope),
144        (&bytes_digest, attested_bytes),
145    ] {
146        let p = blob_path(layout, digest);
147        std::fs::write(&p, content).map_err(|e| io(&p, e))?;
148    }
149
150    let index_path = layout.join("index.json");
151    let mut index: serde_json::Value =
152        serde_json::from_slice(&std::fs::read(&index_path).map_err(|e| io(&index_path, e))?)
153            .map_err(|e| CarryError::Layout {
154                path: index_path.display().to_string(),
155                reason: format!("index.json: {e}"),
156            })?;
157    let entries = index["manifests"]
158        .as_array_mut()
159        .ok_or_else(|| CarryError::Layout {
160            path: index_path.display().to_string(),
161            reason: "index.json has no manifests array".into(),
162        })?;
163    // Replace THIS statement's entries only. A layer has many attestations, so
164    // unlike line-status this must not clear the others.
165    entries.retain(|e| {
166        !(e["digest"] == *st_digest
167            || (e["artifactType"] == ATTESTATION_ARTIFACT_TYPE
168                && e["annotations"][ANN_STATEMENT] == *st_digest))
169    });
170    entries.push(serde_json::json!({
171        "mediaType": "application/json",
172        "artifactType": STATEMENT_ARTIFACT_TYPE,
173        "digest": st_digest,
174        "size": statement_envelope.len(),
175    }));
176    entries.push(serde_json::json!({
177        "mediaType": "application/octet-stream",
178        "artifactType": ATTESTATION_ARTIFACT_TYPE,
179        "digest": bytes_digest,
180        "size": attested_bytes.len(),
181        "annotations": { ANN_STATEMENT: st_digest }
182    }));
183    std::fs::write(
184        &index_path,
185        serde_json::to_vec_pretty(&index).expect("index serializes"),
186    )
187    .map_err(|e| io(&index_path, e))?;
188    Ok(st_digest)
189}
190
191/// Every attestation a layout carries. A statement whose attested bytes are
192/// absent is an ERROR, not a skipped entry: that is precisely the
193/// mirror-boundary failure this requirement exists to catch, and dropping it
194/// silently would reproduce the bug in the code meant to detect it.
195pub fn read_all(layout: &Path, layer: &str) -> Result<Vec<CarriedAttestation>, CarryError> {
196    let index_path = layout.join("index.json");
197    let bytes = match std::fs::read(&index_path) {
198        Ok(b) => b,
199        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
200        Err(source) => return Err(io(&index_path, source)),
201    };
202    let index: serde_json::Value =
203        serde_json::from_slice(&bytes).map_err(|e| CarryError::Layout {
204            path: index_path.display().to_string(),
205            reason: format!("index.json: {e}"),
206        })?;
207    let Some(entries) = index["manifests"].as_array() else {
208        return Ok(Vec::new());
209    };
210
211    let mut out = Vec::new();
212    for entry in entries {
213        if entry["artifactType"] != STATEMENT_ARTIFACT_TYPE {
214            continue;
215        }
216        let Some(st_digest) = entry["digest"].as_str() else {
217            continue;
218        };
219        if !is_content_address(st_digest) {
220            return Err(CarryError::MalformedDigest {
221                layer: layer.to_string(),
222                digest: st_digest.to_string(),
223            });
224        }
225        let st_path = blob_path(layout, st_digest);
226        let statement = std::fs::read(&st_path).map_err(|e| io(&st_path, e))?;
227
228        // Find the bytes this statement is about.
229        let bytes_digest = entries
230            .iter()
231            .find(|e| {
232                e["artifactType"] == ATTESTATION_ARTIFACT_TYPE
233                    && e["annotations"][ANN_STATEMENT] == *st_digest
234            })
235            .and_then(|e| e["digest"].as_str());
236        let Some(bytes_digest) = bytes_digest else {
237            return Err(CarryError::OrphanStatement {
238                layer: layer.to_string(),
239                statement: st_digest.to_string(),
240                digest: "<no referrer entry>".into(),
241            });
242        };
243        if !is_content_address(bytes_digest) {
244            return Err(CarryError::MalformedDigest {
245                layer: layer.to_string(),
246                digest: bytes_digest.to_string(),
247            });
248        }
249        let b_path = blob_path(layout, bytes_digest);
250        let attested = std::fs::read(&b_path).map_err(|_| CarryError::OrphanStatement {
251            layer: layer.to_string(),
252            statement: st_digest.to_string(),
253            digest: bytes_digest.to_string(),
254        })?;
255        out.push(CarriedAttestation {
256            statement_digest: st_digest.to_string(),
257            statement,
258            bytes: attested,
259        });
260    }
261    // Same deterministic order as `read_persisted`. These two readers agreed
262    // by luck until a full-suite run disagreed: index order here, `read_dir`
263    // order there, and `read_dir` order is filesystem-dependent. Evidence that
264    // reshuffles between runs is a diff generator for anyone recording verify
265    // output, and an order-dependent test is a flake waiting to be explained
266    // away.
267    out.sort_by(|a, b| a.statement_digest.cmp(&b.statement_digest));
268    Ok(out)
269}
270
271/// Report on every carried attestation: does it verify against the root, and
272/// does it still bind to THIS layer and THESE bytes?
273///
274/// Reporting, not refusing. An attestation that no longer binds is evidence
275/// about the evidence — a consumer must see it, but a layer whose own
276/// signature and digests are good is still a good layer. Failing the install
277/// on a third party's stale audit would make varve's verdict depend on someone
278/// else's release cadence.
279pub fn report(
280    carried: &[CarriedAttestation],
281    layer_manifest_digest: &str,
282    layer_name: &str,
283    trust: &crate::keyroles::RealmTrust,
284) -> Vec<AttestationReport> {
285    carried
286        .iter()
287        .map(|c| {
288            let st: AttestationStatement =
289                match crate::attest::verify_statement(&c.statement, trust) {
290                    Ok(st) => st,
291                    Err(e) => {
292                        return AttestationReport {
293                            kind: "<unverified>".into(),
294                            producer: "<unverified>".into(),
295                            binds: false,
296                            reason: Some(e.to_string()),
297                            ambient_tools: Vec::new(),
298                        };
299                    }
300                };
301            let reason = crate::attest::check(&st, &c.bytes, layer_manifest_digest, layer_name)
302                .err()
303                .map(|e| e.to_string());
304            AttestationReport {
305                kind: st.kind.to_string(),
306                producer: st.producer.clone(),
307                binds: reason.is_none(),
308                reason,
309                ambient_tools: st.ambient_tools.clone(),
310            }
311        })
312        .collect()
313}
314
315/// Where an installed layer keeps the attestations that travelled with it.
316pub const STORE_DIR: &str = "attestations";
317
318/// Persist carried attestations into an installed layer's root, so they
319/// survive into `archive` and an offline re-export. Without this the evidence
320/// reaches the machine and then dies there — the same mirror-boundary loss,
321/// one hop later.
322pub fn persist(layer_root: &Path, carried: &[CarriedAttestation]) -> Result<(), CarryError> {
323    if carried.is_empty() {
324        return Ok(());
325    }
326    let dir = layer_root.join(STORE_DIR);
327    std::fs::create_dir_all(&dir).map_err(|e| io(&dir, e))?;
328    for c in carried {
329        // The file name is derived from the bytes, never from the declared
330        // `statement_digest`. These records arrive from a SOURCE, and a source
331        // that could choose a file name inside the installed layer root could
332        // overwrite `layer.json` or the retained envelope — the two files the
333        // whole trust chain rests on. Re-deriving costs one hash and removes
334        // the source from the naming decision entirely.
335        let digest = crate::store::manifest_digest(&c.statement);
336        let stem = digest.strip_prefix("sha256:").unwrap_or(&digest);
337        let st = dir.join(format!("{stem}.statement.json"));
338        std::fs::write(&st, &c.statement).map_err(|e| io(&st, e))?;
339        let by = dir.join(format!("{stem}.bytes"));
340        std::fs::write(&by, &c.bytes).map_err(|e| io(&by, e))?;
341    }
342    Ok(())
343}
344
345/// Read back what `persist` wrote. A statement without its bytes is an error
346/// here too — the loss is the thing being detected, wherever it happens.
347pub fn read_persisted(
348    layer_root: &Path,
349    layer: &str,
350) -> Result<Vec<CarriedAttestation>, CarryError> {
351    let dir = layer_root.join(STORE_DIR);
352    let entries = match std::fs::read_dir(&dir) {
353        Ok(e) => e,
354        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
355        Err(source) => return Err(io(&dir, source)),
356    };
357    let mut out = Vec::new();
358    for entry in entries {
359        let path = entry.map_err(|e| io(&dir, e))?.path();
360        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
361            continue;
362        };
363        let Some(stem) = name.strip_suffix(".statement.json") else {
364            continue;
365        };
366        let statement = std::fs::read(&path).map_err(|e| io(&path, e))?;
367        let bytes_path = dir.join(format!("{stem}.bytes"));
368        let bytes = std::fs::read(&bytes_path).map_err(|_| CarryError::OrphanStatement {
369            layer: layer.to_string(),
370            statement: format!("sha256:{stem}"),
371            digest: bytes_path.display().to_string(),
372        })?;
373        out.push(CarriedAttestation {
374            statement_digest: format!("sha256:{stem}"),
375            statement,
376            bytes,
377        });
378    }
379    // Deterministic order — see the note in `read_all`.
380    out.sort_by(|a, b| a.statement_digest.cmp(&b.statement_digest));
381    Ok(out)
382}
383
384/// Install-time carriage: take whatever attestations the source carries beside
385/// the layer and persist them into the installed layer root. Returns how many
386/// travelled.
387///
388/// Nothing here is verified, deliberately. The bytes are a third party's
389/// evidence arriving over an untrusted transport; verifying at fetch time would
390/// mean a stale or foreign-signed attestation could fail an install whose own
391/// signature and digests are perfect, making varve's verdict a function of
392/// someone else's release cadence. The check belongs at `verify`, where it is
393/// REPORTED (`report_installed`). What carriage owes the consumer is that the
394/// evidence is not silently dropped — the failure mode bandersnatch and
395/// Verdaccio actually exhibit.
396pub fn carry_from_source(
397    source: &dyn crate::source::LayerSource,
398    layer: &crate::source::LayerRef,
399    layer_root: &Path,
400) -> Result<usize, CarryError> {
401    let carried = source.fetch_attestations(layer)?;
402    persist(layer_root, &carried)?;
403    Ok(carried.len())
404}
405
406/// What `varve verify` says about an installed layer's carried attestations:
407/// for each, its kind, its producer, and whether it STILL binds to this layer
408/// and these bytes under the trust root.
409///
410/// `layer_manifest_digest` and `layer_name` must be the values the caller has
411/// already RE-VERIFIED (`reverify::verify_installed`), not the store's
412/// directory name and `layer.json` read raw — those are local labels, and
413/// REQ-ATTEST-001 already shipped a defect where `check-attestation` joined on
414/// them and reported OK over a tampered layer.
415pub fn report_installed(
416    layer_root: &Path,
417    layer_name: &str,
418    layer_manifest_digest: &str,
419    trust: &crate::keyroles::RealmTrust,
420) -> Result<Vec<AttestationReport>, CarryError> {
421    let carried = read_persisted(layer_root, layer_name)?;
422    Ok(report(&carried, layer_manifest_digest, layer_name, trust))
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use crate::attest::{AttestationKind, sign, statement};
429    use crate::verify::generate_root_keypair;
430
431    /// A minimal layout with an index.json, as `deposit` writes.
432    fn layout() -> tempfile::TempDir {
433        let tmp = tempfile::tempdir().unwrap();
434        std::fs::write(
435            tmp.path().join("index.json"),
436            br#"{"schemaVersion":2,"manifests":[]}"#,
437        )
438        .unwrap();
439        tmp
440    }
441
442    const LAYER: &str = "2026.08.0";
443    const LAYER_DIGEST: &str =
444        "sha256:1111111111111111111111111111111111111111111111111111111111111111";
445
446    // rivet: verifies REQ-ATTEST-002
447    #[test]
448    fn an_attestation_travels_with_the_layer_and_still_binds() {
449        // The whole point: the statement AND the bytes cross the boundary, and
450        // the claim is still checkable on the far side with no network.
451        let (sk, pk) = generate_root_keypair();
452        let tmp = layout();
453        let bytes = br#"{"_type":"https://in-toto.io/Statement/v1","subject":[]}"#;
454        let st = statement(
455            LAYER,
456            LAYER_DIGEST,
457            AttestationKind::Provenance,
458            bytes,
459            "acme-ci",
460        );
461        let envelope = sign(&st, &sk, "root-1").unwrap();
462
463        attach(tmp.path(), envelope.as_bytes(), bytes).unwrap();
464
465        let carried = read_all(tmp.path(), LAYER).unwrap();
466        assert_eq!(carried.len(), 1, "one attestation carried");
467        assert_eq!(
468            carried[0].bytes, bytes,
469            "the attested bytes travel VERBATIM — varve carries another party's \
470             judgement, it does not restate it"
471        );
472
473        let reports = report(
474            &carried,
475            LAYER_DIGEST,
476            LAYER,
477            &crate::keyroles::test_support::rt(&pk),
478        );
479        assert_eq!(reports.len(), 1);
480        assert!(reports[0].binds, "reason: {:?}", reports[0].reason);
481        assert_eq!(reports[0].producer, "acme-ci");
482    }
483
484    // rivet: verifies REQ-PASSTHROUGH-001
485    #[test]
486    fn the_report_carries_the_signing_sessions_ambient_tools_binding_or_not() {
487        // Clause 4. A statement that verifies but no longer binds still says
488        // what its signer's session allowed; one that does not verify says
489        // nothing, because nothing it states can be trusted.
490        let (sk, pk) = generate_root_keypair();
491        let trust = crate::keyroles::test_support::rt(&pk);
492        let bytes = br#"{"_type":"https://in-toto.io/Statement/v1","subject":[]}"#;
493        let carry = |ambient: &[&str]| {
494            let st = statement(
495                LAYER,
496                LAYER_DIGEST,
497                AttestationKind::Provenance,
498                bytes,
499                "acme-ci",
500            )
501            .with_ambient_tools(ambient.iter().map(|s| s.to_string()).collect());
502            let envelope = sign(&st, &sk, "root-1").unwrap();
503            let tmp = layout();
504            attach(tmp.path(), envelope.as_bytes(), bytes).unwrap();
505            read_all(tmp.path(), LAYER).unwrap()
506        };
507        let pure = report(&carry(&[]), LAYER_DIGEST, LAYER, &trust);
508        assert!(pure[0].binds && pure[0].ambient_tools.is_empty());
509
510        let amb = carry(&["ghost"]);
511        let binding = report(&amb, LAYER_DIGEST, LAYER, &trust);
512        assert!(binding[0].binds);
513        assert_eq!(binding[0].ambient_tools, ["ghost"]);
514
515        let other = "sha256:2222222222222222222222222222222222222222222222222222222222222222";
516        let stale = report(&amb, other, LAYER, &trust);
517        assert!(!stale[0].binds);
518        assert_eq!(stale[0].ambient_tools, ["ghost"]);
519
520        let (_, other_pk) = generate_root_keypair();
521        let forged = report(
522            &amb,
523            LAYER_DIGEST,
524            LAYER,
525            &crate::keyroles::test_support::rt(&other_pk),
526        );
527        assert!(!forged[0].binds);
528        assert!(forged[0].ambient_tools.is_empty());
529    }
530
531    // rivet: verifies REQ-ATTEST-002
532    #[test]
533    fn a_statement_whose_evidence_did_not_travel_is_an_error_not_a_skip() {
534        // THE mirror-boundary failure. bandersnatch and Verdaccio drop
535        // attestations; a consumer must not receive a layout that looks
536        // attested while the evidence is gone. Silently skipping the entry
537        // would reproduce, inside the detector, the exact bug it exists to
538        // detect.
539        let (sk, _pk) = generate_root_keypair();
540        let tmp = layout();
541        let bytes = b"the-evidence";
542        let st = statement(LAYER, LAYER_DIGEST, AttestationKind::Sbom, bytes, "acme-ci");
543        let envelope = sign(&st, &sk, "root-1").unwrap();
544        attach(tmp.path(), envelope.as_bytes(), bytes).unwrap();
545
546        // A mirror drops the evidence blob but keeps the index entry.
547        std::fs::remove_file(blob_path(tmp.path(), &crate::store::manifest_digest(bytes))).unwrap();
548
549        let err = read_all(tmp.path(), LAYER).expect_err("an orphaned statement must be an error");
550        let msg = err.to_string();
551        assert!(msg.contains(LAYER), "names the layer: {msg}");
552        assert!(
553            msg.contains("did not"),
554            "says the evidence failed to travel, not merely that a file is absent: {msg}"
555        );
556    }
557
558    // rivet: verifies REQ-ATTEST-002
559    #[test]
560    fn an_attestation_for_another_layer_is_reported_as_not_binding() {
561        // Carriage must not launder a mis-issued statement into looking
562        // attached just because it physically travelled beside the layer.
563        let (sk, pk) = generate_root_keypair();
564        let tmp = layout();
565        let bytes = b"evidence-for-someone-else";
566        let other = "sha256:2222222222222222222222222222222222222222222222222222222222222222";
567        let st = statement(
568            "2026.01.0",
569            other,
570            AttestationKind::Provenance,
571            bytes,
572            "acme-ci",
573        );
574        attach(
575            tmp.path(),
576            sign(&st, &sk, "root-1").unwrap().as_bytes(),
577            bytes,
578        )
579        .unwrap();
580
581        let carried = read_all(tmp.path(), LAYER).unwrap();
582        let reports = report(
583            &carried,
584            LAYER_DIGEST,
585            LAYER,
586            &crate::keyroles::test_support::rt(&pk),
587        );
588        assert!(
589            !reports[0].binds,
590            "a statement for another layer must not bind"
591        );
592        assert!(
593            reports[0].reason.as_ref().unwrap().contains("refusing"),
594            "the reason must say what was refused: {:?}",
595            reports[0].reason
596        );
597    }
598
599    // rivet: verifies REQ-ATTEST-002
600    #[test]
601    fn an_attestation_signed_by_someone_else_does_not_bind() {
602        // The carried statement is varve's own assertion, so it must verify
603        // under the realm's root. Physical proximity in a layout is not
604        // evidence of anything.
605        let (impostor_sk, _) = generate_root_keypair();
606        let (_realm_sk, realm_pk) = generate_root_keypair();
607        let tmp = layout();
608        let bytes = b"evidence";
609        let st = statement(
610            LAYER,
611            LAYER_DIGEST,
612            AttestationKind::Provenance,
613            bytes,
614            "acme-ci",
615        );
616        attach(
617            tmp.path(),
618            sign(&st, &impostor_sk, "not-the-realm").unwrap().as_bytes(),
619            bytes,
620        )
621        .unwrap();
622
623        let carried = read_all(tmp.path(), LAYER).unwrap();
624        let reports = report(
625            &carried,
626            LAYER_DIGEST,
627            LAYER,
628            &crate::keyroles::test_support::rt(&realm_pk),
629        );
630        assert!(!reports[0].binds);
631        assert_eq!(
632            reports[0].kind, "<unverified>",
633            "an unverified statement's own claims must not be echoed as fact"
634        );
635    }
636
637    // rivet: verifies REQ-ATTEST-002
638    #[test]
639    fn many_attestations_travel_together_and_reattaching_is_idempotent() {
640        // A line-status is one per line and attaching REPLACES. A layer has an
641        // SBOM and a provenance and an audit; attaching must ADD. Getting this
642        // wrong would silently keep only the last one attached.
643        let (sk, pk) = generate_root_keypair();
644        let tmp = layout();
645        let sbom = b"sbom-bytes";
646        let slsa = b"slsa-bytes";
647        for (kind, bytes) in [
648            (AttestationKind::Sbom, sbom.as_slice()),
649            (AttestationKind::Provenance, slsa.as_slice()),
650        ] {
651            let st = statement(LAYER, LAYER_DIGEST, kind, bytes, "acme-ci");
652            attach(
653                tmp.path(),
654                sign(&st, &sk, "root-1").unwrap().as_bytes(),
655                bytes,
656            )
657            .unwrap();
658        }
659        assert_eq!(
660            read_all(tmp.path(), LAYER).unwrap().len(),
661            2,
662            "both carried"
663        );
664
665        // Re-attaching one (a CI re-run) must not duplicate it.
666        let st = statement(LAYER, LAYER_DIGEST, AttestationKind::Sbom, sbom, "acme-ci");
667        attach(
668            tmp.path(),
669            sign(&st, &sk, "root-1").unwrap().as_bytes(),
670            sbom,
671        )
672        .unwrap();
673        let carried = read_all(tmp.path(), LAYER).unwrap();
674        assert_eq!(carried.len(), 2, "re-attaching replaces, never duplicates");
675        // The INDEX itself must not grow either. Two attestations are four
676        // referrer entries, before and after the re-run — a reader that
677        // deduplicates by taking the first match would hide an index quietly
678        // accumulating a stale entry per CI re-run, and the layout is what
679        // `oras cp` publishes, byte for byte.
680        let index: serde_json::Value =
681            serde_json::from_slice(&std::fs::read(tmp.path().join("index.json")).unwrap()).unwrap();
682        assert_eq!(
683            index["manifests"].as_array().unwrap().len(),
684            4,
685            "two attestations are two statements and two payloads — no more, however \
686             many times CI re-runs: {index:#}"
687        );
688        // …and it replaces the RIGHT one. Counting is not enough: a retain
689        // predicate that evicts the other attestations and re-adds this one
690        // twice also counts two, and would silently turn an SBOM+provenance
691        // pair into two copies of the SBOM.
692        let mut kinds: Vec<String> = report(
693            &carried,
694            LAYER_DIGEST,
695            LAYER,
696            &crate::keyroles::test_support::rt(&pk),
697        )
698        .into_iter()
699        .map(|r| r.kind)
700        .collect();
701        kinds.sort();
702        assert_eq!(
703            kinds,
704            vec!["provenance".to_string(), "sbom".to_string()],
705            "re-attaching one attestation must not evict the others — that is the one \
706             deliberate difference from line-status, where attaching REPLACES"
707        );
708        assert!(
709            report(
710                &carried,
711                LAYER_DIGEST,
712                LAYER,
713                &crate::keyroles::test_support::rt(&pk)
714            )
715            .iter()
716            .all(|r| r.binds)
717        );
718    }
719
720    // rivet: verifies REQ-ATTEST-002
721    #[test]
722    fn evidence_survives_the_store_and_can_be_re_emitted() {
723        // The requirement's actual subject: the evidence must cross the air
724        // gap, not merely reach the machine. bandersnatch and Verdaccio drop
725        // attestations and every BCR attestation URL points at github.com, so
726        // a consumer downstream of a mirror gets bytes with no accountability
727        // and no error saying so. Persisting into the installed layer is what
728        // lets `archive` put it back on the wire.
729        let (sk, pk) = generate_root_keypair();
730        let src = layout();
731        let sbom = b"sbom-bytes";
732        let prov = b"provenance-bytes";
733        for (kind, bytes) in [
734            (AttestationKind::Sbom, sbom.as_slice()),
735            (AttestationKind::Provenance, prov.as_slice()),
736        ] {
737            let st = statement(LAYER, LAYER_DIGEST, kind, bytes, "acme-ci");
738            attach(
739                src.path(),
740                sign(&st, &sk, "root-1").unwrap().as_bytes(),
741                bytes,
742            )
743            .unwrap();
744        }
745        let carried = read_all(src.path(), LAYER).unwrap();
746
747        // Install persists it into the layer root…
748        let installed = tempfile::tempdir().unwrap();
749        persist(installed.path(), &carried).unwrap();
750        let back = read_persisted(installed.path(), LAYER).unwrap();
751        assert_eq!(back.len(), 2, "both attestations survive the store");
752
753        // …and it re-emits into a fresh layout, byte-identical, still binding
754        // with NO network and NO trust in the transport.
755        let dest = layout();
756        for c in &back {
757            attach(dest.path(), &c.statement, &c.bytes).unwrap();
758        }
759        let round_tripped = read_all(dest.path(), LAYER).unwrap();
760        assert_eq!(
761            round_tripped, carried,
762            "the evidence that crossed the gap is the evidence that was signed"
763        );
764        assert!(
765            report(
766                &round_tripped,
767                LAYER_DIGEST,
768                LAYER,
769                &crate::keyroles::test_support::rt(&pk)
770            )
771            .iter()
772            .all(|r| r.binds),
773            "every attestation still binds on the far side"
774        );
775    }
776
777    // rivet: verifies REQ-ATTEST-002
778    #[test]
779    fn verify_reports_each_carried_attestation_and_whether_it_still_binds() {
780        // What `varve verify` actually calls. Two attestations under the same
781        // root: one issued for THIS layer, one for another. Both are reported —
782        // reporting, not refusal, is the decision (a layer whose own signature
783        // and digests are good is still a good layer) — but the one that no
784        // longer binds must say so, with its reason, or carriage would launder
785        // a mis-issued statement into looking attached just because it
786        // physically travelled.
787        let (sk, pk) = generate_root_keypair();
788        let installed = tempfile::tempdir().unwrap();
789        let mine = b"sbom-for-this-layer";
790        let theirs = b"audit-for-another-layer";
791        let good = statement(LAYER, LAYER_DIGEST, AttestationKind::Sbom, mine, "acme-ci");
792        let other = statement(
793            "2026.01.0",
794            "sha256:2222222222222222222222222222222222222222222222222222222222222222",
795            AttestationKind::Audit,
796            theirs,
797            "someone-else",
798        );
799        let carried: Vec<CarriedAttestation> =
800            [(&good, mine.as_slice()), (&other, theirs.as_slice())]
801                .into_iter()
802                .map(|(st, bytes)| {
803                    let envelope = sign(st, &sk, "root-1").unwrap();
804                    CarriedAttestation {
805                        statement_digest: crate::store::manifest_digest(envelope.as_bytes()),
806                        statement: envelope.into_bytes(),
807                        bytes: bytes.to_vec(),
808                    }
809                })
810                .collect();
811        persist(installed.path(), &carried).unwrap();
812
813        let reports = report_installed(
814            installed.path(),
815            LAYER,
816            LAYER_DIGEST,
817            &crate::keyroles::test_support::rt(&pk),
818        )
819        .unwrap();
820        assert_eq!(reports.len(), 2, "verify must report EVERY attestation");
821        let sbom = reports.iter().find(|r| r.kind == "sbom").expect("sbom");
822        assert!(sbom.binds, "reason: {:?}", sbom.reason);
823        assert_eq!(sbom.producer, "acme-ci");
824        let audit = reports.iter().find(|r| r.kind == "audit").expect("audit");
825        assert!(
826            !audit.binds,
827            "a statement issued for another layer must not be reported as binding"
828        );
829        assert!(
830            audit.reason.as_ref().unwrap().contains("refusing"),
831            "the reason must say what was refused: {:?}",
832            audit.reason
833        );
834    }
835
836    // rivet: verifies REQ-ATTEST-002
837    #[test]
838    fn a_layer_carrying_nothing_reports_nothing_rather_than_failing() {
839        // Most layers carry no third-party evidence. Demanding some would make
840        // varve's verdict depend on other people's publishing habits.
841        let (_sk, pk) = generate_root_keypair();
842        let installed = tempfile::tempdir().unwrap();
843        assert!(
844            report_installed(
845                installed.path(),
846                LAYER,
847                LAYER_DIGEST,
848                &crate::keyroles::test_support::rt(&pk)
849            )
850            .unwrap()
851            .is_empty()
852        );
853    }
854
855    // rivet: verifies REQ-ATTEST-002
856    #[test]
857    fn install_time_carriage_takes_what_the_source_holds_and_trusts_none_of_it() {
858        // The seam install() runs through. The source is the party that would
859        // benefit from a forged statement, so carriage stores bytes and asks
860        // no questions — and the verdict is still correct afterwards because
861        // `report` re-checks against the root, not against the source.
862        let (impostor, _) = generate_root_keypair();
863        let (_realm_sk, realm_pk) = generate_root_keypair();
864        let bytes = b"evidence";
865        let st = statement(LAYER, LAYER_DIGEST, AttestationKind::Vex, bytes, "acme-ci");
866        let source = crate::source::MemorySource::new().with_attestation(
867            sign(&st, &impostor, "not-the-realm").unwrap().as_bytes(),
868            bytes,
869        );
870        let installed = tempfile::tempdir().unwrap();
871
872        let n = carry_from_source(
873            &source,
874            &crate::source::LayerRef::Name(LAYER.parse().unwrap()),
875            installed.path(),
876        )
877        .unwrap();
878        assert_eq!(n, 1, "the evidence is carried, not judged, at fetch time");
879
880        let reports = report_installed(
881            installed.path(),
882            LAYER,
883            LAYER_DIGEST,
884            &crate::keyroles::test_support::rt(&realm_pk),
885        )
886        .unwrap();
887        assert!(
888            !reports[0].binds,
889            "a statement signed by anyone but the realm's root must not bind"
890        );
891        assert_eq!(
892            reports[0].kind, "<unverified>",
893            "an unverified statement's own claims must not be echoed as fact"
894        );
895    }
896
897    // rivet: verifies REQ-ATTEST-002
898    #[test]
899    fn a_layout_naming_a_blob_outside_itself_is_refused_before_anything_is_read() {
900        // The digest in a layout index is a string a MIRROR wrote, and it is
901        // used as a path component. Left unchecked, `sha256:../../..` reads
902        // outside the layout and — one step later, through `persist` — names a
903        // file inside the installed layer root, where `layer.json` and the
904        // retained envelope live. A content address is exactly the value that
905        // must not be taken on faith by the code resolving it.
906        // BOTH halves of the shape matter and are checked here. The traversal
907        // is the attack; the short-but-hexadecimal case is the reason the rule
908        // is a conjunction — accepting anything that merely *looks* hex-ish
909        // lets a crafted name through on length alone, and a rule that fires
910        // for only one of its two conditions is not the rule.
911        for bad in [
912            "sha256:../../../../../../etc/passwd",
913            "sha256:abc",
914            "sha256:",
915            "not-a-digest-at-all",
916        ] {
917            let tmp = layout();
918            std::fs::write(
919                tmp.path().join("index.json"),
920                serde_json::to_vec_pretty(&serde_json::json!({
921                    "schemaVersion": 2,
922                    "manifests": [{
923                        "mediaType": "application/json",
924                        "artifactType": STATEMENT_ARTIFACT_TYPE,
925                        "digest": bad,
926                        "size": 1,
927                    }]
928                }))
929                .unwrap(),
930            )
931            .unwrap();
932            let err = read_all(tmp.path(), LAYER).expect_err("'{bad}' is not a content address");
933            assert!(
934                matches!(err, CarryError::MalformedDigest { .. }),
935                "'{bad}' must be refused as a malformed digest, not resolved as a path: {err}"
936            );
937        }
938    }
939
940    // rivet: verifies REQ-ATTEST-002
941    #[test]
942    fn persist_names_files_after_the_bytes_not_after_what_the_source_declared() {
943        // Same attack, one layer deeper. A source hands over a record whose
944        // DECLARED digest is a path. persist must derive the name from the
945        // bytes it actually holds, so the source never gets a say in where a
946        // file lands inside the installed layer.
947        let (sk, _pk) = generate_root_keypair();
948        let installed = tempfile::tempdir().unwrap();
949        let bytes = b"evidence";
950        let st = statement(LAYER, LAYER_DIGEST, AttestationKind::Sbom, bytes, "acme");
951        let envelope = sign(&st, &sk, "root-1").unwrap();
952        persist(
953            installed.path(),
954            &[CarriedAttestation {
955                statement_digest: "sha256:../../../../pwned".into(),
956                statement: envelope.clone().into_bytes(),
957                bytes: bytes.to_vec(),
958            }],
959        )
960        .unwrap();
961
962        let hex = crate::store::manifest_digest(envelope.as_bytes())
963            .strip_prefix("sha256:")
964            .unwrap()
965            .to_string();
966        assert!(
967            installed
968                .path()
969                .join(STORE_DIR)
970                .join(format!("{hex}.statement.json"))
971                .is_file(),
972            "the file must be named after the bytes' own content address"
973        );
974        assert!(
975            !installed.path().parent().unwrap().join("pwned").exists()
976                && !installed.path().join("pwned").exists(),
977            "no file may land outside the attestation store"
978        );
979        // …and it reads back intact, so the guard costs nothing.
980        assert_eq!(read_persisted(installed.path(), LAYER).unwrap().len(), 1);
981    }
982
983    // rivet: verifies REQ-ATTEST-002
984    #[test]
985    fn an_absent_layout_carries_nothing_but_an_unreadable_one_is_not_silently_empty() {
986        // The two failures must not look alike. A layout with no index.json
987        // carries no attestations — ordinary and fine. A layout whose index
988        // cannot be READ is a broken artifact, and answering "carries none"
989        // would report an absence that was never established: the same
990        // silent-drop shape this whole requirement exists to make impossible.
991        let empty = tempfile::tempdir().unwrap();
992        assert!(
993            read_all(empty.path(), LAYER).unwrap().is_empty(),
994            "an absent index.json is an empty layout, not an error"
995        );
996
997        #[cfg(unix)]
998        {
999            let broken = tempfile::tempdir().unwrap();
1000            // An index.json that is a directory: present, and unreadable.
1001            std::fs::create_dir(broken.path().join("index.json")).unwrap();
1002            assert!(
1003                read_all(broken.path(), LAYER).is_err(),
1004                "an unreadable index must be an error, never an empty answer"
1005            );
1006        }
1007    }
1008
1009    // rivet: verifies REQ-ATTEST-002
1010    #[test]
1011    fn an_unreadable_attestation_store_is_an_error_not_an_empty_answer() {
1012        // Same rule one hop later, on the installed side. A layer root with no
1013        // `attestations/` carries none; a layer root where that name exists and
1014        // cannot be enumerated is broken, and must say so rather than report
1015        // the layer as carrying nothing.
1016        let none = tempfile::tempdir().unwrap();
1017        assert!(read_persisted(none.path(), LAYER).unwrap().is_empty());
1018
1019        #[cfg(unix)]
1020        {
1021            let broken = tempfile::tempdir().unwrap();
1022            // `attestations` exists as a FILE: read_dir cannot enumerate it.
1023            std::fs::write(broken.path().join(STORE_DIR), b"not a directory").unwrap();
1024            assert!(
1025                read_persisted(broken.path(), LAYER).is_err(),
1026                "a store that cannot be read must not read back as 'this layer carries none'"
1027            );
1028        }
1029    }
1030
1031    // rivet: verifies REQ-ATTEST-002
1032    #[test]
1033    fn a_store_that_lost_the_evidence_is_an_error_on_read_back_too() {
1034        // The loss is the thing being detected, wherever it happens — a
1035        // half-copied store must not read back as "this layer has fewer
1036        // attestations than it does".
1037        let (sk, _pk) = generate_root_keypair();
1038        let installed = tempfile::tempdir().unwrap();
1039        let bytes = b"evidence";
1040        let st = statement(LAYER, LAYER_DIGEST, AttestationKind::Audit, bytes, "acme");
1041        persist(
1042            installed.path(),
1043            &[CarriedAttestation {
1044                statement_digest: crate::store::manifest_digest(
1045                    sign(&st, &sk, "k").unwrap().as_bytes(),
1046                ),
1047                statement: sign(&st, &sk, "k").unwrap().into_bytes(),
1048                bytes: bytes.to_vec(),
1049            }],
1050        )
1051        .unwrap();
1052
1053        // Something copies the statements and not the payloads.
1054        for e in std::fs::read_dir(installed.path().join(STORE_DIR)).unwrap() {
1055            let p = e.unwrap().path();
1056            if p.extension().is_some_and(|x| x == "bytes") {
1057                std::fs::remove_file(p).unwrap();
1058            }
1059        }
1060        assert!(
1061            matches!(
1062                read_persisted(installed.path(), LAYER),
1063                Err(CarryError::OrphanStatement { .. })
1064            ),
1065            "a statement whose evidence is gone must not read back as absent"
1066        );
1067    }
1068}