1use std::path::Path;
29
30use crate::attest::{AttestError, AttestationStatement};
31
32pub const STATEMENT_ARTIFACT_TYPE: &str = crate::attest::PAYLOAD_TYPE;
34
35pub const ATTESTATION_ARTIFACT_TYPE: &str =
37 "application/vnd.pulseengine.varve.attestation-bytes.v1";
38
39pub 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#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct CarriedAttestation {
77 pub statement_digest: String,
79 pub statement: Vec<u8>,
81 pub bytes: Vec<u8>,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct AttestationReport {
88 pub kind: String,
89 pub producer: String,
90 pub binds: bool,
93 pub reason: Option<String>,
95 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
115fn 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
129pub 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 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
191pub 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 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 out.sort_by(|a, b| a.statement_digest.cmp(&b.statement_digest));
268 Ok(out)
269}
270
271pub 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
315pub const STORE_DIR: &str = "attestations";
317
318pub 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 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
345pub 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 out.sort_by(|a, b| a.statement_digest.cmp(&b.statement_digest));
381 Ok(out)
382}
383
384pub 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
406pub 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 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 #[test]
448 fn an_attestation_travels_with_the_layer_and_still_binds() {
449 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 #[test]
486 fn the_report_carries_the_signing_sessions_ambient_tools_binding_or_not() {
487 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 #[test]
533 fn a_statement_whose_evidence_did_not_travel_is_an_error_not_a_skip() {
534 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 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 #[test]
560 fn an_attestation_for_another_layer_is_reported_as_not_binding() {
561 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 #[test]
601 fn an_attestation_signed_by_someone_else_does_not_bind() {
602 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 #[test]
639 fn many_attestations_travel_together_and_reattaching_is_idempotent() {
640 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 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 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 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 #[test]
722 fn evidence_survives_the_store_and_can_be_re_emitted() {
723 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 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 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 #[test]
779 fn verify_reports_each_carried_attestation_and_whether_it_still_binds() {
780 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 #[test]
838 fn a_layer_carrying_nothing_reports_nothing_rather_than_failing() {
839 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 #[test]
857 fn install_time_carriage_takes_what_the_source_holds_and_trusts_none_of_it() {
858 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 #[test]
899 fn a_layout_naming_a_blob_outside_itself_is_refused_before_anything_is_read() {
900 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 #[test]
942 fn persist_names_files_after_the_bytes_not_after_what_the_source_declared() {
943 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 assert_eq!(read_persisted(installed.path(), LAYER).unwrap().len(), 1);
981 }
982
983 #[test]
985 fn an_absent_layout_carries_nothing_but_an_unreadable_one_is_not_silently_empty() {
986 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 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 #[test]
1011 fn an_unreadable_attestation_store_is_an_error_not_an_empty_answer() {
1012 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 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 #[test]
1033 fn a_store_that_lost_the_evidence_is_an_error_on_read_back_too() {
1034 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 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}