1use crate::layer::LayerId;
20use crate::manifest::{LayerManifest, ManifestError};
21use crate::pin::Pin;
22use crate::rollback::{HighWaterMarks, RollbackError, RollbackVerdict};
23use crate::source::{LayerRef, LayerSource, SourceError};
24use crate::store::{Store, StoreError, manifest_digest};
25
26pub trait ManifestVerifier {
33 fn verify(&self, fetched_bytes: &[u8]) -> Result<Vec<u8>, VerifyError>;
34
35 fn trust(&self) -> Option<&crate::keyroles::RealmTrust> {
41 None
42 }
43}
44
45#[derive(Debug, thiserror::Error)]
46#[error("manifest signature verification failed: {0}")]
47pub struct VerifyError(pub String);
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum OmissionSkipped {
52 NoIndex,
54 CannotEnumerate,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct InstallOutcome {
63 pub digest: String,
64 pub layer: LayerId,
65 pub counter: u64,
66 pub staleness_days: Option<i64>,
69 pub index_high_water: Option<u64>,
76 pub attestations_carried: usize,
80 pub attestation_note: Option<String>,
86 pub omission_check_skipped: Option<OmissionSkipped>,
91 pub digest_consent: Option<DigestConsent>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct DigestConsent {
102 pub line: String,
103 pub digest: String,
104 pub presented: u64,
105 pub high_water: u64,
106}
107
108impl DigestConsent {
109 pub fn note(&self) -> String {
112 format!(
113 " note: installed past this machine's anti-rollback mark: the pin selects {} by \
114 digest (counter {}), this machine has seen counter {} on line {}, and the line's \
115 signed line-status reports it supported and not yanked. The mark is unchanged.",
116 self.digest, self.presented, self.high_water, self.line
117 )
118 }
119}
120
121#[derive(Debug, thiserror::Error)]
122pub enum InstallError {
123 #[error(transparent)]
124 Index(#[from] crate::lineindex::IndexError),
125 #[error(transparent)]
126 Source(#[from] SourceError),
127 #[error(transparent)]
128 Verify(#[from] VerifyError),
129 #[error(transparent)]
130 Manifest(#[from] ManifestError),
131 #[error(
132 "source returned manifest {got} where the pin demands {pinned} — refusing (the digest is the artifact)"
133 )]
134 DigestMismatch { pinned: String, got: String },
135 #[error("manifest is for layer {got}, the pin names {pinned} — refusing")]
136 LayerMismatch { pinned: String, got: String },
137 #[error("manifest is on channel '{got}', the pin selects '{pinned}' — refusing")]
138 ChannelMismatch { pinned: String, got: String },
139 #[error(
140 "rollback refused: layer presents counter {presented} but the {line} line's high-water mark is {high_water} — a stale, validly-signed layer cannot be passed off as current"
141 )]
142 Rollback {
143 line: String,
144 presented: u64,
145 high_water: u64,
146 },
147 #[error(
148 "rollback refused: layer presents counter {presented} but the {line} line's high-water \
149 mark is {high_water}. The pin selects it by digest, which would be consent — but digest \
150 consent needs a verifiable line-status that reports the layer supported and not \
151 yanked, and {why}"
152 )]
153 RollbackConsentRefused {
154 line: String,
155 presented: u64,
156 high_water: u64,
157 why: String,
158 },
159 #[error(
160 "first contact with line {line} needs the realm's primary: a mirror cannot prove it is \
161 current, and this machine has no history (no high-water mark, no cached line-status) to \
162 bound it"
163 )]
164 FirstContactNeedsPrimary { line: String },
165 #[error(
166 "first contact with line {line}'s index needs the realm's primary: this machine has no \
167 cached line index for it, so nothing bounds what a mirror says is newest"
168 )]
169 IndexFirstContactNeedsPrimary { line: String },
170 #[error(
171 "an install by digest from a mirror must know the layer's line before the mirror is \
172 contacted, and it cannot: {why}. Take it from the realm's primary"
173 )]
174 LineUnknownForMirror { why: String },
175 #[error(
176 "layer on line {line} presents counter {presented}, below the floor of {floor} this \
177 realm signs for the line — refusing.\n\n\
178 This machine has no high-water mark for {line} (it has never installed from it, or its \
179 marks were reset), so it has no installed history to compare against. That is the one \
180 moment anti-rollback protects nobody, and the moment it is worth \
181 attacking: a fresh checkout, a new CI runner, a new laptop are all first contacts. The \
182 realm states a floor in its signed line-status, served or cached by an earlier install, \
183 so a consumer with no mark still has one.\n\n\
184 Either the pin names a layer the realm has withdrawn from first-contact use, or \
185 something served an old signed layer to a new machine. Both are worth knowing before \
186 installing."
187 )]
188 BelowFloor {
189 line: String,
190 presented: u64,
191 floor: u64,
192 },
193 #[error("blob {digest} fetched for tool '{tool}' does not match its signed digest — refusing")]
194 BlobDigestMismatch { tool: String, digest: String },
195 #[error("manifest entry {digest} is missing the eu.pulseengine.tool annotation")]
196 UnnamedEntry { digest: String },
197 #[error(
198 "layer {layer} carries no entry for platform {platform} — refusing to install a \
199 wrong-architecture toolchain; use --platform only if you know why"
200 )]
201 NoPlatformEntry { layer: String, platform: String },
202 #[error(transparent)]
203 Store(#[from] StoreError),
204 #[error(transparent)]
205 State(#[from] RollbackError),
206}
207
208impl InstallError {
209 pub fn fails_over(&self) -> bool {
222 match self {
223 InstallError::Index(e) => e.fails_over(),
224 InstallError::Source(_)
225 | InstallError::Verify(_)
226 | InstallError::Manifest(_)
227 | InstallError::DigestMismatch { .. }
228 | InstallError::LayerMismatch { .. }
229 | InstallError::BlobDigestMismatch { .. } => true,
230 InstallError::Rollback { .. }
231 | InstallError::RollbackConsentRefused { .. }
232 | InstallError::BelowFloor { .. }
233 | InstallError::FirstContactNeedsPrimary { .. }
234 | InstallError::IndexFirstContactNeedsPrimary { .. }
235 | InstallError::LineUnknownForMirror { .. }
236 | InstallError::ChannelMismatch { .. }
237 | InstallError::NoPlatformEntry { .. }
238 | InstallError::UnnamedEntry { .. }
239 | InstallError::Store(_)
240 | InstallError::State(_) => false,
241 }
242 }
243}
244
245pub struct InstallPolicy<'a> {
248 pub now: &'a str,
250 pub staleness_threshold_days: u32,
251 pub platform: &'a str,
254 pub index: Option<crate::lineindex::IndexPolicy<'a>>,
258}
259
260pub fn install_by_digest(
281 digest: &str,
282 source: &dyn LayerSource,
283 verifier: &dyn ManifestVerifier,
284 store: &Store,
285 marks: &mut HighWaterMarks,
286 policy: &InstallPolicy<'_>,
287) -> Result<InstallOutcome, InstallError> {
288 install_by_digest_from(
289 digest,
290 source,
291 verifier,
292 store,
293 marks,
294 policy,
295 DigestRole::Primary,
296 )
297}
298
299#[derive(Debug, Clone)]
304pub enum DigestRole<'a> {
305 Primary,
307 Mirror {
313 expected_line: Result<&'a crate::layer::Line, String>,
314 },
315}
316
317pub fn install_by_digest_from(
321 digest: &str,
322 source: &dyn LayerSource,
323 verifier: &dyn ManifestVerifier,
324 store: &Store,
325 marks: &mut HighWaterMarks,
326 policy: &InstallPolicy<'_>,
327 role: DigestRole<'_>,
328) -> Result<InstallOutcome, InstallError> {
329 let source_is_primary = matches!(role, DigestRole::Primary);
335 if let DigestRole::Mirror { expected_line } = &role {
336 match expected_line {
337 Err(why) => return Err(InstallError::LineUnknownForMirror { why: why.clone() }),
338 Ok(line) if !has_local_history(line, store, verifier, marks) => {
339 return Err(InstallError::FirstContactNeedsPrimary {
340 line: line.to_string(),
341 });
342 }
343 Ok(_) => {}
344 }
345 }
346 let fetched = source.fetch_manifest(&LayerRef::Digest(digest.to_string()))?;
347 let bytes = verifier.verify(&fetched)?;
348 let manifest = LayerManifest::parse(&bytes)?;
349 let channel = match manifest.channel.as_str() {
350 "qualified" => crate::pin::Channel::Qualified,
351 "rolling" => crate::pin::Channel::Rolling,
352 other => {
353 return Err(InstallError::ChannelMismatch {
354 pinned: "qualified|rolling".to_string(),
355 got: other.to_string(),
356 });
357 }
358 };
359 let pin = Pin {
360 realm: None,
361 channel,
362 layer: manifest.layer.clone(),
363 digest: Some(digest.to_string()),
364 tools: None,
365 exports: Vec::new(),
366 };
367 install_inner(
372 &pin,
373 source,
374 verifier,
375 store,
376 marks,
377 policy,
378 Via {
379 digest_is_consent: false,
380 source_is_primary,
381 },
382 )
383}
384
385pub fn install(
389 pin: &Pin,
390 source: &dyn LayerSource,
391 verifier: &dyn ManifestVerifier,
392 store: &Store,
393 marks: &mut HighWaterMarks,
394 policy: &InstallPolicy<'_>,
395) -> Result<InstallOutcome, InstallError> {
396 install_from(pin, source, verifier, store, marks, policy, true)
397}
398
399pub fn install_from(
411 pin: &Pin,
412 source: &dyn LayerSource,
413 verifier: &dyn ManifestVerifier,
414 store: &Store,
415 marks: &mut HighWaterMarks,
416 policy: &InstallPolicy<'_>,
417 source_is_primary: bool,
418) -> Result<InstallOutcome, InstallError> {
419 install_inner(
420 pin,
421 source,
422 verifier,
423 store,
424 marks,
425 policy,
426 Via {
427 digest_is_consent: true,
428 source_is_primary,
429 },
430 )
431}
432
433#[derive(Clone, Copy)]
436struct Via {
437 digest_is_consent: bool,
438 source_is_primary: bool,
439}
440
441fn has_local_history(
444 line: &crate::layer::Line,
445 store: &Store,
446 verifier: &dyn ManifestVerifier,
447 marks: &HighWaterMarks,
448) -> bool {
449 marks.mark(line).is_some()
450 || verifier.trust().is_some_and(|trust| {
451 matches!(
452 crate::linestatus::StatusCache::at_root(store.root()).load(line, trust),
453 Ok(Some(_))
454 )
455 })
456}
457
458fn install_inner(
459 pin: &Pin,
460 source: &dyn LayerSource,
461 verifier: &dyn ManifestVerifier,
462 store: &Store,
463 marks: &mut HighWaterMarks,
464 policy: &InstallPolicy<'_>,
465 via: Via,
466) -> Result<InstallOutcome, InstallError> {
467 let Via {
468 digest_is_consent,
469 source_is_primary,
470 } = via;
471 if !source_is_primary && !has_local_history(pin.layer.line(), store, verifier, marks) {
484 return Err(InstallError::FirstContactNeedsPrimary {
485 line: pin.layer.line().to_string(),
486 });
487 }
488 let layer_ref = match &pin.digest {
490 Some(digest) => LayerRef::Digest(digest.clone()),
491 None => LayerRef::Name(pin.layer.clone()),
492 };
493 let fetched = source.fetch_manifest(&layer_ref)?;
494
495 let bytes = verifier.verify(&fetched)?;
499
500 let manifest = LayerManifest::parse(&bytes)?;
502 let digest = manifest_digest(&bytes);
503 if let Some(pinned) = &pin.digest
504 && &digest != pinned
505 {
506 return Err(InstallError::DigestMismatch {
507 pinned: pinned.clone(),
508 got: digest,
509 });
510 }
511 if manifest.layer != pin.layer {
512 return Err(InstallError::LayerMismatch {
513 pinned: pin.layer.to_string(),
514 got: manifest.layer.to_string(),
515 });
516 }
517 let pinned_channel = match pin.channel {
518 crate::pin::Channel::Qualified => "qualified",
519 crate::pin::Channel::Rolling => "rolling",
520 };
521 if manifest.channel != pinned_channel {
522 return Err(InstallError::ChannelMismatch {
523 pinned: pinned_channel.to_string(),
524 got: manifest.channel.clone(),
525 });
526 }
527
528 let line = manifest.layer.line();
534 let line_str = line.to_string();
535 let index_cache = crate::lineindex::IndexCache::at_root(store.root());
536 let mut index_high_water: Option<u64> = None;
537 let mut omission_check_skipped: Option<OmissionSkipped> = None;
538 let mut accepted_index: Option<(crate::lineindex::LineIndex, Vec<u8>)> = None;
542 if let Some(index_policy) = &policy.index {
543 let envelope = source.fetch_line_index(&line_str)?;
544 if let Some(doc) = envelope
549 .as_deref()
550 .and_then(|b| crate::lineindex::proven_by(&line_str, b, index_policy.trust))
551 {
552 marks.carry_index(doc);
553 }
554 let served = source.served_layers(&line_str)?;
557 if !source_is_primary {
560 omission_check_skipped = if envelope.is_none() {
561 Some(OmissionSkipped::NoIndex)
562 } else if served.is_none() {
563 Some(OmissionSkipped::CannotEnumerate)
564 } else {
565 None
566 };
567 }
568 let cached = crate::lineindex::higher_counter(
573 index_cache.load(&line_str)?,
574 marks.carried_index(&line_str),
575 );
576 let verified = crate::lineindex::check(
577 &line_str,
578 envelope.as_deref(),
579 served.as_deref(),
580 cached.as_ref(),
581 index_policy,
582 )?;
583 index_high_water = verified.as_ref().and_then(|i| i.high_water());
584 if let (Some(doc), Some(bytes)) = (verified, envelope) {
585 accepted_index = Some((doc, bytes));
586 }
587 }
588
589 let mut first_contact_floor: Option<u64> = None;
615 if marks.mark(line).is_none()
616 && let Some(index_policy) = &policy.index
617 {
618 let cached = crate::linestatus::StatusCache::at_root(store.root())
619 .load(line, index_policy.trust)
620 .ok()
621 .flatten()
622 .filter(|doc| doc.line == line_str);
623 let served = source
624 .fetch_line_status(&layer_ref)?
625 .and_then(|bytes| {
626 crate::linestatus::LineStatus::verify_and_parse(&bytes, index_policy.trust).ok()
627 })
628 .filter(|doc| doc.line == line_str);
629 let carried = marks.carried_status(&line_str);
632 if let Some(doc) = &served {
633 marks.carry_status(doc.clone());
634 }
635 first_contact_floor = [cached, served, carried]
636 .into_iter()
637 .flatten()
638 .max_by_key(|doc| doc.counter)
639 .and_then(|doc| doc.min_counter);
640 }
641
642 let mut digest_consent: Option<DigestConsent> = None;
644 match marks.check_with_floor(&manifest, first_contact_floor) {
645 RollbackVerdict::Rollback {
646 line,
647 presented,
648 high_water,
649 } => match (&pin.digest, digest_is_consent) {
650 (Some(_), true) if !source_is_primary => {
655 return Err(InstallError::RollbackConsentRefused {
658 line,
659 presented,
660 high_water,
661 why: "digest consent is only taken from the realm's primary source, and this \
662 one is a mirror (a mirror may be lagging a yank the primary has made)"
663 .to_string(),
664 });
665 }
666 (Some(pinned), true) => {
667 match consent_why_not(
668 &manifest,
669 &layer_ref,
670 source,
671 store.root(),
672 verifier,
673 policy.now,
674 ) {
675 None => {
676 digest_consent = Some(DigestConsent {
677 line,
678 digest: pinned.clone(),
679 presented,
680 high_water,
681 });
682 }
683 Some(why) => {
684 return Err(InstallError::RollbackConsentRefused {
685 line,
686 presented,
687 high_water,
688 why,
689 });
690 }
691 }
692 }
693 _ => {
694 return Err(InstallError::Rollback {
695 line,
696 presented,
697 high_water,
698 });
699 }
700 },
701 RollbackVerdict::BelowFloor {
702 line,
703 presented,
704 floor,
705 } => {
706 return Err(InstallError::BelowFloor {
707 line,
708 presented,
709 floor,
710 });
711 }
712 RollbackVerdict::Accept => {}
713 }
714
715 struct Fetched {
722 name: String,
723 version: Option<String>,
724 dispatchable: bool,
725 target: Option<String>,
729 bytes: Vec<u8>,
730 }
731 let mut tools: Vec<Fetched> = Vec::new();
732 let mut matched = 0usize;
733 let payload_entries = manifest
740 .entries
741 .iter()
742 .filter(|e| e.kind() != Ok(crate::kind::PayloadKind::Layer))
743 .count();
744 for entry in &manifest.entries {
745 if !crate::platform::entry_matches(
746 entry
747 .annotations
748 .get(crate::platform::ANN_PLATFORM)
749 .map(String::as_str),
750 policy.platform,
751 ) {
752 continue;
753 }
754 if entry.kind() == Ok(crate::kind::PayloadKind::Layer) {
759 continue;
760 }
761 matched += 1;
762 let tool = entry
763 .annotations
764 .get("eu.pulseengine.tool")
765 .ok_or_else(|| InstallError::UnnamedEntry {
766 digest: entry.digest.clone(),
767 })?
768 .clone();
769 let blob = source.fetch_blob(&entry.digest)?;
770 if manifest_digest(&blob) != entry.digest {
771 return Err(InstallError::BlobDigestMismatch {
772 tool,
773 digest: entry.digest.clone(),
774 });
775 }
776 tools.push(Fetched {
777 name: tool,
778 version: crate::store::entry_version(entry).map(str::to_string),
779 dispatchable: crate::store::entry_is_dispatchable(entry),
780 target: crate::platform::entry_target(entry).map(str::to_string),
781 bytes: blob,
782 });
783 }
784
785 if matched == 0 && payload_entries > 0 {
788 return Err(InstallError::NoPlatformEntry {
789 layer: manifest.layer.to_string(),
790 platform: policy.platform.to_string(),
791 });
792 }
793
794 let payloads: Vec<crate::store::Payload<'_>> = tools
796 .iter()
797 .map(|t| crate::store::Payload {
798 name: t.name.as_str(),
799 version: t.version.as_deref(),
800 dispatchable: t.dispatchable,
801 target: t.target.as_deref(),
802 bytes: t.bytes.as_slice(),
803 })
804 .collect();
805 let stored_digest = store.lay_down_payloads(&bytes, &payloads)?;
806 debug_assert_eq!(stored_digest, digest);
807
808 if let Some(entry) = store.get(&digest)? {
812 crate::store::record_install_platform(&entry.root, policy.platform)?;
813 }
814
815 if fetched != bytes
819 && let Some(entry) = store.get(&digest)?
820 {
821 let path = entry.root.join(crate::reverify::ENVELOPE_FILE);
822 std::fs::write(&path, &fetched).map_err(|source| StoreError::Io {
823 path: path.display().to_string(),
824 source,
825 })?;
826 }
827
828 let mut attestations_carried = 0usize;
835 let mut attestation_note = None;
836 if let Some(entry) = store.get(&digest)? {
837 match crate::attestcarry::carry_from_source(source, &layer_ref, &entry.root) {
838 Ok(n) => attestations_carried = n,
839 Err(e) => attestation_note = Some(e.to_string()),
845 }
846 }
847
848 marks.advance(&manifest)?;
851 if let Some((doc, bytes)) = &accepted_index {
852 index_cache.update(&line_str, bytes, doc)?;
853 }
854
855 let staleness_days = crate::rollback::staleness_warning(
856 &manifest.issued_at,
857 policy.now,
858 policy.staleness_threshold_days,
859 );
860 Ok(InstallOutcome {
861 digest,
862 layer: manifest.layer.clone(),
863 counter: manifest.counter,
864 staleness_days,
865 index_high_water,
866 attestations_carried,
867 attestation_note,
868 omission_check_skipped,
869 digest_consent,
870 })
871}
872
873fn consent_why_not(
892 manifest: &LayerManifest,
893 layer_ref: &LayerRef,
894 source: &dyn LayerSource,
895 store_root: &std::path::Path,
896 verifier: &dyn ManifestVerifier,
897 now: &str,
898) -> Option<String> {
899 let Some(trust) = verifier.trust() else {
900 return Some("there is no trust root to verify a line-status against".to_string());
901 };
902 let line = manifest.layer.line();
903 let served = match crate::linestatus::current_line_status(
904 source,
905 layer_ref,
906 line,
907 trust,
908 crate::linestatus::Published::BestEffort,
909 ) {
910 Ok(served) => served.map(|(_, doc)| doc),
911 Err(e) => return Some(format!("the one served does not verify: {e}")),
912 };
913 let cached = match crate::linestatus::StatusCache::at_root(store_root).load(line, trust) {
918 Ok(cached) => cached,
919 Err(e) => return Some(format!("the cached one does not verify: {e}")),
920 };
921 match [served, cached]
924 .into_iter()
925 .flatten()
926 .max_by_key(|d| d.counter)
927 {
928 Some(newest) => consent_from_status(manifest, &newest, now),
929 None => Some(format!(
930 "none is available for line {line}: the source carries none and none was cached by \
931 an earlier install"
932 )),
933 }
934}
935
936pub fn cached_consent_why_not(
940 manifest: &LayerManifest,
941 store_root: &std::path::Path,
942 trust: &crate::keyroles::RealmTrust,
943 now: &str,
944) -> Option<String> {
945 let line = manifest.layer.line();
946 match crate::linestatus::StatusCache::at_root(store_root).load(line, trust) {
947 Ok(Some(doc)) => consent_from_status(manifest, &doc, now),
948 Ok(None) => Some(format!(
949 "none is available for line {line}: the source carries none and none was cached by \
950 an earlier install"
951 )),
952 Err(e) => Some(format!("the cached one does not verify: {e}")),
953 }
954}
955
956fn consent_from_status(
959 manifest: &LayerManifest,
960 doc: &crate::linestatus::LineStatus,
961 now: &str,
962) -> Option<String> {
963 let line = manifest.layer.line();
964 if doc.line != line.to_string() {
965 return Some(format!(
966 "the line-status served covers line {}, not {line}",
967 doc.line
968 ));
969 }
970 if let Some(floor) = doc.min_counter
971 && manifest.counter < floor
972 {
973 return Some(format!(
974 "the line-status sets a floor of counter {floor} for line {line} and this layer \
975 presents {}; consent does not override the line's own floor",
976 manifest.counter
977 ));
978 }
979 let report = doc.report_for(&manifest.layer);
980 if let Some(reason) = report.yanked_reason {
981 return Some(format!(
982 "the line-status reports layer {} YANKED ({reason}); consent does not override a yank",
983 manifest.layer
984 ));
985 }
986 if let Some(until) = &report.support_until {
987 match crate::support::standing(until, now) {
988 Ok(standing) if standing.is_expired() => {
989 return Some(format!(
990 "the line-status reports line {line} out of support since {until}; consent \
991 does not override that"
992 ));
993 }
994 Ok(_) => {}
995 Err(e) => return Some(format!("the line-status support window is unreadable: {e}")),
996 }
997 }
998 None
999}
1000
1001#[cfg(test)]
1002mod failover_class_tests {
1003 use super::*;
1004
1005 #[test]
1007 fn verdicts_about_genuine_bytes_and_local_failures_never_fail_over() {
1008 let terminal = [
1009 InstallError::Rollback {
1010 line: "l".into(),
1011 presented: 1,
1012 high_water: 2,
1013 },
1014 InstallError::ChannelMismatch {
1017 pinned: "a".into(),
1018 got: "b".into(),
1019 },
1020 InstallError::FirstContactNeedsPrimary { line: "l".into() },
1021 InstallError::IndexFirstContactNeedsPrimary { line: "l".into() },
1022 InstallError::LineUnknownForMirror { why: "w".into() },
1023 InstallError::RollbackConsentRefused {
1024 line: "l".into(),
1025 presented: 1,
1026 high_water: 2,
1027 why: "w".into(),
1028 },
1029 InstallError::BelowFloor {
1030 line: "l".into(),
1031 presented: 1,
1032 floor: 2,
1033 },
1034 InstallError::NoPlatformEntry {
1035 layer: "l".into(),
1036 platform: "p".into(),
1037 },
1038 InstallError::UnnamedEntry { digest: "d".into() },
1039 InstallError::State(RollbackError::Io {
1040 path: "p".into(),
1041 source: std::io::Error::other("x"),
1042 }),
1043 ];
1044 for e in &terminal {
1045 assert!(!e.fails_over(), "{e} must be terminal");
1046 }
1047 }
1048
1049 #[test]
1051 fn unavailable_unauthentic_or_substituted_bytes_fail_over() {
1052 let over = [
1053 InstallError::Source(SourceError::Transport("down".into())),
1054 InstallError::Source(SourceError::NotFound("x".into())),
1055 InstallError::DigestMismatch {
1056 pinned: "a".into(),
1057 got: "b".into(),
1058 },
1059 InstallError::LayerMismatch {
1060 pinned: "a".into(),
1061 got: "b".into(),
1062 },
1063 InstallError::BlobDigestMismatch {
1064 tool: "t".into(),
1065 digest: "d".into(),
1066 },
1067 InstallError::Manifest(ManifestError::Json("x".into())),
1068 InstallError::Index(crate::lineindex::IndexError::Payload("x".into())),
1069 ];
1070 for e in &over {
1071 assert!(e.fails_over(), "{e} must fail over");
1072 }
1073 let stale = InstallError::Index(crate::lineindex::IndexError::Stale {
1074 line: "l".into(),
1075 presented: 1,
1076 cached: 2,
1077 });
1078 assert!(
1079 stale.fails_over(),
1080 "a later source is judged against the same local cache, so it can never pass below it"
1081 );
1082 }
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087 use super::*;
1088 use crate::manifest::fixtures::manifest_with_tools;
1089 use crate::pin::Pin;
1090 use crate::rollback::HighWaterMarks;
1091 use crate::source::{DirSource, MemorySource};
1092
1093 struct AcceptAll;
1094 impl ManifestVerifier for AcceptAll {
1095 fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
1096 Ok(fetched.to_vec())
1097 }
1098 }
1099
1100 struct RejectAll;
1101 impl ManifestVerifier for RejectAll {
1102 fn verify(&self, _: &[u8]) -> Result<Vec<u8>, VerifyError> {
1103 Err(VerifyError("untrusted signature (test)".into()))
1104 }
1105 }
1106
1107 fn pin(layer: &str) -> Pin {
1108 Pin::parse(
1109 &format!(
1110 "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\n"
1111 ),
1112 "varve.toml",
1113 )
1114 .unwrap()
1115 }
1116
1117 fn policy() -> InstallPolicy<'static> {
1118 InstallPolicy {
1119 index: None,
1120 now: "2026-08-07T00:00:00Z",
1121 staleness_threshold_days: 90,
1122 platform: "test-platform",
1123 }
1124 }
1125
1126 fn july() -> (Vec<u8>, Vec<(String, Vec<u8>)>) {
1128 let synth = b"july-synth".to_vec();
1129 let rivet = b"july-rivet".to_vec();
1130 let blobs = vec![
1131 (manifest_digest(&synth), synth),
1132 (manifest_digest(&rivet), rivet),
1133 ];
1134 let bytes = manifest_with_tools(
1135 "2026.07.0",
1136 "qualified",
1137 1,
1138 "2026-07-31T09:14:00Z",
1139 &[("synth", &blobs[0].0), ("rivet", &blobs[1].0)],
1140 );
1141 (bytes, blobs)
1142 }
1143
1144 fn memory_source(manifest: &[u8], blobs: &[(String, Vec<u8>)]) -> MemorySource {
1145 let mut source = MemorySource::new().with_manifest(manifest);
1146 for (digest, bytes) in blobs {
1147 source = source.with_blob(digest, bytes);
1148 }
1149 source
1150 }
1151
1152 fn setup() -> (tempfile::TempDir, Store, HighWaterMarks) {
1153 let tmp = tempfile::tempdir().unwrap();
1154 let root = tmp.path().join("varve-root");
1155 let store = Store::at(&root);
1156 let marks = HighWaterMarks::load(&root).unwrap();
1157 (tmp, store, marks)
1158 }
1159
1160 #[test]
1162 fn installs_a_verified_layer_end_to_end() {
1163 let (_tmp, store, mut marks) = setup();
1164 let (bytes, blobs) = july();
1165 let source = memory_source(&bytes, &blobs);
1166 let outcome = install(
1167 &pin("2026.07.0"),
1168 &source,
1169 &AcceptAll,
1170 &store,
1171 &mut marks,
1172 &policy(),
1173 )
1174 .unwrap();
1175 assert_eq!(outcome.layer.to_string(), "2026.07.0");
1176 assert_eq!(outcome.digest, manifest_digest(&bytes));
1177 let entry = store.get(&outcome.digest).unwrap().unwrap();
1179 assert!(store.tool_path(&entry, "synth").is_some());
1180 assert!(store.tool_path(&entry, "rivet").is_some());
1181 }
1182
1183 #[test]
1185 fn installing_two_versions_of_one_crate_lands_both_sets_of_bytes() {
1186 use crate::manifest::fixtures::manifest_with_payloads;
1192 let (_tmp, store, mut marks) = setup();
1193 let (a, b) = (
1194 b"serde-1.0.200-crate".to_vec(),
1195 b"serde-1.0.210-crate".to_vec(),
1196 );
1197 let (da, db) = (manifest_digest(&a), manifest_digest(&b));
1198 let bytes = manifest_with_payloads(
1199 "2026.07.0",
1200 "qualified",
1201 1,
1202 "2026-07-31T09:14:00Z",
1203 &[
1204 ("serde", "1.0.200", "crate", &da),
1205 ("serde", "1.0.210", "crate", &db),
1206 ],
1207 );
1208 let source = memory_source(&bytes, &[(da, a.clone()), (db, b.clone())]);
1209 let outcome = install(
1210 &pin("2026.07.0"),
1211 &source,
1212 &AcceptAll,
1213 &store,
1214 &mut marks,
1215 &policy(),
1216 )
1217 .expect("two versions of one crate is the ordinary shape of a dependency graph");
1218
1219 let entry = store.get(&outcome.digest).unwrap().unwrap();
1220 assert_eq!(
1221 std::fs::read(entry.root.join("payloads/serde/1.0.200")).unwrap(),
1222 a
1223 );
1224 assert_eq!(
1225 std::fs::read(entry.root.join("payloads/serde/1.0.210")).unwrap(),
1226 b,
1227 "the second version must not have overwritten the first"
1228 );
1229 assert!(!entry.root.join("bin/serde").exists());
1231 }
1232
1233 #[test]
1235 fn a_signed_manifest_whose_entries_share_one_identity_is_refused_not_overwritten() {
1236 use crate::manifest::fixtures::manifest_with_payloads;
1242 let (_tmp, store, mut marks) = setup();
1243 let (a, b) = (b"first-bytes".to_vec(), b"second-bytes".to_vec());
1244 let (da, db) = (manifest_digest(&a), manifest_digest(&b));
1245 let bytes = manifest_with_payloads(
1246 "2026.07.0",
1247 "qualified",
1248 1,
1249 "2026-07-31T09:14:00Z",
1250 &[
1251 ("serde", "1.0.200", "crate", &da),
1252 ("serde", "1.0.200", "crate", &db),
1253 ],
1254 );
1255 let source = memory_source(&bytes, &[(da, a), (db, b)]);
1256 let err = install(
1257 &pin("2026.07.0"),
1258 &source,
1259 &AcceptAll,
1260 &store,
1261 &mut marks,
1262 &policy(),
1263 )
1264 .expect_err("one identity, two payloads: the store must refuse");
1265 assert!(
1266 matches!(err, InstallError::Store(StoreError::Collision { .. })),
1267 "got: {err}"
1268 );
1269 assert!(store.list().unwrap().is_empty(), "nothing may be laid down");
1270 assert_eq!(
1271 marks.mark(&"2026.07".parse().unwrap()),
1272 None,
1273 "a refused install must not burn the mark"
1274 );
1275 }
1276
1277 #[test]
1279 fn kill_criterion_two_sources_one_verdict() {
1280 let (bytes, blobs) = july();
1283 let tmp = tempfile::tempdir().unwrap();
1284 let dir = DirSource::at(tmp.path().join("archive"));
1285 dir.put(
1286 &bytes,
1287 &blobs
1288 .iter()
1289 .map(|(d, b)| (d.as_str(), b.as_slice()))
1290 .collect::<Vec<_>>(),
1291 )
1292 .unwrap();
1293 let mem = memory_source(&bytes, &blobs);
1294
1295 let run = |source: &dyn LayerSource, verifier: &dyn ManifestVerifier| {
1296 let (_t, store, mut marks) = setup();
1297 install(
1298 &pin("2026.07.0"),
1299 source,
1300 verifier,
1301 &store,
1302 &mut marks,
1303 &policy(),
1304 )
1305 .map_err(|e| e.to_string())
1306 };
1307
1308 let accept_mem = run(&mem, &AcceptAll).unwrap();
1309 let accept_dir = run(&dir, &AcceptAll).unwrap();
1310 assert_eq!(accept_mem, accept_dir, "same bytes, same acceptance");
1311
1312 let reject_mem = run(&mem, &RejectAll).unwrap_err();
1313 let reject_dir = run(&dir, &RejectAll).unwrap_err();
1314 assert_eq!(reject_mem, reject_dir, "same bytes, same rejection");
1315 }
1316
1317 #[test]
1319 fn an_unverified_manifest_fetches_no_blobs_and_installs_nothing() {
1320 struct CountingSource {
1321 inner: MemorySource,
1322 blob_fetches: std::cell::Cell<usize>,
1323 }
1324 impl LayerSource for CountingSource {
1325 fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
1326 self.inner.fetch_manifest(layer)
1327 }
1328 fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
1329 self.blob_fetches.set(self.blob_fetches.get() + 1);
1330 self.inner.fetch_blob(digest)
1331 }
1332 }
1333 let (_tmp, store, mut marks) = setup();
1334 let (bytes, blobs) = july();
1335 let source = CountingSource {
1336 inner: memory_source(&bytes, &blobs),
1337 blob_fetches: std::cell::Cell::new(0),
1338 };
1339 let err = install(
1340 &pin("2026.07.0"),
1341 &source,
1342 &RejectAll,
1343 &store,
1344 &mut marks,
1345 &policy(),
1346 )
1347 .unwrap_err();
1348 assert!(matches!(err, InstallError::Verify(_)), "got: {err}");
1349 assert_eq!(
1350 source.blob_fetches.get(),
1351 0,
1352 "no blob leaves the source before the signature verdict"
1353 );
1354 assert!(store.list().unwrap().is_empty(), "nothing laid down");
1355 }
1356
1357 #[test]
1359 fn a_source_that_alters_a_blob_is_caught_by_the_signed_digest() {
1360 let (_tmp, store, mut marks) = setup();
1361 let (bytes, blobs) = july();
1362 let mut source = MemorySource::new().with_manifest(&bytes);
1364 source = source.with_blob(&blobs[0].0, b"EVIL");
1365 source = source.with_blob(&blobs[1].0, &blobs[1].1);
1366 let err = install(
1367 &pin("2026.07.0"),
1368 &source,
1369 &AcceptAll,
1370 &store,
1371 &mut marks,
1372 &policy(),
1373 )
1374 .unwrap_err();
1375 assert!(
1376 matches!(err, InstallError::BlobDigestMismatch { .. }),
1377 "got: {err}"
1378 );
1379 assert!(
1380 store.list().unwrap().is_empty(),
1381 "tampered layer must not land"
1382 );
1383 }
1384
1385 #[test]
1387 fn a_source_that_answers_a_digest_request_with_other_bytes_is_caught() {
1388 struct LyingSource(Vec<u8>);
1389 impl LayerSource for LyingSource {
1390 fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
1391 Ok(self.0.clone())
1392 }
1393 fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
1394 Err(SourceError::NotFound(digest.into()))
1395 }
1396 }
1397 let (_tmp, store, mut marks) = setup();
1398 let (bytes, _) = july();
1400 let other = manifest_with_tools("2026.07.0", "qualified", 1, "2026-07-31T09:14:00Z", &[]);
1401 let pinned = manifest_digest(&other);
1402 let hex = pinned.strip_prefix("sha256:").unwrap();
1403 let p = Pin::parse(
1404 &format!(
1405 "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ndigest = \"sha256:{hex}\"\n"
1406 ),
1407 "varve.toml",
1408 )
1409 .unwrap();
1410 let err = install(
1411 &p,
1412 &LyingSource(bytes),
1413 &AcceptAll,
1414 &store,
1415 &mut marks,
1416 &policy(),
1417 )
1418 .unwrap_err();
1419 assert!(
1420 matches!(err, InstallError::DigestMismatch { .. }),
1421 "got: {err}"
1422 );
1423 }
1424
1425 #[test]
1427 fn a_rolled_back_layer_is_refused_at_install() {
1428 let (_tmp, store, mut marks) = setup();
1429 let newer = manifest_with_tools("2026.07.2", "qualified", 5, "2026-08-01T00:00:00Z", &[]);
1431 marks
1432 .advance(&LayerManifest::parse(&newer).unwrap())
1433 .unwrap();
1434 let (bytes, blobs) = july(); let source = memory_source(&bytes, &blobs);
1436 let err = install(
1437 &pin("2026.07.0"),
1438 &source,
1439 &AcceptAll,
1440 &store,
1441 &mut marks,
1442 &policy(),
1443 )
1444 .unwrap_err();
1445 assert!(
1446 matches!(
1447 err,
1448 InstallError::Rollback {
1449 presented: 1,
1450 high_water: 5,
1451 ..
1452 }
1453 ),
1454 "got: {err}"
1455 );
1456 assert!(store.list().unwrap().is_empty());
1457 }
1458
1459 #[test]
1461 fn a_failed_install_does_not_advance_the_high_water_mark() {
1462 let (_tmp, store, mut marks) = setup();
1463 let (bytes, blobs) = july();
1464 let source = MemorySource::new()
1466 .with_manifest(&bytes)
1467 .with_blob(&blobs[0].0, &blobs[0].1);
1468 let err = install(
1469 &pin("2026.07.0"),
1470 &source,
1471 &AcceptAll,
1472 &store,
1473 &mut marks,
1474 &policy(),
1475 )
1476 .unwrap_err();
1477 assert!(
1478 matches!(err, InstallError::Source(SourceError::NotFound(_))),
1479 "got: {err}"
1480 );
1481 let m = LayerManifest::parse(&bytes).unwrap();
1482 assert_eq!(
1483 marks.mark(m.layer.line()),
1484 None,
1485 "failed install must not burn the mark"
1486 );
1487 }
1488
1489 #[test]
1491 fn staleness_is_surfaced_on_an_accepted_layer() {
1492 let (_tmp, store, mut marks) = setup();
1493 let (bytes, blobs) = july(); let source = memory_source(&bytes, &blobs);
1495 let policy = InstallPolicy {
1496 index: None,
1497 now: "2026-12-01T00:00:00Z",
1498 staleness_threshold_days: 90,
1499 platform: "test-platform",
1500 };
1501 let outcome = install(
1502 &pin("2026.07.0"),
1503 &source,
1504 &AcceptAll,
1505 &store,
1506 &mut marks,
1507 &policy,
1508 )
1509 .unwrap();
1510 assert_eq!(outcome.staleness_days, Some(123));
1511 }
1512
1513 #[test]
1515 fn install_selects_only_entries_for_the_target_platform() {
1516 let (_tmp, store, mut marks) = setup();
1517 let here = b"here-tool".to_vec();
1518 let there = b"there-tool".to_vec();
1519 let (d_here, d_there) = (manifest_digest(&here), manifest_digest(&there));
1520 let bytes = crate::manifest::fixtures::manifest_with_platform_tools(
1521 "2026.07.0",
1522 "qualified",
1523 1,
1524 "2026-07-31T09:14:00Z",
1525 &[
1526 ("synth", &d_here, Some("test-platform")),
1527 ("synth", &d_there, Some("other-platform")),
1528 ],
1529 );
1530 let source = MemorySource::new()
1533 .with_manifest(&bytes)
1534 .with_blob(&d_here, &here);
1535 let policy = InstallPolicy {
1536 index: None,
1537 now: "2026-08-07T00:00:00Z",
1538 staleness_threshold_days: 90,
1539 platform: "test-platform",
1540 };
1541 let outcome = install(
1542 &pin("2026.07.0"),
1543 &source,
1544 &AcceptAll,
1545 &store,
1546 &mut marks,
1547 &policy,
1548 )
1549 .unwrap();
1550 let entry = store.get(&outcome.digest).unwrap().unwrap();
1551 assert_eq!(
1552 std::fs::read(store.tool_path(&entry, "synth").unwrap()).unwrap(),
1553 here,
1554 "the host-platform binary landed"
1555 );
1556 }
1557
1558 #[test]
1560 fn a_layer_with_nothing_for_the_host_platform_fails_closed() {
1561 let (_tmp, store, mut marks) = setup();
1562 let there = b"there-tool".to_vec();
1563 let d_there = manifest_digest(&there);
1564 let bytes = crate::manifest::fixtures::manifest_with_platform_tools(
1565 "2026.07.0",
1566 "qualified",
1567 1,
1568 "2026-07-31T09:14:00Z",
1569 &[("synth", &d_there, Some("other-platform"))],
1570 );
1571 let source = MemorySource::new()
1572 .with_manifest(&bytes)
1573 .with_blob(&d_there, &there);
1574 let policy = InstallPolicy {
1575 index: None,
1576 now: "2026-08-07T00:00:00Z",
1577 staleness_threshold_days: 90,
1578 platform: "test-platform",
1579 };
1580 let err = install(
1581 &pin("2026.07.0"),
1582 &source,
1583 &AcceptAll,
1584 &store,
1585 &mut marks,
1586 &policy,
1587 )
1588 .unwrap_err();
1589 assert!(
1590 matches!(err, InstallError::NoPlatformEntry { .. }),
1591 "got: {err}"
1592 );
1593 assert!(store.list().unwrap().is_empty(), "no wrong-arch bytes land");
1594 }
1595
1596 #[test]
1598 fn unstamped_legacy_entries_install_on_any_platform() {
1599 let (_tmp, store, mut marks) = setup();
1600 let (bytes, blobs) = july(); let source = memory_source(&bytes, &blobs);
1602 let policy = InstallPolicy {
1603 index: None,
1604 now: "2026-08-07T00:00:00Z",
1605 staleness_threshold_days: 90,
1606 platform: "any-platform-at-all",
1607 };
1608 assert!(
1609 install(
1610 &pin("2026.07.0"),
1611 &source,
1612 &AcceptAll,
1613 &store,
1614 &mut marks,
1615 &policy
1616 )
1617 .is_ok()
1618 );
1619 }
1620
1621 #[test]
1623 fn channel_and_layer_mismatches_are_refused() {
1624 let (_tmp, store, mut marks) = setup();
1625 let synth = b"s".to_vec();
1627 let d = manifest_digest(&synth);
1628 let bytes = manifest_with_tools(
1629 "2026.07.0",
1630 "rolling",
1631 1,
1632 "2026-07-31T09:14:00Z",
1633 &[("synth", &d)],
1634 );
1635 let source = MemorySource::new()
1636 .with_manifest(&bytes)
1637 .with_blob(&d, &synth);
1638 let err = install(
1639 &pin("2026.07.0"),
1640 &source,
1641 &AcceptAll,
1642 &store,
1643 &mut marks,
1644 &policy(),
1645 )
1646 .unwrap_err();
1647 assert!(
1648 matches!(err, InstallError::ChannelMismatch { .. }),
1649 "got: {err}"
1650 );
1651 }
1652
1653 #[test]
1655 fn install_carries_the_attestations_the_source_holds_into_the_installed_layer() {
1656 use crate::attest::{AttestationKind, sign, statement};
1661 let (sk, pk) = crate::verify::generate_root_keypair();
1662 let (_tmp, store, mut marks) = setup();
1663 let (bytes, blobs) = july();
1664 let layer_digest = manifest_digest(&bytes);
1665 let sbom = b"{\"bomFormat\":\"CycloneDX\"}";
1666 let st = statement(
1667 "2026.07.0",
1668 &layer_digest,
1669 AttestationKind::Sbom,
1670 sbom,
1671 "acme-ci",
1672 );
1673 let envelope = sign(&st, &sk, "root-1").unwrap();
1674 let source = memory_source(&bytes, &blobs).with_attestation(envelope.as_bytes(), sbom);
1675
1676 let outcome = install(
1677 &pin("2026.07.0"),
1678 &source,
1679 &AcceptAll,
1680 &store,
1681 &mut marks,
1682 &policy(),
1683 )
1684 .unwrap();
1685 assert_eq!(
1686 outcome.attestations_carried, 1,
1687 "install must report what travelled"
1688 );
1689 assert_eq!(outcome.attestation_note, None);
1690
1691 let entry = store.get(&outcome.digest).unwrap().unwrap();
1693 let carried = crate::attestcarry::read_persisted(&entry.root, "2026.07.0").unwrap();
1694 assert_eq!(carried.len(), 1, "the evidence reached the installed layer");
1695 assert_eq!(
1696 carried[0].bytes, sbom,
1697 "the attested bytes are stored VERBATIM — varve transports another party's \
1698 judgement, it never restates it"
1699 );
1700 let reports = crate::attestcarry::report(
1701 &carried,
1702 &layer_digest,
1703 "2026.07.0",
1704 &crate::keyroles::test_support::rt(&pk),
1705 );
1706 assert!(reports[0].binds, "reason: {:?}", reports[0].reason);
1707 assert_eq!(reports[0].producer, "acme-ci");
1708 }
1709
1710 #[test]
1712 fn a_source_that_loses_its_attestations_still_installs_but_says_so() {
1713 struct LosesAttestations(MemorySource);
1720 impl LayerSource for LosesAttestations {
1721 fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
1722 self.0.fetch_manifest(layer)
1723 }
1724 fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
1725 self.0.fetch_blob(digest)
1726 }
1727 fn fetch_attestations(
1728 &self,
1729 _layer: &LayerRef,
1730 ) -> Result<Vec<crate::attestcarry::CarriedAttestation>, SourceError> {
1731 Err(SourceError::Transport("the mirror dropped them".into()))
1732 }
1733 }
1734 let (_tmp, store, mut marks) = setup();
1735 let (bytes, blobs) = july();
1736 let outcome = install(
1737 &pin("2026.07.0"),
1738 &LosesAttestations(memory_source(&bytes, &blobs)),
1739 &AcceptAll,
1740 &store,
1741 &mut marks,
1742 &policy(),
1743 )
1744 .expect("a layer whose own signature and digests are good is still a good layer");
1745 assert_eq!(outcome.attestations_carried, 0);
1746 let note = outcome
1747 .attestation_note
1748 .expect("the loss must be reported, never swallowed");
1749 assert!(note.contains("dropped them"), "note: {note}");
1750 }
1751
1752 #[test]
1760 fn a_new_machine_refuses_a_layer_below_the_realms_signed_floor() {
1761 use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
1762 let (sk, pk) = crate::verify::generate_root_keypair();
1763 let (_tmp, store, mut marks) = setup();
1764
1765 let (bytes, blobs) = july(); let mut source = MemorySource::new().with_manifest(&bytes);
1767 for (d, b) in &blobs {
1768 source = source.with_blob(d, b);
1769 }
1770 let source = source
1771 .with_line_index(
1772 LineIndex {
1773 line: "2026.07".into(),
1774 counter: 1,
1775 issued_at: "2026-08-07T00:00:00Z".into(),
1776 layers: vec![IndexedLayer {
1777 layer: "2026.07.0".into(),
1778 digest: manifest_digest(&bytes),
1779 channel: "qualified".into(),
1780 counter: 1,
1781 }],
1782 }
1783 .sign(&sk, "root-1")
1784 .unwrap()
1785 .as_bytes(),
1786 )
1787 .with_line_status(
1789 crate::linestatus::LineStatus {
1790 line: "2026.07".into(),
1791 counter: 1,
1792 issued_at: "2026-08-07T00:00:00Z".into(),
1793 min_counter: Some(5),
1794 support_until: None,
1795 yanked: Default::default(),
1796 known_problems: Vec::new(),
1797 }
1798 .sign(&sk, "root-1")
1799 .unwrap()
1800 .as_bytes(),
1801 );
1802
1803 let policy = InstallPolicy {
1804 index: Some(IndexPolicy {
1805 realm: "acme",
1806 trust: crate::keyroles::test_support::leak_rt(&pk),
1807 required: true,
1808 }),
1809 ..policy()
1810 };
1811 let err = install(
1812 &pin("2026.07.0"),
1813 &source,
1814 &AcceptAll,
1815 &store,
1816 &mut marks,
1817 &policy,
1818 )
1819 .expect_err("a first contact below the signed floor must be refused");
1820 match &err {
1821 InstallError::BelowFloor {
1822 line,
1823 presented,
1824 floor,
1825 } => {
1826 assert_eq!(line, "2026.07");
1827 assert_eq!(*presented, 1);
1828 assert_eq!(*floor, 5);
1829 }
1830 other => panic!("expected BelowFloor, got {other:?}"),
1831 }
1832 assert!(err.to_string().contains("never installed"), "{err}");
1834 }
1835
1836 #[test]
1840 fn a_line_whose_realm_states_no_floor_installs_as_it_always_did() {
1841 use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
1842 let (sk, pk) = crate::verify::generate_root_keypair();
1843 let (_tmp, store, mut marks) = setup();
1844
1845 let (bytes, blobs) = july();
1846 let mut source = MemorySource::new().with_manifest(&bytes);
1847 for (d, b) in &blobs {
1848 source = source.with_blob(d, b);
1849 }
1850 let source = source
1851 .with_line_index(
1852 LineIndex {
1853 line: "2026.07".into(),
1854 counter: 1,
1855 issued_at: "2026-08-07T00:00:00Z".into(),
1856 layers: vec![IndexedLayer {
1857 layer: "2026.07.0".into(),
1858 digest: manifest_digest(&bytes),
1859 channel: "qualified".into(),
1860 counter: 1,
1861 }],
1862 }
1863 .sign(&sk, "root-1")
1864 .unwrap()
1865 .as_bytes(),
1866 )
1867 .with_line_status(
1868 crate::linestatus::LineStatus {
1869 line: "2026.07".into(),
1870 counter: 1,
1871 issued_at: "2026-08-07T00:00:00Z".into(),
1872 min_counter: None,
1873 support_until: None,
1874 yanked: Default::default(),
1875 known_problems: Vec::new(),
1876 }
1877 .sign(&sk, "root-1")
1878 .unwrap()
1879 .as_bytes(),
1880 );
1881
1882 let policy = InstallPolicy {
1883 index: Some(IndexPolicy {
1884 realm: "acme",
1885 trust: crate::keyroles::test_support::leak_rt(&pk),
1886 required: true,
1887 }),
1888 ..policy()
1889 };
1890 install(
1891 &pin("2026.07.0"),
1892 &source,
1893 &AcceptAll,
1894 &store,
1895 &mut marks,
1896 &policy,
1897 )
1898 .expect("no stated floor must not change anything");
1899 }
1900
1901 #[test]
1903 fn install_raises_the_mark_from_the_index_even_when_the_layer_is_hidden() {
1904 use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
1910 let (sk, pk) = crate::verify::generate_root_keypair();
1911 let (_tmp, store, mut marks) = setup();
1912
1913 let (bytes, blobs) = july(); let mut source = MemorySource::new().with_manifest(&bytes);
1915 for (d, b) in &blobs {
1916 source = source.with_blob(d, b);
1917 }
1918 let source = source.with_line_index(
1919 LineIndex {
1920 line: "2026.07".into(),
1921 counter: 1,
1922 issued_at: "2026-08-07T00:00:00Z".into(),
1923 layers: vec![
1924 IndexedLayer {
1925 layer: "2026.07.0".into(),
1926 digest: manifest_digest(&bytes),
1927 channel: "qualified".into(),
1928 counter: 1,
1929 },
1930 IndexedLayer {
1932 layer: "2026.07.9".into(),
1933 digest: "sha256:hidden".into(),
1934 channel: "qualified".into(),
1935 counter: 42,
1936 },
1937 ],
1938 }
1939 .sign(&sk, "root-1")
1940 .unwrap()
1941 .as_bytes(),
1942 );
1943
1944 let policy = InstallPolicy {
1945 index: Some(IndexPolicy {
1946 realm: "acme",
1947 trust: crate::keyroles::test_support::leak_rt(&pk),
1948 required: true,
1949 }),
1950 ..policy()
1951 };
1952 let outcome = install(
1953 &pin("2026.07.0"),
1954 &source,
1955 &AcceptAll,
1956 &store,
1957 &mut marks,
1958 &policy,
1959 )
1960 .expect("a pinned layer must install even when the line has moved on");
1961
1962 assert_eq!(
1965 outcome.index_high_water,
1966 Some(42),
1967 "the realm's assertion must reach the consumer even when the source \
1968 withheld the layer it refers to"
1969 );
1970 assert_eq!(outcome.layer.to_string(), "2026.07.0");
1977 assert_eq!(
1978 marks.mark(&"2026.07".parse().unwrap()),
1979 Some(1),
1980 "the mark records what this machine ACCEPTED, not what exists"
1981 );
1982 }
1983
1984 #[test]
1986 fn a_replayed_older_index_is_refused_on_the_next_install_not_only_in_theory() {
1987 use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
1993 let (sk, pk) = crate::verify::generate_root_keypair();
1994 let (_tmp, store, mut marks) = setup();
1995 let (bytes, blobs) = july();
1996
1997 let signed_index = |counter: u64| {
1998 LineIndex {
1999 line: "2026.07".into(),
2000 counter,
2001 issued_at: "2026-08-07T00:00:00Z".into(),
2002 layers: vec![IndexedLayer {
2003 layer: "2026.07.0".into(),
2004 digest: manifest_digest(&bytes),
2005 channel: "qualified".into(),
2006 counter: 1,
2007 }],
2008 }
2009 .sign(&sk, "root-1")
2010 .unwrap()
2011 };
2012 struct CountingSource {
2020 inner: MemorySource,
2021 blob_fetches: std::cell::Cell<usize>,
2022 }
2023 impl LayerSource for CountingSource {
2024 fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
2025 self.inner.fetch_manifest(layer)
2026 }
2027 fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
2028 self.blob_fetches.set(self.blob_fetches.get() + 1);
2029 self.inner.fetch_blob(digest)
2030 }
2031 fn fetch_line_index(&self, line: &str) -> Result<Option<Vec<u8>>, SourceError> {
2032 self.inner.fetch_line_index(line)
2033 }
2034 fn served_layers(&self, line: &str) -> Result<Option<Vec<String>>, SourceError> {
2035 self.inner.served_layers(line)
2036 }
2037 }
2038 let source_with = |envelope: &str| {
2039 let mut s = MemorySource::new().with_manifest(&bytes);
2040 for (d, b) in &blobs {
2041 s = s.with_blob(d, b);
2042 }
2043 CountingSource {
2044 inner: s.with_line_index(envelope.as_bytes()),
2045 blob_fetches: std::cell::Cell::new(0),
2046 }
2047 };
2048 let policy = InstallPolicy {
2049 index: Some(IndexPolicy {
2050 realm: "acme",
2051 trust: crate::keyroles::test_support::leak_rt(&pk),
2052 required: true,
2053 }),
2054 ..policy()
2055 };
2056
2057 install(
2058 &pin("2026.07.0"),
2059 &source_with(&signed_index(9)),
2060 &AcceptAll,
2061 &store,
2062 &mut marks,
2063 &policy,
2064 )
2065 .expect("the first install accepts index #9");
2066
2067 let replay = source_with(&signed_index(4));
2070 let err = install(
2071 &pin("2026.07.0"),
2072 &replay,
2073 &AcceptAll,
2074 &store,
2075 &mut marks,
2076 &policy,
2077 )
2078 .expect_err("a superseded index must not be replayable over the held one");
2079 assert_eq!(
2080 replay.blob_fetches.get(),
2081 0,
2082 "the index check runs BEFORE anything is fetched or laid down — a \
2083 refusal discovered only when the cache was written would already \
2084 have installed the layer and advanced the mark"
2085 );
2086 assert!(
2087 matches!(
2088 err,
2089 InstallError::Index(crate::lineindex::IndexError::Stale {
2090 presented: 4,
2091 cached: 9,
2092 ..
2093 })
2094 ),
2095 "got: {err}"
2096 );
2097 assert!(
2098 err.to_string().contains('4') && err.to_string().contains('9'),
2099 "names both counters: {err}"
2100 );
2101
2102 assert_eq!(
2105 crate::lineindex::IndexCache::at_root(store.root())
2106 .load("2026.07")
2107 .unwrap()
2108 .unwrap()
2109 .counter,
2110 9
2111 );
2112 }
2113
2114 #[test]
2116 fn install_refuses_a_source_that_hides_an_indexed_layer() {
2117 use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
2120 let (sk, pk) = crate::verify::generate_root_keypair();
2121 let (_tmp, store, mut marks) = setup();
2122
2123 let (bytes, blobs) = july();
2124 let mut source = MemorySource::new().with_manifest(&bytes);
2125 for (d, b) in &blobs {
2126 source = source.with_blob(d, b);
2127 }
2128 let source = source.serving(&["2026.07.0"]).with_line_index(
2131 LineIndex {
2132 line: "2026.07".into(),
2133 counter: 1,
2134 issued_at: "2026-08-07T00:00:00Z".into(),
2135 layers: vec![IndexedLayer {
2136 layer: "2026.07.5".into(),
2137 digest: "sha256:withheld".into(),
2138 channel: "qualified".into(),
2139 counter: 5,
2140 }],
2141 }
2142 .sign(&sk, "root-1")
2143 .unwrap()
2144 .as_bytes(),
2145 );
2146
2147 let policy = InstallPolicy {
2148 index: Some(IndexPolicy {
2149 realm: "acme",
2150 trust: crate::keyroles::test_support::leak_rt(&pk),
2151 required: true,
2152 }),
2153 ..policy()
2154 };
2155 let err = install(
2156 &pin("2026.07.0"),
2157 &source,
2158 &AcceptAll,
2159 &store,
2160 &mut marks,
2161 &policy,
2162 )
2163 .expect_err("a source hiding an indexed layer must be refused");
2164 let msg = err.to_string();
2165 assert!(msg.contains("2026.07.5"), "names the hidden layer: {msg}");
2166 assert!(store.list().unwrap().is_empty(), "no install on a refusal");
2168 }
2169
2170 struct Consent {
2175 _tmp: tempfile::TempDir,
2176 store: Store,
2177 marks: HighWaterMarks,
2178 older: Vec<u8>,
2179 newer: Vec<u8>,
2180 source: MemorySource,
2181 sk: Vec<u8>,
2182 pk: Vec<u8>,
2183 }
2184
2185 fn layer_of(name: &str, counter: u64, tag: &str) -> (Vec<u8>, Vec<(String, Vec<u8>)>) {
2186 let blob = format!("{tag}-tool").into_bytes();
2187 let blobs = vec![(manifest_digest(&blob), blob)];
2188 let bytes = manifest_with_tools(
2189 name,
2190 "qualified",
2191 counter,
2192 "2026-07-31T09:14:00Z",
2193 &[("synth", &blobs[0].0)],
2194 );
2195 (bytes, blobs)
2196 }
2197
2198 fn consent_fixture() -> Consent {
2199 let (sk, pk) = crate::verify::generate_root_keypair();
2200 let (_tmp, store, marks) = setup();
2201 let (older, ob) = layer_of("2026.07.0", 1, "old");
2202 let (newer, nb) = layer_of("2026.07.1", 2, "new");
2203 let mut source = MemorySource::new()
2204 .with_manifest(&older)
2205 .with_manifest(&newer);
2206 for (d, b) in ob.iter().chain(nb.iter()) {
2207 source = source.with_blob(d, b);
2208 }
2209 Consent {
2210 _tmp,
2211 store,
2212 marks,
2213 older,
2214 newer,
2215 source,
2216 sk,
2217 pk,
2218 }
2219 }
2220
2221 fn status_for(
2222 line: &str,
2223 support_until: Option<&str>,
2224 yanked: &[(&str, &str)],
2225 sk: &[u8],
2226 ) -> Vec<u8> {
2227 status_numbered(1, line, support_until, yanked, sk)
2228 }
2229
2230 fn status_numbered(
2231 counter: u64,
2232 line: &str,
2233 support_until: Option<&str>,
2234 yanked: &[(&str, &str)],
2235 sk: &[u8],
2236 ) -> Vec<u8> {
2237 crate::linestatus::LineStatus {
2238 line: line.into(),
2239 counter,
2240 issued_at: "2026-08-01T00:00:00Z".into(),
2241 support_until: support_until.map(str::to_string),
2242 min_counter: None,
2243 yanked: yanked
2244 .iter()
2245 .map(|(l, r)| (l.to_string(), r.to_string()))
2246 .collect(),
2247 known_problems: Vec::new(),
2248 }
2249 .sign(sk, "root-1")
2250 .unwrap()
2251 .as_bytes()
2252 .to_vec()
2253 }
2254
2255 fn digest_pin(layer: &str, digest: &str) -> Pin {
2256 Pin::parse(
2257 &format!(
2258 "manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\ndigest = \"{digest}\"\n"
2259 ),
2260 "varve.toml",
2261 )
2262 .unwrap()
2263 }
2264
2265 struct AcceptWithRoot(crate::keyroles::RealmTrust);
2267 impl ManifestVerifier for AcceptWithRoot {
2268 fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
2269 Ok(fetched.to_vec())
2270 }
2271 fn trust(&self) -> Option<&crate::keyroles::RealmTrust> {
2272 Some(&self.0)
2273 }
2274 }
2275
2276 fn see_the_newer(f: &mut Consent) {
2278 install(
2279 &pin("2026.07.1"),
2280 &f.source,
2281 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2282 &f.store,
2283 &mut f.marks,
2284 &policy(),
2285 )
2286 .unwrap();
2287 assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
2288 }
2289
2290 #[test]
2292 fn a_digest_pinned_older_layer_the_line_supports_installs_past_the_mark() {
2293 let mut f = consent_fixture();
2294 see_the_newer(&mut f);
2295 let source = std::mem::replace(&mut f.source, MemorySource::new());
2296 let source =
2297 source.with_line_status(&status_for("2026.07", Some("2027-01-01"), &[], &f.sk));
2298 let digest = manifest_digest(&f.older);
2299 let outcome = install(
2300 &digest_pin("2026.07.0", &digest),
2301 &source,
2302 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2303 &f.store,
2304 &mut f.marks,
2305 &policy(),
2306 )
2307 .expect("a digest-pinned, supported, unyanked layer installs past the mark");
2308 assert_eq!(outcome.counter, 1);
2309 let consent = outcome.digest_consent.expect("the install must say so");
2310 assert_eq!(consent.high_water, 2);
2311 assert_eq!(consent.presented, 1);
2312 assert_eq!(consent.digest, digest);
2313 let note = consent.note();
2314 for needle in [
2315 digest.as_str(),
2316 "counter 1",
2317 "counter 2",
2318 "2026.07",
2319 "supported",
2320 "not yanked",
2321 ] {
2322 assert!(note.contains(needle), "{needle} missing from: {note}");
2323 }
2324 assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
2326 assert!(f.store.get(&digest).unwrap().is_some());
2327 }
2328
2329 #[test]
2331 fn an_install_at_or_above_the_mark_carries_no_consent_note() {
2332 let mut f = consent_fixture();
2333 let digest = manifest_digest(&f.newer);
2334 let outcome = install(
2335 &digest_pin("2026.07.1", &digest),
2336 &f.source,
2337 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2338 &f.store,
2339 &mut f.marks,
2340 &policy(),
2341 )
2342 .unwrap();
2343 assert_eq!(outcome.digest_consent, None);
2344 }
2345
2346 #[test]
2348 fn resolution_by_name_keeps_the_refusal_even_with_a_supporting_line_status() {
2349 let mut f = consent_fixture();
2350 see_the_newer(&mut f);
2351 let source = std::mem::replace(&mut f.source, MemorySource::new());
2352 let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
2353 let err = install(
2354 &pin("2026.07.0"),
2355 &source,
2356 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2357 &f.store,
2358 &mut f.marks,
2359 &policy(),
2360 )
2361 .expect_err("a name is not consent");
2362 assert!(
2363 matches!(
2364 err,
2365 InstallError::Rollback {
2366 presented: 1,
2367 high_water: 2,
2368 ..
2369 }
2370 ),
2371 "{err:?}"
2372 );
2373 assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
2374 }
2375
2376 #[test]
2378 fn a_yank_is_not_overridden_by_a_digest() {
2379 let mut f = consent_fixture();
2380 see_the_newer(&mut f);
2381 let source = std::mem::replace(&mut f.source, MemorySource::new());
2382 let source = source.with_line_status(&status_for(
2383 "2026.07",
2384 None,
2385 &[("2026.07.0", "regression in synth")],
2386 &f.sk,
2387 ));
2388 let err = install(
2389 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
2390 &source,
2391 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2392 &f.store,
2393 &mut f.marks,
2394 &policy(),
2395 )
2396 .expect_err("a yanked layer stays refused");
2397 let msg = err.to_string();
2398 assert!(
2399 matches!(err, InstallError::RollbackConsentRefused { .. }),
2400 "{msg}"
2401 );
2402 assert!(
2403 msg.contains("YANKED") && msg.contains("regression in synth"),
2404 "{msg}"
2405 );
2406 assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
2407 }
2408
2409 #[test]
2411 fn an_expired_support_window_is_not_overridden_by_a_digest() {
2412 let mut f = consent_fixture();
2413 see_the_newer(&mut f);
2414 let source = std::mem::replace(&mut f.source, MemorySource::new());
2415 let source =
2417 source.with_line_status(&status_for("2026.07", Some("2026-08-06"), &[], &f.sk));
2418 let err = install(
2419 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
2420 &source,
2421 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2422 &f.store,
2423 &mut f.marks,
2424 &policy(),
2425 )
2426 .expect_err("an out-of-support layer stays refused");
2427 let msg = err.to_string();
2428 assert!(
2429 matches!(err, InstallError::RollbackConsentRefused { .. }),
2430 "{msg}"
2431 );
2432 assert!(msg.contains("out of support"), "{msg}");
2433 }
2434
2435 #[test]
2437 fn the_last_supported_day_still_consents() {
2438 let mut f = consent_fixture();
2439 see_the_newer(&mut f);
2440 let source = std::mem::replace(&mut f.source, MemorySource::new());
2441 let source =
2442 source.with_line_status(&status_for("2026.07", Some("2026-08-07"), &[], &f.sk));
2443 install(
2444 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
2445 &source,
2446 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2447 &f.store,
2448 &mut f.marks,
2449 &policy(),
2450 )
2451 .expect("the horizon day is still supported");
2452 }
2453
2454 #[test]
2456 fn no_line_status_at_all_refuses_and_says_consent_needs_one() {
2457 let mut f = consent_fixture();
2458 see_the_newer(&mut f);
2459 let err = install(
2460 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
2461 &f.source,
2462 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2463 &f.store,
2464 &mut f.marks,
2465 &policy(),
2466 )
2467 .expect_err("the pin alone is not trusted");
2468 let msg = err.to_string();
2469 assert!(
2470 matches!(err, InstallError::RollbackConsentRefused { .. }),
2471 "{msg}"
2472 );
2473 assert!(
2474 msg.contains("digest consent needs a verifiable line-status"),
2475 "{msg}"
2476 );
2477 assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
2478 }
2479
2480 #[test]
2482 fn every_refusal_of_digest_consent_is_terminal_so_no_mirror_can_grant_it() {
2483 let refusal = |f: &mut Consent, source: MemorySource, v: &dyn ManifestVerifier| {
2488 install(
2489 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
2490 &source,
2491 v,
2492 &f.store,
2493 &mut f.marks,
2494 &policy(),
2495 )
2496 .expect_err("refused")
2497 };
2498 let mut f = consent_fixture();
2500 see_the_newer(&mut f);
2501 let source = std::mem::replace(&mut f.source, MemorySource::new());
2502 let pk = f.pk.clone();
2503 let err = refusal(
2504 &mut f,
2505 source,
2506 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2507 );
2508 assert!(
2509 matches!(err, InstallError::RollbackConsentRefused { .. }),
2510 "{err}"
2511 );
2512 assert!(
2513 !err.fails_over(),
2514 "an absent status must not send us elsewhere: {err}"
2515 );
2516
2517 let mut f = consent_fixture();
2519 see_the_newer(&mut f);
2520 let (other_sk, _) = crate::verify::generate_root_keypair();
2521 let source = std::mem::replace(&mut f.source, MemorySource::new())
2522 .with_line_status(&status_for("2026.07", None, &[], &other_sk));
2523 let pk = f.pk.clone();
2524 let err = refusal(
2525 &mut f,
2526 source,
2527 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2528 );
2529 assert!(
2530 !err.fails_over(),
2531 "an unverifiable status must not send us elsewhere: {err}"
2532 );
2533
2534 let mut f = consent_fixture();
2536 see_the_newer(&mut f);
2537 let source = std::mem::replace(&mut f.source, MemorySource::new()).with_line_status(
2538 &status_for("2026.07", None, &[("2026.07.0", "regression")], &f.sk),
2539 );
2540 let pk = f.pk.clone();
2541 let err = refusal(
2542 &mut f,
2543 source,
2544 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2545 );
2546 assert!(!err.fails_over(), "a verified yank is terminal: {err}");
2547
2548 let mut f = consent_fixture();
2549 see_the_newer(&mut f);
2550 let source = std::mem::replace(&mut f.source, MemorySource::new())
2551 .with_line_status(&status_for("2026.07", Some("2026-08-06"), &[], &f.sk));
2552 let pk = f.pk.clone();
2553 let err = refusal(
2554 &mut f,
2555 source,
2556 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2557 );
2558 assert!(!err.fails_over(), "a verified expiry is terminal: {err}");
2559
2560 let mut f = consent_fixture();
2561 see_the_newer(&mut f);
2562 let source = std::mem::replace(&mut f.source, MemorySource::new())
2563 .with_line_status(&status_for("2026.07", None, &[], &f.sk));
2564 let err = refusal(&mut f, source, &AcceptAll);
2565 assert!(!err.fails_over(), "no root is local: {err}");
2566 }
2567
2568 #[test]
2570 fn a_mirror_is_never_asked_to_consent_even_when_its_status_would() {
2571 let mut f = consent_fixture();
2574 see_the_newer(&mut f);
2575 let source = std::mem::replace(&mut f.source, MemorySource::new());
2576 let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
2577 let pin = digest_pin("2026.07.0", &manifest_digest(&f.older));
2578 let ok = install_from(
2579 &pin,
2580 &source,
2581 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2582 &f.store,
2583 &mut f.marks,
2584 &policy(),
2585 true,
2586 );
2587 assert!(ok.is_ok(), "the primary may grant consent: {ok:?}");
2588
2589 let mut f = consent_fixture();
2591 see_the_newer(&mut f);
2592 let source = std::mem::replace(&mut f.source, MemorySource::new());
2593 let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
2594 let err = install_from(
2595 &pin,
2596 &source,
2597 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
2598 &f.store,
2599 &mut f.marks,
2600 &policy(),
2601 false,
2602 )
2603 .expect_err("a mirror cannot grant consent");
2604 assert!(
2605 matches!(err, InstallError::RollbackConsentRefused { .. }),
2606 "{err}"
2607 );
2608 assert!(
2609 err.to_string()
2610 .contains("only taken from the realm's primary"),
2611 "{err}"
2612 );
2613 assert!(!err.fails_over());
2614 assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
2615 }
2616
2617 fn first_contact(
2618 f: &mut Consent,
2619 source: &MemorySource,
2620 primary: bool,
2621 ) -> Result<InstallOutcome, InstallError> {
2622 first_contact_from(f, source, primary)
2623 }
2624
2625 fn first_contact_from(
2626 f: &mut Consent,
2627 source: &dyn LayerSource,
2628 primary: bool,
2629 ) -> Result<InstallOutcome, InstallError> {
2630 let pk = f.pk.clone();
2631 let policy = InstallPolicy {
2632 index: Some(crate::lineindex::IndexPolicy {
2633 realm: "acme",
2634 trust: crate::keyroles::test_support::leak_rt(&pk),
2635 required: false,
2636 }),
2637 ..policy()
2638 };
2639 install_from(
2640 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
2641 source,
2642 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2643 &f.store,
2644 &mut f.marks,
2645 &policy,
2646 primary,
2647 )
2648 }
2649
2650 #[test]
2652 fn a_first_contact_is_refused_to_a_mirror_whatever_status_it_carries() {
2653 for status in [
2657 None,
2658 Some(("2026.07", false)), Some(("2026.07", true)), Some(("2026.06", false)), ] {
2662 let mut f = consent_fixture();
2663 let (other_sk, _) = crate::verify::generate_root_keypair();
2664 let mut source = std::mem::replace(&mut f.source, MemorySource::new());
2665 if let Some((line, forged)) = status {
2666 let sk = if forged { &other_sk } else { &f.sk };
2667 source = source.with_line_status(&status_for(line, None, &[], sk));
2668 }
2669 let err = first_contact(&mut f, &source, false)
2670 .expect_err("a mirror must not answer a first contact");
2671 assert!(
2672 matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
2673 "{err}"
2674 );
2675 assert!(
2676 err.to_string()
2677 .contains("first contact with line 2026.07 needs the realm's primary"),
2678 "{err}"
2679 );
2680 assert!(!err.fails_over(), "no other mirror can do better");
2681 assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
2682 }
2683 }
2684
2685 #[test]
2687 fn a_mirror_is_asked_nothing_before_a_first_contact_is_refused() {
2688 struct Untouched;
2690 impl LayerSource for Untouched {
2691 fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
2692 panic!("a mirror was asked about a first contact");
2693 }
2694 fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, SourceError> {
2695 panic!("a mirror was asked about a first contact");
2696 }
2697 }
2698 let mut f = consent_fixture();
2699 let err = first_contact_from(&mut f, &Untouched, false).expect_err("refused");
2700 assert!(matches!(err, InstallError::FirstContactNeedsPrimary { .. }));
2701 }
2702
2703 #[test]
2705 fn the_primary_answers_a_first_contact_and_history_of_either_kind_admits_a_mirror() {
2706 let mut f = consent_fixture();
2708 let source = std::mem::replace(&mut f.source, MemorySource::new());
2709 first_contact(&mut f, &source, true).expect("the primary answers a first contact");
2710
2711 let mut f = consent_fixture();
2713 see_the_newer(&mut f);
2714 let source = std::mem::replace(&mut f.source, MemorySource::new());
2715 let newer = digest_pin("2026.07.1", &manifest_digest(&f.newer));
2716 let pk = f.pk.clone();
2717 let policy = InstallPolicy {
2718 index: Some(crate::lineindex::IndexPolicy {
2719 realm: "acme",
2720 trust: crate::keyroles::test_support::leak_rt(&pk),
2721 required: false,
2722 }),
2723 ..policy()
2724 };
2725 let outcome = install_from(
2726 &newer,
2727 &source,
2728 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2729 &f.store,
2730 &mut f.marks,
2731 &policy,
2732 false,
2733 )
2734 .expect("a mark is history");
2735 assert_eq!(
2736 outcome.omission_check_skipped,
2737 Some(OmissionSkipped::NoIndex),
2738 "a mirror with no index could not run the omission check"
2739 );
2740
2741 let mut f = consent_fixture();
2743 let line: crate::layer::Line = "2026.07".parse().unwrap();
2744 let envelope = status_for("2026.07", None, &[], &f.sk);
2745 let doc = crate::linestatus::LineStatus::verify_and_parse(
2746 &envelope,
2747 &crate::keyroles::test_support::rt(&f.pk),
2748 )
2749 .unwrap();
2750 crate::linestatus::StatusCache::at_root(f.store.root())
2751 .update(&line, &envelope, &doc)
2752 .unwrap();
2753 let source = std::mem::replace(&mut f.source, MemorySource::new());
2754 first_contact(&mut f, &source, false).expect("a cached status is history");
2755 }
2756
2757 fn status_with_floor(counter: u64, min_counter: Option<u64>, sk: &[u8]) -> Vec<u8> {
2759 crate::linestatus::LineStatus {
2760 line: "2026.07".into(),
2761 counter,
2762 issued_at: "2026-08-01T00:00:00Z".into(),
2763 support_until: None,
2764 min_counter,
2765 yanked: Default::default(),
2766 known_problems: Vec::new(),
2767 }
2768 .sign(sk, "root-1")
2769 .unwrap()
2770 .into_bytes()
2771 }
2772
2773 fn install_four_against_a_cached_floor(
2777 source_status: Option<Vec<u8>>,
2778 cached: Vec<u8>,
2779 pk: &[u8],
2780 primary: bool,
2781 ) -> Result<InstallOutcome, InstallError> {
2782 let (_tmp, store, mut marks) = setup();
2783 let (bytes, blobs) = layer_of("2026.07.2", 4, "four");
2784 let mut source = MemorySource::new().with_manifest(&bytes);
2785 for (d, b) in &blobs {
2786 source = source.with_blob(d, b);
2787 }
2788 if let Some(status) = &source_status {
2789 source = source.with_line_status(status);
2790 }
2791 let line: crate::layer::Line = "2026.07".parse().unwrap();
2792 let doc = crate::linestatus::LineStatus::verify_and_parse(
2793 &cached,
2794 &crate::keyroles::test_support::rt(pk),
2795 )
2796 .unwrap();
2797 crate::linestatus::StatusCache::at_root(store.root())
2798 .update(&line, &cached, &doc)
2799 .unwrap();
2800 let policy = InstallPolicy {
2801 index: Some(crate::lineindex::IndexPolicy {
2802 realm: "acme",
2803 trust: crate::keyroles::test_support::leak_rt(pk),
2804 required: false,
2805 }),
2806 ..policy()
2807 };
2808 install_from(
2809 &pin("2026.07.2"),
2810 &source,
2811 &AcceptWithRoot(crate::keyroles::test_support::rt(pk)),
2812 &store,
2813 &mut marks,
2814 &policy,
2815 primary,
2816 )
2817 }
2818
2819 #[test]
2821 fn a_floor_this_machine_already_recorded_is_not_lowered_by_what_a_source_serves() {
2822 let (sk, pk) = crate::verify::generate_root_keypair();
2823 let cached = || status_with_floor(3, Some(5), &sk);
2824 for primary in [false, true] {
2825 let err = install_four_against_a_cached_floor(
2827 Some(status_with_floor(1, None, &sk)),
2828 cached(),
2829 &pk,
2830 primary,
2831 )
2832 .expect_err("counter 4 is below the recorded floor of 5");
2833 assert!(
2834 matches!(err, InstallError::BelowFloor { floor: 5, .. }),
2835 "primary={primary}: {err}"
2836 );
2837 let err = install_four_against_a_cached_floor(None, cached(), &pk, primary)
2839 .expect_err("silence does not lower a recorded floor");
2840 assert!(
2841 matches!(err, InstallError::BelowFloor { floor: 5, .. }),
2842 "primary={primary}: {err}"
2843 );
2844 let (other_sk, _) = crate::verify::generate_root_keypair();
2846 let err = install_four_against_a_cached_floor(
2847 Some(status_with_floor(9, None, &other_sk)),
2848 cached(),
2849 &pk,
2850 primary,
2851 )
2852 .expect_err("a forged status does not lower it either");
2853 assert!(matches!(err, InstallError::BelowFloor { .. }), "{err}");
2854 }
2855 }
2856
2857 #[test]
2859 fn the_newer_verified_status_decides_the_floor_whichever_side_holds_it() {
2860 let (sk, pk) = crate::verify::generate_root_keypair();
2861 let err = install_four_against_a_cached_floor(
2863 Some(status_with_floor(4, Some(7), &sk)),
2864 status_with_floor(3, Some(2), &sk),
2865 &pk,
2866 false,
2867 )
2868 .expect_err("the newer status raised the floor to 7");
2869 assert!(
2870 matches!(err, InstallError::BelowFloor { floor: 7, .. }),
2871 "{err}"
2872 );
2873 install_four_against_a_cached_floor(
2876 Some(status_with_floor(4, Some(2), &sk)),
2877 status_with_floor(3, Some(5), &sk),
2878 &pk,
2879 false,
2880 )
2881 .expect("the newer word lowered the floor");
2882 }
2883
2884 #[test]
2886 fn a_mirror_that_carries_an_index_but_cannot_enumerate_leaves_the_omission_check_unrun() {
2887 let mut f = consent_fixture();
2889 see_the_newer(&mut f);
2890 let pk = f.pk.clone();
2891 let index = crate::lineindex::LineIndex {
2892 line: "2026.07".into(),
2893 counter: 1,
2894 issued_at: "2026-08-07T00:00:00Z".into(),
2895 layers: vec![crate::lineindex::IndexedLayer {
2896 layer: "2026.07.1".into(),
2897 digest: manifest_digest(&f.newer),
2898 channel: "qualified".into(),
2899 counter: 2,
2900 }],
2901 }
2902 .sign(&f.sk, "root-1")
2903 .unwrap();
2904 let source =
2907 std::mem::replace(&mut f.source, MemorySource::new()).with_line_index(index.as_bytes());
2908 let policy = InstallPolicy {
2909 index: Some(crate::lineindex::IndexPolicy {
2910 realm: "acme",
2911 trust: crate::keyroles::test_support::leak_rt(&pk),
2912 required: false,
2913 }),
2914 ..policy()
2915 };
2916 let newer = digest_pin("2026.07.1", &manifest_digest(&f.newer));
2917 let outcome = install_from(
2918 &newer,
2919 &source,
2920 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2921 &f.store,
2922 &mut f.marks,
2923 &policy,
2924 false,
2925 )
2926 .expect("history lets a mirror answer");
2927 assert_eq!(
2928 outcome.omission_check_skipped,
2929 Some(OmissionSkipped::CannotEnumerate),
2930 "an index it cannot compare with a listing is a check that could not run"
2931 );
2932 let mut f = consent_fixture();
2934 see_the_newer(&mut f);
2935 let source =
2936 std::mem::replace(&mut f.source, MemorySource::new()).with_line_index(index.as_bytes());
2937 let outcome = install_from(
2938 &newer,
2939 &source,
2940 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2941 &f.store,
2942 &mut f.marks,
2943 &policy,
2944 true,
2945 )
2946 .unwrap();
2947 assert_eq!(outcome.omission_check_skipped, None);
2948 }
2949
2950 #[test]
2952 fn a_digest_install_refuses_a_mirror_before_contacting_it_when_there_is_no_history() {
2953 struct Untouched;
2954 impl LayerSource for Untouched {
2955 fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
2956 panic!("a mirror was contacted for a first contact");
2957 }
2958 fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, SourceError> {
2959 panic!("a mirror was contacted for a first contact");
2960 }
2961 }
2962 let line: crate::layer::Line = "2026.07".parse().unwrap();
2963 let mut f = consent_fixture();
2964 let pk = f.pk.clone();
2965 let err = install_by_digest_from(
2966 &manifest_digest(&f.older),
2967 &Untouched,
2968 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2969 &f.store,
2970 &mut f.marks,
2971 &policy(),
2972 DigestRole::Mirror {
2973 expected_line: Ok(&line),
2974 },
2975 )
2976 .expect_err("no history, no mirror");
2977 assert!(
2978 matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
2979 "{err}"
2980 );
2981 assert!(!err.fails_over());
2982 for why in [
2985 "the include names no layer",
2986 "the include's layer name \"x\" is not a valid layer id",
2987 ] {
2988 let mut f = consent_fixture();
2989 let err = install_by_digest_from(
2990 &manifest_digest(&f.older),
2991 &Untouched,
2992 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
2993 &f.store,
2994 &mut f.marks,
2995 &policy(),
2996 DigestRole::Mirror {
2997 expected_line: Err(why.to_string()),
2998 },
2999 )
3000 .unwrap_err();
3001 assert!(
3002 matches!(&err, InstallError::LineUnknownForMirror { why: w } if w == why),
3003 "{err}"
3004 );
3005 assert!(err.to_string().contains(why), "{err}");
3006 assert!(!err.to_string().contains("no history"), "{err}");
3007 assert!(!err.fails_over());
3008 }
3009 }
3010
3011 #[test]
3013 fn a_digest_install_from_a_mirror_proceeds_when_the_expected_line_has_history() {
3014 let mut f = consent_fixture();
3015 see_the_newer(&mut f);
3016 let pk = f.pk.clone();
3017 let line: crate::layer::Line = "2026.07".parse().unwrap();
3018 let source = std::mem::replace(&mut f.source, MemorySource::new());
3019 install_by_digest_from(
3020 &manifest_digest(&f.newer),
3021 &source,
3022 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
3023 &f.store,
3024 &mut f.marks,
3025 &policy(),
3026 DigestRole::Mirror {
3027 expected_line: Ok(&line),
3028 },
3029 )
3030 .expect("history for the line admits a mirror");
3031 let mut f = consent_fixture();
3033 see_the_newer(&mut f);
3034 let other: crate::layer::Line = "2026.06".parse().unwrap();
3035 let source = std::mem::replace(&mut f.source, MemorySource::new());
3036 let err = install_by_digest_from(
3037 &manifest_digest(&f.newer),
3038 &source,
3039 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
3040 &f.store,
3041 &mut f.marks,
3042 &policy(),
3043 DigestRole::Mirror {
3044 expected_line: Ok(&other),
3045 },
3046 )
3047 .unwrap_err();
3048 assert!(
3049 matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
3050 "{err}"
3051 );
3052 }
3053
3054 #[test]
3056 fn an_include_that_names_one_line_but_digests_another_is_refused_terminally() {
3057 let mut f = consent_fixture();
3062 see_the_newer(&mut f);
3063 let (other_layer, other_blobs) = layer_of("2026.06.0", 1, "elsewhere");
3064 let mut source =
3065 std::mem::replace(&mut f.source, MemorySource::new()).with_manifest(&other_layer);
3066 for (d, b) in &other_blobs {
3067 source = source.with_blob(d, b);
3068 }
3069 let named: crate::layer::Line = "2026.07".parse().unwrap();
3070 let pk = f.pk.clone();
3071 let err = install_by_digest_from(
3072 &manifest_digest(&other_layer),
3073 &source,
3074 &AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
3075 &f.store,
3076 &mut f.marks,
3077 &policy(),
3078 DigestRole::Mirror {
3079 expected_line: Ok(&named),
3080 },
3081 )
3082 .expect_err("a mislabelled include");
3083 assert!(
3084 matches!(&err, InstallError::FirstContactNeedsPrimary { line } if line == "2026.06"),
3085 "{err}"
3086 );
3087 assert!(!err.fails_over());
3088 assert!(
3089 f.store
3090 .get(&manifest_digest(&other_layer))
3091 .unwrap()
3092 .is_none(),
3093 "nothing may be installed"
3094 );
3095 }
3096
3097 #[test]
3099 fn a_primary_install_never_reports_a_skipped_omission_check() {
3100 let mut f = consent_fixture();
3101 let source = std::mem::replace(&mut f.source, MemorySource::new());
3102 let outcome = first_contact(&mut f, &source, true).unwrap();
3103 assert_eq!(outcome.omission_check_skipped, None);
3104 }
3105
3106 #[test]
3108 fn a_verifier_that_names_no_root_cannot_verify_a_status_so_it_is_refused() {
3109 let mut f = consent_fixture();
3110 see_the_newer(&mut f);
3111 let source = std::mem::replace(&mut f.source, MemorySource::new());
3112 let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
3113 let err = install(
3114 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3115 &source,
3116 &AcceptAll,
3117 &f.store,
3118 &mut f.marks,
3119 &policy(),
3120 )
3121 .expect_err("no root, no consent");
3122 assert!(err.to_string().contains("no trust root"), "{err}");
3123 }
3124
3125 #[test]
3127 fn a_status_signed_by_another_root_gives_no_consent() {
3128 let mut f = consent_fixture();
3129 see_the_newer(&mut f);
3130 let (other_sk, _) = crate::verify::generate_root_keypair();
3131 let source = std::mem::replace(&mut f.source, MemorySource::new());
3132 let source = source.with_line_status(&status_for("2026.07", None, &[], &other_sk));
3133 let err = install(
3134 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3135 &source,
3136 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3137 &f.store,
3138 &mut f.marks,
3139 &policy(),
3140 )
3141 .expect_err("a forged status must not consent");
3142 assert!(
3143 matches!(err, InstallError::RollbackConsentRefused { .. }),
3144 "{err}"
3145 );
3146 }
3147
3148 #[test]
3150 fn a_status_for_another_line_gives_no_consent() {
3151 let mut f = consent_fixture();
3152 see_the_newer(&mut f);
3153 let source = std::mem::replace(&mut f.source, MemorySource::new());
3154 let source = source.with_line_status(&status_for("2026.06", None, &[], &f.sk));
3155 let err = install(
3156 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3157 &source,
3158 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3159 &f.store,
3160 &mut f.marks,
3161 &policy(),
3162 )
3163 .expect_err("a status of another line says nothing about this one");
3164 assert!(
3165 matches!(err, InstallError::RollbackConsentRefused { .. }),
3166 "{err}"
3167 );
3168 }
3169
3170 #[test]
3172 fn a_cached_line_status_consents_when_the_source_carries_none() {
3173 let mut f = consent_fixture();
3174 see_the_newer(&mut f);
3175 let line: crate::layer::Line = "2026.07".parse().unwrap();
3176 let envelope = status_for("2026.07", None, &[], &f.sk);
3177 let doc = crate::linestatus::LineStatus::verify_and_parse(
3178 &envelope,
3179 &crate::keyroles::test_support::rt(&f.pk),
3180 )
3181 .unwrap();
3182 crate::linestatus::StatusCache::at_root(f.store.root())
3183 .update(&line, &envelope, &doc)
3184 .unwrap();
3185 let outcome = install(
3186 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3187 &f.source,
3188 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3189 &f.store,
3190 &mut f.marks,
3191 &policy(),
3192 )
3193 .expect("an offline machine that cached a verified status may consent");
3194 assert!(outcome.digest_consent.is_some());
3195 }
3196
3197 #[test]
3199 fn a_registry_replaying_an_older_status_cannot_undo_a_cached_yank() {
3200 let mut f = consent_fixture();
3205 see_the_newer(&mut f);
3206 let line: crate::layer::Line = "2026.07".parse().unwrap();
3207 let yank = status_numbered(2, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
3208 let doc = crate::linestatus::LineStatus::verify_and_parse(
3209 &yank,
3210 &crate::keyroles::test_support::rt(&f.pk),
3211 )
3212 .unwrap();
3213 crate::linestatus::StatusCache::at_root(f.store.root())
3214 .update(&line, &yank, &doc)
3215 .unwrap();
3216 let source = std::mem::replace(&mut f.source, MemorySource::new());
3217 let source = source.with_line_status(&status_numbered(1, "2026.07", None, &[], &f.sk));
3218 let err = install(
3219 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3220 &source,
3221 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3222 &f.store,
3223 &mut f.marks,
3224 &policy(),
3225 )
3226 .expect_err("an older served status must not outrank the cached yank");
3227 assert!(err.to_string().contains("YANKED"), "{err}");
3228 assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
3229 }
3230
3231 #[test]
3233 fn a_signed_floor_is_not_overridden_by_a_digest() {
3234 let mut f = consent_fixture();
3238 see_the_newer(&mut f);
3239 let mut doc = crate::linestatus::LineStatus::verify_and_parse(
3240 &status_for("2026.07", None, &[], &f.sk),
3241 &crate::keyroles::test_support::rt(&f.pk),
3242 )
3243 .unwrap();
3244 doc.min_counter = Some(2);
3245 let envelope = doc.sign(&f.sk, "root-1").unwrap().as_bytes().to_vec();
3246 let source = std::mem::replace(&mut f.source, MemorySource::new());
3247 let source = source.with_line_status(&envelope);
3248 let err = install(
3249 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3250 &source,
3251 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3252 &f.store,
3253 &mut f.marks,
3254 &policy(),
3255 )
3256 .expect_err("a counter below the signed floor stays refused");
3257 assert!(err.to_string().contains("floor"), "{err}");
3258 }
3259
3260 #[test]
3262 fn a_layer_exactly_at_the_signed_floor_still_consents() {
3263 let mut f = consent_fixture();
3264 see_the_newer(&mut f);
3265 let mut doc = crate::linestatus::LineStatus::verify_and_parse(
3266 &status_for("2026.07", None, &[], &f.sk),
3267 &crate::keyroles::test_support::rt(&f.pk),
3268 )
3269 .unwrap();
3270 doc.min_counter = Some(1); let envelope = doc.sign(&f.sk, "root-1").unwrap().as_bytes().to_vec();
3272 let source = std::mem::replace(&mut f.source, MemorySource::new());
3273 let source = source.with_line_status(&envelope);
3274 let outcome = install(
3275 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3276 &source,
3277 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3278 &f.store,
3279 &mut f.marks,
3280 &policy(),
3281 )
3282 .expect("a floor AT the layer's counter does not exclude it");
3283 assert!(outcome.digest_consent.is_some());
3284 }
3285
3286 #[test]
3288 fn verifys_offline_judgment_reads_the_cache_and_names_why() {
3289 let f = consent_fixture();
3291 let older = LayerManifest::parse(&f.older).unwrap();
3292 let now = "2026-08-07T00:00:00Z";
3293 let none = cached_consent_why_not(
3294 &older,
3295 f.store.root(),
3296 &crate::keyroles::test_support::rt(&f.pk),
3297 now,
3298 )
3299 .expect("nothing cached is not consent");
3300 assert!(
3301 none.contains("none is available for line 2026.07"),
3302 "{none}"
3303 );
3304
3305 let line: crate::layer::Line = "2026.07".parse().unwrap();
3306 let cache = crate::linestatus::StatusCache::at_root(f.store.root());
3307 let ok = status_numbered(1, "2026.07", None, &[], &f.sk);
3308 let doc = crate::linestatus::LineStatus::verify_and_parse(
3309 &ok,
3310 &crate::keyroles::test_support::rt(&f.pk),
3311 )
3312 .unwrap();
3313 cache.update(&line, &ok, &doc).unwrap();
3314 assert_eq!(
3315 cached_consent_why_not(
3316 &older,
3317 f.store.root(),
3318 &crate::keyroles::test_support::rt(&f.pk),
3319 now
3320 ),
3321 None
3322 );
3323
3324 let yank = status_numbered(2, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
3325 let doc = crate::linestatus::LineStatus::verify_and_parse(
3326 &yank,
3327 &crate::keyroles::test_support::rt(&f.pk),
3328 )
3329 .unwrap();
3330 cache.update(&line, &yank, &doc).unwrap();
3331 let why = cached_consent_why_not(
3332 &older,
3333 f.store.root(),
3334 &crate::keyroles::test_support::rt(&f.pk),
3335 now,
3336 )
3337 .expect("a cached yank refuses");
3338 assert!(why.contains("YANKED") && why.contains("bad"), "{why}");
3339 }
3340
3341 #[test]
3343 fn a_newer_served_status_outranks_an_older_cached_one() {
3344 let mut f = consent_fixture();
3347 see_the_newer(&mut f);
3348 let line: crate::layer::Line = "2026.07".parse().unwrap();
3349 let yank = status_numbered(1, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
3350 let doc = crate::linestatus::LineStatus::verify_and_parse(
3351 &yank,
3352 &crate::keyroles::test_support::rt(&f.pk),
3353 )
3354 .unwrap();
3355 crate::linestatus::StatusCache::at_root(f.store.root())
3356 .update(&line, &yank, &doc)
3357 .unwrap();
3358 let source = std::mem::replace(&mut f.source, MemorySource::new());
3359 let source = source.with_line_status(&status_numbered(2, "2026.07", None, &[], &f.sk));
3360 let outcome = install(
3361 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3362 &source,
3363 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3364 &f.store,
3365 &mut f.marks,
3366 &policy(),
3367 )
3368 .expect("a newer signed status that lifts the yank consents");
3369 assert!(outcome.digest_consent.is_some());
3370 }
3371
3372 #[test]
3374 fn a_cached_status_that_yanks_the_layer_refuses_offline() {
3375 let mut f = consent_fixture();
3376 see_the_newer(&mut f);
3377 let line: crate::layer::Line = "2026.07".parse().unwrap();
3378 let envelope = status_for("2026.07", None, &[("2026.07.0", "bad")], &f.sk);
3379 let doc = crate::linestatus::LineStatus::verify_and_parse(
3380 &envelope,
3381 &crate::keyroles::test_support::rt(&f.pk),
3382 )
3383 .unwrap();
3384 crate::linestatus::StatusCache::at_root(f.store.root())
3385 .update(&line, &envelope, &doc)
3386 .unwrap();
3387 let err = install(
3388 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3389 &f.source,
3390 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3391 &f.store,
3392 &mut f.marks,
3393 &policy(),
3394 )
3395 .expect_err("the cached yank binds");
3396 assert!(err.to_string().contains("YANKED"), "{err}");
3397 }
3398
3399 #[test]
3401 fn a_pin_naming_one_layer_with_anothers_digest_is_refused_not_consented() {
3402 let mut f = consent_fixture();
3403 see_the_newer(&mut f);
3404 let source = std::mem::replace(&mut f.source, MemorySource::new());
3405 let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
3406 let err = install(
3408 &digest_pin("2026.07.0", &manifest_digest(&f.newer)),
3409 &source,
3410 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3411 &f.store,
3412 &mut f.marks,
3413 &policy(),
3414 )
3415 .expect_err("a digest that is not the named layer's is refused");
3416 assert!(matches!(err, InstallError::LayerMismatch { .. }), "{err}");
3417 let wrong = format!("sha256:{}", "ab".repeat(32));
3419 assert!(
3420 install(
3421 &digest_pin("2026.07.0", &wrong),
3422 &source,
3423 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3424 &f.store,
3425 &mut f.marks,
3426 &policy(),
3427 )
3428 .is_err()
3429 );
3430 assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
3431 }
3432
3433 #[test]
3435 fn a_digest_named_by_a_composition_is_not_consent() {
3436 let mut f = consent_fixture();
3437 see_the_newer(&mut f);
3438 let source = std::mem::replace(&mut f.source, MemorySource::new());
3439 let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
3440 let err = install_by_digest(
3441 &manifest_digest(&f.older),
3442 &source,
3443 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3444 &f.store,
3445 &mut f.marks,
3446 &policy(),
3447 )
3448 .expect_err("an include is a signer's choice, not this project's consent");
3449 assert!(matches!(err, InstallError::Rollback { .. }), "{err:?}");
3450 }
3451
3452 #[test]
3454 fn a_cached_status_filed_under_the_wrong_line_gives_no_consent() {
3455 let mut f = consent_fixture();
3456 see_the_newer(&mut f);
3457 let line: crate::layer::Line = "2026.07".parse().unwrap();
3458 let envelope = status_for("2026.06", None, &[], &f.sk);
3460 let doc = crate::linestatus::LineStatus::verify_and_parse(
3461 &envelope,
3462 &crate::keyroles::test_support::rt(&f.pk),
3463 )
3464 .unwrap();
3465 crate::linestatus::StatusCache::at_root(f.store.root())
3466 .update(&line, &envelope, &doc)
3467 .unwrap();
3468 let err = install(
3469 &digest_pin("2026.07.0", &manifest_digest(&f.older)),
3470 &f.source,
3471 &AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
3472 &f.store,
3473 &mut f.marks,
3474 &policy(),
3475 )
3476 .expect_err("a status about another line says nothing about this one");
3477 assert!(err.to_string().contains("covers line 2026.06"), "{err}");
3478 }
3479}