use crate::layer::LayerId;
use crate::manifest::{LayerManifest, ManifestError};
use crate::pin::Pin;
use crate::rollback::{HighWaterMarks, RollbackError, RollbackVerdict};
use crate::source::{LayerRef, LayerSource, SourceError};
use crate::store::{Store, StoreError, manifest_digest};
pub trait ManifestVerifier {
fn verify(&self, fetched_bytes: &[u8]) -> Result<Vec<u8>, VerifyError>;
fn trust(&self) -> Option<&crate::keyroles::RealmTrust> {
None
}
}
#[derive(Debug, thiserror::Error)]
#[error("manifest signature verification failed: {0}")]
pub struct VerifyError(pub String);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OmissionSkipped {
NoIndex,
CannotEnumerate,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallOutcome {
pub digest: String,
pub layer: LayerId,
pub counter: u64,
pub staleness_days: Option<i64>,
pub index_high_water: Option<u64>,
pub attestations_carried: usize,
pub attestation_note: Option<String>,
pub omission_check_skipped: Option<OmissionSkipped>,
pub digest_consent: Option<DigestConsent>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DigestConsent {
pub line: String,
pub digest: String,
pub presented: u64,
pub high_water: u64,
}
impl DigestConsent {
pub fn note(&self) -> String {
format!(
" note: installed past this machine's anti-rollback mark: the pin selects {} by \
digest (counter {}), this machine has seen counter {} on line {}, and the line's \
signed line-status reports it supported and not yanked. The mark is unchanged.",
self.digest, self.presented, self.high_water, self.line
)
}
}
#[derive(Debug, thiserror::Error)]
pub enum InstallError {
#[error(transparent)]
Index(#[from] crate::lineindex::IndexError),
#[error(transparent)]
Source(#[from] SourceError),
#[error(transparent)]
Verify(#[from] VerifyError),
#[error(transparent)]
Manifest(#[from] ManifestError),
#[error(
"source returned manifest {got} where the pin demands {pinned} — refusing (the digest is the artifact)"
)]
DigestMismatch { pinned: String, got: String },
#[error("manifest is for layer {got}, the pin names {pinned} — refusing")]
LayerMismatch { pinned: String, got: String },
#[error("manifest is on channel '{got}', the pin selects '{pinned}' — refusing")]
ChannelMismatch { pinned: String, got: String },
#[error(
"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"
)]
Rollback {
line: String,
presented: u64,
high_water: u64,
},
#[error(
"rollback refused: layer presents counter {presented} but the {line} line's high-water \
mark is {high_water}. The pin selects it by digest, which would be consent — but digest \
consent needs a verifiable line-status that reports the layer supported and not \
yanked, and {why}"
)]
RollbackConsentRefused {
line: String,
presented: u64,
high_water: u64,
why: String,
},
#[error(
"first contact with line {line} needs the realm's primary: a mirror cannot prove it is \
current, and this machine has no history (no high-water mark, no cached line-status) to \
bound it"
)]
FirstContactNeedsPrimary { line: String },
#[error(
"first contact with line {line}'s index needs the realm's primary: this machine has no \
cached line index for it, so nothing bounds what a mirror says is newest"
)]
IndexFirstContactNeedsPrimary { line: String },
#[error(
"an install by digest from a mirror must know the layer's line before the mirror is \
contacted, and it cannot: {why}. Take it from the realm's primary"
)]
LineUnknownForMirror { why: String },
#[error(
"layer on line {line} presents counter {presented}, below the floor of {floor} this \
realm signs for the line — refusing.\n\n\
This machine has no high-water mark for {line} (it has never installed from it, or its \
marks were reset), so it has no installed history to compare against. That is the one \
moment anti-rollback protects nobody, and the moment it is worth \
attacking: a fresh checkout, a new CI runner, a new laptop are all first contacts. The \
realm states a floor in its signed line-status, served or cached by an earlier install, \
so a consumer with no mark still has one.\n\n\
Either the pin names a layer the realm has withdrawn from first-contact use, or \
something served an old signed layer to a new machine. Both are worth knowing before \
installing."
)]
BelowFloor {
line: String,
presented: u64,
floor: u64,
},
#[error("blob {digest} fetched for tool '{tool}' does not match its signed digest — refusing")]
BlobDigestMismatch { tool: String, digest: String },
#[error("manifest entry {digest} is missing the eu.pulseengine.tool annotation")]
UnnamedEntry { digest: String },
#[error(
"layer {layer} carries no entry for platform {platform} — refusing to install a \
wrong-architecture toolchain; use --platform only if you know why"
)]
NoPlatformEntry { layer: String, platform: String },
#[error(transparent)]
Store(#[from] StoreError),
#[error(transparent)]
State(#[from] RollbackError),
}
impl InstallError {
pub fn fails_over(&self) -> bool {
match self {
InstallError::Index(e) => e.fails_over(),
InstallError::Source(_)
| InstallError::Verify(_)
| InstallError::Manifest(_)
| InstallError::DigestMismatch { .. }
| InstallError::LayerMismatch { .. }
| InstallError::BlobDigestMismatch { .. } => true,
InstallError::Rollback { .. }
| InstallError::RollbackConsentRefused { .. }
| InstallError::BelowFloor { .. }
| InstallError::FirstContactNeedsPrimary { .. }
| InstallError::IndexFirstContactNeedsPrimary { .. }
| InstallError::LineUnknownForMirror { .. }
| InstallError::ChannelMismatch { .. }
| InstallError::NoPlatformEntry { .. }
| InstallError::UnnamedEntry { .. }
| InstallError::Store(_)
| InstallError::State(_) => false,
}
}
}
pub struct InstallPolicy<'a> {
pub now: &'a str,
pub staleness_threshold_days: u32,
pub platform: &'a str,
pub index: Option<crate::lineindex::IndexPolicy<'a>>,
}
pub fn install_by_digest(
digest: &str,
source: &dyn LayerSource,
verifier: &dyn ManifestVerifier,
store: &Store,
marks: &mut HighWaterMarks,
policy: &InstallPolicy<'_>,
) -> Result<InstallOutcome, InstallError> {
install_by_digest_from(
digest,
source,
verifier,
store,
marks,
policy,
DigestRole::Primary,
)
}
#[derive(Debug, Clone)]
pub enum DigestRole<'a> {
Primary,
Mirror {
expected_line: Result<&'a crate::layer::Line, String>,
},
}
pub fn install_by_digest_from(
digest: &str,
source: &dyn LayerSource,
verifier: &dyn ManifestVerifier,
store: &Store,
marks: &mut HighWaterMarks,
policy: &InstallPolicy<'_>,
role: DigestRole<'_>,
) -> Result<InstallOutcome, InstallError> {
let source_is_primary = matches!(role, DigestRole::Primary);
if let DigestRole::Mirror { expected_line } = &role {
match expected_line {
Err(why) => return Err(InstallError::LineUnknownForMirror { why: why.clone() }),
Ok(line) if !has_local_history(line, store, verifier, marks) => {
return Err(InstallError::FirstContactNeedsPrimary {
line: line.to_string(),
});
}
Ok(_) => {}
}
}
let fetched = source.fetch_manifest(&LayerRef::Digest(digest.to_string()))?;
let bytes = verifier.verify(&fetched)?;
let manifest = LayerManifest::parse(&bytes)?;
let channel = match manifest.channel.as_str() {
"qualified" => crate::pin::Channel::Qualified,
"rolling" => crate::pin::Channel::Rolling,
other => {
return Err(InstallError::ChannelMismatch {
pinned: "qualified|rolling".to_string(),
got: other.to_string(),
});
}
};
let pin = Pin {
realm: None,
channel,
layer: manifest.layer.clone(),
digest: Some(digest.to_string()),
tools: None,
exports: Vec::new(),
};
install_inner(
&pin,
source,
verifier,
store,
marks,
policy,
Via {
digest_is_consent: false,
source_is_primary,
},
)
}
pub fn install(
pin: &Pin,
source: &dyn LayerSource,
verifier: &dyn ManifestVerifier,
store: &Store,
marks: &mut HighWaterMarks,
policy: &InstallPolicy<'_>,
) -> Result<InstallOutcome, InstallError> {
install_from(pin, source, verifier, store, marks, policy, true)
}
pub fn install_from(
pin: &Pin,
source: &dyn LayerSource,
verifier: &dyn ManifestVerifier,
store: &Store,
marks: &mut HighWaterMarks,
policy: &InstallPolicy<'_>,
source_is_primary: bool,
) -> Result<InstallOutcome, InstallError> {
install_inner(
pin,
source,
verifier,
store,
marks,
policy,
Via {
digest_is_consent: true,
source_is_primary,
},
)
}
#[derive(Clone, Copy)]
struct Via {
digest_is_consent: bool,
source_is_primary: bool,
}
fn has_local_history(
line: &crate::layer::Line,
store: &Store,
verifier: &dyn ManifestVerifier,
marks: &HighWaterMarks,
) -> bool {
marks.mark(line).is_some()
|| verifier.trust().is_some_and(|trust| {
matches!(
crate::linestatus::StatusCache::at_root(store.root()).load(line, trust),
Ok(Some(_))
)
})
}
fn install_inner(
pin: &Pin,
source: &dyn LayerSource,
verifier: &dyn ManifestVerifier,
store: &Store,
marks: &mut HighWaterMarks,
policy: &InstallPolicy<'_>,
via: Via,
) -> Result<InstallOutcome, InstallError> {
let Via {
digest_is_consent,
source_is_primary,
} = via;
if !source_is_primary && !has_local_history(pin.layer.line(), store, verifier, marks) {
return Err(InstallError::FirstContactNeedsPrimary {
line: pin.layer.line().to_string(),
});
}
let layer_ref = match &pin.digest {
Some(digest) => LayerRef::Digest(digest.clone()),
None => LayerRef::Name(pin.layer.clone()),
};
let fetched = source.fetch_manifest(&layer_ref)?;
let bytes = verifier.verify(&fetched)?;
let manifest = LayerManifest::parse(&bytes)?;
let digest = manifest_digest(&bytes);
if let Some(pinned) = &pin.digest
&& &digest != pinned
{
return Err(InstallError::DigestMismatch {
pinned: pinned.clone(),
got: digest,
});
}
if manifest.layer != pin.layer {
return Err(InstallError::LayerMismatch {
pinned: pin.layer.to_string(),
got: manifest.layer.to_string(),
});
}
let pinned_channel = match pin.channel {
crate::pin::Channel::Qualified => "qualified",
crate::pin::Channel::Rolling => "rolling",
};
if manifest.channel != pinned_channel {
return Err(InstallError::ChannelMismatch {
pinned: pinned_channel.to_string(),
got: manifest.channel.clone(),
});
}
let line = manifest.layer.line();
let line_str = line.to_string();
let index_cache = crate::lineindex::IndexCache::at_root(store.root());
let mut index_high_water: Option<u64> = None;
let mut omission_check_skipped: Option<OmissionSkipped> = None;
let mut accepted_index: Option<(crate::lineindex::LineIndex, Vec<u8>)> = None;
if let Some(index_policy) = &policy.index {
let envelope = source.fetch_line_index(&line_str)?;
if let Some(doc) = envelope
.as_deref()
.and_then(|b| crate::lineindex::proven_by(&line_str, b, index_policy.trust))
{
marks.carry_index(doc);
}
let served = source.served_layers(&line_str)?;
if !source_is_primary {
omission_check_skipped = if envelope.is_none() {
Some(OmissionSkipped::NoIndex)
} else if served.is_none() {
Some(OmissionSkipped::CannotEnumerate)
} else {
None
};
}
let cached = crate::lineindex::higher_counter(
index_cache.load(&line_str)?,
marks.carried_index(&line_str),
);
let verified = crate::lineindex::check(
&line_str,
envelope.as_deref(),
served.as_deref(),
cached.as_ref(),
index_policy,
)?;
index_high_water = verified.as_ref().and_then(|i| i.high_water());
if let (Some(doc), Some(bytes)) = (verified, envelope) {
accepted_index = Some((doc, bytes));
}
}
let mut first_contact_floor: Option<u64> = None;
if marks.mark(line).is_none()
&& let Some(index_policy) = &policy.index
{
let cached = crate::linestatus::StatusCache::at_root(store.root())
.load(line, index_policy.trust)
.ok()
.flatten()
.filter(|doc| doc.line == line_str);
let served = source
.fetch_line_status(&layer_ref)?
.and_then(|bytes| {
crate::linestatus::LineStatus::verify_and_parse(&bytes, index_policy.trust).ok()
})
.filter(|doc| doc.line == line_str);
let carried = marks.carried_status(&line_str);
if let Some(doc) = &served {
marks.carry_status(doc.clone());
}
first_contact_floor = [cached, served, carried]
.into_iter()
.flatten()
.max_by_key(|doc| doc.counter)
.and_then(|doc| doc.min_counter);
}
let mut digest_consent: Option<DigestConsent> = None;
match marks.check_with_floor(&manifest, first_contact_floor) {
RollbackVerdict::Rollback {
line,
presented,
high_water,
} => match (&pin.digest, digest_is_consent) {
(Some(_), true) if !source_is_primary => {
return Err(InstallError::RollbackConsentRefused {
line,
presented,
high_water,
why: "digest consent is only taken from the realm's primary source, and this \
one is a mirror (a mirror may be lagging a yank the primary has made)"
.to_string(),
});
}
(Some(pinned), true) => {
match consent_why_not(
&manifest,
&layer_ref,
source,
store.root(),
verifier,
policy.now,
) {
None => {
digest_consent = Some(DigestConsent {
line,
digest: pinned.clone(),
presented,
high_water,
});
}
Some(why) => {
return Err(InstallError::RollbackConsentRefused {
line,
presented,
high_water,
why,
});
}
}
}
_ => {
return Err(InstallError::Rollback {
line,
presented,
high_water,
});
}
},
RollbackVerdict::BelowFloor {
line,
presented,
floor,
} => {
return Err(InstallError::BelowFloor {
line,
presented,
floor,
});
}
RollbackVerdict::Accept => {}
}
struct Fetched {
name: String,
version: Option<String>,
dispatchable: bool,
target: Option<String>,
bytes: Vec<u8>,
}
let mut tools: Vec<Fetched> = Vec::new();
let mut matched = 0usize;
let payload_entries = manifest
.entries
.iter()
.filter(|e| e.kind() != Ok(crate::kind::PayloadKind::Layer))
.count();
for entry in &manifest.entries {
if !crate::platform::entry_matches(
entry
.annotations
.get(crate::platform::ANN_PLATFORM)
.map(String::as_str),
policy.platform,
) {
continue;
}
if entry.kind() == Ok(crate::kind::PayloadKind::Layer) {
continue;
}
matched += 1;
let tool = entry
.annotations
.get("eu.pulseengine.tool")
.ok_or_else(|| InstallError::UnnamedEntry {
digest: entry.digest.clone(),
})?
.clone();
let blob = source.fetch_blob(&entry.digest)?;
if manifest_digest(&blob) != entry.digest {
return Err(InstallError::BlobDigestMismatch {
tool,
digest: entry.digest.clone(),
});
}
tools.push(Fetched {
name: tool,
version: crate::store::entry_version(entry).map(str::to_string),
dispatchable: crate::store::entry_is_dispatchable(entry),
target: crate::platform::entry_target(entry).map(str::to_string),
bytes: blob,
});
}
if matched == 0 && payload_entries > 0 {
return Err(InstallError::NoPlatformEntry {
layer: manifest.layer.to_string(),
platform: policy.platform.to_string(),
});
}
let payloads: Vec<crate::store::Payload<'_>> = tools
.iter()
.map(|t| crate::store::Payload {
name: t.name.as_str(),
version: t.version.as_deref(),
dispatchable: t.dispatchable,
target: t.target.as_deref(),
bytes: t.bytes.as_slice(),
})
.collect();
let stored_digest = store.lay_down_payloads(&bytes, &payloads)?;
debug_assert_eq!(stored_digest, digest);
if let Some(entry) = store.get(&digest)? {
crate::store::record_install_platform(&entry.root, policy.platform)?;
}
if fetched != bytes
&& let Some(entry) = store.get(&digest)?
{
let path = entry.root.join(crate::reverify::ENVELOPE_FILE);
std::fs::write(&path, &fetched).map_err(|source| StoreError::Io {
path: path.display().to_string(),
source,
})?;
}
let mut attestations_carried = 0usize;
let mut attestation_note = None;
if let Some(entry) = store.get(&digest)? {
match crate::attestcarry::carry_from_source(source, &layer_ref, &entry.root) {
Ok(n) => attestations_carried = n,
Err(e) => attestation_note = Some(e.to_string()),
}
}
marks.advance(&manifest)?;
if let Some((doc, bytes)) = &accepted_index {
index_cache.update(&line_str, bytes, doc)?;
}
let staleness_days = crate::rollback::staleness_warning(
&manifest.issued_at,
policy.now,
policy.staleness_threshold_days,
);
Ok(InstallOutcome {
digest,
layer: manifest.layer.clone(),
counter: manifest.counter,
staleness_days,
index_high_water,
attestations_carried,
attestation_note,
omission_check_skipped,
digest_consent,
})
}
fn consent_why_not(
manifest: &LayerManifest,
layer_ref: &LayerRef,
source: &dyn LayerSource,
store_root: &std::path::Path,
verifier: &dyn ManifestVerifier,
now: &str,
) -> Option<String> {
let Some(trust) = verifier.trust() else {
return Some("there is no trust root to verify a line-status against".to_string());
};
let line = manifest.layer.line();
let served = match crate::linestatus::current_line_status(
source,
layer_ref,
line,
trust,
crate::linestatus::Published::BestEffort,
) {
Ok(served) => served.map(|(_, doc)| doc),
Err(e) => return Some(format!("the one served does not verify: {e}")),
};
let cached = match crate::linestatus::StatusCache::at_root(store_root).load(line, trust) {
Ok(cached) => cached,
Err(e) => return Some(format!("the cached one does not verify: {e}")),
};
match [served, cached]
.into_iter()
.flatten()
.max_by_key(|d| d.counter)
{
Some(newest) => consent_from_status(manifest, &newest, now),
None => Some(format!(
"none is available for line {line}: the source carries none and none was cached by \
an earlier install"
)),
}
}
pub fn cached_consent_why_not(
manifest: &LayerManifest,
store_root: &std::path::Path,
trust: &crate::keyroles::RealmTrust,
now: &str,
) -> Option<String> {
let line = manifest.layer.line();
match crate::linestatus::StatusCache::at_root(store_root).load(line, trust) {
Ok(Some(doc)) => consent_from_status(manifest, &doc, now),
Ok(None) => Some(format!(
"none is available for line {line}: the source carries none and none was cached by \
an earlier install"
)),
Err(e) => Some(format!("the cached one does not verify: {e}")),
}
}
fn consent_from_status(
manifest: &LayerManifest,
doc: &crate::linestatus::LineStatus,
now: &str,
) -> Option<String> {
let line = manifest.layer.line();
if doc.line != line.to_string() {
return Some(format!(
"the line-status served covers line {}, not {line}",
doc.line
));
}
if let Some(floor) = doc.min_counter
&& manifest.counter < floor
{
return Some(format!(
"the line-status sets a floor of counter {floor} for line {line} and this layer \
presents {}; consent does not override the line's own floor",
manifest.counter
));
}
let report = doc.report_for(&manifest.layer);
if let Some(reason) = report.yanked_reason {
return Some(format!(
"the line-status reports layer {} YANKED ({reason}); consent does not override a yank",
manifest.layer
));
}
if let Some(until) = &report.support_until {
match crate::support::standing(until, now) {
Ok(standing) if standing.is_expired() => {
return Some(format!(
"the line-status reports line {line} out of support since {until}; consent \
does not override that"
));
}
Ok(_) => {}
Err(e) => return Some(format!("the line-status support window is unreadable: {e}")),
}
}
None
}
#[cfg(test)]
mod failover_class_tests {
use super::*;
#[test]
fn verdicts_about_genuine_bytes_and_local_failures_never_fail_over() {
let terminal = [
InstallError::Rollback {
line: "l".into(),
presented: 1,
high_water: 2,
},
InstallError::ChannelMismatch {
pinned: "a".into(),
got: "b".into(),
},
InstallError::FirstContactNeedsPrimary { line: "l".into() },
InstallError::IndexFirstContactNeedsPrimary { line: "l".into() },
InstallError::LineUnknownForMirror { why: "w".into() },
InstallError::RollbackConsentRefused {
line: "l".into(),
presented: 1,
high_water: 2,
why: "w".into(),
},
InstallError::BelowFloor {
line: "l".into(),
presented: 1,
floor: 2,
},
InstallError::NoPlatformEntry {
layer: "l".into(),
platform: "p".into(),
},
InstallError::UnnamedEntry { digest: "d".into() },
InstallError::State(RollbackError::Io {
path: "p".into(),
source: std::io::Error::other("x"),
}),
];
for e in &terminal {
assert!(!e.fails_over(), "{e} must be terminal");
}
}
#[test]
fn unavailable_unauthentic_or_substituted_bytes_fail_over() {
let over = [
InstallError::Source(SourceError::Transport("down".into())),
InstallError::Source(SourceError::NotFound("x".into())),
InstallError::DigestMismatch {
pinned: "a".into(),
got: "b".into(),
},
InstallError::LayerMismatch {
pinned: "a".into(),
got: "b".into(),
},
InstallError::BlobDigestMismatch {
tool: "t".into(),
digest: "d".into(),
},
InstallError::Manifest(ManifestError::Json("x".into())),
InstallError::Index(crate::lineindex::IndexError::Payload("x".into())),
];
for e in &over {
assert!(e.fails_over(), "{e} must fail over");
}
let stale = InstallError::Index(crate::lineindex::IndexError::Stale {
line: "l".into(),
presented: 1,
cached: 2,
});
assert!(
stale.fails_over(),
"a later source is judged against the same local cache, so it can never pass below it"
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::manifest::fixtures::manifest_with_tools;
use crate::pin::Pin;
use crate::rollback::HighWaterMarks;
use crate::source::{DirSource, MemorySource};
struct AcceptAll;
impl ManifestVerifier for AcceptAll {
fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
Ok(fetched.to_vec())
}
}
struct RejectAll;
impl ManifestVerifier for RejectAll {
fn verify(&self, _: &[u8]) -> Result<Vec<u8>, VerifyError> {
Err(VerifyError("untrusted signature (test)".into()))
}
}
fn pin(layer: &str) -> Pin {
Pin::parse(
&format!(
"manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\n"
),
"varve.toml",
)
.unwrap()
}
fn policy() -> InstallPolicy<'static> {
InstallPolicy {
index: None,
now: "2026-08-07T00:00:00Z",
staleness_threshold_days: 90,
platform: "test-platform",
}
}
fn july() -> (Vec<u8>, Vec<(String, Vec<u8>)>) {
let synth = b"july-synth".to_vec();
let rivet = b"july-rivet".to_vec();
let blobs = vec![
(manifest_digest(&synth), synth),
(manifest_digest(&rivet), rivet),
];
let bytes = manifest_with_tools(
"2026.07.0",
"qualified",
1,
"2026-07-31T09:14:00Z",
&[("synth", &blobs[0].0), ("rivet", &blobs[1].0)],
);
(bytes, blobs)
}
fn memory_source(manifest: &[u8], blobs: &[(String, Vec<u8>)]) -> MemorySource {
let mut source = MemorySource::new().with_manifest(manifest);
for (digest, bytes) in blobs {
source = source.with_blob(digest, bytes);
}
source
}
fn setup() -> (tempfile::TempDir, Store, HighWaterMarks) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("varve-root");
let store = Store::at(&root);
let marks = HighWaterMarks::load(&root).unwrap();
(tmp, store, marks)
}
#[test]
fn installs_a_verified_layer_end_to_end() {
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let source = memory_source(&bytes, &blobs);
let outcome = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap();
assert_eq!(outcome.layer.to_string(), "2026.07.0");
assert_eq!(outcome.digest, manifest_digest(&bytes));
let entry = store.get(&outcome.digest).unwrap().unwrap();
assert!(store.tool_path(&entry, "synth").is_some());
assert!(store.tool_path(&entry, "rivet").is_some());
}
#[test]
fn installing_two_versions_of_one_crate_lands_both_sets_of_bytes() {
use crate::manifest::fixtures::manifest_with_payloads;
let (_tmp, store, mut marks) = setup();
let (a, b) = (
b"serde-1.0.200-crate".to_vec(),
b"serde-1.0.210-crate".to_vec(),
);
let (da, db) = (manifest_digest(&a), manifest_digest(&b));
let bytes = manifest_with_payloads(
"2026.07.0",
"qualified",
1,
"2026-07-31T09:14:00Z",
&[
("serde", "1.0.200", "crate", &da),
("serde", "1.0.210", "crate", &db),
],
);
let source = memory_source(&bytes, &[(da, a.clone()), (db, b.clone())]);
let outcome = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.expect("two versions of one crate is the ordinary shape of a dependency graph");
let entry = store.get(&outcome.digest).unwrap().unwrap();
assert_eq!(
std::fs::read(entry.root.join("payloads/serde/1.0.200")).unwrap(),
a
);
assert_eq!(
std::fs::read(entry.root.join("payloads/serde/1.0.210")).unwrap(),
b,
"the second version must not have overwritten the first"
);
assert!(!entry.root.join("bin/serde").exists());
}
#[test]
fn a_signed_manifest_whose_entries_share_one_identity_is_refused_not_overwritten() {
use crate::manifest::fixtures::manifest_with_payloads;
let (_tmp, store, mut marks) = setup();
let (a, b) = (b"first-bytes".to_vec(), b"second-bytes".to_vec());
let (da, db) = (manifest_digest(&a), manifest_digest(&b));
let bytes = manifest_with_payloads(
"2026.07.0",
"qualified",
1,
"2026-07-31T09:14:00Z",
&[
("serde", "1.0.200", "crate", &da),
("serde", "1.0.200", "crate", &db),
],
);
let source = memory_source(&bytes, &[(da, a), (db, b)]);
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.expect_err("one identity, two payloads: the store must refuse");
assert!(
matches!(err, InstallError::Store(StoreError::Collision { .. })),
"got: {err}"
);
assert!(store.list().unwrap().is_empty(), "nothing may be laid down");
assert_eq!(
marks.mark(&"2026.07".parse().unwrap()),
None,
"a refused install must not burn the mark"
);
}
#[test]
fn kill_criterion_two_sources_one_verdict() {
let (bytes, blobs) = july();
let tmp = tempfile::tempdir().unwrap();
let dir = DirSource::at(tmp.path().join("archive"));
dir.put(
&bytes,
&blobs
.iter()
.map(|(d, b)| (d.as_str(), b.as_slice()))
.collect::<Vec<_>>(),
)
.unwrap();
let mem = memory_source(&bytes, &blobs);
let run = |source: &dyn LayerSource, verifier: &dyn ManifestVerifier| {
let (_t, store, mut marks) = setup();
install(
&pin("2026.07.0"),
source,
verifier,
&store,
&mut marks,
&policy(),
)
.map_err(|e| e.to_string())
};
let accept_mem = run(&mem, &AcceptAll).unwrap();
let accept_dir = run(&dir, &AcceptAll).unwrap();
assert_eq!(accept_mem, accept_dir, "same bytes, same acceptance");
let reject_mem = run(&mem, &RejectAll).unwrap_err();
let reject_dir = run(&dir, &RejectAll).unwrap_err();
assert_eq!(reject_mem, reject_dir, "same bytes, same rejection");
}
#[test]
fn an_unverified_manifest_fetches_no_blobs_and_installs_nothing() {
struct CountingSource {
inner: MemorySource,
blob_fetches: std::cell::Cell<usize>,
}
impl LayerSource for CountingSource {
fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
self.inner.fetch_manifest(layer)
}
fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
self.blob_fetches.set(self.blob_fetches.get() + 1);
self.inner.fetch_blob(digest)
}
}
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let source = CountingSource {
inner: memory_source(&bytes, &blobs),
blob_fetches: std::cell::Cell::new(0),
};
let err = install(
&pin("2026.07.0"),
&source,
&RejectAll,
&store,
&mut marks,
&policy(),
)
.unwrap_err();
assert!(matches!(err, InstallError::Verify(_)), "got: {err}");
assert_eq!(
source.blob_fetches.get(),
0,
"no blob leaves the source before the signature verdict"
);
assert!(store.list().unwrap().is_empty(), "nothing laid down");
}
#[test]
fn a_source_that_alters_a_blob_is_caught_by_the_signed_digest() {
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let mut source = MemorySource::new().with_manifest(&bytes);
source = source.with_blob(&blobs[0].0, b"EVIL");
source = source.with_blob(&blobs[1].0, &blobs[1].1);
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap_err();
assert!(
matches!(err, InstallError::BlobDigestMismatch { .. }),
"got: {err}"
);
assert!(
store.list().unwrap().is_empty(),
"tampered layer must not land"
);
}
#[test]
fn a_source_that_answers_a_digest_request_with_other_bytes_is_caught() {
struct LyingSource(Vec<u8>);
impl LayerSource for LyingSource {
fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
Ok(self.0.clone())
}
fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound(digest.into()))
}
}
let (_tmp, store, mut marks) = setup();
let (bytes, _) = july();
let other = manifest_with_tools("2026.07.0", "qualified", 1, "2026-07-31T09:14:00Z", &[]);
let pinned = manifest_digest(&other);
let hex = pinned.strip_prefix("sha256:").unwrap();
let p = Pin::parse(
&format!(
"manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"2026.07.0\"\ndigest = \"sha256:{hex}\"\n"
),
"varve.toml",
)
.unwrap();
let err = install(
&p,
&LyingSource(bytes),
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap_err();
assert!(
matches!(err, InstallError::DigestMismatch { .. }),
"got: {err}"
);
}
#[test]
fn a_rolled_back_layer_is_refused_at_install() {
let (_tmp, store, mut marks) = setup();
let newer = manifest_with_tools("2026.07.2", "qualified", 5, "2026-08-01T00:00:00Z", &[]);
marks
.advance(&LayerManifest::parse(&newer).unwrap())
.unwrap();
let (bytes, blobs) = july(); let source = memory_source(&bytes, &blobs);
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap_err();
assert!(
matches!(
err,
InstallError::Rollback {
presented: 1,
high_water: 5,
..
}
),
"got: {err}"
);
assert!(store.list().unwrap().is_empty());
}
#[test]
fn a_failed_install_does_not_advance_the_high_water_mark() {
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let source = MemorySource::new()
.with_manifest(&bytes)
.with_blob(&blobs[0].0, &blobs[0].1);
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap_err();
assert!(
matches!(err, InstallError::Source(SourceError::NotFound(_))),
"got: {err}"
);
let m = LayerManifest::parse(&bytes).unwrap();
assert_eq!(
marks.mark(m.layer.line()),
None,
"failed install must not burn the mark"
);
}
#[test]
fn staleness_is_surfaced_on_an_accepted_layer() {
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july(); let source = memory_source(&bytes, &blobs);
let policy = InstallPolicy {
index: None,
now: "2026-12-01T00:00:00Z",
staleness_threshold_days: 90,
platform: "test-platform",
};
let outcome = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.unwrap();
assert_eq!(outcome.staleness_days, Some(123));
}
#[test]
fn install_selects_only_entries_for_the_target_platform() {
let (_tmp, store, mut marks) = setup();
let here = b"here-tool".to_vec();
let there = b"there-tool".to_vec();
let (d_here, d_there) = (manifest_digest(&here), manifest_digest(&there));
let bytes = crate::manifest::fixtures::manifest_with_platform_tools(
"2026.07.0",
"qualified",
1,
"2026-07-31T09:14:00Z",
&[
("synth", &d_here, Some("test-platform")),
("synth", &d_there, Some("other-platform")),
],
);
let source = MemorySource::new()
.with_manifest(&bytes)
.with_blob(&d_here, &here);
let policy = InstallPolicy {
index: None,
now: "2026-08-07T00:00:00Z",
staleness_threshold_days: 90,
platform: "test-platform",
};
let outcome = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.unwrap();
let entry = store.get(&outcome.digest).unwrap().unwrap();
assert_eq!(
std::fs::read(store.tool_path(&entry, "synth").unwrap()).unwrap(),
here,
"the host-platform binary landed"
);
}
#[test]
fn a_layer_with_nothing_for_the_host_platform_fails_closed() {
let (_tmp, store, mut marks) = setup();
let there = b"there-tool".to_vec();
let d_there = manifest_digest(&there);
let bytes = crate::manifest::fixtures::manifest_with_platform_tools(
"2026.07.0",
"qualified",
1,
"2026-07-31T09:14:00Z",
&[("synth", &d_there, Some("other-platform"))],
);
let source = MemorySource::new()
.with_manifest(&bytes)
.with_blob(&d_there, &there);
let policy = InstallPolicy {
index: None,
now: "2026-08-07T00:00:00Z",
staleness_threshold_days: 90,
platform: "test-platform",
};
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.unwrap_err();
assert!(
matches!(err, InstallError::NoPlatformEntry { .. }),
"got: {err}"
);
assert!(store.list().unwrap().is_empty(), "no wrong-arch bytes land");
}
#[test]
fn unstamped_legacy_entries_install_on_any_platform() {
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july(); let source = memory_source(&bytes, &blobs);
let policy = InstallPolicy {
index: None,
now: "2026-08-07T00:00:00Z",
staleness_threshold_days: 90,
platform: "any-platform-at-all",
};
assert!(
install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy
)
.is_ok()
);
}
#[test]
fn channel_and_layer_mismatches_are_refused() {
let (_tmp, store, mut marks) = setup();
let synth = b"s".to_vec();
let d = manifest_digest(&synth);
let bytes = manifest_with_tools(
"2026.07.0",
"rolling",
1,
"2026-07-31T09:14:00Z",
&[("synth", &d)],
);
let source = MemorySource::new()
.with_manifest(&bytes)
.with_blob(&d, &synth);
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap_err();
assert!(
matches!(err, InstallError::ChannelMismatch { .. }),
"got: {err}"
);
}
#[test]
fn install_carries_the_attestations_the_source_holds_into_the_installed_layer() {
use crate::attest::{AttestationKind, sign, statement};
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let layer_digest = manifest_digest(&bytes);
let sbom = b"{\"bomFormat\":\"CycloneDX\"}";
let st = statement(
"2026.07.0",
&layer_digest,
AttestationKind::Sbom,
sbom,
"acme-ci",
);
let envelope = sign(&st, &sk, "root-1").unwrap();
let source = memory_source(&bytes, &blobs).with_attestation(envelope.as_bytes(), sbom);
let outcome = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.unwrap();
assert_eq!(
outcome.attestations_carried, 1,
"install must report what travelled"
);
assert_eq!(outcome.attestation_note, None);
let entry = store.get(&outcome.digest).unwrap().unwrap();
let carried = crate::attestcarry::read_persisted(&entry.root, "2026.07.0").unwrap();
assert_eq!(carried.len(), 1, "the evidence reached the installed layer");
assert_eq!(
carried[0].bytes, sbom,
"the attested bytes are stored VERBATIM — varve transports another party's \
judgement, it never restates it"
);
let reports = crate::attestcarry::report(
&carried,
&layer_digest,
"2026.07.0",
&crate::keyroles::test_support::rt(&pk),
);
assert!(reports[0].binds, "reason: {:?}", reports[0].reason);
assert_eq!(reports[0].producer, "acme-ci");
}
#[test]
fn a_source_that_loses_its_attestations_still_installs_but_says_so() {
struct LosesAttestations(MemorySource);
impl LayerSource for LosesAttestations {
fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
self.0.fetch_manifest(layer)
}
fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
self.0.fetch_blob(digest)
}
fn fetch_attestations(
&self,
_layer: &LayerRef,
) -> Result<Vec<crate::attestcarry::CarriedAttestation>, SourceError> {
Err(SourceError::Transport("the mirror dropped them".into()))
}
}
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let outcome = install(
&pin("2026.07.0"),
&LosesAttestations(memory_source(&bytes, &blobs)),
&AcceptAll,
&store,
&mut marks,
&policy(),
)
.expect("a layer whose own signature and digests are good is still a good layer");
assert_eq!(outcome.attestations_carried, 0);
let note = outcome
.attestation_note
.expect("the loss must be reported, never swallowed");
assert!(note.contains("dropped them"), "note: {note}");
}
#[test]
fn a_new_machine_refuses_a_layer_below_the_realms_signed_floor() {
use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july(); let mut source = MemorySource::new().with_manifest(&bytes);
for (d, b) in &blobs {
source = source.with_blob(d, b);
}
let source = source
.with_line_index(
LineIndex {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
layers: vec![IndexedLayer {
layer: "2026.07.0".into(),
digest: manifest_digest(&bytes),
channel: "qualified".into(),
counter: 1,
}],
}
.sign(&sk, "root-1")
.unwrap()
.as_bytes(),
)
.with_line_status(
crate::linestatus::LineStatus {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
min_counter: Some(5),
support_until: None,
yanked: Default::default(),
known_problems: Vec::new(),
}
.sign(&sk, "root-1")
.unwrap()
.as_bytes(),
);
let policy = InstallPolicy {
index: Some(IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: true,
}),
..policy()
};
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.expect_err("a first contact below the signed floor must be refused");
match &err {
InstallError::BelowFloor {
line,
presented,
floor,
} => {
assert_eq!(line, "2026.07");
assert_eq!(*presented, 1);
assert_eq!(*floor, 5);
}
other => panic!("expected BelowFloor, got {other:?}"),
}
assert!(err.to_string().contains("never installed"), "{err}");
}
#[test]
fn a_line_whose_realm_states_no_floor_installs_as_it_always_did() {
use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let mut source = MemorySource::new().with_manifest(&bytes);
for (d, b) in &blobs {
source = source.with_blob(d, b);
}
let source = source
.with_line_index(
LineIndex {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
layers: vec![IndexedLayer {
layer: "2026.07.0".into(),
digest: manifest_digest(&bytes),
channel: "qualified".into(),
counter: 1,
}],
}
.sign(&sk, "root-1")
.unwrap()
.as_bytes(),
)
.with_line_status(
crate::linestatus::LineStatus {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
min_counter: None,
support_until: None,
yanked: Default::default(),
known_problems: Vec::new(),
}
.sign(&sk, "root-1")
.unwrap()
.as_bytes(),
);
let policy = InstallPolicy {
index: Some(IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: true,
}),
..policy()
};
install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.expect("no stated floor must not change anything");
}
#[test]
fn install_raises_the_mark_from_the_index_even_when_the_layer_is_hidden() {
use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july(); let mut source = MemorySource::new().with_manifest(&bytes);
for (d, b) in &blobs {
source = source.with_blob(d, b);
}
let source = source.with_line_index(
LineIndex {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
layers: vec![
IndexedLayer {
layer: "2026.07.0".into(),
digest: manifest_digest(&bytes),
channel: "qualified".into(),
counter: 1,
},
IndexedLayer {
layer: "2026.07.9".into(),
digest: "sha256:hidden".into(),
channel: "qualified".into(),
counter: 42,
},
],
}
.sign(&sk, "root-1")
.unwrap()
.as_bytes(),
);
let policy = InstallPolicy {
index: Some(IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: true,
}),
..policy()
};
let outcome = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.expect("a pinned layer must install even when the line has moved on");
assert_eq!(
outcome.index_high_water,
Some(42),
"the realm's assertion must reach the consumer even when the source \
withheld the layer it refers to"
);
assert_eq!(outcome.layer.to_string(), "2026.07.0");
assert_eq!(
marks.mark(&"2026.07".parse().unwrap()),
Some(1),
"the mark records what this machine ACCEPTED, not what exists"
);
}
#[test]
fn a_replayed_older_index_is_refused_on_the_next_install_not_only_in_theory() {
use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let signed_index = |counter: u64| {
LineIndex {
line: "2026.07".into(),
counter,
issued_at: "2026-08-07T00:00:00Z".into(),
layers: vec![IndexedLayer {
layer: "2026.07.0".into(),
digest: manifest_digest(&bytes),
channel: "qualified".into(),
counter: 1,
}],
}
.sign(&sk, "root-1")
.unwrap()
};
struct CountingSource {
inner: MemorySource,
blob_fetches: std::cell::Cell<usize>,
}
impl LayerSource for CountingSource {
fn fetch_manifest(&self, layer: &LayerRef) -> Result<Vec<u8>, SourceError> {
self.inner.fetch_manifest(layer)
}
fn fetch_blob(&self, digest: &str) -> Result<Vec<u8>, SourceError> {
self.blob_fetches.set(self.blob_fetches.get() + 1);
self.inner.fetch_blob(digest)
}
fn fetch_line_index(&self, line: &str) -> Result<Option<Vec<u8>>, SourceError> {
self.inner.fetch_line_index(line)
}
fn served_layers(&self, line: &str) -> Result<Option<Vec<String>>, SourceError> {
self.inner.served_layers(line)
}
}
let source_with = |envelope: &str| {
let mut s = MemorySource::new().with_manifest(&bytes);
for (d, b) in &blobs {
s = s.with_blob(d, b);
}
CountingSource {
inner: s.with_line_index(envelope.as_bytes()),
blob_fetches: std::cell::Cell::new(0),
}
};
let policy = InstallPolicy {
index: Some(IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: true,
}),
..policy()
};
install(
&pin("2026.07.0"),
&source_with(&signed_index(9)),
&AcceptAll,
&store,
&mut marks,
&policy,
)
.expect("the first install accepts index #9");
let replay = source_with(&signed_index(4));
let err = install(
&pin("2026.07.0"),
&replay,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.expect_err("a superseded index must not be replayable over the held one");
assert_eq!(
replay.blob_fetches.get(),
0,
"the index check runs BEFORE anything is fetched or laid down — a \
refusal discovered only when the cache was written would already \
have installed the layer and advanced the mark"
);
assert!(
matches!(
err,
InstallError::Index(crate::lineindex::IndexError::Stale {
presented: 4,
cached: 9,
..
})
),
"got: {err}"
);
assert!(
err.to_string().contains('4') && err.to_string().contains('9'),
"names both counters: {err}"
);
assert_eq!(
crate::lineindex::IndexCache::at_root(store.root())
.load("2026.07")
.unwrap()
.unwrap()
.counter,
9
);
}
#[test]
fn install_refuses_a_source_that_hides_an_indexed_layer() {
use crate::lineindex::{IndexPolicy, IndexedLayer, LineIndex};
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = july();
let mut source = MemorySource::new().with_manifest(&bytes);
for (d, b) in &blobs {
source = source.with_blob(d, b);
}
let source = source.serving(&["2026.07.0"]).with_line_index(
LineIndex {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
layers: vec![IndexedLayer {
layer: "2026.07.5".into(),
digest: "sha256:withheld".into(),
channel: "qualified".into(),
counter: 5,
}],
}
.sign(&sk, "root-1")
.unwrap()
.as_bytes(),
);
let policy = InstallPolicy {
index: Some(IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: true,
}),
..policy()
};
let err = install(
&pin("2026.07.0"),
&source,
&AcceptAll,
&store,
&mut marks,
&policy,
)
.expect_err("a source hiding an indexed layer must be refused");
let msg = err.to_string();
assert!(msg.contains("2026.07.5"), "names the hidden layer: {msg}");
assert!(store.list().unwrap().is_empty(), "no install on a refusal");
}
struct Consent {
_tmp: tempfile::TempDir,
store: Store,
marks: HighWaterMarks,
older: Vec<u8>,
newer: Vec<u8>,
source: MemorySource,
sk: Vec<u8>,
pk: Vec<u8>,
}
fn layer_of(name: &str, counter: u64, tag: &str) -> (Vec<u8>, Vec<(String, Vec<u8>)>) {
let blob = format!("{tag}-tool").into_bytes();
let blobs = vec![(manifest_digest(&blob), blob)];
let bytes = manifest_with_tools(
name,
"qualified",
counter,
"2026-07-31T09:14:00Z",
&[("synth", &blobs[0].0)],
);
(bytes, blobs)
}
fn consent_fixture() -> Consent {
let (sk, pk) = crate::verify::generate_root_keypair();
let (_tmp, store, marks) = setup();
let (older, ob) = layer_of("2026.07.0", 1, "old");
let (newer, nb) = layer_of("2026.07.1", 2, "new");
let mut source = MemorySource::new()
.with_manifest(&older)
.with_manifest(&newer);
for (d, b) in ob.iter().chain(nb.iter()) {
source = source.with_blob(d, b);
}
Consent {
_tmp,
store,
marks,
older,
newer,
source,
sk,
pk,
}
}
fn status_for(
line: &str,
support_until: Option<&str>,
yanked: &[(&str, &str)],
sk: &[u8],
) -> Vec<u8> {
status_numbered(1, line, support_until, yanked, sk)
}
fn status_numbered(
counter: u64,
line: &str,
support_until: Option<&str>,
yanked: &[(&str, &str)],
sk: &[u8],
) -> Vec<u8> {
crate::linestatus::LineStatus {
line: line.into(),
counter,
issued_at: "2026-08-01T00:00:00Z".into(),
support_until: support_until.map(str::to_string),
min_counter: None,
yanked: yanked
.iter()
.map(|(l, r)| (l.to_string(), r.to_string()))
.collect(),
known_problems: Vec::new(),
}
.sign(sk, "root-1")
.unwrap()
.as_bytes()
.to_vec()
}
fn digest_pin(layer: &str, digest: &str) -> Pin {
Pin::parse(
&format!(
"manifest-version = 1\n[toolchain]\nchannel = \"qualified\"\nlayer = \"{layer}\"\ndigest = \"{digest}\"\n"
),
"varve.toml",
)
.unwrap()
}
struct AcceptWithRoot(crate::keyroles::RealmTrust);
impl ManifestVerifier for AcceptWithRoot {
fn verify(&self, fetched: &[u8]) -> Result<Vec<u8>, VerifyError> {
Ok(fetched.to_vec())
}
fn trust(&self) -> Option<&crate::keyroles::RealmTrust> {
Some(&self.0)
}
}
fn see_the_newer(f: &mut Consent) {
install(
&pin("2026.07.1"),
&f.source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.unwrap();
assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
}
#[test]
fn a_digest_pinned_older_layer_the_line_supports_installs_past_the_mark() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source =
source.with_line_status(&status_for("2026.07", Some("2027-01-01"), &[], &f.sk));
let digest = manifest_digest(&f.older);
let outcome = install(
&digest_pin("2026.07.0", &digest),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect("a digest-pinned, supported, unyanked layer installs past the mark");
assert_eq!(outcome.counter, 1);
let consent = outcome.digest_consent.expect("the install must say so");
assert_eq!(consent.high_water, 2);
assert_eq!(consent.presented, 1);
assert_eq!(consent.digest, digest);
let note = consent.note();
for needle in [
digest.as_str(),
"counter 1",
"counter 2",
"2026.07",
"supported",
"not yanked",
] {
assert!(note.contains(needle), "{needle} missing from: {note}");
}
assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
assert!(f.store.get(&digest).unwrap().is_some());
}
#[test]
fn an_install_at_or_above_the_mark_carries_no_consent_note() {
let mut f = consent_fixture();
let digest = manifest_digest(&f.newer);
let outcome = install(
&digest_pin("2026.07.1", &digest),
&f.source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.unwrap();
assert_eq!(outcome.digest_consent, None);
}
#[test]
fn resolution_by_name_keeps_the_refusal_even_with_a_supporting_line_status() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let err = install(
&pin("2026.07.0"),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a name is not consent");
assert!(
matches!(
err,
InstallError::Rollback {
presented: 1,
high_water: 2,
..
}
),
"{err:?}"
);
assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
}
#[test]
fn a_yank_is_not_overridden_by_a_digest() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for(
"2026.07",
None,
&[("2026.07.0", "regression in synth")],
&f.sk,
));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a yanked layer stays refused");
let msg = err.to_string();
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{msg}"
);
assert!(
msg.contains("YANKED") && msg.contains("regression in synth"),
"{msg}"
);
assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
}
#[test]
fn an_expired_support_window_is_not_overridden_by_a_digest() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source =
source.with_line_status(&status_for("2026.07", Some("2026-08-06"), &[], &f.sk));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("an out-of-support layer stays refused");
let msg = err.to_string();
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{msg}"
);
assert!(msg.contains("out of support"), "{msg}");
}
#[test]
fn the_last_supported_day_still_consents() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source =
source.with_line_status(&status_for("2026.07", Some("2026-08-07"), &[], &f.sk));
install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect("the horizon day is still supported");
}
#[test]
fn no_line_status_at_all_refuses_and_says_consent_needs_one() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&f.source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("the pin alone is not trusted");
let msg = err.to_string();
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{msg}"
);
assert!(
msg.contains("digest consent needs a verifiable line-status"),
"{msg}"
);
assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
}
#[test]
fn every_refusal_of_digest_consent_is_terminal_so_no_mirror_can_grant_it() {
let refusal = |f: &mut Consent, source: MemorySource, v: &dyn ManifestVerifier| {
install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
v,
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("refused")
};
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let pk = f.pk.clone();
let err = refusal(
&mut f,
source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
);
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{err}"
);
assert!(
!err.fails_over(),
"an absent status must not send us elsewhere: {err}"
);
let mut f = consent_fixture();
see_the_newer(&mut f);
let (other_sk, _) = crate::verify::generate_root_keypair();
let source = std::mem::replace(&mut f.source, MemorySource::new())
.with_line_status(&status_for("2026.07", None, &[], &other_sk));
let pk = f.pk.clone();
let err = refusal(
&mut f,
source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
);
assert!(
!err.fails_over(),
"an unverifiable status must not send us elsewhere: {err}"
);
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new()).with_line_status(
&status_for("2026.07", None, &[("2026.07.0", "regression")], &f.sk),
);
let pk = f.pk.clone();
let err = refusal(
&mut f,
source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
);
assert!(!err.fails_over(), "a verified yank is terminal: {err}");
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new())
.with_line_status(&status_for("2026.07", Some("2026-08-06"), &[], &f.sk));
let pk = f.pk.clone();
let err = refusal(
&mut f,
source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
);
assert!(!err.fails_over(), "a verified expiry is terminal: {err}");
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new())
.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let err = refusal(&mut f, source, &AcceptAll);
assert!(!err.fails_over(), "no root is local: {err}");
}
#[test]
fn a_mirror_is_never_asked_to_consent_even_when_its_status_would() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let pin = digest_pin("2026.07.0", &manifest_digest(&f.older));
let ok = install_from(
&pin,
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
true,
);
assert!(ok.is_ok(), "the primary may grant consent: {ok:?}");
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let err = install_from(
&pin,
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
false,
)
.expect_err("a mirror cannot grant consent");
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{err}"
);
assert!(
err.to_string()
.contains("only taken from the realm's primary"),
"{err}"
);
assert!(!err.fails_over());
assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
}
fn first_contact(
f: &mut Consent,
source: &MemorySource,
primary: bool,
) -> Result<InstallOutcome, InstallError> {
first_contact_from(f, source, primary)
}
fn first_contact_from(
f: &mut Consent,
source: &dyn LayerSource,
primary: bool,
) -> Result<InstallOutcome, InstallError> {
let pk = f.pk.clone();
let policy = InstallPolicy {
index: Some(crate::lineindex::IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: false,
}),
..policy()
};
install_from(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy,
primary,
)
}
#[test]
fn a_first_contact_is_refused_to_a_mirror_whatever_status_it_carries() {
for status in [
None,
Some(("2026.07", false)), Some(("2026.07", true)), Some(("2026.06", false)), ] {
let mut f = consent_fixture();
let (other_sk, _) = crate::verify::generate_root_keypair();
let mut source = std::mem::replace(&mut f.source, MemorySource::new());
if let Some((line, forged)) = status {
let sk = if forged { &other_sk } else { &f.sk };
source = source.with_line_status(&status_for(line, None, &[], sk));
}
let err = first_contact(&mut f, &source, false)
.expect_err("a mirror must not answer a first contact");
assert!(
matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
"{err}"
);
assert!(
err.to_string()
.contains("first contact with line 2026.07 needs the realm's primary"),
"{err}"
);
assert!(!err.fails_over(), "no other mirror can do better");
assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
}
}
#[test]
fn a_mirror_is_asked_nothing_before_a_first_contact_is_refused() {
struct Untouched;
impl LayerSource for Untouched {
fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
panic!("a mirror was asked about a first contact");
}
fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, SourceError> {
panic!("a mirror was asked about a first contact");
}
}
let mut f = consent_fixture();
let err = first_contact_from(&mut f, &Untouched, false).expect_err("refused");
assert!(matches!(err, InstallError::FirstContactNeedsPrimary { .. }));
}
#[test]
fn the_primary_answers_a_first_contact_and_history_of_either_kind_admits_a_mirror() {
let mut f = consent_fixture();
let source = std::mem::replace(&mut f.source, MemorySource::new());
first_contact(&mut f, &source, true).expect("the primary answers a first contact");
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let newer = digest_pin("2026.07.1", &manifest_digest(&f.newer));
let pk = f.pk.clone();
let policy = InstallPolicy {
index: Some(crate::lineindex::IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: false,
}),
..policy()
};
let outcome = install_from(
&newer,
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy,
false,
)
.expect("a mark is history");
assert_eq!(
outcome.omission_check_skipped,
Some(OmissionSkipped::NoIndex),
"a mirror with no index could not run the omission check"
);
let mut f = consent_fixture();
let line: crate::layer::Line = "2026.07".parse().unwrap();
let envelope = status_for("2026.07", None, &[], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&envelope,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(f.store.root())
.update(&line, &envelope, &doc)
.unwrap();
let source = std::mem::replace(&mut f.source, MemorySource::new());
first_contact(&mut f, &source, false).expect("a cached status is history");
}
fn status_with_floor(counter: u64, min_counter: Option<u64>, sk: &[u8]) -> Vec<u8> {
crate::linestatus::LineStatus {
line: "2026.07".into(),
counter,
issued_at: "2026-08-01T00:00:00Z".into(),
support_until: None,
min_counter,
yanked: Default::default(),
known_problems: Vec::new(),
}
.sign(sk, "root-1")
.unwrap()
.into_bytes()
}
fn install_four_against_a_cached_floor(
source_status: Option<Vec<u8>>,
cached: Vec<u8>,
pk: &[u8],
primary: bool,
) -> Result<InstallOutcome, InstallError> {
let (_tmp, store, mut marks) = setup();
let (bytes, blobs) = layer_of("2026.07.2", 4, "four");
let mut source = MemorySource::new().with_manifest(&bytes);
for (d, b) in &blobs {
source = source.with_blob(d, b);
}
if let Some(status) = &source_status {
source = source.with_line_status(status);
}
let line: crate::layer::Line = "2026.07".parse().unwrap();
let doc = crate::linestatus::LineStatus::verify_and_parse(
&cached,
&crate::keyroles::test_support::rt(pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(store.root())
.update(&line, &cached, &doc)
.unwrap();
let policy = InstallPolicy {
index: Some(crate::lineindex::IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(pk),
required: false,
}),
..policy()
};
install_from(
&pin("2026.07.2"),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(pk)),
&store,
&mut marks,
&policy,
primary,
)
}
#[test]
fn a_floor_this_machine_already_recorded_is_not_lowered_by_what_a_source_serves() {
let (sk, pk) = crate::verify::generate_root_keypair();
let cached = || status_with_floor(3, Some(5), &sk);
for primary in [false, true] {
let err = install_four_against_a_cached_floor(
Some(status_with_floor(1, None, &sk)),
cached(),
&pk,
primary,
)
.expect_err("counter 4 is below the recorded floor of 5");
assert!(
matches!(err, InstallError::BelowFloor { floor: 5, .. }),
"primary={primary}: {err}"
);
let err = install_four_against_a_cached_floor(None, cached(), &pk, primary)
.expect_err("silence does not lower a recorded floor");
assert!(
matches!(err, InstallError::BelowFloor { floor: 5, .. }),
"primary={primary}: {err}"
);
let (other_sk, _) = crate::verify::generate_root_keypair();
let err = install_four_against_a_cached_floor(
Some(status_with_floor(9, None, &other_sk)),
cached(),
&pk,
primary,
)
.expect_err("a forged status does not lower it either");
assert!(matches!(err, InstallError::BelowFloor { .. }), "{err}");
}
}
#[test]
fn the_newer_verified_status_decides_the_floor_whichever_side_holds_it() {
let (sk, pk) = crate::verify::generate_root_keypair();
let err = install_four_against_a_cached_floor(
Some(status_with_floor(4, Some(7), &sk)),
status_with_floor(3, Some(2), &sk),
&pk,
false,
)
.expect_err("the newer status raised the floor to 7");
assert!(
matches!(err, InstallError::BelowFloor { floor: 7, .. }),
"{err}"
);
install_four_against_a_cached_floor(
Some(status_with_floor(4, Some(2), &sk)),
status_with_floor(3, Some(5), &sk),
&pk,
false,
)
.expect("the newer word lowered the floor");
}
#[test]
fn a_mirror_that_carries_an_index_but_cannot_enumerate_leaves_the_omission_check_unrun() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let pk = f.pk.clone();
let index = crate::lineindex::LineIndex {
line: "2026.07".into(),
counter: 1,
issued_at: "2026-08-07T00:00:00Z".into(),
layers: vec![crate::lineindex::IndexedLayer {
layer: "2026.07.1".into(),
digest: manifest_digest(&f.newer),
channel: "qualified".into(),
counter: 2,
}],
}
.sign(&f.sk, "root-1")
.unwrap();
let source =
std::mem::replace(&mut f.source, MemorySource::new()).with_line_index(index.as_bytes());
let policy = InstallPolicy {
index: Some(crate::lineindex::IndexPolicy {
realm: "acme",
trust: crate::keyroles::test_support::leak_rt(&pk),
required: false,
}),
..policy()
};
let newer = digest_pin("2026.07.1", &manifest_digest(&f.newer));
let outcome = install_from(
&newer,
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy,
false,
)
.expect("history lets a mirror answer");
assert_eq!(
outcome.omission_check_skipped,
Some(OmissionSkipped::CannotEnumerate),
"an index it cannot compare with a listing is a check that could not run"
);
let mut f = consent_fixture();
see_the_newer(&mut f);
let source =
std::mem::replace(&mut f.source, MemorySource::new()).with_line_index(index.as_bytes());
let outcome = install_from(
&newer,
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy,
true,
)
.unwrap();
assert_eq!(outcome.omission_check_skipped, None);
}
#[test]
fn a_digest_install_refuses_a_mirror_before_contacting_it_when_there_is_no_history() {
struct Untouched;
impl LayerSource for Untouched {
fn fetch_manifest(&self, _: &LayerRef) -> Result<Vec<u8>, SourceError> {
panic!("a mirror was contacted for a first contact");
}
fn fetch_blob(&self, _: &str) -> Result<Vec<u8>, SourceError> {
panic!("a mirror was contacted for a first contact");
}
}
let line: crate::layer::Line = "2026.07".parse().unwrap();
let mut f = consent_fixture();
let pk = f.pk.clone();
let err = install_by_digest_from(
&manifest_digest(&f.older),
&Untouched,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy(),
DigestRole::Mirror {
expected_line: Ok(&line),
},
)
.expect_err("no history, no mirror");
assert!(
matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
"{err}"
);
assert!(!err.fails_over());
for why in [
"the include names no layer",
"the include's layer name \"x\" is not a valid layer id",
] {
let mut f = consent_fixture();
let err = install_by_digest_from(
&manifest_digest(&f.older),
&Untouched,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy(),
DigestRole::Mirror {
expected_line: Err(why.to_string()),
},
)
.unwrap_err();
assert!(
matches!(&err, InstallError::LineUnknownForMirror { why: w } if w == why),
"{err}"
);
assert!(err.to_string().contains(why), "{err}");
assert!(!err.to_string().contains("no history"), "{err}");
assert!(!err.fails_over());
}
}
#[test]
fn a_digest_install_from_a_mirror_proceeds_when_the_expected_line_has_history() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let pk = f.pk.clone();
let line: crate::layer::Line = "2026.07".parse().unwrap();
let source = std::mem::replace(&mut f.source, MemorySource::new());
install_by_digest_from(
&manifest_digest(&f.newer),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy(),
DigestRole::Mirror {
expected_line: Ok(&line),
},
)
.expect("history for the line admits a mirror");
let mut f = consent_fixture();
see_the_newer(&mut f);
let other: crate::layer::Line = "2026.06".parse().unwrap();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let err = install_by_digest_from(
&manifest_digest(&f.newer),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy(),
DigestRole::Mirror {
expected_line: Ok(&other),
},
)
.unwrap_err();
assert!(
matches!(err, InstallError::FirstContactNeedsPrimary { .. }),
"{err}"
);
}
#[test]
fn an_include_that_names_one_line_but_digests_another_is_refused_terminally() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let (other_layer, other_blobs) = layer_of("2026.06.0", 1, "elsewhere");
let mut source =
std::mem::replace(&mut f.source, MemorySource::new()).with_manifest(&other_layer);
for (d, b) in &other_blobs {
source = source.with_blob(d, b);
}
let named: crate::layer::Line = "2026.07".parse().unwrap();
let pk = f.pk.clone();
let err = install_by_digest_from(
&manifest_digest(&other_layer),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&pk)),
&f.store,
&mut f.marks,
&policy(),
DigestRole::Mirror {
expected_line: Ok(&named),
},
)
.expect_err("a mislabelled include");
assert!(
matches!(&err, InstallError::FirstContactNeedsPrimary { line } if line == "2026.06"),
"{err}"
);
assert!(!err.fails_over());
assert!(
f.store
.get(&manifest_digest(&other_layer))
.unwrap()
.is_none(),
"nothing may be installed"
);
}
#[test]
fn a_primary_install_never_reports_a_skipped_omission_check() {
let mut f = consent_fixture();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let outcome = first_contact(&mut f, &source, true).unwrap();
assert_eq!(outcome.omission_check_skipped, None);
}
#[test]
fn a_verifier_that_names_no_root_cannot_verify_a_status_so_it_is_refused() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptAll,
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("no root, no consent");
assert!(err.to_string().contains("no trust root"), "{err}");
}
#[test]
fn a_status_signed_by_another_root_gives_no_consent() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let (other_sk, _) = crate::verify::generate_root_keypair();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &other_sk));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a forged status must not consent");
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{err}"
);
}
#[test]
fn a_status_for_another_line_gives_no_consent() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.06", None, &[], &f.sk));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a status of another line says nothing about this one");
assert!(
matches!(err, InstallError::RollbackConsentRefused { .. }),
"{err}"
);
}
#[test]
fn a_cached_line_status_consents_when_the_source_carries_none() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let line: crate::layer::Line = "2026.07".parse().unwrap();
let envelope = status_for("2026.07", None, &[], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&envelope,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(f.store.root())
.update(&line, &envelope, &doc)
.unwrap();
let outcome = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&f.source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect("an offline machine that cached a verified status may consent");
assert!(outcome.digest_consent.is_some());
}
#[test]
fn a_registry_replaying_an_older_status_cannot_undo_a_cached_yank() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let line: crate::layer::Line = "2026.07".parse().unwrap();
let yank = status_numbered(2, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&yank,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(f.store.root())
.update(&line, &yank, &doc)
.unwrap();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_numbered(1, "2026.07", None, &[], &f.sk));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("an older served status must not outrank the cached yank");
assert!(err.to_string().contains("YANKED"), "{err}");
assert!(f.store.get(&manifest_digest(&f.older)).unwrap().is_none());
}
#[test]
fn a_signed_floor_is_not_overridden_by_a_digest() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let mut doc = crate::linestatus::LineStatus::verify_and_parse(
&status_for("2026.07", None, &[], &f.sk),
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
doc.min_counter = Some(2);
let envelope = doc.sign(&f.sk, "root-1").unwrap().as_bytes().to_vec();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&envelope);
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a counter below the signed floor stays refused");
assert!(err.to_string().contains("floor"), "{err}");
}
#[test]
fn a_layer_exactly_at_the_signed_floor_still_consents() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let mut doc = crate::linestatus::LineStatus::verify_and_parse(
&status_for("2026.07", None, &[], &f.sk),
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
doc.min_counter = Some(1); let envelope = doc.sign(&f.sk, "root-1").unwrap().as_bytes().to_vec();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&envelope);
let outcome = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect("a floor AT the layer's counter does not exclude it");
assert!(outcome.digest_consent.is_some());
}
#[test]
fn verifys_offline_judgment_reads_the_cache_and_names_why() {
let f = consent_fixture();
let older = LayerManifest::parse(&f.older).unwrap();
let now = "2026-08-07T00:00:00Z";
let none = cached_consent_why_not(
&older,
f.store.root(),
&crate::keyroles::test_support::rt(&f.pk),
now,
)
.expect("nothing cached is not consent");
assert!(
none.contains("none is available for line 2026.07"),
"{none}"
);
let line: crate::layer::Line = "2026.07".parse().unwrap();
let cache = crate::linestatus::StatusCache::at_root(f.store.root());
let ok = status_numbered(1, "2026.07", None, &[], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&ok,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
cache.update(&line, &ok, &doc).unwrap();
assert_eq!(
cached_consent_why_not(
&older,
f.store.root(),
&crate::keyroles::test_support::rt(&f.pk),
now
),
None
);
let yank = status_numbered(2, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&yank,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
cache.update(&line, &yank, &doc).unwrap();
let why = cached_consent_why_not(
&older,
f.store.root(),
&crate::keyroles::test_support::rt(&f.pk),
now,
)
.expect("a cached yank refuses");
assert!(why.contains("YANKED") && why.contains("bad"), "{why}");
}
#[test]
fn a_newer_served_status_outranks_an_older_cached_one() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let line: crate::layer::Line = "2026.07".parse().unwrap();
let yank = status_numbered(1, "2026.07", None, &[("2026.07.0", "bad")], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&yank,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(f.store.root())
.update(&line, &yank, &doc)
.unwrap();
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_numbered(2, "2026.07", None, &[], &f.sk));
let outcome = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect("a newer signed status that lifts the yank consents");
assert!(outcome.digest_consent.is_some());
}
#[test]
fn a_cached_status_that_yanks_the_layer_refuses_offline() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let line: crate::layer::Line = "2026.07".parse().unwrap();
let envelope = status_for("2026.07", None, &[("2026.07.0", "bad")], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&envelope,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(f.store.root())
.update(&line, &envelope, &doc)
.unwrap();
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&f.source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("the cached yank binds");
assert!(err.to_string().contains("YANKED"), "{err}");
}
#[test]
fn a_pin_naming_one_layer_with_anothers_digest_is_refused_not_consented() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.newer)),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a digest that is not the named layer's is refused");
assert!(matches!(err, InstallError::LayerMismatch { .. }), "{err}");
let wrong = format!("sha256:{}", "ab".repeat(32));
assert!(
install(
&digest_pin("2026.07.0", &wrong),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.is_err()
);
assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
}
#[test]
fn a_digest_named_by_a_composition_is_not_consent() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let source = std::mem::replace(&mut f.source, MemorySource::new());
let source = source.with_line_status(&status_for("2026.07", None, &[], &f.sk));
let err = install_by_digest(
&manifest_digest(&f.older),
&source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("an include is a signer's choice, not this project's consent");
assert!(matches!(err, InstallError::Rollback { .. }), "{err:?}");
}
#[test]
fn a_cached_status_filed_under_the_wrong_line_gives_no_consent() {
let mut f = consent_fixture();
see_the_newer(&mut f);
let line: crate::layer::Line = "2026.07".parse().unwrap();
let envelope = status_for("2026.06", None, &[], &f.sk);
let doc = crate::linestatus::LineStatus::verify_and_parse(
&envelope,
&crate::keyroles::test_support::rt(&f.pk),
)
.unwrap();
crate::linestatus::StatusCache::at_root(f.store.root())
.update(&line, &envelope, &doc)
.unwrap();
let err = install(
&digest_pin("2026.07.0", &manifest_digest(&f.older)),
&f.source,
&AcceptWithRoot(crate::keyroles::test_support::rt(&f.pk)),
&f.store,
&mut f.marks,
&policy(),
)
.expect_err("a status about another line says nothing about this one");
assert!(err.to_string().contains("covers line 2026.06"), "{err}");
}
}