Skip to main content

varve_core/
install.rs

1//! The verified install pipeline (REQ-VERIFY-001, REQ-ROLLBACK-001).
2//!
3//! Order is the security argument, so it is fixed here and tested:
4//!
5//! 1. fetch manifest bytes (by pin digest if pinned, else by name)
6//! 2. **verify the manifest signature** against the trust root
7//! 3. parse strictly; cross-check layer name, channel, pinned digest
8//! 4. anti-rollback check against the per-line high-water mark
9//! 5. fetch each blob; **verify each digest** against the signed manifest
10//! 6. lay down in the core
11//! 7. only now advance the high-water mark
12//!
13//! Nothing a source returns reaches the core unverified, and a failed
14//! install leaves both the core and the high-water marks untouched. The
15//! kill-criterion (REQ-VERIFY-001): running the same bytes through two
16//! different sources yields identical verdicts — a source that could
17//! influence acceptance has joined the trusted base, and the design is broken.
18
19use 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
26/// Signature verification over fetched manifest bytes, against the
27/// PulseEngine trust root. Returns the *authenticated payload* (the layer
28/// manifest itself) — for DSSE-enveloped transport the fetched bytes and the
29/// trusted bytes differ, and everything downstream must use only the latter.
30/// Implementations carry the trust root; callers cannot relax it per-source —
31/// the pipeline takes exactly one verifier for all sources.
32pub trait ManifestVerifier {
33    fn verify(&self, fetched_bytes: &[u8]) -> Result<Vec<u8>, VerifyError>;
34
35    /// The trust this verifier judges by, when it has one to name. A signed
36    /// document OTHER than the layer (the line-status digest consent rests on,
37    /// REQ-ROLLBACK-002) is verified against this same trust and no other, each
38    /// under the role its payload type belongs to (REQ-KEYROLES-001).
39    /// `None` means "cannot say", which consumers must read as "cannot verify".
40    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/// Why the omission check could not run against a MIRROR.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum OmissionSkipped {
52    /// The mirror carries no line index at all.
53    NoIndex,
54    /// The mirror carries an index but cannot enumerate the layers it serves
55    /// (a directory or OCI layout), so the index has nothing to be compared
56    /// with.
57    CannotEnumerate,
58}
59
60/// A successful install.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct InstallOutcome {
63    pub digest: String,
64    pub layer: LayerId,
65    pub counter: u64,
66    /// `Some(age_days)` when the accepted layer is older than the staleness
67    /// threshold — surfaced, never fatal.
68    pub staleness_days: Option<i64>,
69    /// The greatest counter the realm's signed index asserts for this line
70    /// (REQ-INDEXAUTH-001 clause 4). Reported, NOT enforced: the high-water
71    /// mark records what this machine has accepted, and raising it to what
72    /// merely EXISTS would refuse a deliberately-pinned older layer the moment
73    /// a newer one is published — an availability failure wearing a security
74    /// control's clothes, in the one tool whose purpose is frozen toolchains.
75    pub index_high_water: Option<u64>,
76    /// How many attestations travelled with the layer and were persisted into
77    /// its root (REQ-ATTEST-002). Unverified at this point, by design — see
78    /// `attestcarry::carry_from_source`; `varve verify` is what checks them.
79    pub attestations_carried: usize,
80    /// Why carriage was incomplete, when it was. REPORTED, never fatal: a
81    /// mirror that dropped an attestation blob must not be able to make a
82    /// correctly-signed layer uninstallable, but the loss must not be silent
83    /// either — silence is the exact bandersnatch/Verdaccio failure this
84    /// requirement exists to surface.
85    pub attestation_note: Option<String>,
86    /// The source was a MIRROR and carried no line index, so the omission
87    /// check (a layer the signed index names but the source hides) could not
88    /// run against it. Reported, never silent: the install proceeds only
89    /// because this machine has local history bounding what a mirror says.
90    pub omission_check_skipped: Option<OmissionSkipped>,
91    /// Set when this install went ahead of the machine's anti-rollback
92    /// high-water mark on the strength of a digest in the project's pin
93    /// (REQ-ROLLBACK-002). Carries what the caller must say out loud.
94    pub digest_consent: Option<DigestConsent>,
95}
96
97/// An install that was below the machine's mark and accepted anyway because the
98/// pin names the layer by digest and the line's signed line-status supports it
99/// (REQ-ROLLBACK-002).
100#[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    /// The one line the install prints: pinned digest, the machine's higher
110    /// counter, and why that was not a refusal.
111    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    /// May ANOTHER source of the same realm be asked after this failure?
210    /// (REQ-MIRROR-002 clause 2.)
211    ///
212    /// Only when this source's BYTES are the problem: unavailable, not
213    /// authentic, malformed, or substituted. A verified verdict about genuine
214    /// bytes (rollback, floor, no platform entry) or a local failure is
215    /// TERMINAL: asking a lagging mirror afterwards would hand the same
216    /// machine a second chance against a lower bar, and failover itself would
217    /// become the freeze/rollback attack.
218    ///
219    /// An exhaustive `match` with no `_` arm, so a new variant cannot be added
220    /// without deciding which side of that line it is on.
221    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
245/// Policy inputs the caller supplies; time is data, not something the
246/// pipeline samples.
247pub struct InstallPolicy<'a> {
248    /// RFC 3339 "now" for the staleness verdict.
249    pub now: &'a str,
250    pub staleness_threshold_days: u32,
251    /// Target platform (a triple) entries must match. Entries without a
252    /// platform annotation are platform-independent (REQ-PLATFORM-001).
253    pub platform: &'a str,
254    /// The realm's line-index obligation (REQ-INDEXAUTH-001). `None` where the
255    /// pin names no realm — there is then no root that could have signed an
256    /// index, so there is nothing to check.
257    pub index: Option<crate::lineindex::IndexPolicy<'a>>,
258}
259
260/// Install a layer named only by the digest of its signed manifest — what an
261/// `[[include]]` names (REQ-COMPOSEINSTALL-001).
262///
263/// A composition names the layers it needs by digest, and until v0.38.0 varve
264/// declined to FETCH them: an operator installing a four-layer composition from
265/// one registry had to create a pinned directory per layer and install each by
266/// hand. The refusal bought nothing. A digest is fixed at signing, so whatever
267/// arrives either hashes to it or is refused; declining to fetch bytes varve
268/// can name exactly is friction wearing the clothes of caution.
269///
270/// What it does NOT do is pin: no varve.toml is written, because obtaining a
271/// layer and choosing it are different acts, and a pin that appeared by itself
272/// would be a decision nobody made.
273///
274/// Every check a direct install makes still runs — the realm's signed index,
275/// anti-rollback, the platform filter — because this delegates to `install`
276/// rather than reimplementing it. The cost is re-fetching one small manifest to
277/// learn the layer id and channel the digest belongs to; the alternative was a
278/// second copy of two hundred lines that decide whether bytes are acceptable,
279/// and a second copy is how those two answers drift apart.
280pub 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/// Which source an install-by-digest is reading from. A digest names no line,
300/// so a MIRROR carries the line the caller expects (from the include that
301/// named the digest) and the first-contact refusal is decided on it BEFORE the
302/// mirror is asked anything.
303#[derive(Debug, Clone)]
304pub enum DigestRole<'a> {
305    /// The realm's primary (or its only source).
306    Primary,
307    /// A mirror. `expected_line` is the line of the layer the digest should
308    /// turn out to be, if the caller knows it. `Err(why)` says why the line
309    /// cannot be known before fetching (the include names no layer, or names
310    /// one that is not a valid layer id); a mirror is then refused, because no
311    /// history can be shown for an unknown line.
312    Mirror {
313        expected_line: Result<&'a crate::layer::Line, String>,
314    },
315}
316
317/// [`install_by_digest`] from a source that is, or is not, the realm's
318/// PRIMARY. A non-primary source (a mirror, asked after the primary failed)
319/// may not relax a protection: see [`install_from`].
320pub 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    // First contact is decided BEFORE a mirror is contacted: reading the
330    // manifest here would otherwise be a fetch from a source that may not be
331    // allowed to answer. The line comes from the caller (the include that
332    // named this digest); `install_inner` re-checks it against the real
333    // manifest's line afterwards.
334    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    // The digest here comes from a composing layer, not from a project's pin,
368    // so it is NOT consent to go below the mark (REQ-ROLLBACK-002 speaks of
369    // the project's pin): a layer's include list is the signer's choice, and
370    // what this machine accepts is still the machine's.
371    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
385/// Install the layer a project's pin selects. A pin that names the layer by
386/// digest is consent to go below the machine's high-water mark when the line's
387/// signed line-status supports the layer (REQ-ROLLBACK-002).
388pub 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
399/// [`install`] from a source that is, or is not, the realm's PRIMARY.
400///
401/// Once the primary has failed in an attempt, a MIRROR's answer may not RELAX
402/// a protection: absence or an older document on a mirror is "unknown", not
403/// "none". So from a non-primary source (a) digest CONSENT to go below the
404/// mark is refused, because it lifts a protection and the mirror may be
405/// lagging a yank, and (b) a FIRST CONTACT (no local history for the line: no
406/// high-water mark and no cached line-status) is refused outright with
407/// [`InstallError::FirstContactNeedsPrimary`], before anything is fetched,
408/// because a mirror cannot prove it is current and nothing bounds it. With
409/// history a mirror answers, bounded by the marks and the cached status.
410pub 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/// How an install reached its source: whether a digest in the pin is consent
434/// to go below the mark, and whether the source is the realm's primary.
435#[derive(Clone, Copy)]
436struct Via {
437    digest_is_consent: bool,
438    source_is_primary: bool,
439}
440
441/// Whether this machine has ANY record of `line`: a high-water mark, or a
442/// cached line-status that verifies against the realm's root.
443fn 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    // 0. FIRST CONTACT is answered only by the realm's primary. With no local
472    // history for the line (no high-water mark and no cached line-status) a
473    // mirror's answer is bounded by nothing: a lagging mirror can serve a
474    // genuine but OLD layer with a genuine but OLD status (no raised floor, a
475    // pre-demotion channel, no omission check), and this machine has nothing to
476    // notice that it is old. Asked before anything is fetched from it.
477    //
478    // WITH history a mirror's answer is accepted, bounded by the marks and the
479    // cached status below as for any source. The residual is the documented
480    // one: a machine that has installed before can be served a state no older
481    // than it last recorded — including a pre-demotion manifest whose channel
482    // still matches — but not a state older than that.
483    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    // 1. Fetch.
489    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    // 2. Signature first: nothing else is read from unverified bytes, and no
496    // blob is fetched on the strength of an unverified manifest. Only the
497    // authenticated payload the verifier returns is used from here on.
498    let bytes = verifier.verify(&fetched)?;
499
500    // 3. Strict parse + cross-checks against the pin.
501    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    // 3b. The realm's signed index (REQ-INDEXAUTH-001). Before anti-rollback,
529    // because the index can RAISE the mark: a registry that hides the newest
530    // layer must not lower the bar this install has to clear. Everything here
531    // is verified against the realm's root — the source is the party being
532    // constrained and is never asked whether its own listing is honest.
533    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    // The verified index and the bytes it came from, held until the install
539    // lands: a refused install must not leave a raised index behind, for the
540    // same reason it must not burn the high-water mark.
541    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        // What this source PROVED is a baseline for every later source in the
545        // run, whatever happens to the rest of this attempt (varve#311): the
546        // listing below or a blob later may fail and fail over, and a mirror
547        // must not then pass against an older index than this one.
548        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        // A mirror with no index leaves the omission check unable to run: that
555        // is UNKNOWN, not "nothing hidden", and it is reported (D4).
556        let served = source.served_layers(&line_str)?;
557        // ... and so is a mirror whose index cannot be compared with a listing
558        // (it cannot enumerate what it serves): the check cannot run either.
559        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        // Clause 2 needs something to compare AGAINST, and it is the cache
569        // that supplies it. Passing `None` here left the whole
570        // presented-older-than-held rule unreachable from the pipeline: it
571        // could only ever fire in a test that called `check` itself.
572        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    // REQ-FIRSTCONTACT-001: the realm's signed floor for this line, for a
590    // consumer that has no mark of its own.
591    //
592    // Read from the line-status document, which is already DSSE-signed by the
593    // realm root and already distributed beside the layer — a floor is worth
594    // nothing if whoever serves the bytes can choose it. Verified here against
595    // the same root the index policy carries; a document that does not verify,
596    // or that covers another line, yields NO floor rather than a trusted zero.
597    //
598    // Best-effort, and the residual is worth stating plainly: a source that
599    // simply omits the line-status removes the floor, exactly as it could
600    // before this existed. That is not a regression, and it is not full
601    // protection either — closing it needs the realm to REQUIRE a status the
602    // way `signed-index` requires an index, which is a realm-policy change and
603    // not this requirement.
604    //
605    // With NO mark the floor is the one stated by the HIGHER-counter verified
606    // status among the one this machine already CACHED, the one the source
607    // serves, and the one an earlier source VERIFIED in this run (varve#311).
608    // An OLDER status (a lower or absent `min_counter`), no status, or an
609    // unverifiable one leaves the recorded floor in force: that is what bounds
610    // a mirror's answer by what this machine has already recorded, primary or
611    // not. A NEWER realm-signed status supersedes an older one and states its
612    // own floor, which may be lower: that is intended, and a served status
613    // always could do it.
614    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        // A status an earlier source proved in this run holds for this one,
630        // though that source's attempt failed over after (varve#311).
631        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    // 4. Anti-rollback, before any blob moves.
643    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            // REQ-ROLLBACK-002: a digest in the project's pin is a decision a
651            // reviewer saw; resolution by name is the replay REQ-ROLLBACK-001
652            // exists for. The digest was already matched against the
653            // verified manifest in step 3.
654            (Some(_), true) if !source_is_primary => {
655                // Consent LIFTS the mark. A mirror asked after the primary
656                // failed may be lagging a yank, so it cannot grant it.
657                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    // 5. Fetch blobs; each is accepted only if it matches its signed digest.
716    // Platform filtering happens BEFORE any fetch: a foreign entry's blob
717    // never even leaves the source (REQ-PLATFORM-001).
718    // Name, version and dispatchability travel with the bytes: a payload that
719    // is not dispatched by name is laid down under its version too, so two
720    // versions of one crate cannot overwrite each other (REQ-STORE-002).
721    struct Fetched {
722        name: String,
723        version: Option<String>,
724        dispatchable: bool,
725        /// What the payload builds for, when it says (REQ-SDKTARGET-001).
726        /// Two cross-toolchains for one host differ ONLY here, so it has to
727        /// survive the fetch or they collide on one path.
728        target: Option<String>,
729        bytes: Vec<u8>,
730    }
731    let mut tools: Vec<Fetched> = Vec::new();
732    let mut matched = 0usize;
733    // Entries that COULD match a platform — everything that is not a
734    // composition edge. The fail-closed check below compares against this and
735    // not against the manifest's whole entry list, because an `[[include]]`
736    // carries no bytes and is never stamped for a platform: counting it would
737    // make a layer that is ONLY a composition look like a layer whose every
738    // payload was for the wrong architecture.
739    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        // A composed layer is a REFERENCE, not a blob to lay down: its digest
755        // names another layer's manifest, which has its own install. Skip it
756        // here — install rejected it outright before, so a real composed layer
757        // could not be installed at all (REQ-COMPOSE-001).
758        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    // A fully-stamped layer with nothing for this platform fails closed —
786    // a wrong-architecture toolchain must not land looking installed.
787    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    // 6. Lay down.
795    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    // Record WHICH platform these payloads were selected for, so `verify`
809    // filters by the decision made here instead of re-deriving one from
810    // whatever host it is run on later (varve#189).
811    if let Some(entry) = store.get(&digest)? {
812        crate::store::record_install_platform(&entry.root, policy.platform)?;
813    }
814
815    // Retain the signature envelope beside the payload, so `varve verify`
816    // can repeat the install-time verdict offline, forever. (When transport
817    // was already the bare payload — test doubles — there is nothing to keep.)
818    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    // 6b. Carry the layer's attestations into its root (REQ-ATTEST-002).
829    // Registries publish this evidence and mirrors drop it: bandersnatch and
830    // Verdaccio carry none, and every Bazel Central Registry attestation URL
831    // points at github.com — so without this an air-gapped consumer receives
832    // the bytes and none of the accountability, with no error saying so.
833    // Persisting here is also what lets `archive` put it back on the wire.
834    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            // Never fatal. The layer's own signature and digests decided the
840            // install several steps ago; a third party's evidence being
841            // missing, malformed, or unfetchable is evidence ABOUT the
842            // evidence, and refusing here would hand a mirror the power to
843            // make a perfectly-signed layer uninstallable.
844            Err(e) => attestation_note = Some(e.to_string()),
845        }
846    }
847
848    // 7. Only a fully landed layer advances the high-water mark — or the
849    // cached index it was checked against (REQ-INDEXAUTH-001 clause 2).
850    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
873/// Why a digest-pinned layer below the mark may NOT be installed on the pin's
874/// word alone; `None` when the line's signed line-status consents
875/// (REQ-ROLLBACK-002).
876///
877/// The pin is not trusted by itself: the digest being in the file proves the
878/// reviewer chose THIS layer, not that the line still stands behind it. That
879/// is the line-status's word, and it has to verify against the realm's root —
880/// fetched from the source when it carries one, else the copy cached by an
881/// earlier install. A yank is never overridden, and neither is an expired
882/// support window; no verifiable document means no consent.
883///
884/// EVERY refusal here is terminal for failover (`InstallError::fails_over`),
885/// including "this source carries no line-status". Consent LIFTS a protection
886/// (the machine's own rollback mark), so it must not be obtainable by asking
887/// another source: a lagging mirror's older line-status, from before a yank,
888/// could grant consent the primary would have refused. The cost is chosen:
889/// a digest-pinned rollback install is unavailable while the primary's status
890/// cannot be had.
891fn 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    // The registry is the party anti-rollback constrains, so what it serves
914    // cannot outrank what this machine already holds: a validly-signed status
915    // from BEFORE a yank, replayed, would otherwise re-enable the yanked
916    // layer. The newer signed word decides, whichever side it came from.
917    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    // One counter names one signed document, so which side wins a tie does
922    // not matter; the greatest counter is the line's latest word.
923    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
936/// The same judgment from the line-status an earlier install cached, with no
937/// source — what `varve verify` has, because it runs offline and must not
938/// disagree with the install that put the layer there (REQ-ROLLBACK-002).
939pub 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
956/// What a VERIFIED line-status says about one layer, as consent: a yank or a
957/// lapsed support window refuses; silence on both consents.
958fn 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    // rivet: verifies REQ-MIRROR-002
1006    #[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            // A realm-signed verdict about the requested layer (a demotion),
1015            // not a fault of the source that served it.
1016            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    // rivet: verifies REQ-MIRROR-002
1050    #[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    /// One layer's worth of test material: manifest bytes + blobs.
1127    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    // rivet: verifies REQ-VERIFY-001
1161    #[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        // The layer is resolvable afterwards — install feeds resolution.
1178        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    // rivet: verifies REQ-STORE-002
1184    #[test]
1185    fn installing_two_versions_of_one_crate_lands_both_sets_of_bytes() {
1186        // Clause 2 through the function that actually runs it. `install`
1187        // collected (name, bytes) pairs and handed them to a store that wrote
1188        // `bin/<name>`, so the second serde's bytes landed under the first's
1189        // name: ONE file, the WRONG contents, and `verify` then failing on the
1190        // other entry with nothing explaining why.
1191        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        // Nothing landed under the bare name, where one version would have won.
1230        assert!(!entry.root.join("bin/serde").exists());
1231    }
1232
1233    // rivet: verifies REQ-STORE-002
1234    #[test]
1235    fn a_signed_manifest_whose_entries_share_one_identity_is_refused_not_overwritten() {
1236        // `deposit` refuses this, but deposit is not the only producer varve
1237        // installs from: any realm root can sign a manifest, built by any
1238        // software. If two entries ever reach one path, install must fail
1239        // LOUDLY — writing one over the other would put the wrong bytes under
1240        // the right name and make `verify` fail on the innocent entry.
1241        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    // rivet: verifies REQ-VERIFY-001
1278    #[test]
1279    fn kill_criterion_two_sources_one_verdict() {
1280        // The same bytes through two different transports must produce
1281        // identical verdicts — accept AND reject cases.
1282        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    // rivet: verifies REQ-VERIFY-001
1318    #[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    // rivet: verifies REQ-VERIFY-001
1358    #[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        // Serve the right manifest but tamper with one blob.
1363        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    // rivet: verifies REQ-VERIFY-001
1386    #[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        // Pin a digest that is NOT the digest of what the source returns.
1399        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    // rivet: verifies REQ-ROLLBACK-001
1426    #[test]
1427    fn a_rolled_back_layer_is_refused_at_install() {
1428        let (_tmp, store, mut marks) = setup();
1429        // The line's high-water mark is already at 5.
1430        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(); // counter 1 < 5
1435        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    // rivet: verifies REQ-ROLLBACK-001
1460    #[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        // Source is missing one blob: install fails after the rollback check.
1465        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    // rivet: verifies REQ-ROLLBACK-001
1490    #[test]
1491    fn staleness_is_surfaced_on_an_accepted_layer() {
1492        let (_tmp, store, mut marks) = setup();
1493        let (bytes, blobs) = july(); // issued 2026-07-31
1494        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    // rivet: verifies REQ-PLATFORM-001
1514    #[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        // Only the matching blob is served — a correct install never asks
1531        // for the foreign one.
1532        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    // rivet: verifies REQ-PLATFORM-001
1559    #[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    // rivet: verifies REQ-PLATFORM-001
1597    #[test]
1598    fn unstamped_legacy_entries_install_on_any_platform() {
1599        let (_tmp, store, mut marks) = setup();
1600        let (bytes, blobs) = july(); // fixtures without platform annotations
1601        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    // rivet: verifies REQ-PIN-001
1622    #[test]
1623    fn channel_and_layer_mismatches_are_refused() {
1624        let (_tmp, store, mut marks) = setup();
1625        // Manifest says rolling; pin says qualified.
1626        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    // rivet: verifies REQ-ATTEST-002
1654    #[test]
1655    fn install_carries_the_attestations_the_source_holds_into_the_installed_layer() {
1656        // The transport half. Binding shipped in v0.22.0 and reached nobody:
1657        // an attestation that stays in the producer's CI is not evidence a
1658        // consumer has. This asserts the evidence lands in the installed layer
1659        // root — the only place `archive` and `verify` can find it later.
1660        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        // …and it is really on disk, verbatim, and still binds offline.
1692        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    // rivet: verifies REQ-ATTEST-002
1711    #[test]
1712    fn a_source_that_loses_its_attestations_still_installs_but_says_so() {
1713        // Deliberate: REPORTING, not refusal. A mirror that drops the evidence
1714        // must not gain the power to make a correctly-signed layer
1715        // uninstallable — that would make varve's availability a function of
1716        // someone else's mirroring. But the loss must not be SILENT either:
1717        // silence is precisely the bandersnatch/Verdaccio failure this
1718        // requirement exists to surface.
1719        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    /// REQ-FIRSTCONTACT-001 end to end, through install().
1753    ///
1754    /// A machine with no marks file — a fresh checkout, a new CI runner — used
1755    /// to accept ANY counter on a line it had never seen, because there was
1756    /// nothing to compare against. That is the one moment anti-rollback
1757    /// protects nobody, and it is the moment worth attacking.
1758    // rivet: verifies REQ-FIRSTCONTACT-001
1759    #[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(); // 2026.07.0, counter 1
1766        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            // The realm signs a floor of 5 for this line; the layer is 1.
1788            .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        // And the refusal explains why a NEW machine is the interesting case.
1833        assert!(err.to_string().contains("never installed"), "{err}");
1834    }
1835
1836    /// The same layer, same realm, no stated floor: unchanged behaviour, so a
1837    /// realm that has not adopted this keeps installing exactly as before.
1838    // rivet: verifies REQ-FIRSTCONTACT-001
1839    #[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    // rivet: verifies REQ-INDEXAUTH-001
1902    #[test]
1903    fn install_raises_the_mark_from_the_index_even_when_the_layer_is_hidden() {
1904        // Clause 4 end to end, through install() — the Uptane property. The
1905        // registry serves ONLY the old layer and its signature is perfect. The
1906        // realm's signed index says a newer one exists. Without this, the
1907        // registry's silence sets the bar, and the hidden layer's counter
1908        // never constrains anything.
1909        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(); // 2026.07.0, counter 1
1914        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                    // The layer the registry is not serving.
1931                    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        // The consumer LEARNS what the realm says the line contains, even
1963        // though the registry never offered it.
1964        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        // …and the pinned layer still installed. This assertion is the whole
1971        // correction: an earlier draft raised the ENFORCEMENT mark to 42, and
1972        // this very install then failed with `rollback refused: presented 1,
1973        // high_water 42` — a deliberately-pinned layer made uninstallable by
1974        // someone else publishing. varve exists to freeze toolchains; a
1975        // freshness control that unfreezes them is not a fix.
1976        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    // rivet: verifies REQ-INDEXAUTH-001
1985    #[test]
1986    fn a_replayed_older_index_is_refused_on_the_next_install_not_only_in_theory() {
1987        // Clause 2 through the pipeline. `check` has always refused a
1988        // regression against a `cached` document — and install passed `None`
1989        // for `cached`, so the rule could not fire on any real machine: there
1990        // was nothing that REMEMBERED. This test installs twice, and the
1991        // second source replays a superseded index.
1992        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        // Counting the blob fetches is what makes this test able to tell WHERE
2013        // the refusal happened. Without it the test passed with `check` handed
2014        // `None` for the cached document, because the cache's own write-time
2015        // regression guard raised the identical error — after the layer had
2016        // been fetched, laid down, and the mark advanced. Same message, wholly
2017        // different behaviour, and the version that only compared messages
2018        // could not see the difference.
2019        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        // A second source — a stale mirror, or an attacker who kept a copy of
2068        // a pre-yank index — offers #4. Everything about it verifies.
2069        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        // …and the held document is still #9, so a third attempt at the same
2103        // replay fails the same way rather than sliding down.
2104        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    // rivet: verifies REQ-INDEXAUTH-001
2115    #[test]
2116    fn install_refuses_a_source_that_hides_an_indexed_layer() {
2117        // Clause 3 through install(). Every byte this source serves verifies;
2118        // the defect is what it withholds.
2119        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        // It admits to serving only the old layer, while the realm's index
2129        // names another.
2130        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        // Nothing was laid down on the strength of a dishonest listing.
2167        assert!(store.list().unwrap().is_empty(), "no install on a refusal");
2168    }
2169
2170    // ---- REQ-ROLLBACK-002: a digest in the pin is consent --------------------
2171
2172    /// Two layers of ONE line: 2026.07.0 (counter 1) and 2026.07.1 (counter 2),
2173    /// and a source that serves both.
2174    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    /// Accepts every manifest and names a root, as `PinnedKeyVerifier` does.
2266    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    /// Install the NEWER layer by name, advancing the machine's mark to 2.
2277    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    // rivet: verifies REQ-ROLLBACK-002
2291    #[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        // Clause 3: installing the older layer must NOT lower the mark.
2325        assert_eq!(f.marks.mark(&"2026.07".parse().unwrap()), Some(2));
2326        assert!(f.store.get(&digest).unwrap().is_some());
2327    }
2328
2329    // rivet: verifies REQ-ROLLBACK-002
2330    #[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    // rivet: verifies REQ-ROLLBACK-002
2347    #[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    // rivet: verifies REQ-ROLLBACK-002
2377    #[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    // rivet: verifies REQ-ROLLBACK-002
2410    #[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        // policy().now is 2026-08-07.
2416        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    // rivet: verifies REQ-ROLLBACK-002
2436    #[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    // rivet: verifies REQ-ROLLBACK-002
2455    #[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    // rivet: verifies REQ-MIRROR-002
2481    #[test]
2482    fn every_refusal_of_digest_consent_is_terminal_so_no_mirror_can_grant_it() {
2483        // Consent LIFTS a protection (the machine's own rollback mark), so it
2484        // must not be obtainable by asking another source: a lagging mirror's
2485        // older line-status, from before a yank, could grant what the primary
2486        // would refuse. Availability is the price, and it is chosen.
2487        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        // No status carried by this source.
2499        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        // A status that does not verify.
2518        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        // A verified yank, a verified lapsed window, and no trust root.
2535        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    // rivet: verifies REQ-MIRROR-002
2569    #[test]
2570    fn a_mirror_is_never_asked_to_consent_even_when_its_status_would() {
2571        // The status SUPPORTS the layer, so from the primary this installs
2572        // (see `a_cached_line_status_consents...` and `the_last_supported_day`).
2573        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        // The same pin, same status, from a MIRROR: refused, and terminal.
2590        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    // rivet: verifies REQ-MIRROR-002
2651    #[test]
2652    fn a_first_contact_is_refused_to_a_mirror_whatever_status_it_carries() {
2653        // No mark and no cached status for the line: nothing bounds a mirror.
2654        // Not even a genuine status that VERIFIES helps: an old one states no
2655        // raised floor, and the machine cannot tell it is old.
2656        for status in [
2657            None,
2658            Some(("2026.07", false)), // genuine, same line, states no floor
2659            Some(("2026.07", true)),  // forged
2660            Some(("2026.06", false)), // another line
2661        ] {
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    // rivet: verifies REQ-MIRROR-002
2686    #[test]
2687    fn a_mirror_is_asked_nothing_before_a_first_contact_is_refused() {
2688        // The refusal comes before any fetch: a source that panics if touched.
2689        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    // rivet: verifies REQ-MIRROR-002
2704    #[test]
2705    fn the_primary_answers_a_first_contact_and_history_of_either_kind_admits_a_mirror() {
2706        // The primary may omit the status (a stated, pre-existing residual).
2707        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        // History as a high-water MARK admits a mirror.
2712        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        // History as a cached LINE-STATUS alone (no mark) also admits one.
2742        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    /// A status document with a stated `min_counter`, signed by `sk`.
2758    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    /// No MARK for the line, but a verified status #3 cached with a raised
2774    /// floor of 5. Installing layer counter 4 from `source` as the primary or a
2775    /// mirror: the outcome.
2776    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    // rivet: verifies REQ-MIRROR-002
2820    #[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            // The source serves an OLDER status that states no floor.
2826            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            // The source serves no status at all.
2838            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            // The source serves a status that does not verify.
2845            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    // rivet: verifies REQ-MIRROR-002
2858    #[test]
2859    fn the_newer_verified_status_decides_the_floor_whichever_side_holds_it() {
2860        let (sk, pk) = crate::verify::generate_root_keypair();
2861        // The source serves a NEWER status (#4) with a higher floor: it binds.
2862        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        // A newer status that LOWERS the floor is the realm's later word, and
2874        // the cached one is outranked by it (counter 4 clears a floor of 2).
2875        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    // rivet: verifies REQ-MIRROR-002
2885    #[test]
2886    fn a_mirror_that_carries_an_index_but_cannot_enumerate_leaves_the_omission_check_unrun() {
2887        // History as a MARK, so a mirror may answer.
2888        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        // The source carries the index but, like a directory or OCI layout,
2905        // cannot ENUMERATE what it serves (`served_layers` is None).
2906        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        // The same source as the PRIMARY reports nothing skipped.
2933        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    // rivet: verifies REQ-MIRROR-002
2951    #[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        // An include whose line CANNOT be known: refused in words that say so,
2983        // not as a missing history. Absent and unparseable read differently.
2984        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    // rivet: verifies REQ-MIRROR-002
3012    #[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        // History for ANOTHER line does not.
3032        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    // rivet: verifies REQ-MIRROR-002
3055    #[test]
3056    fn an_include_that_names_one_line_but_digests_another_is_refused_terminally() {
3057        // The include NAMES a layer of line 2026.07 (which this machine has
3058        // history for) but the DIGEST is a layer of line 2026.06 (which it does
3059        // not). The early check passes on the named line; install_inner then
3060        // checks the REAL manifest's line and refuses.
3061        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    // rivet: verifies REQ-MIRROR-002
3098    #[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    // rivet: verifies REQ-ROLLBACK-002
3107    #[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    // rivet: verifies REQ-ROLLBACK-002
3126    #[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    // rivet: verifies REQ-ROLLBACK-002
3149    #[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    // rivet: verifies REQ-ROLLBACK-002
3171    #[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    // rivet: verifies REQ-ROLLBACK-002
3198    #[test]
3199    fn a_registry_replaying_an_older_status_cannot_undo_a_cached_yank() {
3200        // The attacker REQ-ROLLBACK-001 exists for controls the registry. A
3201        // yank issued at status #2 is cached here; the registry then serves
3202        // the validly-signed status #1 from before the yank. Consent must
3203        // follow the NEWER signed word, or a replay re-enables a yanked layer.
3204        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    // rivet: verifies REQ-ROLLBACK-002
3232    #[test]
3233    fn a_signed_floor_is_not_overridden_by_a_digest() {
3234        // The line-status's `min-counter` is the line's own statement that no
3235        // layer below it is acceptable. Consent is the line standing behind a
3236        // layer; a floor above it says the line does not.
3237        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    // rivet: verifies REQ-ROLLBACK-002
3261    #[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); // the older layer presents counter 1
3271        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    // rivet: verifies REQ-ROLLBACK-002
3287    #[test]
3288    fn verifys_offline_judgment_reads_the_cache_and_names_why() {
3289        // `varve verify` calls this with no source; it must agree with install.
3290        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    // rivet: verifies REQ-ROLLBACK-002
3342    #[test]
3343    fn a_newer_served_status_outranks_an_older_cached_one() {
3344        // The other direction: a cached yank later LIFTED by a newer status
3345        // the registry serves. The newer word wins here too.
3346        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    // rivet: verifies REQ-ROLLBACK-002
3373    #[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    // rivet: verifies REQ-ROLLBACK-002
3400    #[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        // Names 2026.07.0 but carries the digest of 2026.07.1.
3407        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        // And a digest the source cannot match against its own bytes.
3418        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    // rivet: verifies REQ-ROLLBACK-002
3434    #[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    // rivet: verifies REQ-ROLLBACK-002
3453    #[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        // Validly signed, but about line 2026.06 — cached under 2026.07.
3459        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}